UNPKG

paddleocr-js

Version:

JavaScript wrapper for PaddleOCR, providing OCR capabilities in browser and Node.js

2 lines 1.71 MB
/*! For license information please see index.min.js.LICENSE.txt */
!function(e,t){"object"===typeof exports&&"object"===typeof module?module.exports=t():"function"===typeof define&&define.amd?define([],t):"object"===typeof exports?exports.PaddleOCR=t():e.PaddleOCR=t()}(this,(()=>(()=>{var e={112:(e,t,n)=>{"use strict";n.d(t,{V:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({relu_:function(e){const t={x:(0,s.YT)(e,"x","relu")};return r.T2.runKernel(a.fUj,t)}})},125:(e,t,n)=>{"use strict";n.d(t,{o:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({clone_:function(e){const t={x:(0,s.YT)(e,"x","clone","string_or_numeric")};return r.T2.runKernel(a.lzr,t)}})},126:e=>{"use strict";const t="'([^']+)'|\"([^\"]+)\"|[\\w\\s-]+",n=new RegExp("(bold|bolder|lighter|[1-9]00) +","i"),r=new RegExp("(italic|oblique) +","i"),a=new RegExp("(small-caps) +","i"),s=new RegExp("(ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded) +","i"),i=new RegExp(`([\\d\\.]+)(px|pt|pc|in|cm|mm|%|em|ex|ch|rem|q) *((?:${t})( *, *(?:${t}))*)`),o={};e.exports=e=>{if(o[e])return o[e];const t=i.exec(e);if(!t)return;const u={weight:"normal",style:"normal",stretch:"normal",variant:"normal",size:parseFloat(t[1]),unit:t[2],family:t[3].replace(/["']/g,"").replace(/ *, */g,",")};let l,c,d,p;const h=e.substring(0,t.index);switch((l=n.exec(h))&&(u.weight=l[1]),(c=r.exec(h))&&(u.style=c[1]),(d=a.exec(h))&&(u.variant=d[1]),(p=s.exec(h))&&(u.stretch=p[1]),u.unit){case"pt":u.size/=.75;break;case"pc":u.size*=16;break;case"in":u.size*=96;break;case"cm":u.size*=96/2.54;break;case"mm":u.size*=96/25.4;break;case"%":break;case"em":case"rem":u.size*=16/.75;break;case"q":u.size*=96/25.4/4}return o[e]=u}},152:(e,t,n)=>{"use strict";n.d(t,{z:()=>o});var r=n(1585),a=n(5441),s=n(565),i=n(8189);const o=(0,n(929).op)({mod_:function(e,t){let n=(0,i.YT)(e,"a","mod"),o=(0,i.YT)(t,"b","mod");[n,o]=(0,s.makeTypesMatch)(n,o);const u={a:n,b:o};return r.T2.runKernel(a.BLA,u)}})},178:(e,t,n)=>{"use strict";n.d(t,{P:()=>l});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198),u=n(9809);const l=(0,n(929).op)({maximum_:function(e,t){let n=(0,i.YT)(e,"a","maximum"),l=(0,i.YT)(t,"b","maximum");[n,l]=(0,s.makeTypesMatch)(n,l),"bool"===n.dtype&&(n=(0,u.w)(n,"int32"),l=(0,u.w)(l,"int32")),(0,o.assertAndGetBroadcastShape)(n.shape,l.shape);const c={a:n,b:l};return r.T2.runKernel(a.LDN,c)}})},252:(e,t,n)=>{"use strict";n.d(t,{v:()=>l});var r=n(1585),a=n(5441),s=n(5119),i=n(7195),o=n(929),u=n(2302);const l=(0,o.op)({conv2DBackpropInput_:function(e,t,n,o,l,c="NHWC",d){s.vA(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let p=e,h=t,f=!1;3===t.rank&&(f=!0,h=(0,u.t)(t,[1,t.shape[0],t.shape[1],t.shape[2]]),p=[1,e[0],e[1],e[2]]),s.vA(4===p.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${p.length}.`)),s.vA(4===h.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${h.rank}`)),s.vA(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const m="NHWC"===c?p[3]:p[1],g="NHWC"===c?h.shape[3]:h.shape[1];s.vA(m===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${m}) must match input depth for filter ${n.shape[2]}.`)),s.vA(g===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${g}) must match output depth for filter ${n.shape[3]}.`)),i.s_("conv2dDerInput",l,d);const y={dy:h,filter:n},b={strides:o,pad:l,dataFormat:c,dimRoundingMode:d,inputShape:p},x=r.T2.runKernel(a.jfg,y,b);return f?(0,u.t)(x,[x.shape[1],x.shape[2],x.shape[3]]):x}})},259:(e,t,n)=>{"use strict";n.d(t,{qY:()=>b,yl:()=>d,rT:()=>w,tp:()=>x,B4:()=>y,Q5:()=>g,qP:()=>m});var r=n(1743),a=n(5119);function s(e,t,n,r){const s=(0,a.Ur)(t),o=function(e,t,n,r){const s=(0,a.Ze)(t),o=r[r.length-1],u=new Array(o).fill(0),c=t.length,d="complex64"===n?l(e):e;if(c>1)for(let a=0;a<s/o;a++){const e=a*o;for(let t=0;t<o;t++)u[t]=Math.max(u[t],i(d[e+t],0,n).length)}return u}(e,t,n,s),c=t.length,d=u(e,t,n,s,o),p=["Tensor"];return r&&(p.push(`  dtype: ${n}`),p.push(`  rank: ${c}`),p.push(`  shape: [${t}]`),p.push("  values:")),p.push(d.map((e=>"    "+e)).join("\n")),p.join("\n")}function i(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:(0,a.Kg)(e)?`'${e}'`:"bool"===n?o(e):parseFloat(e.toFixed(7)).toString(),(0,a.av)(r,t)}function o(e){return 0===e?"false":"true"}function u(e,t,n,r,a,s=!0){const c="complex64"===n?2:1,d=t[0],p=t.length;if(0===p){if("complex64"===n){return[i(l(e)[0],0,n)]}return"bool"===n?[o(e[0])]:[e[0].toString()]}if(1===p){if(d>20){const t=3*c;let r=Array.from(e.slice(0,t)),s=Array.from(e.slice((d-3)*c,d*c));return"complex64"===n&&(r=l(r),s=l(s)),["["+r.map(((e,t)=>i(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>i(e,a[d-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?l(e):Array.from(e)).map(((e,t)=>i(e,a[t],n))).join(", ")+"]"]}const h=t.slice(1),f=r.slice(1),m=r[0]*c,g=[];if(d>20){for(let t=0;t<3;t++){const r=t*m,s=r+m;g.push(...u(e.slice(r,s),h,n,f,a,!1))}g.push("...");for(let t=d-3;t<d;t++){const r=t*m,s=r+m;g.push(...u(e.slice(r,s),h,n,f,a,t===d-1))}}else for(let i=0;i<d;i++){const t=i*m,r=t+m;g.push(...u(e.slice(t,r),h,n,f,a,i===d-1))}const y=2===p?",":"";g[0]="["+(d>0?g[0]+y:"");for(let i=1;i<g.length-1;i++)g[i]=" "+g[i]+y;let b=",\n";for(let i=2;i<p;i++)b+="\n";return g[g.length-1]=" "+g[g.length-1]+"]"+(s?"":b),g}function l(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var c=n(3879);class d{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=a.Ze(e),null!=n){const e=n.length;a.vA(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||a.Ab(t,this.size),this.strides=(0,a.Ur)(e)}set(e,...t){0===t.length&&(t=[0]),a.vA(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 p().makeTensor(this.values,this.shape,this.dtype)}}let p=null,h=null,f=null;function m(e){p=e}function g(e){h=e}function y(e){f=e}class b{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=a.Ze(e),this.strides=(0,a.Ur)(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 h.buffer(this.shape,this.dtype,e)}bufferSync(){return h.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return(0,a.yw)(this.shape,e,"complex64"===this.dtype)}arraySync(){return(0,a.yw)(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=p().read(this.dataId);if("string"===this.dtype){const n=await e;try{return n.map((e=>c.decodeString(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(),p().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=p().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>c.decodeString(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 p().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),p().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return h.print(this,e)}clone(){return this.throwIfDisposed(),h.clone(this)}toString(e=!1){return s(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),h.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),p().makeVariable(this,e,t,n)}}function x(){return(0,r.m)("Tensor",(()=>b))}Object.defineProperty(b,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),x();class w extends b{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(!a.r1(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);p().disposeTensor(this),this.dataId=e.dataId,p().incRef(this,null)}dispose(){p().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(w,Symbol.hasInstance,{value:e=>e instanceof b&&null!=e.assign&&e.assign instanceof Function})},269:(e,t,n)=>{"use strict";n.d(t,{y:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({asinh_:function(e){const t={x:(0,s.YT)(e,"x","asinh")};return r.T2.runKernel(a.epO,t)}})},302:(e,t,n)=>{"use strict";n.d(t,{L:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({cumprod_:function(e,t=0,n=!1,i=!1){const o={x:(0,s.YT)(e,"x","cumprod")},u={axis:t,exclusive:n,reverse:i};return r.T2.runKernel(a.jj_,o,u)}})},448:(e,t,n)=>{"use strict";n.d(t,{r:()=>s});var r=n(259),a=n(5119);function s(e,t="float32",n){return t=t||"float32",a.SA(e),new r.yl(e,t,n)}},517:(e,t,n)=>{"use strict";n.d(t,{I:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({expm1_:function(e){const t={x:(0,s.YT)(e,"x","expm1")};return r.T2.runKernel(a.ybj,t)}})},551:()=>{},565:(e,t,n)=>{"use strict";n.r(t),n.d(t,{assertTypesMatch:()=>o,getTensorsInContainer:()=>l,isTensorInList:()=>u,makeTypesMatch:()=>i});var r=n(259),a=n(2046),s=n(5119);function i(e,t){if(e.dtype===t.dtype)return[e,t];const n=(0,a.Tu)(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function o(e,t){(0,s.vA)(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function u(e,t){return t.some((t=>t.id===e.id))}function l(e){const t=[];return c(e,t,new Set),t}function c(e,t,n){if(null==e)return;if(e instanceof r.qY)return void t.push(e);if(a=e,!Array.isArray(a)&&"object"!==typeof a)return;var a;const s=e;for(const r in s){const e=s[r];n.has(e)||(n.add(e),c(e,t,n))}}},676:(e,t,n)=>{"use strict";n.d(t,{G:()=>c});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(7195),u=n(929),l=n(2302);const c=(0,u.op)({depthwiseConv2d_:function(e,t,n,u,c="NHWC",d=[1,1],p){const h=(0,s.YT)(e,"x","depthwiseConv2d","float32"),f=(0,s.YT)(t,"filter","depthwiseConv2d","float32");let m=h,g=!1;3===h.rank&&(g=!0,m=(0,l.t)(h,[1,h.shape[0],h.shape[1],h.shape[2]])),i.vA(4===m.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${m.rank}.`)),i.vA(4===f.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${f.rank}.`));const y="NHWC"===c?m.shape[3]:m.shape[1];i.vA(y===f.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${y}) must match the inChannels dimension in filter ${f.shape[2]}.`)),o.s_("depthwiseConv2d",u,p);const b={x:m,filter:f},x={strides:n,pad:u,dataFormat:c,dilations:d,dimRoundingMode:p},w=r.T2.runKernel(a.tGH,b,x);return g?(0,l.t)(w,[w.shape[1],w.shape[2],w.shape[3]]):w}})},700:(e,t,n)=>{"use strict";n.d(t,{P:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({step_:function(e,t=0){const n={x:(0,s.YT)(e,"x","step")},i={alpha:t};return r.T2.runKernel(a.pnw,n,i)}})},776:(e,t,n)=>{"use strict";n.d(t,{e:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({spaceToBatchND_:function(e,t,n){const o=(0,s.YT)(e,"x","spaceToBatchND");i.vA(o.rank>=1+t.length,(()=>`input rank ${o.rank} should be > than [blockShape] ${t.length}`)),i.vA(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),i.vA(o.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 ${o.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const u={x:o},l={blockShape:t,paddings:n};return r.T2.runKernel(a.A8B,u,l)}})},855:(e,t,n)=>{"use strict";n.d(t,{m:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({ceil_:function(e){const t={x:(0,s.YT)(e,"x","ceil","float32")};return r.T2.runKernel(a.QDP,t)}})},897:(e,t,n)=>{"use strict";n.d(t,{F:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({argMax_:function(e,t=0){const n={x:(0,s.YT)(e,"x","argMax")},i={axis:t};return r.T2.runKernel(a.Jp_,n,i)}})},919:(e,t,n)=>{"use strict";n.d(t,{e:()=>c});var r=n(565),a=n(8189),s=n(9359),i=n(3020),o=n(929),u=n(2151),l=n(5537);const c=(0,o.op)({divNoNan_:function(e,t){let n=(0,a.YT)(e,"a","div"),o=(0,a.YT)(t,"b","div");[n,o]=(0,r.makeTypesMatch)(n,o);const c=(0,s.y)(n,o),d=(0,l.P)(c),p=(0,i.L)(o,d);return(0,u._)(p,d,c)}})},929:(e,t,n)=>{"use strict";n.d(t,{B:()=>s,op:()=>i});var r=n(1585),a=n(5119);const s="__op";function i(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 i=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=s;const o=(...e)=>{r.T2.startScope(n);try{const t=i(...e);return(0,a.yL)(t),r.T2.endScope(t),t}catch(t){throw r.T2.endScope(null),t}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}},1078:(e,t,n)=>{"use strict";n.d(t,{Em:()=>l,SM:()=>o,WC:()=>u,WH:()=>a,aF:()=>s,fK:()=>d,gx:()=>c,lb:()=>i});var r=n(5119);function a(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function s(e,t,n){const r=e.length+t.length,a=[];let s=0,i=0;for(let o=0;o<r;o++)-1===n.indexOf(o)?a.push(e[s++]):a.push(t[i++]);return a}function i(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 o(e,t){return s(e,t.map((e=>1)),t)}function u(e,t,n){r.vA(a(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function l(e,t){if(a(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 c(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function d(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}},1106:(e,t,n)=>{"use strict";n.d(t,{w:()=>s});var r=n(8189),a=n(252);const s=(0,n(929).op)({conv2dTranspose_:function(e,t,n,s,i,o){const u=(0,r.YT)(e,"x","conv2dTranspose"),l=(0,r.YT)(t,"filter","conv2dTranspose");return(0,a.v)(n,u,l,s,i,"NHWC",o)}})},1115:(e,t,n)=>{"use strict";n.d(t,{_:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({sign_:function(e){const t={x:(0,s.YT)(e,"x","sign")};return r.T2.runKernel(a.YVe,t)}})},1190:(e,t,n)=>{"use strict";n.d(t,{r:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({topk_:function(e,t=1,n=!0){const i=(0,s.YT)(e,"x","topk");if(0===i.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const o=i.shape[i.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${t}`);const u={x:i},l={k:t,sorted:n},[c,d]=r.T2.runKernel(a.TBb,u,l);return{values:c,indices:d}}})},1216:(e,t,n)=>{"use strict";n.d(t,{R:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({depthToSpace_:function(e,t,n="NHWC"){const o=(0,s.YT)(e,"x","depthToSpace","float32"),u="NHWC"===n?o.shape[1]:o.shape[2],l="NHWC"===n?o.shape[2]:o.shape[3],c="NHWC"===n?o.shape[3]:o.shape[1];i.vA(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),i.vA(u*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n    ${u} and ${t}  for depthToSpace with input shape\n    ${o.shape}`)),i.vA(l*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n    ${l} and ${t} for depthToSpace with input shape\n        ${o.shape}`)),i.vA(c%(t*t)===0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${c} for depthToSpace with input shape ${o.shape}`));const d={x:o},p={blockSize:t,dataFormat:n};return r.T2.runKernel(a.TMz,d,p)}})},1234:()=>{},1303:(e,t,n)=>{"use strict";n.d(t,{M:()=>u});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198);const u=(0,n(929).op)({less_:function(e,t){let n=(0,i.YT)(e,"a","less","string_or_numeric"),u=(0,i.YT)(t,"b","less","string_or_numeric");[n,u]=(0,s.makeTypesMatch)(n,u),(0,o.assertAndGetBroadcastShape)(n.shape,u.shape);const l={a:n,b:u};return r.T2.runKernel(a.mIA,l)}})},1361:(e,t,n)=>{"use strict";n.d(t,{h:()=>i});var r=n(1585),a=n(5441),s=n(5119);const i=(0,n(929).op)({fft_:function(e){(0,s.vA)("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return r.T2.runKernel(a.rGP,t)}})},1404:(e,t,n)=>{"use strict";n.d(t,{F:()=>o});var r=n(1585),a=n(5441),s=n(565),i=n(8189);const o=(0,n(929).op)({atan2_:function(e,t){let n=(0,i.YT)(e,"a","atan2"),o=(0,i.YT)(t,"b","atan2");[n,o]=(0,s.makeTypesMatch)(n,o);const u={a:n,b:o};return r.T2.runKernel(a.lxb,u)}})},1411:(e,t,n)=>{"use strict";n.d(t,{S:()=>o});var r=n(1585),a=n(5119),s=n(7148),i=n(2855);function o(e,t="float32"){if((0,a.SA)(e),"complex64"===t){const t=o(e,"float32"),n=(0,i.U)(e,"float32");return(0,s.f)(t,n)}const n=(0,a.FZ)((0,a.Ze)(e),t);return r.T2.makeTensor(n,e,t)}},1585:(e,t,n)=>{"use strict";n.d(t,{T2:()=>w,Ye:()=>x});var r=n(5149),a=n(6574),s=n(1743),i=n(5441),o=n(7074),u=n(3673),l=n(3879),c=n(5119);class d{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new h)}profileKernel(e,t,n){let r;const s=()=>{r=n()};let i;const o=l.now();if(this.backendTimer.timerAvailable())i=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();i=Promise.resolve({kernelMs:l.now()-o})}if((0,a._K)().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let a=0;a<r.length;a++){const t=r[a];t.data().then((n=>{p(n,t.dtype,e)}))}return{kernelName:e,outputs:r,inputs:t,timeMs:i.then((e=>e.kernelMs)),extraInfo:i.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 p(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!0}return!1}class h{logKernelProfile(e,t,n,r,a,s){"number"===typeof r?c.av(`${r}ms`,9):r.error,c.av(e,25),t.rank,t.size,c.av(t.shape.toString(),14);let i="";for(const o in a){const e=a[o];if(null!=e){const n=e.shape||t.shape,r=n.length;i+=`${o}: ${r}D ${r>0?n:""} `}}}}var f=n(259),m=n(565);function g(e){return null!=e.kernelName}class y{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 b{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new y}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?(u.i(`${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 d(this.backendInstance),!0}setupRegisteredKernels(){(0,o.Op)(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){(0,o.Op)(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 n=t.factory();if(!n||n instanceof r.uI||"function"!==typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,u.i(`Initialization of backend ${e} failed`),u.i(n.stack||n.message)),!1)));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(n){return u.i(`Initialization of backend ${e} failed`),u.i(n.stack||n.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)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(r){throw t(),r}}nextTensorId(){return b.nextTensorId++}nextVariableId(){return b.nextVariableId++}clone(e){const t=w.runKernel(i.lzr,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return w.runKernel(i.KXH,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=(0,o._5)(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],i=r-t-a-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let i,u;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=g(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(g(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=(0,o._5)(t,this.backendName);c.vA(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();u=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const i=Array.isArray(u)?u:[u];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const o=i.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(r){const e=this.getTensorsForGradient(t,a,o);n=this.saveTensorsForBackwardMode(e)}return o}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{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:d,attrs:p}=e,h=g(e)?null:e.backwardsFunc;let f;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(f=this.profiler.profileKernel(l,d,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),t=f.outputs):t=i()})),r&&this.addTapeNode(l,d,t,h,n,p),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(d).map((e=>null!=d[e]?d[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(u)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=(0,o.vQ)(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(c.vA(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 i=n.filter(((e,t)=>a[t]));return s.concat(i)}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&&c.Kg(e[0])&&(a=e.map((e=>l.encodeString(e))));const s=r.write(a,t,n),i=new f.qY(t,n,s,this.nextTensorId());if(this.trackTensor(i,r),"string"===n){const e=this.state.tensorInfo.get(s),t=(0,c.SL)(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}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 f.qY(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 f.rT(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*c.jv(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 f.rT||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*c.jv(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 i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},u=(0,o.vQ)(e);null!=u&&(r=u.gradFunc),null!=r&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=c.Ty(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(i)}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=(0,m.getTensorsInContainer)(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(c.vA(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)));c.vA(a instanceof f.qY,(()=>"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 i=s[e];let o=!1;for(let e=0;e<t.length;e++)if(r[i.id]){n.outputs.forEach((e=>r[e.id]=!0)),o=!0,a[n.id]=!0;break}if(o)break}}const s={};s[n.id]=!0;const i={};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,i[t.id]=!0;break}}const o=[];for(let u=0;u<e.length;u++){const t=e[u];if(a[t.id]&&i[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,o.push(n)}}return o}(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]=null==n?function(e){const t=(0,c.FZ)((0,c.Ze)(e),"float32");return w.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,r){for(let a=t.length-1;a>=0;a--){const s=t[a],i=[];if(s.outputs.forEach((t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)})),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const o=s.gradient(i);for(const t in s.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const a=n((()=>o[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 i=s.inputs[t];if(!c.r1(a.shape,i.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 '${i.shape}'`);if(null==e[i.id])e[i.id]=a;else{const t=e[i.id];e[i.id]=r(t,a),t.dispose()}}}}(e,s,(e=>this.tidy(e)),v);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 c.vA(c.Tn(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;c.vA(t.every((e=>e instanceof f.qY)),(()=>"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),c.vA(n.value instanceof f.qY,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),c.vA(c.Tn(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];c.vA(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(...).")),c.vA(s.every((e=>e instanceof f.qY)),(()=>"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 i={};return s.forEach(((e,t)=>{i[t]=()=>e})),i},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=(0,l.now)(),n=await this.backend.time(e);return n.wallMs=(0,l.now)()-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 y;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 x(){const e=(0,s.L)();if(null==e._tfengine){const t=new a.OH(e);e._tfengine=new b(t)}return(0,a.tj)(e._tfengine.ENV),(0,f.qP)((()=>e._tfengine)),e._tfengine}b.nextTensorId=0,b.nextVariableId=0;const w=x();function v(e,t){const n={a:e,b:t};return w.runKernel(i.OMN,n)}},1603:(e,t,n)=>{"use strict";var r=(()=>{var e,t,r,a,s,i,o,u,l,c,d,p,h,f,m,g,y,b,x,w,v,k,S,_,I,T,$,C,N,E,A,R=Object.defineProperty,D=Object.getOwnPropertyDescriptor,F=Object.getOwnPropertyNames,M=Object.prototype.hasOwnProperty,O=n(4687),z=(e,t)=>()=>(e&&(t=e(e=0)),t),L=(e,t)=>{for(var n in t)R(e,n,{get:t[n],enumerable:!0})},P=e=>((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of F(t))!M.call(e,a)&&a!==n&&R(e,a,{get:()=>t[a],enumerable:!(r=D(t,a))||r.enumerable});return e})(R({},"__esModule",{value:!0}),e),B=z((()=>{e=new Map,t=[],r=(n,r,a)=>{if(!r||"function"!=typeof r.init||"function"!=typeof r.createInferenceSessionHandler)throw new TypeError("not a valid backend");{let s=e.get(n);if(void 0===s)e.set(n,{backend:r,priority:a});else{if(s.priority>a)return;if(s.priority===a&&s.backend!==r)throw new Error(`cannot register backend "${n}" using priority ${a}`)}if(a>=0){let r=t.indexOf(n);-1!==r&&t.splice(r,1);for(let s=0;s<t.length;s++)if(e.get(t[s]).priority<=a)return void t.splice(s,0,n);t.push(n)}}},a=async t=>{let n=e.get(t);if(!n)return"backend not found.";if(n.initialized)return n.backend;if(n.aborted)return n.error;{let e=!!n.initPromise;try{return e||(n.initPromise=n.backend.init(t)),await n.initPromise,n.initialized=!0,n.backend}catch(r){return e||(n.error=`${r}`,n.aborted=!0),n.error}finally{delete n.initPromise}}},s=async e=>{let n,r=e.executionProviders||[],s=r.map((e=>"string"==typeof e?e:e.name)),i=0===s.length?t:s,o=[],u=new Set;for(let t of i){let e=await a(t);"string"==typeof e?o.push({name:t,err:e}):(n||(n=e),n===e&&u.add(t))}if(!n)throw new Error(`no available backend found. ERR: ${o.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`);for(let{name:t,err:a}of o)s.includes(t);let l=r.filter((e=>u.has("string"==typeof e?e:e.name)));return[n,new Proxy(e,{get:(e,t)=>"executionProviders"===t?l:Reflect.get(e,t)})]}})),W=z((()=>{B()})),V=z((()=>{i="1.21.0"})),U=z((()=>{V(),o="warning",u={wasm:{},webgl:{},webgpu:{},versions:{common:i},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);o=e}},get logLevel(){return o}},Object.defineProperty(u,"logLevel",{enumerable:!0})})),G=z((()=>{U(),l=u})),H=z((()=>{c=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext("2d");if(null!=r){let a,s;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(a=e.dims[2],s=e.dims[3]):(a=e.dims[3],s=e.dims[2]);let i,o,u=void 0!==t?.format?t.format:"RGB",l=t?.norm;void 0===l||void 0===l.mean?i=[255,255,255,255]:"number"==typeof l.mean?i=[l.mean,l.mean,l.mean,l.mean]:(i=[l.mean[0],l.mean[1],l.mean[2],0],void 0!==l.mean[3]&&(i[3]=l.mean[3])),void 0===l||void 0===l.bias?o=[0,0,0,0]:"number"==typeof l.bias?o=[l.bias,l.bias,l.bias,l.bias]:(o=[l.bias[0],l.bias[1],l.bias[2],0],void 0!==l.bias[3]&&(o[3]=l.bias[3]));let c=s*a,d=0,p=c,h=2*c,f=-1;"RGBA"===u?(d=0,p=c,h=2*c,f=3*c):"RGB"===u?(d=0,p=c,h=2*c):"RBG"===u&&(d=0,h=c,p=2*c);for(let t=0;t<s;t++)for(let n=0;n<a;n++){let a=(e.data[d++]-o[0])*i[0],s=(e.data[p++]-o[1])*i[1],u=(e.data[h++]-o[2])*i[2],l=-1===f?255:(e.data[f++]-o[3])*i[3];r.fillStyle="rgba("+a+","+s+","+u+","+l+")",r.fillRect(n,t,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}throw new Error("Can not access image data")},d=(e,t)=>{let n,r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");if(null==r)throw new Error("Can not access image data");{let a,s,i;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(a=e.dims[2],s=e.dims[1],i=e.dims[3]):(a=e.dims[3],s=e.dims[2],i=e.dims[1]);let o,u,l=void 0!==t&&void 0!==t.format?t.format:"RGB",c=t?.norm;void 0===c||void 0===c.mean?o=[255,255,255,255]:"number"==typeof c.mean?o=[c.mean,c.mean,c.mean,c.mean]:(o=[c.mean[0],c.mean[1],c.mean[2],255],void 0!==c.mean[3]&&(o[3]=c.mean[3])),void 0===c||void 0===c.bias?u=[0,0,0,0]:"number"==typeof c.bias?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],void 0!==c.bias[3]&&(u[3]=c.bias[3]));let d=s*a;if(void 0!==t&&(void 0!==t.format&&4===i&&"RGBA"!==t.format||3===i&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");let p=4,h=0,f=1,m=2,g=3,y=0,b=d,x=2*d,w=-1;"RGBA"===l?(y=0,b=d,x=2*d,w=3*d):"RGB"===l?(y=0,b=d,x=2*d):"RBG"===l&&(y=0,x=d,b=2*d),n=r.createImageData(a,s);for(let t=0;t<s*a;h+=p,f+=p,m+=p,g+=p,t++)n.data[h]=(e.data[y++]-u[0])*o[0],n.data[f]=(e.data[b++]-u[1])*o[1],n.data[m]=(e.data[x++]-u[2])*o[2],n.data[g]=-1===w?255:(e.data[w++]-u[3])*o[3]}return n}})),j=z((()=>{K(),p=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");let n,r,{height:a,width:s}=t,i=t.norm??{mean:255,bias:0};n="number"==typeof i.mean?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],r="number"==typeof i.bias?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let o=void 0!==t.format?t.format:"RGBA",u=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",l=a*s,c="RGBA"===u?new Float32Array(4*l):new Float32Array(3*l),d=4,p=0,h=1,f=2,m=3,g=0,y=l,b=2*l,x=-1;"RGB"===o&&(d=3,p=0,h=1,f=2,m=-1),"RGBA"===u?x=3*l:"RBG"===u?(g=0,b=l,y=2*l):"BGR"===u&&(b=0,y=l,g=2*l);for(let w=0;w<l;w++,p+=d,f+=d,h+=d,m+=d)c[g++]=(e[p]+r[0])/n[0],c[y++]=(e[h]+r[1])/n[1],c[b++]=(e[f]+r[2])/n[2],-1!==x&&-1!==m&&(c[x++]=(e[m]+r[3])/n[3]);return new _("float32",c,"RGBA"===u?[1,4,a,s]:[1,3,a,s])},h=async(e,t)=>{let n,r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,a=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i="string"==typeof e,o=t??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},l=e=>typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(r){let r=u();r.width=e.width,r.height=e.height;let a=l(r);if(null==a)throw new Error("Can not access image data");{let r=e.height,s=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(r=t.resizedHeight,s=t.resizedWidth),void 0!==t){if(o=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=r,o.width=s}else o.tensorFormat="RGBA",o.height=r,o.width=s;a.drawImage(e,0,0),n=a.getImageData(0,0,s,r).data}}else{if(!a){if(s){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");let r=u();r.width=e.width,r.height=e.height;let a=l(r);if(null!=a){let t=e.height,r=e.width;return a.drawImage(e,0,0,r,t),n=a.getImageData(0,0,r,t).data,o.height=t,o.width=r,p(n,o)}throw new Error("Can not access image data")}if(i)return new Promise(((t,n)=>{let r=u(),a=l(r);if(!e||!a)return n();let s=new Image;s.crossOrigin="Anonymous",s.src=e,s.onload=()=>{r.width=s.width,r.height=s.height,a.drawImage(s,0,0,r.width,r.height);let e=a.getImageData(0,0,r.width,r.height);o.height=r.height,o.width=r.width,t(p(e.data,o))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let r,a;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(r=t.resizedHeight,a=t.resizedWidth):(r=e.height,a=e.width),void 0!==t&&(o=t),o.format="RGBA",o.height=r,o.width=a,void 0!==t){let t=u();t.width=a,t.height=r;let s=l(t);if(null==s)throw new Error("Can not access image data");s.putImageData(e,0,0),n=s.getImageData(0,0,a,r).data}else n=e.data}}if(void 0!==n)return p(n,o);throw new Error("Input data provided is not supported - aborted tensor creation")},f=(e,t)=>{let{width:n,height:r,download:a,dispose:s}=t;return new _({location:"texture",type:"float32",texture:e,dims:[1,r,n,4],download:a,dispose:s})},m=(e,t)=>{let{dataType:n,dims:r,download:a,dispose:s}=t;return new _({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:r,download:a,dispose:s})},g=(e,t)=>{let{dataType:n,dims:r,download:a,dispose:s}=t;return new _({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:r,download:a,dispose:s})},y=(e,t,n)=>new _({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})})),q=z((()=>{b=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),x=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),w=!1,v=()=>{if(!w){w=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<"u"&&n.from;e&&(b.set("int64",BigInt64Array),x.set(BigInt64Array,"int64")),t&&(b.set("uint64",BigUint64Array),x.set(BigUint64Array,"uint64")),r?(b.set("float16",n),x.set(n,"float16")):b.set("float16",Uint16Array)}}})),Z=z((()=>{K(),k=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if("number"!=typeof r||!Number.isSafeInteger(r))throw new TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},S=(e,t)=>{switch(e.location){case"cpu":return new _(e.type,e.data,t);case"cpu-pinned":return new _({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new _({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new _({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new _({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}})),K=z((()=>{H(),j(),q(),Z(),_=class{constructor(e,t,n){let r,a;if(v(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,r=e.type,a=e.dims,e.location){case"cpu-pinned":{let t=b.get(r);if(!t)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint8"!==r&&"bool"!==r&&"uint4"!==r&&"int4"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint64"!==r&&"int8"!==r&&"uint8"!==r&&"bool"!==r&&"uint4"!==r&&"int4"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,i;if("string"==typeof e)if(r=e,i=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");s=t}else{let n=b.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&n===Uint16Array||"uint4"===e||"int4"===e)throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);s="uint64"===e||"int64"===e?n.from(t,BigInt):n.from(t)}else if(t instanceof n)s=t;else if(t instanceof Uint8ClampedArray){if("uint8"!==e)throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");s=Uint8Array.from(t)}else{if(!("float16"===e&&t instanceof Uint16Array&&n!==Uint16Array))throw new TypeError(`A ${r} tensor's data must be type of ${n}`);s=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length)}}else if(i=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");let t=typeof e[0];if("string"===t)r="string",s=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",s=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)r="uint8",s=Uint8Array.from(e);else{let t=x.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,s=e}if(void 0===i)i=[s.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");a=i,this.cpuData=s,this.dataLocation="cpu"}let s=k(a);if(this.cpuData&&s!==this.cpuData.length&&("uint4"!==r&&"int4"!==r||Math.ceil(s/2)!==this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=a,this.size=s}static async fromImage(e,t){return h(e,t)}static fromTexture(e,t){return f(e,t)}static fromGpuBuffer(e,t){return m(e,t)}static fromMLTensor(e,t){return g(e,t)}static fromPinnedBuffer(e,t,n){return y(e,t,n)}toDataURL(e){return c(this,e)}toImageData(e){return d(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if("none"===this.dataLocation)throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return S(this,e)}}})),Y=z((()=>{K(),I=_})),Q=z((()=>{U(),T=(e,t)=>{typeof u.trace>"u"?u.wasm.trace:u.trace},$=(e,t)=>{let n=(new Error).stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let a=0;a<n.length;a++){if(r&&!n[a].includes("TRACE_FUNC")){let r=`FUNC_${e}::${n[a].trim().split(" ")[1]}`;return t&&(r+=`::${t}`),void T("CPU",r)}n[a].includes("TRACE_FUNC")&&(r=!0)}},C=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||$("BEGIN",e)},N=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||$("END",e)}})),X=z((()=>{B(),Y(),Q(),E=class e{constructor(e){this.handler=e}async run(e,t,n){C();let r={},a={};if("object"!=typeof e||null===e||e instanceof I||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof I)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if("object"==typeof n&&null!==n)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,i=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(-1!==i.indexOf(n)){let a=t[n];(null===a||a instanceof I)&&(e=!0,s=!1,r[n]=a)}if(e){if("object"==typeof n&&null!==n)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of this.inputNames)if(typeof e[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(s)for(let u of this.outputNames)r[u]=null;let i=await this.handler.run(e,r,a),o={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let e=i[u];o[u]=e instanceof I?e:new I(e.type,e.data,e.dims)}return N(),o}async release(){return this.handler.dispose()}static async create(t,n,r,a){C();let i,o={};if("string"==typeof t){if(i=t,"object"==typeof n&&null!==n)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,"object"==typeof n&&null!==n)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{let e=t,s=0,u=t.byteLength;if("object"==typeof n&&null!==n)o=n;else if("number"==typeof n){if(s=n,!Number.isSafeInteger(s))throw new RangeError("'byteOffset' must be an integer.");if(s<0||s>=e.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(u=t.byteLength-s,"number"==typeof r){if(u=r,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||s+u>e.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if("object"==typeof a&&null!==a)o=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(e,s,u)}}let[u,l]=await s(o),c=await u.createInferenceSessionHandler(i,l);return N(),new e(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}})),J=z((()=>{X(),A=E})),ee=z((()=>{})),te=z((()=>{})),ne=z((()=>{})),re=z((()=>{})),ae={};L(ae,{InferenceSession:()=>A,TRACE:()=>T,TRACE_FUNC_BEGIN:()=>C,TRACE_FUNC_END:()=>N,Tensor:()=>I,env:()=>l,registerBackend:()=>r});var se=z((()=>{W(),G(),J(),Y(),ee(),te(),Q(),ne(),re()})),ie=z((()=>{})),oe={};L(oe,{default:()=>ce});var ue,le,ce,de,pe,he,fe,me,ge,ye,be,xe,we,ve,ke,Se,_e,Ie,Te,$e,Ce,Ne,Ee,Ae,Re,De,Fe,Me,Oe,ze,Le,Pe,Be,We,Ve,Ue,Ge,He,je,qe,Ze,Ke,Ye,Qe,Xe,Je,et,tt,nt,rt,at,st,it,ot,ut,lt,ct,dt,pt,ht,ft,mt,gt,yt,bt,xt,wt,vt,kt,St,_t,It,Tt,$t,Ct,Nt,Et,At,Rt,Dt,Ft,Mt,Ot,zt,Lt,Pt,Bt,Wt,Vt,Ut,Gt,Ht,jt,qt,Zt,Kt,Yt,Qt,Xt,Jt,en,tn,nn,rn,an,sn,on,un,ln,cn,dn,pn,hn,fn,mn,gn,yn,bn,xn,wn,vn,kn,Sn,_n,In,Tn,$n,Cn,Nn,En,An,Rn,Dn,Fn,Mn,On,zn,Ln,Pn,Bn,Wn,Vn,Un,Gn,Hn,jn,qn,Zn,Kn,Yn,Qn,Xn,Jn,er,tr,nr,rr,ar,sr,ir,or,ur,lr,cr,dr,pr,hr,fr,mr,gr,yr,br,xr,wr,vr,kr,Sr,_r,Ir,Tr,$r,Cr,Nr,Er,Ar,Rr,Dr,Fr,Mr,Or,zr,Lr,Pr,Br,Wr,Vr,Ur,Gr,Hr,jr,qr,Zr,Kr,Yr,Qr,Xr,Jr,ea,ta,na,ra,aa,sa,ia,oa,ua,la,ca,da,pa,ha,fa,ma,ga,ya,ba,xa,wa,va,ka,Sa,_a,Ia,Ta,$a,Ca,Na,Ea,Aa,Ra,Da,Fa,Ma,Oa,za,La,Pa,Ba,Wa,Va,Ua,Ga,Ha,ja,qa,Za,Ka,Ya,Qa,Xa,Ja,es,ts,ns,rs,as,ss,is,os,us,ls,cs,ds,ps,hs,fs,ms,gs,ys,bs,xs,ws,vs,ks,Ss,_s,Is,Ts,$s,Cs,Ns,Es,As,Rs,Ds,Fs,Ms,Os,zs,Ls,Ps,Bs,Ws,Vs,Us,Gs,Hs,js,qs,Zs,Ks,Ys,Qs,Xs,Js,ei,ti,ni,ri,ai,si,ii,oi,ui,li,ci,di,pi,hi,fi,mi,gi,yi,bi,xi,wi,vi,ki,Si,_i,Ii,Ti,$i,Ci,Ni,Ei,Ai,Ri,Di,Fi,Mi,Oi,zi,Li,Pi,Bi,Wi,Vi,Ui,Gi,Hi,ji,qi,Zi,Ki,Yi,Qi,Xi,Ji,eo,to,no,ro,ao,so,io,oo,uo,lo,co,po,ho,fo,mo,go,yo,bo,xo,wo,vo,ko,So,_o,Io,To,$o,Co,No,Eo,Ao,Ro,Do,Fo,Mo,Oo,zo,Lo,Po,Bo,Wo,Vo,Uo,Go,Ho,jo,qo,Zo,Ko,Yo,Qo,Xo,Jo,eu,tu,nu,ru,au,su,iu,ou,uu,lu,cu,du,pu,hu,fu,mu,gu,yu,bu,xu,wu,vu,ku,Su,_u,Iu,Tu,$u,Cu,Nu,Eu,Au,Ru,Du,Fu,Mu,Ou,zu,Lu,Pu,Bu,Wu=z((()=>{Uc(),Uu(),Vu(),ue="ort-wasm-proxy-worker",(le=globalThis.self?.name===ue)&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":Ce(n.wasm).then((()=>{cc(n).then((()=>{postMessage({type:t})}),(e=>{postMessage({type:t,err:e})}))}),(e=>{postMessage({type:t,err:e})}));break;case"init-ep":{let{epName:e,env:r}=n;dc(r,e).then((()=>{postMessage({type:t})}),(e=>{postMessage({type:t,err:e})}));break}case"copy-from":{let{buffer:e}=n,r=fc(e);postMessage({type:t,out:r});break}case"create":{let{model:e,options:r}=n;mc(e,r).then((e=>{postMessage({type:t,out:e})}),(e=>{postMessage({type:t,err:e})}));break}case"release":gc(n),postMessage({type:t});break;case"run":{let{sessionId:e,inputIndices:r,inputs:a,outputIndices:s,options:i}=n;bc(e,r,a,s,new Array(s.length).fill(null),i).then((e=>{e.some((e=>"cpu"!==e[3]))?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:e},wc([...a,...e]))}),(e=>{postMessage({type:t,err:e})}));break}case"end-profiling":xc(n),postMessage({type:t})}}catch(r){postMessage({type:t,err:r})}}),ce=le?null:e=>new Worker(e??pe,{type:"classic",name:ue})})),Vu=z((()=>{ie(),de=typeof location>"u"?void 0:location.origin,pe=(()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0)(),he=()=>{if(pe&&!pe.startsWith("blob:"))return pe.substring(0,pe.lastIndexOf("/")+1)},fe=(e,t)=>{try{let n=t??pe;return(n?new URL(e,n):new URL(e)).origin===de}catch{return!1}},me=(e,t)=>{let n=t??pe;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},ge=(e,t)=>`${t??"./"}${e}`,ye=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},be=async e=>(await import(e)).default,xe=(Wu(),P(oe)).default,we=async()=>{if(!pe)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(fe(pe))return[void 0,xe()];let e=await ye(pe);return[e,xe(e)]},ve=async(e,t,n)=>{{let r="ort-wasm-simd-threaded.jsep.mjs",a=e??me(r,t),s=n&&a&&!fe(a,t),i=s?await ye(a):a??ge(r,t);return[s?i:void 0,await be(i)]}}})),Uu=z((()=>{Vu(),Se=!1,_e=!1,Ie=!1,Te=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},$e=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Ce=async e=>{if(Se)return Promise.resolve();if(_e)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ie)throw new Error("previous call to 'initializeWebAssembly()' failed.");_e=!0;let t=e.initTimeout,n=e.numThreads;if(!$e())throw new Error("WebAssembly SIMD is not supported in the current environment.");let r=Te();n>1&&!r&&(typeof self<"u"&&self.crossOriginIsolated,e.numThreads=n=1);let a=e.wasmPaths,s="string"==typeof a?a:void 0,i=a?.mjs,o=i?.href??i,u=a?.wasm,l=u?.href??u,c=e.wasmBinary,[d,p]=await ve(o,s,n>1),h=!1,f=[];if(t>0&&f.push(new Promise((e=>{setTimeout((()=>{h=!0,e()}),t)}))),f.push(new Promise(((e,t)=>{let r={numThreads:n};if(c)r.wasmBinary=c;else if(l||s)r.locateFile=e=>l??s+e;else if(o&&0!==o.indexOf("blob:"))r.locateFile=e=>new URL(e,o).href;else if(d){let e=he();e&&(r.locateFile=t=>e+t)}p(r).then((t=>{_e=!1,Se=!0,ke=t,e(),d&&URL.revokeObjectURL(d)}),(e=>{_e=!1,Ie=!0,t(e)}))}))),await Promise.race(f),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ne=()=>{if(Se&&ke)return ke;throw new Error("WebAssembly is not initialized yet.")}})),Gu=z((()=>{Uu(),Ee=(e,t)=>{let n=Ne(),r=n.lengthBytesUTF8(e)+1,a=n._malloc(r);return n.stringToUTF8(e,a,r),t.push(a),a},Ae=(e,t,n,r)=>{if("object"==typeof e&&null!==e){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach((([e,a])=>{let s=t?t+e:e;if("object"==typeof a)Ae(a,s+".",n,r);else if("string"==typeof a||"number"==typeof a)r(s,a.toString());else{if("boolean"!=typeof a)throw new Error("Can't handle extra config type: "+typeof a);r(s,a?"1":"0")}}))},Re=e=>{let t=Ne(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let a=Number(t.getValue(r,4===n?"i32":"i64")),s=t.getValue(r+n,"*"),i=s?t.UTF8ToString(s):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(n)}}})),Hu=z((()=>{Uu(),Gu(),De=e=>{let t=Ne(),n=0,r=[],a=e||{};try{if(void 0===e?.logSeverityLevel)a.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===e?.logVerbosityLevel)a.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===e?.terminate&&(a.terminate=!1);let s=0;return void 0!==e?.tag&&(s=Ee(e.tag,r)),n=t._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,s),0===n&&Re("Can't create run options."),void 0!==e?.extra&&Ae(e.extra,"",new WeakSet,((e,a)=>{let s=Ee(e,r),i=Ee(a,r);0!==t._OrtAddRunConfigEntry(n,s,i)&&Re(`Can't set a run config entry: ${e} - ${a}.`)})),[n,r]}catch(s){throw 0!==n&&t._OrtReleaseRunOptions(n),r.forEach((e=>t._free(e))),s}}})),ju=z((()=>{Uu(),Gu(),Fe=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Me=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Oe=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some((e=>"webgpu"===("string"==typeof e?e:e.name)))&&(e.enableMemPattern=!1)},ze=(e,t,n)=>{for(let r of t){let t="string"==typeof r?r:r.name;switch(t){case"webnn":if(t="WEBNN","string"!=typeof r){let t=r?.deviceType;if(t){let r=Ee("deviceType",n),a=Ee(t,n);0!==Ne()._OrtAddSessionConfigEntry(e,r,a)&&Re(`Can't set a session config entry: 'deviceType' - ${t}.`)}}break;case"webgpu":if(t="JS","string"!=typeof r){let t=r;if(t?.preferredLayout){if("NCHW"!==t.preferredLayout&&"NHWC"!==t.preferredLayout)throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${t.preferredLayout}`);let r=Ee("preferredLayout",n),a=Ee(t.preferredLayout,n);0!==Ne()._OrtAddSessionConfigEntry(e,r,a)&&Re(`Can't set a session config entry: 'preferredLayout' - ${t.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${t}`)}let a=Ee(t,n);0!==Ne()._OrtAppendExecutionProvider(e,a)&&Re(`Can't append execution provider: ${t}.`)}},Le=e=>{let t=Ne(),n=0,r=[],a=e||{};Oe(a);try{let e=Fe(a.graphOptimizationLevel??"all"),s=Me(a.executionMode??"sequential"),i="string"==typeof a.logId?Ee(a.logId,r):0,o=a.logSeverityLevel??2;if(!Number.isInteger(o)||o<0||o>4)throw new Error(`log serverity level is not valid: ${o}`);let u=a.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let l="string"==typeof a.optimizedModelFilePath?Ee(a.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!a.enableCpuMemArena,!!a.enableMemPattern,s,!!a.enableProfiling,0,i,o,u,l),0===n&&Re("Can't create session options."),a.executionProviders&&ze(n,a.executionProviders,r),void 0!==a.enableGraphCapture){if("boolean"!=typeof a.enableGraphCapture)throw new Error(`enableGraphCapture must be a boolean value: ${a.enableGraphCapture}`);let e=Ee("enableGraphCapture",r),s=Ee(a.enableGraphCapture.toString(),r);0!==t._OrtAddSessionConfigEntry(n,e,s)&&Re(`Can't set a session config entry: 'enableGraphCapture' - ${a.enableGraphCapture}.`)}if(a.freeDimensionOverrides)for(let[c,d]of Object.entries(a.freeDimensionOverrides)){if("string"!=typeof c)throw new Error(`free dimension override name must be a string: ${c}`);if("number"!=typeof d||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let e=Ee(c,r);0!==t._OrtAddFreeDimensionOverride(n,e,d)&&Re(`Can't set a free dimension override: ${c} - ${d}.`)}return void 0!==a.extra&&Ae(a.extra,"",new WeakSet,((e,a)=>{let s=Ee(e,r),i=Ee(a,r);0!==t._OrtAddSessionConfigEntry(n,s,i)&&Re(`Can't set a session config entry: ${e} - ${a}.`)})),[n,r]}catch(s){throw 0!==n&&0!==t._OrtReleaseSessionOptions(n)&&Re("Can't release session options."),r.forEach((e=>t._free(e))),s}}})),qu=z((()=>{Pe=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Be=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},We=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r="number"==typeof t?t:t.reduce(((e,t)=>e*t),1);return n>0?Math.ceil(r*n):void 0},Ve=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ue=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Ge=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,He=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint64"===e||"int8"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,je=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}})),Zu=z((()=>{ie(),qe=async e=>{if("string"==typeof e){{let n=await fetch(e);if(!n.ok)throw new Error(`failed to load external data file: ${e}`);let r=n.headers.get("Content-Length"),a=r?parseInt(r,10):0;if(a<1073741824)return new Uint8Array(await n.arrayBuffer());{if(!n.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let r,s=n.body.getReader();try{r=new ArrayBuffer(a)}catch(t){if(!(t instanceof RangeError))throw t;{let e=Math.ceil(a/65536);r=new WebAssembly.Memory({initial:e,maximum:e}).buffer}}let i=0;for(;;){let{done:e,value:t}=await s.read();if(e)break;let n=t.byteLength;new Uint8Array(r,i,n).set(t),i+=n}return new Uint8Array(r,0,a)}}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}})),Ku=z((()=>{qu(),Ye=(e,t)=>{Ze=e,Ke=t},Qe=(e,t)=>{let n=Ue(e);n>=Ue(Ze)&&"function"==typeof t&&t()},Xe=(...e)=>{Ke&&Qe(...e)}})),Yu=z((()=>{qu(),Je=(e,t)=>new(Ve(t))(e)})),Qu=z((()=>{})),Xu=z((()=>{Ku(),Qu(),et=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),tt=[],nt=e=>16*Math.ceil(Number(e)/16),rt=e=>{for(let t=0;t<tt.length;t++){let n=tt[t];if(e<=n)return n}return 16*Math.ceil(e/16)},at=1,st=()=>at++,it=async(e,t,n,r)=>{let a=nt(n),s=e.device.createBuffer({size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,s,0,a),e.flush(),await s.mapAsync(GPUMapMode.READ);let o=s.getMappedRange();if(r){let e=r();return e.set(new Uint8Array(o,0,n)),e}return new Uint8Array(o.slice(0,n))}finally{s.destroy()}},ot=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of et)tt.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,r=t.byteOffset,a=t.byteLength,s=nt(a),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==a)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${a}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:s,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),u=o.getMappedRange();new Uint8Array(u).set(new Uint8Array(n,r,a)),o.unmap();let l=this.backend.device.createCommandEncoder();l.copyBufferToBuffer(o,0,i.gpuData.buffer,0,s),this.backend.device.queue.submit([l.finish()]),o.destroy(),Xe("verbose",(()=>`[WebGPU] GpuDataManager.upload(id=${e})`))}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let r=this.storageCache.get(t);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");let a=nt(n.originalSize),s=this.backend.getCommandEncoder();this.backend.endComputePass(),s.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,a)}registerExternalBuffer(e,t,n){let r;if(n){if(r=n[0],e===n[1])return Xe("verbose",(()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`)),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error("Registering a different external buffer under graph capture mode is not supported yet.\n             Please use the previous external buffer!")}else r=st();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),Xe("verbose",(()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`)),r}unregisterExternalBuffer(e){void 0!==e&&(this.storageCache.delete(e),Xe("verbose",(()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`)))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n,r=rt(e),a=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,s=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(a||s){let e=(a?this.freeBuffers:this.freeUniformBuffers).get(r);n=e&&e.length>0?e.pop():this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let i={id:st(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Xe("verbose",(()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`)),i}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t="bigint"==typeof e?Number(e):e,n=this.storageCache.get(t);if(!n){if(0===this.storageCache.size)return 0;throw new Error("releasing data does not exist")}return Xe("verbose",(()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`)),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await it(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(0!==this.buffersPending.length)if("default"===this.backend.sessionStatus){for(let e of this.buffersPending){let t=et.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];void 0===t||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];void 0===t||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.freeUniformBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.storageCache.forEach((e=>{e.gpuData.buffer.destroy()})),this.capturedPendingBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach((e=>{e.destroy()})),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,0===this.sessionCount&&(Xe("warning",(()=>"[WebGPU] Clearing webgpu buffer cache")),this.storageCache.forEach((e=>{e.gpuData.buffer.destroy()})),this.storageCache=new Map)}},ut=(...e)=>new ot(...e)})),Ju=z((()=>{lt=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map((e=>`${this[e]}`)).join(";")),this.key}},ct=e=>new lt(e)})),el=z((()=>{dt=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},pt=class{static calcShape(e,t,n=!1){let r=e.length,a=t.length;if(0===r)return t;if(0===a)return e;let s=Math.max(e.length,t.length),i=new Array(s);if(n){if(r<2||a<2)return;let n=dt.calcMatMulShape([e[r-2],e[r-1]],[t[a-2],t[a-1]]);if(void 0===n)return;[i[s-2],i[s-1]]=n}for(let o=n?3:1;o<=s;o++){let n=r-o<0?1:e[r-o],u=a-o<0?1:t[a-o];if(n!==u&&n>1&&u>1)return;let l=Math.max(n,u);if(n&&u)i[s-o]=Math.max(n,u);else{if(l>1)return;i[s-o]=0}}return i}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let a=1;a<=n;a++)if(1!==e[n-a]&&e[n-a]!==t[r-a])return!1;return!0}},ht=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(0===n)return[];let r=new Array(n),a=n-1;for(;a>=0;){if(e[a]%t===0){r[a]=e[a]/t;break}if(t%e[a]!==0)throw new Error("cannot convert shape");r[a]=1,t/=e[a],a--}for(a--;a>=0;a--)r[a]=e[a];return r}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let a=t;a<n;a++){if(e[a]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");r*=Number(e[a])}return r}static computeStrides(e){let t=e.length;if(0===t)return[];if(1===t)return[1];let n=new Array(t);n[t-1]=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}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((n=>this.normalizeAxis(n,t??e.length)))}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}},ft=class e{static adjustPoolAttributes(e,t,n,r,a,s){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let i=0;i<t.length-2;i++)i>=n.length?n.push(t[i+2]):n[i]=t[i+2];for(let i=0;i<n.length;i++)if(i<r.length){if(r[i]<0)throw new Error("strides should be greater than or equal to 1")}else r.push(1);for(let i=0;i<n.length;i++)if(i<a.length){if(a[i]<0)throw new Error("dilations should be greater than or equal to 1")}else a.push(1);for(let i=0;i<2*n.length;i++)if(i<s.length){if(s[i]<0)throw new Error("pad should be greater than or equal to 1")}else s.push(0);for(let i=0;i<n.length;i++){if(n[i]<=0)throw new Error("kernel shapes need to be greater than 0");if(s[i]>=n[i]||s[i+n.length]>=n[i])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,r,a,s,i,o){if(o){if(s.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(a.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let u=0;u<t.length-2;u++)e.adjustPadAndReturnShape(t[u+(i?1:2)],n[u],r[u],a[u],s,u,u+t.length-2,o)}}static computePoolOutputShape(t,n,r,a,s,i,o){if(n.length<=0)throw new Error("input shape must be of size greater than 0");let u=[n[0],n[1]];return e.computeShapeHelper(t,n,u,r,a,s,i,o),u}static computeConvOutputShape(t,n,r,a,s,i,o){if(t.length<=0||n.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let u=[t[0],n[0]];return e.computeShapeHelper(!1,t,u,r,a,s,i,o),u}static computeShapeHelper(t,n,r,a,s,i,o,u){if(t)for(let e=0;e<n.length-2;e++)r.push(1);else for(let l=0;l<n.length-2;l++)r.push(e.adjustPadAndReturnShape(n[l+2],a[l],s[l],i[l],o,l,l+n.length-2,u))}static adjustPadAndReturnShape(e,t,n,r,a,s,i,o){let u=n*(r-1)+1;if(!o||"NOTSET"===o)return Math.floor((e+a[s]+a[i]-u)/t+1);switch(o){case"VALID":return a[s]=0,a[i]=0,Math.floor((e-u)/t+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let n=((e+t-1)/t-1)*t+r-e;return a[s]=Math.floor("SAME_LOWER"===o?(n+1)/2:n/2),a[i]=n-a[s],Math.floor((e+n-r)/t+1)}default:throw new Error("Unsupported AutoPad type")}}},mt=class{static getShapeOfGemmResult(e,t,n,r,a){if(2!==e.length||2!==n.length)throw new Error("shape need to be of size 2");let s,i,o;t?(s=e[1],i=e[0]):(s=e[0],i=e[1]);let u=-1;if(r?(o=n[0],u=1):(o=n[1],u=0),n[u]!==i)throw new Error("dimension mismatch");if(s<=0||o<=0||i<=0)throw new Error("invalid shape specified");if(a&&!pt.isValidBroadcast(a,[s,o]))throw new Error("gemm: invalid bias shape for broadcast");return[s,o,i]}},gt=-34028234663852886e22,yt=34028234663852886e22})),tl=z((()=>{qu(),el(),bt=64,xt=(e,t)=>{if(3===t)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:"f16";case 1:return t>1?`vec${t}<f32>`:"f32";case 6:return t>1?`vec${t}<i32>`:"i32";case 12:return t>1?`vec${t}<u32>`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(4!==t)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},wt=(e,t=1)=>{let n=xt(e,t);return"string"==typeof n?n:n[0]},vt=(e,t=1)=>{let n=xt(e,t);return"string"==typeof n?n:n[1]},kt=(...e)=>{let t=[];return e.forEach((e=>{0!==e.length&&t.push({type:12,data:e},{type:12,data:ht.computeStrides(e)})})),t},St=e=>e%4===0?4:e%2===0?2:1,_t=(e="f32",t,n="0")=>t&&1!==t?`vec${t}<${e}>(${n})`:`${e}(${n})`,It=(e,t,n)=>"f32"===e?n:1===t?`f32(${n})`:`vec${t}<f32>(${n})`,Tt=(e,t)=>4===t?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:2===t?`(${e}.x + ${e}.y)`:3===t?`(${e}.x + ${e}.y + ${e}.z)`:e,$t=(e,t,n,r)=>e.startsWith("uniforms.")&&n>4?"string"==typeof t?"f16"===r?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:"f16"===r?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,Ct=(e,t,n,r,a)=>{let s="number"==typeof n,i=s?n:n.length,o=[...new Array(i).keys()],u=i<2?"u32":i<=4?`vec${i}<u32>`:`array<u32, ${i}>`,l=xt(t,a),c="string"==typeof l?l:l[1],d="string"==typeof l?l:l[0],p={indices:u,value:c,storage:d,tensor:t},h=e=>"string"==typeof e?e:`${e}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},m=s?"uniforms.":"",g=`${m}${e}_shape`,y=`${m}${e}_strides`,b="";for(let A=0;A<i-1;A++)b+=`\n    let dim${A} = current / ${$t(y,A,i)};\n    let rest${A} = current % ${$t(y,A,i)};\n    indices[${A}] = dim${A};\n    current = rest${A};\n    `;b+=`indices[${i-1}] = current;`;let x=i<2?"":`\n  fn o2i_${e}(offset: u32) -> ${p.indices} {\n    var indices: ${p.indices};\n    var current = offset;\n    ${b}\n    return indices;\n  }`,w=[];if(i>=2)for(let A=i-1;A>=0;A--)w.push(`${$t(y,A,i)} * (indices[${A}])`);let v=i<2?"":`\n  fn i2o_${e}(indices: ${p.indices}) -> u32 {\n    return ${w.join("+")};\n  }`,k=(...e)=>0===i?"0u":`${p.indices}(${e.map(h).join(",")})`,S=(e,t)=>i<2?`${e}`:`${$t(e,t,i)}`,_={},I=(t,n)=>(()=>{if(p.storage===p.value)return`${e}[${t}]=${n};`;if("vec2<u32>"===p.storage&&"i32"===p.value)return`${e}[${t}]=vec2<u32>(u32(${n}), select(0u, 0xFFFFFFFFu, ${n} < 0));`;if("vec2<u32>"===p.storage&&"u32"===p.value)return`${e}[${t}]=vec2<u32>(u32(${n}), 0u);`;if("u32"===p.storage&&"vec4<bool>"===p.value)return`${e}[${t}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${n}));`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),T=t=>(()=>{if(p.storage===p.value)return`${e}[${t}]`;if("vec2<u32>"===p.storage&&"i32"===p.value)return`i32(${e}[${t}].x)`;if("vec2<u32>"===p.storage&&"u32"===p.value)return`u32(${e}[${t}].x)`;if("u32"===p.storage&&"vec4<bool>"===p.value)return`vec4<bool>(bool(${e}[${t}] & 0xFFu), bool(${e}[${t}] & 0xFF00u), bool(${e}[${t}] & 0xFF0000u), bool(${e}[${t}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),$=i<2?"":`\n  fn get_${e}ByIndices(indices: ${p.indices}) -> ${c} {\n    return ${T(`i2o_${e}(indices)`)};\n  }`,C=i<2?"":(()=>{let t=o.map((e=>`d${e}: u32`)).join(", "),n=o.map((e=>`d${e}`)).join(", ");return`\n  fn get_${e}(${t}) -> ${c} {\n    return get_${e}ByIndices(${k(n)});\n  }`})(),N=i<2?"":`\n  fn set_${e}ByIndices(indices: ${p.indices}, value: ${c}) {\n    ${I(`i2o_${e}(indices)`,"value")}\n  }`,E=i<2?"":(()=>{let t=o.map((e=>`d${e}: u32`)).join(", "),n=o.map((e=>`d${e}`)).join(", ");return`\n  fn set_${e}(${t}, value: ${c}) {\n    set_${e}ByIndices(${k(n)}, value);\n  }`})();return{impl:()=>{let e=[],t=!1;return f.offsetToIndices&&(e.push(x),t=!0),f.indicesToOffset&&(e.push(v),t=!0),f.broadcastedIndicesToOffset&&(Object.values(_).forEach((t=>e.push(t))),t=!0),f.set&&(e.push(E),t=!0),f.setByIndices&&(e.push(N),t=!0),f.get&&(e.push(C),t=!0),f.getByIndices&&(e.push($),t=!0),!s&&t&&e.unshift(`const ${g} = ${p.indices}(${n.join(",")});`,`const ${y} = ${p.indices}(${ht.computeStrides(n).join(",")});`),e.join("\n")},type:p,offsetToIndices:t=>(f.offsetToIndices=!0,i<2?t:`o2i_${e}(${t})`),indicesToOffset:t=>(f.indicesToOffset=!0,i<2?t:`i2o_${e}(${t})`),broadcastedIndicesToOffset:(t,n)=>{f.broadcastedIndicesToOffset=!0;let r=`${n.name}broadcastedIndicesTo${e}Offset`;if(r in _)return`${r}(${t})`;let a=[];for(let e=i-1;e>=0;e--){let t=n.indicesGet("outputIndices",e+n.rank-i);a.push(`${S(y,e)} * (${t} % ${S(g,e)})`)}return _[r]=`fn ${r}(outputIndices: ${n.type.indices}) -> u32 {\n             return ${a.length>0?a.join("+"):"0u"};\n           }`,`${r}(${t})`},indices:k,indicesGet:S,indicesSet:(e,t,n)=>i<2?`${e}=${n};`:`${$t(e,t,i)}=${n};`,set:(...t)=>{if(t.length!==i+1)throw new Error(`indices length must be ${i}`);let n=t[i];if("string"!=typeof n)throw new Error("value must be string");let r=t.slice(0,i).map(h).join(",");return 0===i?I("0u",n):1===i?I(r[0],n):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${r}, ${n})`)},setByOffset:I,setByIndices:(t,n)=>i<2?I(t,n):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${t}, ${n});`),get:(...t)=>{if(t.length!==i)throw new Error(`indices length must be ${i}`);let n=t.map(h).join(",");return 0===i?T("0u"):1===i?T(n[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${n})`)},getByOffset:T,getByIndices:t=>i<2?T(t):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${t})`),usage:r,name:e,strides:y,shape:g,rank:i}},Nt=(e,t,n,r=1)=>Ct(e,t,n,"input",r),Et=(e,t,n,r=1)=>Ct(e,t,n,"output",r),At=(e,t,n)=>Ct(e,t,n,"atomicOutput",1),Rt=(e,t,n,r=1)=>Ct(e,t,n,"internal",r),Dt=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${"number"==typeof e?`${e}u`:e}) { return; }`}mainStart(e=bt){let t="number"==typeof e?e:e[0],n="number"==typeof e?1:e[1],r="number"==typeof e?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||r>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*r>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let a=1===this.normalizedDispatchGroup[1]&&1===this.normalizedDispatchGroup[2];return`@compute @workgroup_size(${t}, ${n}, ${r})\n  fn main(${a?"@builtin(global_invocation_id) global_id : vec3<u32>,\n    @builtin(workgroup_id) workgroup_id : vec3<u32>,\n    @builtin(local_invocation_index) local_idx : u32,\n    @builtin(local_invocation_id) local_id : vec3<u32>":"@builtin(global_invocation_id) global_id : vec3<u32>,\n                                             @builtin(local_invocation_id) local_id : vec3<u32>,\n    @builtin(local_invocation_index) local_idx : u32,\n    @builtin(workgroup_id) workgroup_id : vec3<u32>,\n    @builtin(num_workgroups) num_workgroups : vec3<u32>"}) {\n    ${a?"let global_idx = global_id.x;\n         let workgroup_index = workgroup_id.x;":`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n             workgroup_id.y * num_workgroups[0] + workgroup_id.x;\n         let global_idx = workgroup_index * ${t*n*r}u + local_idx;`}\n  `}appendVariableUniforms(e){0!==e.rank&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if("internal"===e.usage)throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let n="input"===e.usage?"read":"read_write",r="atomicOutput"===e.usage?"atomic<i32>":e.type.storage;return`@group(0) @binding(${t}) var<storage, ${n}> ${e.name}: array<${r}>;`}declareVariables(...e){return e.map((e=>this.declareVariable(e,this.variableIndex++))).join("\n")}registerInternalVariable(e){if("internal"!==e.usage)throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach((e=>this.registerInternalVariable(e))),this}registerUniform(e,t,n=1){return this.uniforms.push({name:e,type:t,length:n}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(0===this.uniforms.length)return"";let e=[];for(let{name:t,type:n,length:r}of this.uniforms)if(r&&r>4)"f16"===n?e.push(`@align(16) ${t}:array<mat2x4<${n}>, ${Math.ceil(r/8)}>`):e.push(`${t}:array<vec4<${n}>, ${Math.ceil(r/4)}>`);else{let a=null==r||1===r?n:`vec${r}<${n}>`;e.push(`${t}:${a}`)}return`\n      struct Uniforms { ${e.join(", ")} };\n      @group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map((e=>e.impl())).join("\n")+this.internalVariables.map((e=>e.impl())).join("\n")}get variablesInfo(){if(0===this.uniforms.length)return;let e=e=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(e)];return this.uniforms.map((t=>[e(t.type),t.length??1]))}},Ft=(e,t)=>new Dt(e,t)})),nl=z((()=>{qu(),el(),Ju(),tl(),Mt=(e,t)=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.");if(0!==t.length&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},Ot=(e,t)=>0!==t.length?t:[...new Array(e).keys()].reverse(),zt=(e,t)=>ht.sortBasedOnPerm(e,Ot(e.length,t)),Lt=(e,t,n,r)=>{let a=`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {\n    var a: ${n.type.indices};`;for(let s=0;s<t;++s)a+=`a[${e[s]}]=i[${s}];`;return a+"return a;}"},Pt=(e,t)=>{let n=[],r=[];for(let a=0;a<e.length;++a)1!==e[a]&&n.push(e[a]),1!==e[t[a]]&&r.push(t[a]);return{newShape:n,newPerm:r}},Bt=(e,t)=>{let n=0;for(let r=0;r<e.length;++r)if(1!==t[e[r]]){if(e[r]<n)return!1;n=e[r]}return!0},Wt=(e,t)=>{let n,r=e.dataType,a=e.dims.length,s=Ot(a,t),i=zt(e.dims,s),o=e.dims,u=i;if(a<2||Bt(s,e.dims))return n=e=>{let t=Nt("input",r,o,4),n=Et("output",r,u,4);return`\n  ${e.registerUniform("output_size","u32").declareVariables(t,n)}\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n    output[global_idx] = input[global_idx];\n  }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let t=ht.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64/4)},programUniforms:[{type:12,data:Math.ceil(t/4)}]}},getShaderSource:n};let{newShape:l,newPerm:c}=Pt(e.dims,s),d=ht.areEqual(c,[2,3,1]),p=ht.areEqual(c,[3,1,2]);if(2===l.length||d||p){o=d?[l[0],l[1]*l[2]]:p?[l[0]*l[1],l[2]]:l,u=[o[1],o[0]];let t=16;return n=e=>{let n=Nt("a",r,o.length),a=Et("output",r,u.length);return`\n  ${e.registerUniform("output_size","u32").declareVariables(n,a)}\n  var<workgroup> tile : array<array<${a.type.value}, ${t+1}>, ${t}>;\n  ${e.mainStart([t,t,1])}\n    let stride = (uniforms.output_shape[1] - 1) / ${t} + 1;\n    let workgroup_id_x = workgroup_index % stride;\n    let workgroup_id_y = workgroup_index / stride;\n    let input_col = workgroup_id_y * ${t}u + local_id.x;\n    let input_row = workgroup_id_x * ${t}u + local_id.y;\n    if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {\n      tile[local_id.y][local_id.x] = ${n.getByIndices(`${n.type.indices}(input_row, input_col)`)};\n    }\n    workgroupBarrier();\n\n    let output_col = workgroup_id_x * ${t}u + local_id.x;\n    let output_row = workgroup_id_y * ${t}u + local_id.y;\n    if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {\n      ${a.setByIndices(`${a.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}\n    }\n  }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let n=ht.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/t),y:Math.ceil(u[0]/t)},programUniforms:[{type:12,data:n},...kt(o,u)]}},getShaderSource:n}}return n=e=>{let t=Nt("a",r,o.length),n=Et("output",r,u.length);return`\n  ${e.registerUniform("output_size","u32").declareVariables(t,n)}\n\n  ${Lt(s,a,t,n)}\n\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n    let indices = ${n.offsetToIndices("global_idx")};\n    let aIndices = perm(indices);\n\n    ${n.setByOffset("global_idx",t.getByIndices("aIndices"))}\n  }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let t=ht.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:[{type:12,data:t},...kt(o,u)]}},getShaderSource:n}},Vt=(e,t)=>{Mt(e.inputs,t.perm),e.compute(Wt(e.inputs[0],t.perm))},Ut=e=>ct({perm:e.perm})})),rl=z((()=>{qu(),el(),tl(),al(),nl(),Gt={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Ht={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},jt={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},qt={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Zt=(e,t)=>{let n=[];for(let r=t-e;r<t;++r)n.push(r);return n},Kt=(e,t)=>{let 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]))]},Yt=(e,t)=>{let n=e.length+t.length,r=[],a=0;for(let s=0;s<n;s++)-1===t.indexOf(s)?r.push(e[a++]):r.push(1);return r},Qt=(e,t)=>{for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0},Xt=(e,t)=>{let n=[];if(!Qt(e,t)){for(let r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);e.forEach((e=>n.push(e)))}return n},Jt=(e,t,n,r,a,s,i)=>{let o=n[0].dims,u=ht.size(s),l=ht.size(i),c=Nt("_A",n[0].dataType,o),d=Et("output",a,s),p=64;1===u&&(p=256);let h=`\n          var<workgroup> aBestValues : array<f32, ${p}>;\n       `;return{name:e,shaderCache:{hint:`${t};${p}`,inputDependencies:["type"]},getShaderSource:e=>`\n        ${e.registerUniform("reduceSize","u32").declareVariables(c,d)}\n        ${h}\n        fn DIV_CEIL(a : u32, b : u32) -> u32 {\n          return ((a - 1u) / b + 1u);\n         }\n         ${e.mainStart(p)}\n\n          let outputIndex = global_idx / ${p};\n          let offset = outputIndex * uniforms.reduceSize;\n\n          var bestValue = f32(${jt[r]});\n          let Length = uniforms.reduceSize;\n          for (var k = local_idx; k < Length; k = k + ${p}) {\n           let candidate = f32(${c.getByOffset("offset + k")});\n           bestValue = ${Gt[r]};\n          }\n          aBestValues[local_idx] = bestValue;\n          workgroupBarrier();\n\n         var reduceSize = min(Length, ${p}u);\n         for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n             currentSize = reduceSize / 2u) {\n           let interval = DIV_CEIL(reduceSize, 2u);\n           if (local_idx < currentSize) {\n            let candidate = aBestValues[local_idx + interval];\n            bestValue = ${Ht[r]};\n            aBestValues[local_idx] = bestValue;\n           }\n           reduceSize = interval;\n           workgroupBarrier();\n         }\n\n         if (local_idx == 0u) {\n          ${d.setByOffset("outputIndex",""+("mean"===r?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${qt[r]})`))};\n         }\n        }`,getRunData:()=>({outputs:[{dims:s,dataType:a}],dispatchGroup:{x:u},programUniforms:[{type:12,data:l}]})}},en=(e,t,n,r)=>{let a=1===e.inputs.length?n:mn(e.inputs,n),s=a.axes;0===s.length&&!a.noopWithEmptyAxes&&(s=e.inputs[0].dims.map(((e,t)=>t)));let i=ht.normalizeAxes(s,e.inputs[0].dims.length),o=i,u=e.inputs[0],l=Xt(o,e.inputs[0].dims.length);l.length>0&&(u=e.compute(Wt(e.inputs[0],l),{inputs:[0],outputs:[-1]})[0],o=Zt(o.length,u.dims.length));let[c,d]=Kt(u.dims,o),p=c;a.keepDims&&(p=Yt(c,i)),e.compute(Jt(t,a.cacheKey,[u],r,e.inputs[0].dataType,p,d),{inputs:[u]})},tn=(e,t)=>{en(e,"ReduceMeanShared",t,"mean")},nn=(e,t)=>{en(e,"ReduceL1Shared",t,"l1")},rn=(e,t)=>{en(e,"ReduceL2Shared",t,"l2")},an=(e,t)=>{en(e,"ReduceLogSumExpShared",t,"logSumExp")},sn=(e,t)=>{en(e,"ReduceMaxShared",t,"max")},on=(e,t)=>{en(e,"ReduceMinShared",t,"min")},un=(e,t)=>{en(e,"ReduceProdShared",t,"prod")},ln=(e,t)=>{en(e,"ReduceSumShared",t,"sum")},cn=(e,t)=>{en(e,"ReduceSumSquareShared",t,"sumSquare")},dn=(e,t)=>{en(e,"ReduceLogSumShared",t,"logSum")}})),al=z((()=>{qu(),el(),Ju(),tl(),rl(),pn=e=>{if(!e||0===e.length||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(2===e.length&&1!==e[1].dims.length)throw new Error("Invalid axes input dims.")},hn=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],fn=(e,t,n,r,a,s,i=!1,o=!1)=>{let u=[],l=n[0].dims,c=l.length,d=ht.normalizeAxes(a,c),p=!o&&0===d.length;l.forEach(((e,t)=>{p||d.indexOf(t)>=0?i&&u.push(1):u.push(e)}));let h=u.length,f=ht.size(u);return{name:e,shaderCache:t,getShaderSource:e=>{let t=[],a=Nt("_A",n[0].dataType,c),o=Et("output",s,h),u=r(a,o,d),f=u[2];for(let n=0,r=0;n<c;n++)p||d.indexOf(n)>=0?(i&&r++,f=`for(var j${n}: u32 = 0; j${n} < ${l[n]}; j${n}++) {\n                  ${u[2].includes("last_index")?`let last_index = j${n};`:""}\n                  ${a.indicesSet("input_indices",n,`j${n}`)}\n                  ${f}\n                }`):(t.push(`${a.indicesSet("input_indices",n,o.indicesGet("output_indices",r))};`),r++);return`\n\n        ${e.registerUniform("output_size","u32").declareVariables(a,o)}\n\n        ${e.mainStart()}\n          ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n          var input_indices: ${a.type.indices};\n          let output_indices = ${o.offsetToIndices("global_idx")};\n\n          ${t.join("\n")}\n          ${u[0]}       // init ops for reduce max/min\n          ${u[1]}\n          ${f}\n          ${u[3]}\n          ${4===u.length?o.setByOffset("global_idx","value"):u.slice(4).join("\n")}\n        }`},getRunData:()=>({outputs:[{dims:u,dataType:s}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...kt(l,u)]})}},mn=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach((e=>n.push(Number(e)))),ct({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},gn=(e,t,n,r)=>{let a=e.inputs,s=1===a.length?n:mn(a,n);e.compute(fn(t,{hint:s.cacheKey,inputDependencies:["rank"]},[a[0]],s.noopWithEmptyAxes&&0===s.axes.length?hn:r,s.axes,a[0].dataType,s.keepDims,s.noopWithEmptyAxes),{inputs:[0]})},yn=(e,t)=>{pn(e.inputs),gn(e,"ReduceLogSum",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,"value = log(value);"]))},bn=(e,t)=>{pn(e.inputs),gn(e,"ReduceL1",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += abs(${e.getByIndices("input_indices")});`,""]))},xn=(e,t)=>{pn(e.inputs),gn(e,"ReduceL2",t,((e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"]))},wn=(e,t)=>{pn(e.inputs),gn(e,"ReduceLogSumExp",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += exp(${e.getByIndices("input_indices")});`,"value = log(value);"]))},vn=(e,t)=>{pn(e.inputs),gn(e,"ReduceMax",t,((e,t,n)=>{let r=[];for(let a=0;a<e.rank;a++)(n.indexOf(a)>=0||0===n.length)&&r.push(e.indicesSet("input_indices",a,0));return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = max(value, ${e.getByIndices("input_indices")});`,""]}))},kn=(e,t)=>{pn(e.inputs),gn(e,"ReduceMean",t,((t,n,r)=>{let a=1;for(let s=0;s<t.rank;s++)(r.indexOf(s)>=0||0===r.length)&&(a*=e.inputs[0].dims[s]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]}))},Sn=(e,t)=>{pn(e.inputs),gn(e,"ReduceMin",t,((e,t,n)=>{let r=[];for(let a=0;a<e.rank;a++)(n.indexOf(a)>=0||0===n.length)&&r.push(`input_indices[${a}] = 0;`);return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = min(value, ${e.getByIndices("input_indices")});`,""]}))},_n=(e,t)=>{pn(e.inputs),gn(e,"ReduceProd",t,((e,t)=>[`var value = ${t.type.storage}(1);`,"",`value *= ${e.getByIndices("input_indices")};`,""]))},In=(e,t)=>{pn(e.inputs),gn(e,"ReduceSum",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,""]))},Tn=(e,t)=>{pn(e.inputs),gn(e,"ReduceSumSquare",t,((e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += t * t;`,""]))},$n=(e,t,n)=>{if(0===t.length)return n;let r=1,a=1;for(let s=0;s<t.length;s++)-1===t.indexOf(s)?r*=e[s]:a*=e[s];return a<32&&r>1024},Cn=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?kn(e,t):tn(e,t)},Nn=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bn(e,t):nn(e,t)},En=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xn(e,t):rn(e,t)},An=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?wn(e,t):an(e,t)},Rn=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vn(e,t):sn(e,t)},Dn=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sn(e,t):on(e,t)},Fn=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_n(e,t):un(e,t)},Mn=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?In(e,t):ln(e,t)},On=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tn(e,t):cn(e,t)},zn=(e,t)=>{$n(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?yn(e,t):dn(e,t)}})),sl=z((()=>{qu(),Ju(),al(),Ln=e=>{if(!e||0===e.length||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(1!==e[0].dataType)throw new Error("Invalid input type.")},Pn=(e,t)=>{Ln(e.inputs);e.compute(fn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],((e,n,r)=>{let a=[];for(let t=0;t<e.rank;t++)(r.indexOf(t)>=0||0===r.length)&&a.push(`input_indices[${t}] = 0;`);return[`${a.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n         value = ${e.getByIndices("input_indices")};\n         best_index = i32(last_index);\n       }`,"",n.setByOffset("global_idx","best_index")]}),[t.axis],7,t.keepDims),{inputs:[0]})},Bn=(e,t)=>{Ln(e.inputs);e.compute(fn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],((e,n,r)=>{let a=[];for(let t=0;t<e.rank;t++)(r.indexOf(t)>=0||0===r.length)&&a.push(`input_indices[${t}] = 0;`);return[`${a.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n         value = ${e.getByIndices("input_indices")};\n         best_index = i32(last_index);\n       }`,"",n.setByOffset("global_idx","best_index")]}),[t.axis],7,t.keepDims),{inputs:[0]})},Wn=e=>ct(e)})),il=z((()=>{qu(),el(),Qu(),tl(),Vn=(e,t)=>{let n=e[0],r=e[1],a=e[2],s=e[3],i=e[4],o=e[5];if(i&&o)throw new Error("Attention cannot have both past and attention_bias");if(3!==n.dims.length)throw new Error('Input "input" must have 3 dimensions');let u=n.dims[0],l=n.dims[1],c=n.dims[2];if(1!==a.dims.length)throw new Error('Input "bias" is expected to have 1 dimensions');if(2!==r.dims.length)throw new Error('Input "weights" is expected to have 2 dimensions');if(r.dims[0]!==c)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(a.dims[0]!==r.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=a.dims[0]/3,p=d,h=p;if(t.qkvHiddenSizes.length>0){if(3!==t.qkvHiddenSizes.length)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let e of t.qkvHiddenSizes)if(e%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=t.qkvHiddenSizes[0],p=t.qkvHiddenSizes[1],h=t.qkvHiddenSizes[2]}let f=l;if(d!==p)throw new Error("qkv_hidden_sizes first element should be same as the second");if(a.dims[0]!==d+p+h)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let m=0;if(i){if(p!==h)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(5!==i.dims.length)throw new Error('Input "past" must have 5 dimensions');if(2!==i.dims[0])throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==u)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==p/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(m=i.dims[3])}let g=f+m;if(s)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(o){if(4!==o.dims.length)throw new Error('Input "attention_bias" must have 4 dimensions');if(o.dims[0]!==u||o.dims[1]!==t.numHeads||o.dims[2]!==l||o.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:u,sequenceLength:l,pastSequenceLength:m,kvSequenceLength:f,totalSequenceLength:g,maxSequenceLength:-1,inputHiddenSize:c,hiddenSize:d,vHiddenSize:h,headSize:Math.floor(d/t.numHeads),vHeadSize:Math.floor(h/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Un=(e,t,n)=>t&&e?`\n      let total_sequence_length_input = u32(${t.getByOffset("0")});\n      let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);\n      let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;\n      let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;\n      total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;\n      var past_sequence_length: u32 = 0;\n      if (is_first_prompt == false) {\n        past_sequence_length = total_sequence_length - sequence_length;\n      }\n       `:`\n    ${n?"let past_sequence_length = uniforms.past_sequence_length":""};\n    let present_sequence_length = total_sequence_length;\n    `,Gn=(e,t,n,r,a,s,i,o)=>{let u=St(i?1:s),l=64,c=s/u;c<l&&(l=32);let d=Math.ceil(s/u/l),p=[{type:12,data:t},{type:12,data:n},{type:12,data:r},{type:12,data:a},{type:12,data:c},{type:12,data:d}],h=wt(e.dataType,u),f=vt(1,u),m=["type"];i&&m.push("type"),o&&m.push("type");return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${l};${h};${u}`,inputDependencies:m},getShaderSource:t=>{let n=Et("x",e.dataType,e.dims,u),r=[n],a=i?Nt("seq_lens",i.dataType,i.dims):void 0;a&&r.push(a);let s=o?Nt("total_sequence_length_input",o.dataType,o.dims):void 0;s&&r.push(s);let c=vt(e.dataType);return`\n  var<workgroup> thread_max: array<f32, ${l}>;\n  var<workgroup> thread_sum: array<f32, ${l}>;\n  ${t.registerUniforms([{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}]).declareVariables(...r)}\n  ${t.mainStart([l,1,1])}\n    let batchIdx = workgroup_id.z / uniforms.num_heads;\n    let headIdx = workgroup_id.z % uniforms.num_heads;\n    let sequence_length = uniforms.sequence_length;\n    var total_sequence_length = uniforms.total_sequence_length;\n    ${Un(a,s,!1)}\n    let local_offset = local_idx * uniforms.elements_per_thread;\n    let offset = (global_idx / ${l}) * uniforms.total_sequence_length + local_offset;\n    let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};\n    var thread_max_vector = ${f}(-3.402823e+38f);\n    for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n      thread_max_vector = max(${f}(x[offset + i]), thread_max_vector);\n    }\n    thread_max[local_idx] = ${(()=>{switch(u){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${u}`)}})()};\n    workgroupBarrier();\n\n    var max_value =  f32(-3.402823e+38f);\n    for (var i = 0u; i < ${l}; i++) {\n      max_value = max(thread_max[i], max_value);\n    }\n\n    var sum_vector = ${f}(0);\n    for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n      sum_vector += exp(${f}(x[offset + i]) - max_value);\n    }\n    thread_sum[local_idx] = ${(()=>{switch(u){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${u}`)}})()};\n    workgroupBarrier();\n\n    var sum: f32 = 0;\n    for (var i = 0u; i < ${l}; i++) {\n      sum += thread_sum[i];\n    }\n\n    if (sum == 0) {\n      for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n        x[offset + i] = ${n.type.value}(${c}(1.0) / ${c}(seq_causal_length));\n      }\n    } else {\n      for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n        var f32input = ${f}(x[offset + i]);\n        x[offset + i] = ${n.type.value}(exp(f32input - max_value) / sum);\n      }\n    }\n      ${i?`\n        for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {\n          x[offset + total_seq_id] = ${n.type.value}(${c}(0));\n        }`:""};\n  }`},getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(s/l),y:a,z:t*n},programUniforms:p})}},Hn=(e,t,n,r,a,s,i,o,u)=>{let l=i+s.kvSequenceLength,c=[s.batchSize,s.numHeads,s.sequenceLength,l],d=e>1&&r,p=s.kvNumHeads?s.kvNumHeads:s.numHeads,h=d?[s.batchSize,p,l,s.headSize]:void 0,f=s.nReps?s.nReps:1,m=0===s.scale?1/Math.sqrt(s.headSize):s.scale,g=St(s.headSize),y=s.headSize/g,b=12,x={x:Math.ceil(l/b),y:Math.ceil(s.sequenceLength/b),z:s.batchSize*s.numHeads},w=[{type:12,data:s.sequenceLength},{type:12,data:y},{type:12,data:l},{type:12,data:s.numHeads},{type:12,data:s.headSize},{type:1,data:m},{type:12,data:i},{type:12,data:s.kvSequenceLength},{type:12,data:f}],v=d&&r&&ht.size(r.dims)>0,k=["type","type"];v&&k.push("type"),a&&k.push("type"),o&&k.push("type"),u&&k.push("type");let S=[{dims:c,dataType:t.dataType,gpuDataType:0}];d&&S.push({dims:h,dataType:t.dataType,gpuDataType:0});return{name:"AttentionProbs",shaderCache:{hint:`${g};${void 0!==a};${void 0!==r};${e}`,inputDependencies:k},getRunData:()=>({outputs:S,dispatchGroup:x,programUniforms:w}),getShaderSource:e=>{let s=Nt("q",t.dataType,t.dims,g),i=[s,Nt("key",n.dataType,n.dims,g)];if(v){let e=Nt("past_key",r.dataType,r.dims,g);i.push(e)}a&&i.push(Nt("attention_bias",a.dataType,a.dims));let l=o?Nt("seq_lens",o.dataType,o.dims):void 0;l&&i.push(l);let p=u?Nt("total_sequence_length_input",u.dataType,u.dims):void 0;p&&i.push(p);let m=Et("output",t.dataType,c),y=[m];d&&y.push(Et("present_key",t.dataType,h,g));let x=vt(1,g);return`\n  const TILE_SIZE = 12u;\n\n  var<workgroup> tileQ: array<${s.type.storage}, 144>;\n  var<workgroup> tileK: array<${s.type.storage}, 144>;\n  ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}]).declareVariables(...i,...y)}\n  ${e.mainStart([b,b,1])}\n    // x holds the N and y holds the M\n    let headIdx = workgroup_id.z % uniforms.num_heads;\n    let kvHeadIdx = ${1===f?"headIdx":"headIdx / uniforms.n_reps"};\n    let kv_num_heads = ${1===f?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};\n    let batchIdx = workgroup_id.z / uniforms.num_heads;\n    let m = workgroup_id.y * TILE_SIZE;\n    let n = workgroup_id.x * TILE_SIZE;\n    let sequence_length = uniforms.M;\n    var total_sequence_length = uniforms.N;\n    ${Un(l,p,!0)}\n    let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;\n    let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n    ${v&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};\n    let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;\n    ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}\n    var value = ${x}(0);\n    for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n      if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n        tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n      }\n      if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n        var idx = TILE_SIZE * local_id.y + local_id.x;\n      ${v&&d?"\n              if (n + local_id.y < past_sequence_length) {\n                tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n              } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n                tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];\n              }":"\n          if (n + local_id.y < uniforms.kv_sequence_length) {\n            tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n          }"}\n      ${d?"if (n + local_id.y < present_sequence_length) {\n        present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];\n      }":""}\n      }\n      workgroupBarrier();\n\n      for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n          value += ${x}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n      }\n\n      workgroupBarrier();\n    }\n\n    if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {\n      let headOffset = workgroup_id.z * uniforms.M * uniforms.N;\n      let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n      var sum: f32 = ${(()=>{switch(g){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${g}`)}})()};\n        output[outputIdx] = ${m.type.value} (sum * uniforms.alpha) + ${a?"attention_bias[outputIdx]":"0.0"};\n    }\n  }`}}},jn=(e,t,n,r,a,s,i=void 0,o=void 0)=>{let u=s+a.kvSequenceLength,l=a.nReps?a.nReps:1,c=a.vHiddenSize*l,d=e>1&&r,p=a.kvNumHeads?a.kvNumHeads:a.numHeads,h=d?[a.batchSize,p,u,a.headSize]:void 0,f=[a.batchSize,a.sequenceLength,c],m=12,g={x:Math.ceil(a.vHeadSize/m),y:Math.ceil(a.sequenceLength/m),z:a.batchSize*a.numHeads},y=[{type:12,data:a.sequenceLength},{type:12,data:u},{type:12,data:a.vHeadSize},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:12,data:c},{type:12,data:s},{type:12,data:a.kvSequenceLength},{type:12,data:l}],b=d&&r&&ht.size(r.dims)>0,x=["type","type"];b&&x.push("type"),i&&x.push("type"),o&&x.push("type");let w=[{dims:f,dataType:t.dataType,gpuDataType:0}];d&&w.push({dims:h,dataType:t.dataType,gpuDataType:0});return{name:"AttentionScore",shaderCache:{hint:`${void 0!==r};${e}`,inputDependencies:x},getRunData:()=>({outputs:w,dispatchGroup:g,programUniforms:y}),getShaderSource:e=>{let a=Nt("probs",t.dataType,t.dims),s=[a,Nt("v",n.dataType,n.dims)];b&&s.push(Nt("past_value",r.dataType,r.dims));let u=i?Nt("seq_lens",i.dataType,i.dims):void 0;i&&s.push(u);let c=o?Nt("total_sequence_length_input",o.dataType,o.dims):void 0;o&&s.push(c);let p=[Et("output",t.dataType,f)];d&&p.push(Et("present_value",t.dataType,h));return`\n  const TILE_SIZE = 12u;\n  var<workgroup> tileQ: array<${a.type.value}, 144>;\n  var<workgroup> tileV: array<${a.type.value}, 144>;\n  ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}]).declareVariables(...s,...p)}\n  ${e.mainStart([m,m,1])}\n   let headIdx = workgroup_id.z % uniforms.num_heads;\n   let batchIdx = workgroup_id.z / uniforms.num_heads;\n   let kvHeadIdx = ${1===l?"headIdx":"headIdx / uniforms.n_reps"};\n   let kv_num_heads = ${1===l?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};\n   let m = global_id.y;\n   let n = global_id.x;\n   let sequence_length = uniforms.M;\n   var total_sequence_length = uniforms.K;\n   ${Un(u,c,!0)}\n   let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n   let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch\n   ${b&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};\n   let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;\n   ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}\n   var value = ${a.type.storage}(0);\n   for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n      if (m < uniforms.M && w + local_id.x < uniforms.K) {\n        tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n      }\n      if (n < uniforms.N && w + local_id.y < uniforms.K) {\n        var idx = TILE_SIZE * local_id.y + local_id.x;\n        ${b&&d?"\n        if (w + local_id.y < past_sequence_length) {\n          tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];\n        } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n          tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];\n        }\n      ":"\n            if (w + local_id.y < uniforms.kv_sequence_length) {\n              tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];\n            }"}\n        ${d?"\n            if (w + local_id.y < present_sequence_length) {\n          present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];\n        }":""}\n      }\n     workgroupBarrier();\n     for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {\n       value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];\n     }\n     workgroupBarrier();\n   }\n\n   // we need to transpose output from BNSH_v to BSND_v\n   if (m < uniforms.M && n < uniforms.N) {\n     let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n       + headIdx * uniforms.N + n;\n     output[outputIdx] = value;\n   }\n  }`}}},qn=(e,t,n,r,a,s,i,o,u,l,c=void 0,d=void 0)=>{let p=Math.min(e.outputCount,1+(i?1:0)+(o?1:0)),h=p>1?l.pastSequenceLength:0,f=h+l.kvSequenceLength,m=u&&ht.size(u.dims)>0?u:void 0,g=[t,n];p>1&&i&&ht.size(i.dims)>0&&g.push(i),m&&g.push(m),c&&g.push(c),d&&g.push(d);let y=e.compute(Hn(p,t,n,i,m,l,h,c,d),{inputs:g,outputs:p>1?[-1,1]:[-1]})[0];e.compute(Gn(y,l.batchSize,l.numHeads,h,l.sequenceLength,f,c,d),{inputs:c&&d?[y,c,d]:[y],outputs:[]});let b=[y,r];p>1&&o&&ht.size(o.dims)>0&&b.push(o),c&&b.push(c),d&&b.push(d),e.compute(jn(p,y,r,o,l,h,c,d),{inputs:b,outputs:p>1?[0,2]:[0]})},Zn=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],r=t.sequenceLength,a=t.inputHiddenSize,s=t.headSize,i=12,o={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},u=[e.inputs[0],e.inputs[1],e.inputs[2]],l=[{type:12,data:r},{type:12,data:a},{type:12,data:s},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}];return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:l}),getShaderSource:e=>{let t=Et("output_q",u[0].dataType,n),r=Et("output_k",u[0].dataType,n),a=Et("output_v",u[0].dataType,n),s=Nt("input",u[0].dataType,u[0].dims),o=Nt("weight",u[1].dataType,u[1].dims),l=Nt("bias",u[2].dataType,u[2].dims),c=s.type.storage;return`\n  const TILE_SIZE = 12u;\n  var<workgroup> tileInput: array<${c}, 144>;\n  var<workgroup> tileWeightQ: array<${c}, 144>;\n  var<workgroup> tileWeightK: array<${c}, 144>;\n  var<workgroup> tileWeightV: array<${c}, 144>;\n  ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}]).declareVariables(s,o,l,t,r,a)}\n  ${e.mainStart([i,i,1])}\n    let batchIndex = workgroup_id.z / uniforms.num_heads;\n    let headNumber = workgroup_id.z % uniforms.num_heads;\n    let m = global_id.y;\n    let n = global_id.x;\n\n    let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n    let biasOffsetQ = headNumber * uniforms.head_size;\n    let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n    let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n    var valueQ = ${c}(0);\n    var valueK = ${c}(0);\n    var valueV = ${c}(0);\n    for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n      if (m < uniforms.M && w + local_id.x < uniforms.K) {\n        tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n      }\n      if (n < uniforms.N && w + local_id.y < uniforms.K) {\n        let offset = n + (w + local_id.y) * uniforms.ldb;\n        tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n        tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n        tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n      }\n      workgroupBarrier();\n      for (var k: u32 = 0u; k<TILE_SIZE && w+k < uniforms.K; k++) {\n        let inputTileOffset = TILE_SIZE * local_id.y + k;\n        let weightTileOffset = TILE_SIZE * k + local_id.x;\n        valueQ += tileInput[inputTileOffset] * tileWeightQ[weightTileOffset];\n        valueK += tileInput[inputTileOffset] * tileWeightK[weightTileOffset];\n        valueV += tileInput[inputTileOffset] * tileWeightV[weightTileOffset];\n      }\n\n      workgroupBarrier();\n    }\n\n    let headOffset = (m * uniforms.N + n) % uniforms.head_size;\n    valueQ += bias[headOffset + biasOffsetQ];\n    valueK += bias[headOffset + biasOffsetK];\n    valueV += bias[headOffset + biasOffsetV];\n\n    let offset = workgroup_id.z * uniforms.M * uniforms.N;\n    if (m < uniforms.M && n < uniforms.N) {\n      let outputIdx = offset + m * uniforms.N + n;\n      output_q[outputIdx] = valueQ;\n      output_k[outputIdx] = valueK;\n      output_v[outputIdx] = valueV;\n    }\n  }`}},{inputs:u,outputs:[-1,-1,-1]})},Kn=(e,t)=>{let n=Vn(e.inputs,t),[r,a,s]=Zn(e,n);return qn(e,r,a,s,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}})),ol=z((()=>{se(),qu(),el(),Ju(),tl(),Yn=(e,t)=>{if(!e||5!==e.length)throw new Error("BatchNormalization requires 5 inputs");let n=(e,t,n)=>{let r=t.length;if(r!==e.length)throw new Error(`${n}: num dimensions != ${r}`);t.forEach(((t,r)=>{if(t!==e[r])throw new Error(`${n}: dim[${r}] do not match`)}))};if(e[0].dims.length>1){let r="NHWC"===t.format?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,r,"Invalid input scale"),n(e[2].dims,r,"Invalid input B"),n(e[3].dims,r,"Invalid input mean"),n(e[4].dims,r,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},Qn=(e,t)=>{let{epsilon:n,spatial:r,format:a}=t,s=e[0].dims,i=r?St(s[s.length-1]):1,o="NHWC"===a&&s.length>1?i:1,u=ht.size(s)/i,l=r,c=l?s.length:s,d=Nt("x",e[0].dataType,e[0].dims,i),p=Nt("scale",e[1].dataType,e[1].dims,o),h=Nt("bias",e[2].dataType,e[2].dims,o),f=Nt("inputMean",e[3].dataType,e[3].dims,o),m=Nt("inputVar",e[4].dataType,e[4].dims,o),g=Et("y",e[0].dataType,c,i);return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${r}_${i}`,inputDependencies:l?["rank","type","type","type","type"]:void 0},getShaderSource:e=>`\n  const epsilon = ${n};\n  ${e.registerUniform("outputSize","u32").declareVariables(d,p,h,f,m,g)}\n  ${e.mainStart()}\n  ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n    var outputIndices = ${g.offsetToIndices(`global_idx * ${i}`)};\n    ${(()=>{let e="";if(r)e=`let cOffset = ${1===s.length?"0u":"NHWC"===a?`outputIndices[${s.length-1}] / ${i}`:"outputIndices[1]"};`;else if("NCHW"===a)e=`\n            ${g.indicesSet("outputIndices","0","0")}\n            let cOffset = ${g.indicesToOffset("outputIndices")};`;else{e=`var cIndices = ${p.type.indices}(0);\n                       cIndices[0] = outputIndices[${s.length-1}];`;for(let t=1;t<p.rank;t++)e+=`cIndices[${t}] = outputIndices[${t}];`;e+=`let cOffset = ${p.indicesToOffset("cIndices")};`}return e})()}\n    let scale = ${p.getByOffset("cOffset")};\n    let bias = ${h.getByOffset("cOffset")};\n    let inputMean = ${f.getByOffset("cOffset")};\n    let inputVar = ${m.getByOffset("cOffset")};\n    let x = ${d.getByOffset("global_idx")};\n    let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n    ${g.setByOffset("global_idx","value")}\n  }`,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l?[{type:12,data:u},...kt(s)]:[{type:12,data:u}]})}},Xn=e=>ct(e),Jn=(e,t)=>{let{inputs:n,outputCount:r}=e,a=Xn({...t,outputCount:r});if(l.webgpu.validateInputContent&&Yn(n,a),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Qn(n,a))}})),ul=z((()=>{el(),tl(),er=e=>{if(3!==e[0].dims.length)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(1!==e[1].dims.length)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},tr=e=>{let t=e[0].dims,n=e[0].dims[2],r=ht.size(t)/4,a=e[0].dataType,s=Nt("input",a,t,4),i=Nt("bias",a,[n],4),o=Nt("residual",a,t,4),u=Et("output",a,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:e=>`\n  const channels = ${n}u / 4;\n  ${e.declareVariables(s,i,o,u)}\n\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes(r)}\n    let value = ${s.getByOffset("global_idx")}\n      + ${i.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")};\n    ${u.setByOffset("global_idx","value")}\n  }`}},nr=e=>{er(e.inputs),e.compute(tr(e.inputs))}})),ll=z((()=>{qu(),el(),Ju(),tl(),rr=(e,t,n,r,a,s,i)=>{let o=Math.ceil(t/4),u="";u="string"==typeof a?`${a}(a)`:a("a");let l=Nt("inputData",n,[o],4),c=Et("outputData",r,[o],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),`\n      ${e.registerUniforms(d).declareVariables(l,c)}\n\n  ${s??""}\n\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n    let a = ${l.getByOffset("global_idx")};\n    ${c.setByOffset("global_idx",u)}\n  }`},ar=(e,t,n,r,a,s=e.dataType,i,o)=>{let u=[{type:12,data:Math.ceil(ht.size(e.dims)/4)}];return i&&u.push(...i),{name:t,shaderCache:{hint:a,inputDependencies:["type"]},getShaderSource:t=>rr(t,ht.size(e.dims),e.dataType,s,n,r,o),getRunData:t=>({outputs:[{dims:e.dims,dataType:s}],dispatchGroup:{x:Math.ceil(ht.size(t[0].dims)/64/4)},programUniforms:u})}},sr=e=>{e.compute(ar(e.inputs[0],"Abs","abs"))},ir=e=>{e.compute(ar(e.inputs[0],"Acos","acos"))},or=e=>{e.compute(ar(e.inputs[0],"Acosh","acosh"))},ur=e=>{e.compute(ar(e.inputs[0],"Asin","asin"))},lr=e=>{e.compute(ar(e.inputs[0],"Asinh","asinh"))},cr=e=>{e.compute(ar(e.inputs[0],"Atan","atan"))},dr=e=>{e.compute(ar(e.inputs[0],"Atanh","atanh"))},pr=e=>ct(e),hr=(e,t)=>{let n;switch(t.to){case 10:n="vec4<f16>";break;case 1:n="vec4<f32>";break;case 12:n="vec4<u32>";break;case 6:n="vec4<i32>";break;case 9:n="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ar(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},fr=e=>{let t,n,r=e.length>=2&&0!==e[1].data,a=e.length>=3&&0!==e[2].data;switch(e[0].dataType){case 1:t=r?e[1].getFloat32Array()[0]:-34028234663852886e22,n=a?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=r?e[1].getUint16Array()[0]:64511,n=a?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return ct({min:t,max:n})},mr=(e,t)=>{let n=t||fr(e.inputs),r=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Clip",(e=>`clamp(${e}, vec4<${r}>(uniforms.min), vec4<${r}>(uniforms.max))`),void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:r},{name:"max",type:r}]),{inputs:[0]})},gr=e=>{e.compute(ar(e.inputs[0],"Ceil","ceil"))},yr=e=>{e.compute(ar(e.inputs[0],"Cos","cos"))},br=e=>{e.compute(ar(e.inputs[0],"Cosh","cosh"))},xr=e=>ct(e),wr=(e,t)=>{let n=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Elu",(e=>`elu_vf32(${e})`),`\n  const elu_alpha_ = ${n}(${t.alpha});\n\n  fn elu_f32(a: ${n}) -> ${n} {\n  return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n  }\n\n  fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {\n  return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n  }`,t.cacheKey))},vr=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n  let absv = abs(v);\n  let x = 1.0 / (1.0 + r0 * absv);\n  return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,kr=e=>{let t=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Erf",(e=>`erf_vf32(${e})`),vr(t)))},Sr=e=>{e.compute(ar(e.inputs[0],"Exp","exp"))},_r=e=>{e.compute(ar(e.inputs[0],"Floor","floor"))},Ir=e=>{let t=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Gelu",(e=>`0.5 * ${e} * (1.0 + erf_vf32(${e} * 0.7071067811865475))`),vr(t)))},Tr=(e,t)=>{let n=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"LeakyRelu",(e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<${n}>(0.0))`),`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},$r=e=>{e.compute(ar(e.inputs[0],"Not",(e=>`!${e}`)))},Cr=e=>{e.compute(ar(e.inputs[0],"Neg",(e=>`-${e}`)))},Nr=e=>{e.compute(ar(e.inputs[0],"Reciprocal",(e=>`1.0/${e}`)))},Er=e=>{let t=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"Relu",(e=>`select(vec4<${t}>(0.0), ${e}, ${e} > vec4<${t}>(0.0))`)))},Ar=e=>{e.compute(ar(e.inputs[0],"Sigmoid",(e=>`(1.0 / (1.0 + exp(-${e})))`)))},Rr=e=>ct(e),Dr=(e,t)=>{let n=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"HardSigmoid",(e=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${e} + vec4<${n}>(${t.beta})))`),void 0,t.cacheKey))},Fr=e=>{e.compute(ar(e.inputs[0],"Sin","sin"))},Mr=e=>{e.compute(ar(e.inputs[0],"Sinh","sinh"))},Or=e=>{e.compute(ar(e.inputs[0],"Sqrt","sqrt"))},zr=e=>{e.compute(ar(e.inputs[0],"Tan","tan"))},Lr=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Pr=e=>{e.compute(ar(e.inputs[0],"Tanh",Lr))},Br=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n  return ${Lr("v")};\n}\n`,Wr=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Vr=e=>{let t=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"FastGelu",Wr,Br(t),void 0,e.inputs[0].dataType))},Ur=(e,t)=>{let n=vt(e.inputs[0].dataType);return e.compute(ar(e.inputs[0],"ThresholdedRelu",(e=>`select(vec4<${n}>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`),`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},Gr=e=>{e.compute(ar(e.inputs[0],"Log","log"))},Hr=(e,t)=>`\nconst alpha = vec4<${e}>(${t});\nconst one = ${e}(1.0);\nconst zero = ${e}(0.0);\n\nfn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {\n  let v = x *alpha;\n  var x1 : vec4<${e}>;\n  for (var i = 0; i < 4; i = i + 1) {\n    if (v[i] >= zero) {\n      x1[i] = one / (one + exp(-v[i]));\n    } else {\n      x1[i] = one - one / (one + exp(v[i]));\n    }\n  }\n  return x * x1;\n}\n`,jr=e=>`quick_gelu_impl(${e})`,qr=(e,t)=>{let n=vt(e.inputs[0].dataType);e.compute(ar(e.inputs[0],"QuickGelu",jr,Hr(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}})),cl=z((()=>{el(),tl(),ll(),Zr=e=>{if(3!==e[0].dims.length)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(1!==e[1].dims.length)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Kr=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=Nt("input",e[0].dataType,e[0].dims,4),r=Nt("bias",e[0].dataType,[e[0].dims[2]],4),a=Et("output",e[0].dataType,t,4),s=ht.size(t)/4,i=wt(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:t=>`\n  const M_SQRT2 = sqrt(2.0);\n  const halfChannels = ${e[0].dims[2]/4/2}u;\n\n  ${t.declareVariables(n,r,a)}\n\n  ${vr(i)}\n\n  ${t.mainStart()}\n    ${t.guardAgainstOutOfBoundsWorkgroupSizes(s)}\n    let biasIdx = global_idx % halfChannels;\n    let batchIndex = global_idx / halfChannels;\n    let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n    let valueLeft = input[inputOffset] + bias[biasIdx];\n    let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n    let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n    ${a.setByOffset("global_idx","valueLeft * geluRight")}\n  }`}},Yr=e=>{Zr(e.inputs),e.compute(Kr(e.inputs))}})),dl=z((()=>{qu(),el(),tl(),Qr=(e,t,n,r,a,s,i,o,u,l,c,d)=>{let p,h;"string"==typeof o?p=h=(e,t)=>`${o}((${e}),(${t}))`:"function"==typeof o?p=h=o:(p=o.scalar,h=o.vector);let f,m=Et("outputData",c,r.length,4),g=Nt("aData",u,t.length,4),y=Nt("bData",l,n.length,4);if(a)if(s){let e=1===ht.size(t),r=1===ht.size(n),a=t.length>0&&t[t.length-1]%4===0,s=n.length>0&&n[n.length-1]%4===0;f=e||r?m.setByOffset("global_idx",h(e?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),r?`${y.type.value}(${y.getByOffset("0")}.x)`:y.getByOffset("global_idx"))):`\n            let outputIndices = ${m.offsetToIndices("global_idx * 4u")};\n            let offsetA = ${g.broadcastedIndicesToOffset("outputIndices",m)};\n            let offsetB = ${y.broadcastedIndicesToOffset("outputIndices",m)};\n            ${m.setByOffset("global_idx",h(i||a?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||s?y.getByOffset("offsetB / 4u"):`${y.type.value}(${y.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n          `}else f=m.setByOffset("global_idx",h(g.getByOffset("global_idx"),y.getByOffset("global_idx")));else{if(!s)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let e=(e,t,n="")=>{let r=`aData[indexA${t}][componentA${t}]`,a=`bData[indexB${t}][componentB${t}]`;return`\n            let outputIndices${t} = ${m.offsetToIndices(`global_idx * 4u + ${t}u`)};\n            let offsetA${t} = ${g.broadcastedIndicesToOffset(`outputIndices${t}`,m)};\n            let offsetB${t} = ${y.broadcastedIndicesToOffset(`outputIndices${t}`,m)};\n            let indexA${t} = offsetA${t} / 4u;\n            let indexB${t} = offsetB${t} / 4u;\n            let componentA${t} = offsetA${t} % 4u;\n            let componentB${t} = offsetB${t} % 4u;\n            ${e}[${t}] = ${n}(${p(r,a)});\n          `};f=9===c?`\n            var data = vec4<u32>(0);\n            ${e("data",0,"u32")}\n            ${e("data",1,"u32")}\n            ${e("data",2,"u32")}\n            ${e("data",3,"u32")}\n            outputData[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:`\n            ${e("outputData[global_idx]",0)}\n            ${e("outputData[global_idx]",1)}\n            ${e("outputData[global_idx]",2)}\n            ${e("outputData[global_idx]",3)}\n          `}return`\n        ${e.registerUniform("vec_size","u32").declareVariables(g,y,m)}\n\n        ${d??""}\n\n        ${e.mainStart()}\n        ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n        ${f}\n      }`},Xr=(e,t,n,r,a,s,i=n.dataType)=>{let o=n.dims.map((e=>Number(e)??1)),u=r.dims.map((e=>Number(e)??1)),l=!ht.areEqual(o,u),c=o,d=ht.size(o),p=!1,h=!1,f=[l];if(l){let e=pt.calcShape(o,u,!1);if(!e)throw new Error("Can't perform binary op on the given tensors");c=e.slice(),d=ht.size(c);let t=1===ht.size(o),n=1===ht.size(u),r=o.length>0&&o[o.length-1]%4===0,a=u.length>0&&u[u.length-1]%4===0;f.push(t),f.push(n),f.push(r),f.push(a);let s=1;for(let i=1;i<c.length;i++){let e=o[o.length-i];if(e!==u[u.length-i])break;s*=e}s%4===0?(h=!0,p=!0):(t||n||r||a)&&(p=!0)}else p=!0;return f.push(p),{name:e,shaderCache:{hint:t+f.map((e=>e.toString())).join("_"),inputDependencies:["rank","rank"]},getShaderSource:e=>Qr(e,o,u,c,p,l,h,a,n.dataType,r.dataType,i,s),getRunData:()=>({outputs:[{dims:c,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(ht.size(c)/4)},...kt(o,u,c)]})}},Jr=(e,t,n,r,a,s)=>{e.compute(Xr(t,a??"",e.inputs[0],e.inputs[1],n,r,s))},ea=e=>{Jr(e,"Add",((e,t)=>`${e}+${t}`))},ta=e=>{Jr(e,"Div",((e,t)=>`${e}/${t}`))},na=e=>{Jr(e,"Equal",{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4<u32>(${e}==${t})`},void 0,void 0,9)},ra=e=>{Jr(e,"Mul",((e,t)=>`${e}*${t}`))},aa=e=>{let t=Nt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Jr(e,"Pow",{scalar:(e,t)=>`pow_custom(${e},${t})`,vector:(e,t)=>`pow_vector_custom(${e},${t})`},`\n    fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n      if (b == ${t}(0.0)) {\n        return ${t}(1.0);\n      } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n        return ${t}(pow(f32(a), f32(b))); // NaN\n      }\n      return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${"i32"===t?"round":""}(pow(f32(abs(a)), f32(b))));\n    }\n    fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n      // TODO: implement vectorized pow\n      return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n    }\n      `)},sa=e=>{Jr(e,"Sub",((e,t)=>`${e}-${t}`))},ia=e=>{Jr(e,"Greater",{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4<u32>(${e}>${t})`},void 0,void 0,9)},oa=e=>{Jr(e,"Less",{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4<u32>(${e}<${t})`},void 0,void 0,9)},ua=e=>{Jr(e,"GreaterOrEqual",{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4<u32>(${e}>=${t})`},void 0,void 0,9)},la=e=>{Jr(e,"LessOrEqual",{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4<u32>(${e}<=${t})`},void 0,void 0,9)}})),pl=z((()=>{qu(),el(),Ju(),tl(),ca=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=e[0],r=n.dataType,a=n.dims.length;e.forEach(((e,s)=>{if(0!==s){if(e.dataType!==r)throw new Error("input tensors should be one type");if(e.dims.length!==a)throw new Error("input tensors should have the same shape");e.dims.forEach(((e,r)=>{if(r!==t&&e!==n.dims[r])throw new Error("non concat dimensions must match")}))}}))},da=(e,t)=>`\n  fn calculateInputIndex(index: u32) -> u32 {\n    let sizeInConcatAxis = array<u32, ${e}u>(${t});\n    for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n      if (index < sizeInConcatAxis[i]) {\n        return i;\n      }\n    }\n    return ${e}u;\n  }`,pa=(e,t)=>{let n=e.length,r=[];for(let a=0;a<n;++a){let s=t.setByOffset("global_idx",e[a].getByIndices("indices"));1===n?r.push(s):0===a?r.push(`if (inputIndex == ${a}u) { ${s} }`):a===n-1?r.push(`else { ${s} }`):r.push(`else if (inputIndex == ${a}) { ${s} }`)}return r.join("\n")},ha=(e,t,n,r)=>{let a=ht.size(n),s=new Array(e.length),i=new Array(e.length),o=0,u=[],l=[],c=[{type:12,data:a}];for(let f=0;f<e.length;++f)o+=e[f].dims[t],s[f]=o,l.push(e[f].dims.length),i[f]=Nt(`input${f}`,r,l[f]),u.push("rank"),c.push({type:12,data:s[f]});for(let f=0;f<e.length;++f)c.push(...kt(e[f].dims));c.push(...kt(n));let d=Et("output",r,n.length),p=d.indicesGet("indices",t),h=Array.from(Array(s.length).keys()).map((e=>`uniforms.sizeInConcatAxis${e}`)).join(",");return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:t=>`\n\n  ${(()=>{t.registerUniform("outputSize","u32");for(let n=0;n<e.length;n++)t.registerUniform(`sizeInConcatAxis${n}`,"u32");return t.declareVariables(...i,d)})()}\n\n  ${da(s.length,h)}\n\n  ${t.mainStart()}\n    ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n    var indices = ${d.offsetToIndices("global_idx")};\n\n    let inputIndex = calculateInputIndex(${p});\n    if (inputIndex != 0u) {\n      let sizeInConcatAxis = array<u32, ${s.length}u>(${h});\n      ${p} -= sizeInConcatAxis[inputIndex - 1u];\n    }\n\n    ${pa(i,d)}\n  }`}},fa=(e,t)=>{let n=e.inputs,r=n[0].dims,a=ht.normalizeAxis(t.axis,r.length);ca(n,a);let s=r.slice();s[a]=n.reduce(((e,t)=>e+(t.dims.length>a?t.dims[a]:0)),0);let i=n.filter((e=>ht.size(e.dims)>0));e.compute(ha(i,a,s,n[0].dataType),{inputs:i})},ma=e=>ct({axis:e.axis})})),hl=z((()=>{qu(),el(),ga=(e,t,n="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return"let e2x = exp(-2.0 * abs(value));\n              value = sign(value) * (1.0 - e2x) / (1.0 + e2x);\n        ";case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},ya=(e,t)=>{"Clip"===e.activation?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):"HardSigmoid"===e.activation?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):"LeakyRelu"===e.activation&&t.push({type:1,data:e.alpha})},ba=(e,t)=>{"Clip"===e.activation?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):"HardSigmoid"===e.activation?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):"LeakyRelu"===e.activation&&t.push({name:"alpha",type:"f32"})},xa=e=>{let t=e?.activation||"";if("HardSigmoid"===t){let[n,r]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:r}}if("Clip"===t){let[n,r]=e?.activation_params||[gt,yt];return{activation:t,clipMax:r,clipMin:n}}if("LeakyRelu"===t){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}})),fl=z((()=>{wa=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},va=e=>`\n      ${e?"value = value + getBiasByOutputCoords(coords);":""}\n      `})),ml=z((()=>{ka=e=>`\nfn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {\n  return dot(coords, vec4<i32>(\n      shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {\n  return dot(coords, vec4<i32>(\n    i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`})),gl=z((()=>{qu(),el(),tl(),hl(),Sa=(e,t,n,r,a)=>{let s=r-n;return`\n      ${Array.from({length:n}).map(((n,i)=>`\n      if (${$t(t.shape,i,t.rank)} != 1) {\n        ${t.indicesSet(e,i,$t(a,i+s,r))}\n      } else {\n        ${t.indicesSet(e,i,0)}\n      }`)).join("")}\n`},_a=(e,t,n,r,a=!1,s)=>{let i=e[0].dims,o=e[1].dims,u=i[i.length-2],l=o[o.length-1],c=i[i.length-1],d=St(l),p=St(c),h=St(u),f=ht.size(n)/d/h,m=e.length>2,g=r?r.slice(0,-2):n.slice(0,-2),y=[ht.size(g),u,l],b=[{type:12,data:f},{type:12,data:u},{type:12,data:l},{type:12,data:c}];ya(t,b),b.push(...kt(g,i,o)),m&&b.push(...kt(e[2].dims)),b.push(...kt(y));return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${d};${p};${h};${a}`,inputDependencies:m?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:b}),getShaderSource:r=>{let s=Rt("batch_dims",e[0].dataType,g.length),u=Nt("a",e[0].dataType,i.length,p),l=Nt("b",e[1].dataType,o.length,d),c=Et("output",e[0].dataType,y.length,d),f=wt(c.type.tensor),b=ga(t,c.type.value,f),x=[u,l],w="";if(m){let t=a?d:1;x.push(Nt("bias",e[2].dataType,e[2].dims.length,t)),w=""+(a?`value += bias[col / ${t}];`:`value += ${c.type.value}(bias[row + i]);`)}let v=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ba(t,v);return`\n  ${r.registerUniforms(v).registerInternalVariables(s).declareVariables(...x,c)}\n  ${r.mainStart()}\n    ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n    let col = (global_idx % (uniforms.N / ${d})) * ${d};\n    var index1 = global_idx / (uniforms.N / ${d});\n    let stride1 = uniforms.M / ${h};\n    let row = (index1 % stride1) * ${h};\n    let batch = index1 / stride1;\n\n    ${2===n.length?"":`let batch_indices = ${s.offsetToIndices("batch")};`}\n\n    var a_indices: ${u.type.indices};\n    ${Sa("a_indices",u,u.rank-2,s.rank,"batch_indices")}\n    ${u.indicesSet("a_indices",u.rank-2,0)}\n    ${u.indicesSet("a_indices",u.rank-1,0)}\n    let a_offset = ${u.indicesToOffset("a_indices")};\n\n    var b_indices: ${l.type.indices};\n    ${Sa("b_indices",l,l.rank-2,s.rank,"batch_indices")}\n    ${l.indicesSet("b_indices",l.rank-2,0)}\n    ${l.indicesSet("b_indices",l.rank-1,0)}\n    let b_offset = ${l.indicesToOffset("b_indices")};\n    var values: array<${c.type.value}, ${h}>;\n    for (var k: u32 = 0u; k < uniforms.K; k = k + ${p}) {\n      ${(()=>{let e=`var a_data: ${u.type.value};`;for(let t=0;t<p;t++)e+=`\n              let b_data${t} = b[(b_offset + (k + ${t}) * uniforms.N + col) / ${d}];`;for(let t=0;t<h;t++){e+=`a_data = a[(a_offset + (row + ${t}) * uniforms.K + k) / ${p}];`;for(let n=0;n<p;n++)e+=`\n            values[${t}] = fma(${l.type.value}(a_data${1===p?"":`[${n}]`}), b_data${n}, values[${t}]);\n`}return e})()}\n    }\n    for (var i = 0u; i < ${h}u; i++) {\n      var value = values[i];\n      ${w}\n      ${b}\n      let cur_indices = ${c.type.indices}(batch, row + i, col);\n      let offset = ${c.indicesToOffset("cur_indices")};\n      ${c.setByOffset(`offset / ${d}`,"value")};\n    }\n  }\n  `}}}})),yl=z((()=>{qu(),el(),tl(),hl(),gl(),fl(),Ia=(e,t)=>e?`\n        mm_Asub[inputRow][inputCol] = mm_readA(batch,\n          kStart + inputRow,\n          globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n        `:`\n        mm_Asub[inputRow][inputCol] = mm_readA(batch,\n          globalRow + innerRow,\n          kStart / innerElementSize + inputCol${t?", batchIndices":""});\n        `,Ta=(e,t)=>e?`\n        let ACached0 = mm_Asub[k * innerElementSize][localRow];\n        let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n        let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n        ${3===t?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n        for (var i = 0; i < rowPerThread; i = i + 1) {\n          acc[i] = BCached0 * ACached0[i] + acc[i];\n          acc[i] = BCached1 * ACached1[i] + acc[i];\n          acc[i] = BCached2 * ACached2[i] + acc[i];\n          ${3===t?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n        }`:`\n        for (var i = 0; i < rowPerThread; i = i + 1) {\n          let ACached = mm_Asub[tileRow + i][k];\n          acc[i] = BCached0 * ACached.x + acc[i];\n          acc[i] = BCached1 * ACached.y + acc[i];\n          acc[i] = BCached2 * ACached.z + acc[i];\n          ${3===t?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n        }`,$a=(e,t,n="f32",r,a=!1,s=32,i=!1,o=32)=>{let u=t[1]*e[1],l=t[0]*e[0],c=a?u:s,d=a?s:u,p=c/t[0],h=s/t[1];if((!a||4!==p||4!==e[1])&&(a||3!==p&&4!==p)||c%t[0]!==0||s%t[1]!==0||4!==e[0])throw new Error(`If transposeA ${a} is true, innerElementSize ${p} and workPerThread[1] ${e[1]} must be 4.\n      Otherwise, innerElementSize ${p} must be 3 or 4.\n  tileAWidth ${c} must be divisible by workgroupSize[0]${t[0]}. tileInner ${s} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar<workgroup> mm_Asub: array<array<vec${p}<${n}>, ${c/p}>, ${d}>;\nvar<workgroup> mm_Bsub: array<array<vec4<${n}>, ${l/e[0]}>, ${s}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${p};\nconst tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3<u32>,\n        @builtin(global_invocation_id) globalId : vec3<u32>,\n        @builtin(workgroup_id) workgroupId : vec3<u32>) {\n  let localRow = i32(localId.y);\n  let tileRow = localRow * rowPerThread;\n  let tileCol = i32(localId.x);\n\n  let globalRow =i32(globalId.y) * rowPerThread;\n  let globalCol = i32(globalId.x);\n  let batch = ${i?"0":"i32(globalId.z)"};\n  ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""}\n  let globalRowStart = i32(workgroupId.y) * ${u};\n\n  let num_tiles = ${i?`${Math.ceil(o/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n  var kStart = ${i?`i32(globalId.z) * ${o}`:"0"};\n\n  var acc: array<vec4<${n}>, rowPerThread>;\n\n  // Loop over shared dimension.\n  let tileRowB = localRow * ${h};\n  for (var t = 0; t < num_tiles; t = t + 1) {\n      // Load one tile of A into local memory.\n      for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n          let inputRow = tileRow + innerRow;\n          let inputCol = tileCol;\n          ${Ia(a,r)}\n      }\n\n      // Load one tile of B into local memory.\n      for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n          let inputRow = tileRowB + innerRow;\n          let inputCol = tileCol;\n          mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${r?", batchIndices":""});\n      }\n      kStart = kStart + tileInner;\n      workgroupBarrier();\n\n      // Compute acc values for a single thread.\n      for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n          let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n          let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n          let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n          ${3===p?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n          ${Ta(a,p)}\n      }\n\n      workgroupBarrier();\n  }\n\n  for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n      mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n  }\n}`},Ca=(e,t)=>e?`\n            mm_Asub[inputRow][inputCol] = mm_readA(batch,\n              kStart + inputRow,\n              globalRowStart + inputCol${t?", batchIndices":""});\n            `:`\n            mm_Asub[inputRow][inputCol] = mm_readA(batch,\n              globalRowStart + inputRow,\n              kStart + inputCol${t?", batchIndices":""});\n            `,Na=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ea=(e,t,n="f32",r,a=!1,s=32,i=!1,o=32,u=!1)=>{let l=e[1]*t[1],c=e[0]*t[0],d=a?l:s,p=a?s:l;if(p%t[1]!==0||d%t[0]!==0||s%t[1]!==0)throw new Error(`tileAHight ${p} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}, tileInner ${s} must be divisible by workgroupSize[1]${t[1]}`);let h=p/t[1],f=d/t[0],m=s/t[1],g=u?`\n    let localRow = i32(localId.y);\n    let localCol = i32(localId.x);\n    let globalRowStart = i32(workgroupId.y) * ${l};\n    let globalColStart = i32(workgroupId.x) * ${c};\n\n    // Loop over shared dimension.\n    for (var t = 0; t < num_tiles; t = t + 1) {\n      // Load one tile of A into local memory.\n      for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${t[1]}) {\n        for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {\n          ${Ca(a,r)}\n        }\n      }\n      // Load one tile of B into local memory.\n      for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${t[1]}) {\n            for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${t[0]}) {\n          mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n            kStart + inputRow,\n            globalColStart + inputCol${r?", batchIndices":""});\n        }\n      }\n      kStart = kStart + tileInner;\n      workgroupBarrier();\n\n      // Compute acc values for a single thread.\n      var BCached : array<${n}, colPerThread>;\n      for (var k = 0; k < tileInner; k = k + 1) {\n        for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n          BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n        }\n        for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n          let ACached = ${a?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n          for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n            acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n                ACached * BCached[innerCol];\n          }\n        }\n      }\n      workgroupBarrier();\n    }\n    for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n      let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n      for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n        let gCol = globalColStart + localCol + innerCol * ${t[0]};\n        mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n      }\n    }\n    `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${l};\n\nlet tileRowA = i32(localId.y) * ${h};\nlet tileColA = i32(localId.x) * ${f};\nlet tileRowB = i32(localId.y) * ${m};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n  // Load one tile of A into local memory.\n  for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n    for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) {\n      let inputRow = tileRowA + innerRow;\n      let inputCol = tileColA + innerCol;\n      ${Ca(a,r)}\n    }\n  }\n\n  // Load one tile of B into local memory.\n  for (var innerRow = 0; innerRow < ${m}; innerRow = innerRow + 1) {\n    for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n      let inputRow = tileRowB + innerRow;\n      let inputCol = tileCol + innerCol;\n      mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n        kStart + inputRow,\n        globalCol + innerCol${r?", batchIndices":""});\n    }\n  }\n  kStart = kStart + tileInner;\n  workgroupBarrier();\n\n  // Compute acc values for a single thread.\n  var BCached : array<${n}, colPerThread>;\n  for (var k = 0; k < tileInner; k = k + 1) {\n    for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n      BCached[inner] = mm_Bsub[k][tileCol + inner];\n    }\n\n    for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n      ${Na(a)}\n      for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n        acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n      }\n    }\n  }\n\n  workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n  for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n    mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n        acc[innerRow][innerCol]);\n  }\n}\n`;return`\n  var<workgroup> mm_Asub : array<array<${n}, ${d}>, ${p}>;\n  var<workgroup> mm_Bsub : array<array<${n}, ${c}>, ${s}>;\n  const rowPerThread = ${e[1]};\n  const colPerThread = ${e[0]};\n  const tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3<u32>,\n        @builtin(global_invocation_id) globalId : vec3<u32>,\n        @builtin(workgroup_id) workgroupId : vec3<u32>) {\n    let batch = ${i?"0":"i32(globalId.z)"};\n    ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""}\n    let num_tiles = ${i?`${Math.ceil(o/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n    var kStart = ${i?`i32(globalId.z) * ${o}`:"0"};\n\n    var acc : array<array<${n}, colPerThread>, rowPerThread>;\n    ${g}\n  }\n`},Aa=(e,t,n,r,a=!1)=>{let[s,i,o,u]=r,l=wt(r[0].type.tensor);return`\n    fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${s.type.indices}) -> ${wa(e,l)} {\n      var value = ${wa(e,l)}(0.0);\n      let col = colIn * ${e};\n      if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n      {\n        var aIndices: ${i.type.indices};\n        ${Sa("aIndices",i,i.rank-2,s.rank,"batchIndices")}\n        ${i.indicesSet("aIndices",i.rank-2,"u32(row)")}\n        ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")}\n        value = ${i.getByIndices("aIndices")};\n      }\n      return value;\n    }\n\n    fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${s.type.indices}) -> ${wa(e,l)} {\n      var value = ${wa(e,l)}(0.0);\n      let col = colIn * ${e};\n      if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n      {\n        var bIndices: ${o.type.indices};\n        ${Sa("bIndices",o,o.rank-2,s.rank,"batchIndices")}\n        ${o.indicesSet("bIndices",o.rank-2,"u32(row)")}\n        ${o.indicesSet("bIndices",o.rank-1,"u32(colIn)")}\n        value = ${o.getByIndices("bIndices")};\n      }\n      return value;\n    }\n\n    fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${wa(e,l)}) {\n      let col = colIn * ${e};\n      if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n        var value = valueIn;\n        let coords = vec3<i32>(batch, row, colIn);\n        ${t?`value = value + ${a?"bias[colIn]":`${wa(e,l)}(bias[row])`};`:""}\n        ${n}\n        ${u.setByIndices("vec3<u32>(coords)","value")}\n      }\n    }\n    `},Ra=(e,t,n,r,a=!1,s)=>{let i=e[0].dims,o=e[1].dims,u=i.slice(0,-2),l=o.slice(0,-2),c=r?r.slice(0,-2):n.slice(0,-2),d=ht.size(c),p=i[i.length-2],h=i[i.length-1],f=o[o.length-1],m=h%4===0&&f%4===0,g=p<=8?[4,1,1]:[4,4,1],y=[8,8,1],b=[Math.ceil(f/y[0]/g[0]),Math.ceil(p/y[1]/g[1]),Math.ceil(d/y[2]/g[2])],x=m?4:1,w=[...u,p,h/x],v=w.length,k=[...l,h,f/x],S=k.length,_=[d,p,f/x],I=[{type:6,data:p},{type:6,data:f},{type:6,data:h}];ya(t,I),I.push(...kt(c,w,k));let T=["rank","rank"],$=e.length>2;$&&(I.push(...kt(e[2].dims)),T.push("rank")),I.push(...kt(_));return{name:"MatMul",shaderCache:{hint:`${g};${t.activation};${m};${a}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:s?s(n):n,dataType:e[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:I}),getShaderSource:n=>{let r=c.length,s=Rt("batchDims",e[0].dataType,r,1),i=wt(e[0].dataType),o=Nt("a",e[0].dataType,v,x),u=Nt("b",e[1].dataType,S,x),l=Et("result",e[0].dataType,_.length,x),d=[o,u];if($){let t=a?x:1;d.push(Nt("bias",e[2].dataType,e[2].dims.length,t))}let p=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ba(t,p);let h=wt(l.type.tensor),f=ga(t,l.type.value,h),b=Aa(x,$,f,[s,o,u,l],a);return`\n  ${n.registerUniforms(p).registerInternalVariables(s).declareVariables(...d,l)}\n  ${b}\n  ${m?$a(g,y,i,s):Ea(g,y,i,s)}\n                   `}}}})),bl=z((()=>{qu(),Ku(),tl(),hl(),fl(),ml(),yl(),Da=(e,t,n,r,a=!1,s,i=4,o=4,u=4,l="f32")=>{let c=e=>{switch(e){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${e} is not supported.`)}},d=e?"\n    let coord = vec4<i32>(batch, xRow, xCol, xCh);\n    ":"\n    let coord = vec4<i32>(batch, xCh, xRow, xCol);\n    ",p=e?"\n    let coords = vec4<i32>(\n      batch,\n      row / outWidth,\n      row % outWidth,\n      col);\n    ":"\n    let coords = vec4<i32>(\n      batch,\n      row,\n      col / outWidth,\n      col % outWidth);\n    ",h=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",f=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",m=e?"row":"col",g=e?"col":"row",y=`\n    let inChannels = i32(uniforms.w_shape[2]);\n    let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n    let outRow = ${m} / outWidth;\n    let outCol = ${m} % outWidth;\n\n    let WRow = ${g} / (i32(uniforms.w_shape[1]) * inChannels);\n    let WCol = ${g} / inChannels % i32(uniforms.w_shape[1]);\n    let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n    let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n    let xCh = ${g} % inChannels;\n    var resData = ${wa(i,l)}(0.0);\n    // The bounds checking is always needed since we use it to pad zero for\n    // the 'same' padding type.\n    if (xRow >= 0 && xRow < ${h} && xCol >= 0 && xCol < ${f}) {\n      ${d}\n      let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape));\n      ${(e=>{switch(e){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${l}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(i)}\n    }\n    return resData;`,b=e?t&&r?`\n    let col = colIn * ${i};\n    ${y}`:`\n    let col = colIn * ${i};\n    if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n      ${y}\n    }\n    return ${wa(i,l)}(0.0);`:r&&n?`\n    let col = colIn * ${i};\n    ${y}`:`\n    let col = colIn * ${i};\n    if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n      ${y}\n    }\n    return ${wa(i,l)}(0.0);`,x=e?r&&n?c(o):`\n    let col = colIn * ${o};\n    if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n      ${c(o)}\n    }\n    return ${wa(o,l)}(0.0);`:`\n    let col = colIn * ${o};\n    if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {\n      ${c(o)}\n    }\n    return ${wa(o,l)}(0.0);`,w=wa(u,l),v=wa(e?i:o,l),k=wa(e?o:i,l),S=ga(s,w,l);return`\n    fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${v} {\n      ${e?b:x}\n    }\n\n    fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${k} {\n      ${e?x:b}\n    }\n\n    fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${w}) {\n      let col = colIn * ${u};\n      if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n      {\n      var value = valueIn;\n      let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n      ${p}\n      ${va(a)}\n      ${S}\n      setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n      }\n    }`},Fa=(e,t,n,r,a,s,i,o,u)=>{let l="NHWC"===t.format,c=l?e[0].dims[3]:e[0].dims[1],d=n[0],p=l?n[2]:n[3],h=l?n[1]:n[2],f=l?n[3]:n[1],m=l&&(c%4===0||c%3===0)&&f%4===0,g=l?f:p*h,y=l?p*h:f,b=[8,8,1],x=r<=8?[4,1,1]:[4,4,1],w=[Math.ceil(g/b[0]/x[0]),Math.ceil(y/b[1]/x[1]),Math.ceil(d/b[2]/x[2])];Xe("verbose",(()=>`[conv2d_mm_webgpu] dispatch = ${w}`));let v=m?l&&c%4!==0?3:4:1,k=b[1]*x[1],S=b[0]*x[0],_=Math.max(b[0]*v,b[1]),I=r%k===0,T=a%S===0,$=s%_===0,C=m?[v,4,4]:[1,1,1],N=[{type:6,data:r},{type:6,data:a},{type:6,data:s},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];ya(t,N),N.push(...kt(e[0].dims,e[1].dims));let E=["rank","rank"];i&&(N.push(...kt(e[2].dims)),E.push("rank")),N.push(...kt(n));return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${v};${m};${I};${T};${$};${k};${S};${_}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:u?u(n):n,dataType:e[0].dataType}],dispatchGroup:{x:w[0],y:w[1],z:w[2]},programUniforms:N}),getShaderSource:r=>{let a=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];ba(t,a);let s=m?4:1,u=wt(e[0].dataType),c=`\n      fn setOutputAtIndex(flatIndex : i32, value : ${m?`vec4<${u}>`:u}) {\n        result[flatIndex] = ${m?`vec4<${u}>`:u}(value);\n      }\n      fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${m?`vec4<${u}>`:u}) {\n        let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));\n        setOutputAtIndex(flatIndex ${m?"/ 4":""}, value);\n      }`,d=[Nt("x",e[0].dataType,e[0].dims.length,3===v?1:v),Nt("w",e[1].dataType,e[1].dims.length,s)],p=Et("result",e[0].dataType,n.length,s);if(i){let t=Nt("bias",e[2].dataType,e[2].dims.length,s);d.push(t),c+=`\n        fn getBiasByOutputCoords(coords : vec4<i32>) -> ${m?`vec4<${u}>`:u} {\n          return bias[coords.${l?"w":"y"}${m?"/ 4":""}];\n        }`}return`\n        ${ka("uniforms.result_strides")}\n        //struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,\n        //  outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,\n        //  dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n        ${r.registerUniforms(a).declareVariables(...d,p)}\n        ${c}\n        ${Da(l,I,T,$,i,t,C[0],C[1],C[2],u)}\n        ${m?$a(x,b,u,void 0,!l,_):Ea(x,b,u,void 0,!l,_,!1,void 0,o)}`}}}})),xl=z((()=>{qu(),Ku(),el(),tl(),hl(),fl(),Ma=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t},Oa=e=>"number"==typeof e?[e,e,e]:e,za=(e,t)=>t<=1?e:e+(e-1)*(t-1),La=(e,t,n,r=1)=>{let a=za(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)},Pa=(e,t,n,r,a)=>{null==a&&(a=La(e,t[0],r[0]));let s=[0,0,0,n];for(let i=0;i<3;i++)e[i]+2*a>=t[i]&&(s[i]=Math.trunc((e[i]-t[i]+2*a)/r[i]+1));return s},Ba=(e,t,n,r,a,s,i,o,u,l)=>{let c,d,p,h;if("VALID"===e&&(e=0),"number"==typeof e){c={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=Pa([t,n,r,1],[o,u,l],1,[a,s,i],e);d=f[0],p=f[1],h=f[2]}else if(Array.isArray(e)){if(!e.every(((e,t,n)=>e===n[0])))throw Error(`Unsupported padding parameter: ${e}`);c={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let f=Pa([t,n,r,1],[o,u,l],1,[a,s,i],e[0]);d=f[0],p=f[1],h=f[2]}else{if("SAME_UPPER"!==e)throw Error(`Unknown padding parameter: ${e}`);{d=Math.ceil(t/a),p=Math.ceil(n/s),h=Math.ceil(r/i);let e=(d-1)*a+o-t,f=(p-1)*s+u-n,m=(h-1)*i+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(f/2),x=f-b,w=Math.floor(m/2);c={top:b,bottom:x,left:w,right:m-w,front:g,back:y}}}return{padInfo:c,outDepth:d,outHeight:p,outWidth:h}},Wa=(e,t,n,r,a,s=!1,i="channelsLast")=>{let o,u,l,c,d;if("channelsLast"===i)[o,u,l,c,d]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[o,d,u,l,c]=e}let[p,,h,f,m]=t,[g,y,b]=Oa(n),[x,w,v]=Oa(r),k=za(h,x),S=za(f,w),_=za(m,v),{padInfo:I,outDepth:T,outHeight:$,outWidth:C}=Ba(a,u,l,c,g,y,b,k,S,_),N=s?p*d:p,E=[0,0,0,0,0];return"channelsFirst"===i?E=[o,N,T,$,C]:"channelsLast"===i&&(E=[o,T,$,C,N]),{batchSize:o,dataFormat:i,inDepth:u,inHeight:l,inWidth:c,inChannels:d,outDepth:T,outHeight:$,outWidth:C,outChannels:N,padInfo:I,strideDepth:g,strideHeight:y,strideWidth:b,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:k,effectiveFilterHeight:S,effectiveFilterWidth:_,dilationDepth:x,dilationHeight:w,dilationWidth:v,inShape:e,outShape:E,filterShape:t}},Va=(e,t,n,r,a,s)=>{let i="channelsLast"===s,o=(i?e[0].dims[3]:e[0].dims[1],{x:n.map(((e,t)=>t))}),u=[Math.ceil(Ma(o.x.map((e=>n[e])))/64),1,1];Xe("verbose",(()=>`[conv3d_naive_webgpu] dispatch = ${u}`));let l=[{type:12,data:ht.size(n)},{type:12,data:r},{type:12,data:a},{type:12,data:t.strides},{type:12,data:t.dilations}];ya(t,l),l.push(...kt(e[0].dims,e[1].dims));let c=["rank","rank"],d=3===e.length;d&&(l.push(...kt(e[2].dims)),c.push("rank")),l.push(...kt(n));return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};1;${d}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:l}),getShaderSource:s=>{let o=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:r.length},{name:"pads",type:"u32",length:a.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];ba(t,o);let u=wt(e[0].dataType),l=Nt("x",e[0].dataType,e[0].dims.length,1),c=Nt("W",e[1].dataType,e[1].dims.length,1),p=[l,c],h=Et("result",e[0].dataType,n.length,1),f="";if(d){let t=Nt("bias",e[2].dataType,e[2].dims.length,1);p.push(t),f+=`\n        fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${u} {\n          return bias[${$t("coords",i?4:1,5)}];\n        }`}let m=wa(1,u),g=ga(t,m,u);return`\n            ${f}\n            fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n              let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);\n              return ${l.getByIndices("aIndices")};\n            }\n            fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n              let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);\n              return ${c.getByIndices("aIndices")};\n            }\n          ${s.registerUniforms(o).declareVariables(...p,h)}\n          ${s.mainStart()}\n          ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n              let coords = ${h.offsetToIndices("global_idx")};\n              let batch = ${$t("coords",0,l.rank)};\n              let d2 = ${$t("coords",i?l.rank-1:1,l.rank)};\n              let xFRCCorner = vec3<u32>(${$t("coords",i?1:2,l.rank)},\n              ${$t("coords",i?2:3,l.rank)},\n              ${$t("coords",i?3:4,l.rank)}) * uniforms.strides - uniforms.pads;\n              let xFCorner = xFRCCorner.x;\n              let xRCorner = xFRCCorner.y;\n              let xCCorner = xFRCCorner.z;\n              let xShapeY = ${$t("uniforms.x_shape",i?1:2,l.rank)};\n              let xShapeZ = ${$t("uniforms.x_shape",i?2:3,l.rank)};\n              let xShapeW = ${$t("uniforms.x_shape",i?3:4,l.rank)};\n              let xShapeU = ${$t("uniforms.x_shape",i?4:1,l.rank)};\n              let inputDepthNearestVec4 = (xShapeU / 4) * 4;\n              let inputDepthVec4Remainder = xShapeU % 4;\n\n              var value = 0.0;\n              for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {\n                let xF = xFCorner + wF * uniforms.dilations[0];\n                if (xF < 0 || xF >= xShapeY) {\n                  continue;\n                }\n\n                for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {\n                  let xR = xRCorner + wR * uniforms.dilations[1];\n                  if (xR < 0 || xR >= xShapeZ) {\n                    continue;\n                  }\n\n                  for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {\n                    let xC = xCCorner + wC * uniforms.dilations[2];\n                    if (xC < 0 || xC >= xShapeW) {\n                      continue;\n                    }\n\n                    for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {\n                      ${i?"let xValues = vec4<f32>(\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                            ":"let xValues = vec4<f32>(\n                               getX(batch, d1, xF, xR, xC),\n                               getX(batch, d1 + 1, xF, xR, xC),\n                               getX(batch, d1 + 2, xF, xR, xC),\n                               getX(batch, d1 + 3, xF, xR, xC));\n                            "}\n                            let wValues = vec4<f32>(\n                              getW(d2, d1, wF, wR, wC),\n                              getW(d2, d1 + 1, wF, wR, wC),\n                              getW(d2, d1 + 2, wF, wR, wC),\n                              getW(d2, d1 + 3, wF, wR, wC));\n                      value += dot(xValues, wValues);\n                    }\n                    if (inputDepthVec4Remainder == 1) {\n                        ${i?"value += getX(batch, xF, xR, xC, inputDepthNearestVec4)\n                          * getW(d2, inputDepthNearestVec4, wF, wR, wC);":"value += getX(batch, inputDepthNearestVec4, xF, xR, xC)\n                          * getW(d2, inputDepthNearestVec4, wF, wR, wC);"}\n                    } else if (inputDepthVec4Remainder == 2) {\n                      ${i?"let xValues = vec2<f32>(\n                        getX(batch, xF, xR, xC, inputDepthNearestVec4),\n                        getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));\n                      ":"let xValues = vec2<f32>(\n                        getX(batch, inputDepthNearestVec4, xF, xR, xC),\n                        getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));\n                    "}\n                    let wValues = vec2<f32>(\n                      getW(d2, inputDepthNearestVec4, wF, wR, wC),\n                      getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));\n                      value += dot(xValues, wValues);\n                    } else if (inputDepthVec4Remainder == 3) {\n                      ${i?"let xValues = vec3<f32>(\n                        getX(batch, xF, xR, xC, inputDepthNearestVec4),\n                        getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),\n                        getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));\n                      ":"let xValues = vec3<f32>(\n                        getX(batch, inputDepthNearestVec4, xF, xR, xC),\n                        getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),\n                        getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));\n                    "}\n                    let wValues = vec3<f32>(\n                      getW(d2, inputDepthNearestVec4, wF, wR, wC),\n                      getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),\n                      getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));\n                      value += dot(xValues, wValues);\n                    }\n                  }\n                }\n              }\n              ${d?"value = value + getBiasByOutputCoords(coords)":""};\n              ${g}\n              result[global_idx] = f32(value);\n          }`}}}})),wl=z((()=>{qu(),el(),tl(),hl(),Ua=(e,t,n,r)=>{let a=e.length>2,s=a?"value += b[output_channel];":"",i=e[0].dims,o=e[1].dims,u="NHWC"===t.format,l=u?n[3]:n[1],c=l/t.group,d=u&&c>=4?St(l):1,p=ht.size(n)/d,h=[{type:12,data:p},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:c}];ya(t,h),h.push(...kt(i,[o[0],o[1],o[2],o[3]/d]));let f=a?["rank","rank","rank"]:["rank","rank"];h.push(...kt([n[0],n[1],n[2],n[3]/d]));return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${d}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:r=>{let l=Et("output",e[0].dataType,n.length,d),c=wt(l.type.tensor),p=ga(t,l.type.value,c),h=Nt("x",e[0].dataType,i.length),f=Nt("w",e[1].dataType,o.length,d),m=[h,f];a&&m.push(Nt("b",e[2].dataType,e[2].dims,d));let g=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];ba(t,g);let y=u?`\n      for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {\n        let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n        if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {\n          continue;\n        }\n\n        for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {\n          let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n          if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {\n            continue;\n          }\n\n          for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {\n            let input_channel = in_channel_offset + wInChannel;\n            let xVal = ${h.get("batch","xHeight","xWidth","input_channel")};\n            let wVal = ${f.get("wHeight","wWidth","wInChannel","output_channel")};\n            value += xVal * wVal;\n          }\n        }\n      }\n      `:`\n      for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n        let input_channel = in_channel_offset + wInChannel;\n        for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n          let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n          if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {\n            continue;\n          }\n\n          for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n            let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n            if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {\n              continue;\n            }\n\n            let xVal = ${h.get("batch","input_channel","xHeight","xWidth")};\n            let wVal = ${f.get("output_channel","wInChannel","wHeight","wWidth")};\n            value += xVal * wVal;\n          }\n        }\n      }\n      `;return`\n  ${r.registerUniforms(g).declareVariables(...m,l)}\n\n  ${r.mainStart()}\n    ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n    let outputIndices = ${l.offsetToIndices("global_idx")};\n    let batch: u32 = outputIndices[0];\n    let output_channel: u32 = outputIndices[${u?3:1}];\n    let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${u?1:2}], outputIndices[${u?2:3}]) * uniforms.strides - uniforms.pads;\n    let group_id: u32 = output_channel * ${d} / uniforms.output_channels_per_group;\n    var in_channel_offset = group_id * uniforms.w_shape[${u?2:1}];\n\n    var value: ${l.type.value} = ${l.type.value}(0);\n    ${y}\n    ${s}\n    ${p}\n    ${l.setByOffset("global_idx","value")}\n  }`}}},Ga=(e,t,n,r)=>{let a=e.length>2,s=St(n[3]),i=St(n[2]),o=ht.size(n)/s/i,u=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/s],l=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/s],c=[n[0],n[1],n[2],n[3]/s],d=[{type:12,data:o},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];ya(t,d),d.push(...kt(u,l,c));let p=(i-1)*t.strides[1]+l[1];return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${s};${i};${p};${l[0]};${l[1]}`,inputDependencies:a?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:d}),getShaderSource:n=>{let r=Et("output",e[0].dataType,c.length,s),o=wt(r.type.tensor),d=ga(t,r.type.value,o),h=Nt("x",e[0].dataType,u.length,s),f=Nt("w",e[1].dataType,l.length,s),m=[h,f];a&&m.push(Nt("b",e[2].dataType,e[2].dims,s));let g=a?"value += b[output_channel];":"",y=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ba(t,y),`\n  ${n.registerUniforms(y).declareVariables(...m,r)}\n  ${n.mainStart()}\n    ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n    let width0 = uniforms.output_shape[3];\n    let output_channel = global_idx % width0;\n    var index1 = global_idx / width0;\n    let width1 = uniforms.output_shape[2] / ${i}u;\n    let col = (index1 % width1) * ${i}u;\n    index1 = index1 / width1;\n    let row = index1 % uniforms.output_shape[1];\n    let batch = index1 / uniforms.output_shape[1];\n\n    let x_corner = vec2<i32>(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n    var x_vals: array<${h.type.value}, ${p}>;\n    var values: array<${r.type.value}, ${i}>;\n    let input_channel = output_channel;\n    // Use constant instead of uniform can give better performance for w's height/width.\n    for (var w_height: u32 = 0u; w_height < ${l[0]}; w_height++) {\n      let x_height = x_corner.x + i32(w_height);\n      if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n        for (var i = 0; i < ${p}; i++) {\n          let x_width = x_corner.y + i;\n          if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n            x_vals[i] = ${h.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n          } else {\n            x_vals[i] = ${h.type.value}(0);\n          }\n        }\n        for (var w_width: u32 = 0u; w_width < ${l[1]}; w_width++) {\n          let w_val = ${f.get("w_height","w_width","0","output_channel")};\n          for (var i = 0u; i < ${i}u; i++) {\n            values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n          }\n        }\n      }\n    }\n\n    for (var i = 0u; i < ${i}u; i++) {\n      var value = values[i];\n      ${g}\n      ${d}\n      ${r.set("batch","row","col + i","output_channel","value")};\n    }\n  }`}}}})),vl=z((()=>{el(),bl(),xl(),yl(),wl(),hl(),gl(),nl(),Ha=(e,t,n,r,a,s)=>{let i=e[0],o=e.slice(s?1:2,s?3:4),u=o.length,l=t[0],c=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),d=o.map(((e,t)=>e+r[t]+r[t+u])).map(((e,t)=>Math.floor((e-c[t]+a[t])/a[t])));return d.splice(0,0,i),d.splice(s?3:1,0,l),d},ja=[2,3,1,0],qa=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Za=(e,t)=>{let n=e.kernelShape.slice();n.length<t[1].dims.length-2&&n.push(...Array(t[1].dims.length-2-n.length).fill(0));for(let s=2;s<t[1].dims.length;++s)0===n[s-2]&&(n[s-2]=t[1].dims[s]);let r=e.pads.slice();ft.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,r,"NHWC"===e.format,e.autoPad);let a=Object.assign({},e);return Object.assign(a,{kernelShape:n,pads:r}),a},Ka=e=>{let t=xa(e),n=e.format;return{autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],format:n,dilations:e.dilations,group:e.group,kernelShape:e.kernel_shape,pads:e.pads,strides:e.strides,wIsConst:e.w_is_const(),...t,cacheKey:`${e.format};${t.activation};`}},Ya=(e,t,n,r)=>{let a="NHWC"===n.format,s=Ha(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,a);if(1!==n.group){let i=[t[0]];if(a){let r=e.kernelCustomData.wT??e.compute(Wt(t[1],ja),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),i.push(r)}else i.push(t[1]);return 3===t.length&&i.push(t[2]),void(!e.adapterInfo.isArchitecture("ampere")&&a&&t[1].dims[0]===n.group&&1===t[1].dims[1]&&1===n.dilations[0]&&1===n.dilations[1]?e.compute(Ga(i,n,s,r),{inputs:i}):e.compute(Ua(i,n,s,r),{inputs:i}))}let i=3===t.length,o=t[0].dims[a?1:2],u=t[0].dims[a?2:3],l=t[0].dims[a?3:1],c=t[1].dims[2],d=t[1].dims[3],p=s[a?1:2],h=s[a?2:3],f=s[a?3:1],m=a&&c===o&&d===u&&0===n.pads[0]&&0===n.pads[1];if(m||1===c&&1===d&&1===n.dilations[0]&&1===n.dilations[1]&&1===n.strides[0]&&1===n.strides[1]&&0===n.pads[0]&&0===n.pads[1]){let c,d,g,y=s[0],b=[];if(a){let r=e.kernelCustomData.wT??e.compute(Wt(t[1],ja),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),m){let e=o*u*l;c=t[0].reshape([1,y,e]),d=r.reshape([1,e,f]),g=[1,y,f]}else c=t[0].reshape([y,o*u,l]),d=r.reshape([1,l,f]),g=[y,p*h,f];b.push(c),b.push(d)}else c=t[0].reshape([y,l,o*u]),d=t[1].reshape([1,f,l]),g=[y,f,p*h],b.push(d),b.push(c);i&&b.push(t[2]);let x=g[2],w=b[0].dims[b[0].dims.length-1];return void(x<8&&w<8?e.compute(_a(b,n,s,g,a,r),{inputs:b}):e.compute(Ra(b,n,s,g,a,r),{inputs:b}))}let g=e.kernelCustomData.wT??e.compute(Wt(t[1],ja),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let y=[t[0],g];i&&y.push(t[2]);let b=a?p*h:f,x=a?f:p*h,w=c*d*l;e.compute(Fa(y,n,s,b,x,w,i,!0,r),{inputs:y})},Qa=(e,t)=>{let n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];3===e.inputs.length&&r.push(e.inputs[2]);let a=[0,t.pads[0],0,t.pads[1]],s=[1].concat(t.strides),i=[1].concat(t.dilations),o=[1].concat(t.kernelShape),u=Za({...t,pads:a,strides:s,dilations:i,kernelShape:o},r);Ya(e,r,u,(e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]]))},Xa=(e,t,n)=>{let r="NHWC"===n.format?"channelsLast":"channelsFirst",a=Za(n,t),s="NOTSET"===n.autoPad?n.pads:n.autoPad,i=Wa(t[0].dims,t[1].dims,n.strides,n.dilations,s,!1,r);e.compute(Va(t,a,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],r))},Ja=(e,t)=>{if(qa(e.inputs,t),3===e.inputs[0].dims.length)Qa(e,t);else if(5===e.inputs[0].dims.length)Xa(e,e.inputs,t);else{let n=Za(t,e.inputs);Ya(e,e.inputs,n)}}})),kl=z((()=>{qu(),Ku(),el(),tl(),es=(e,t,n)=>{let r=e.length>2,a=t.outputShape,s="NHWC"===t.format,i=t.group,o=e[1].dims,u=o[2]/i,l=o[3],c=s?St(u):1,d=s?St(l):1,p=s?1===l?c:d:1,h=ht.size(a)/d,f=[Math.ceil(h/64),1,1];Xe("verbose",(()=>`[conv2d_backprop_webgpu] dispatch = ${f}`));let m=["rank","rank"],g=[t.strides[0],t.strides[1]],y=[t.kernelShape[s?1:2],t.kernelShape[s?2:3]],b=[t.dilations[0],t.dilations[1]],x=[y[0]+(t.dilations[0]<=1?0:(t.kernelShape[s?1:2]-1)*(t.dilations[0]-1)),y[1]+(t.dilations[1]<=1?0:(t.kernelShape[s?2:3]-1)*(t.dilations[1]-1))],w=[x[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),x[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],v=[{type:12,data:h},{type:12,data:g},{type:12,data:y},{type:12,data:b},{type:12,data:x},{type:6,data:w},{type:12,data:u},{type:12,data:l},...kt(e[0].dims,e[1].dims)];r&&(v.push(...kt(e[2].dims)),m.push("rank")),v.push(...kt(a));return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${c}${p}${d}${1===l}`,inputDependencies:m},getRunData:()=>({dispatchGroup:{x:f[0],y:f[1],z:f[2]},outputs:[{dims:n?n(a):a,dataType:e[0].dataType}],programUniforms:v}),getShaderSource:t=>{let n=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:g.length},{name:"filter_dims",type:"u32",length:y.length},{name:"dilations",type:"u32",length:y.length},{name:"effective_filter_dims",type:"u32",length:x.length},{name:"pads",type:"i32",length:w.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],i=wt(e[0].dataType),o=s?1:2,u=s?2:3,h=s?3:1,f=Nt("W",e[1].dataType,e[1].dims.length,p),m=Nt("Dy",e[0].dataType,e[0].dims.length,c),b=[m,f];r&&b.push(Nt("bias",e[2].dataType,[a[h]].length,d));let v=Et("result",e[0].dataType,a.length,d),k=`\n            let outputIndices = ${v.offsetToIndices(`global_idx * ${d}`)};\n            let batch = ${v.indicesGet("outputIndices",0)};\n            let d1 = ${v.indicesGet("outputIndices",h)};\n            let r = ${v.indicesGet("outputIndices",o)};\n            let c = ${v.indicesGet("outputIndices",u)};\n            let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads;\n            let dyRCorner = dyCorner.x;\n            let dyCCorner = dyCorner.y;\n            let groupId = d1 / uniforms.output_channels_per_group;\n            let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\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            var dotProd = ${v.type.value}(0.0);\n            var wR: u32 = 0;\n            if (uniforms.dilations.x == 1) {\n              // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0\n              wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);\n            }\n            for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n              if (wR % uniforms.dilations.x != 0) {\n                continue;\n              }\n              let dyR = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]);\n              let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n              if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[${o}]) || fract(dyR) > 0.0 ||\n                  wRPerm < 0) {\n                continue;\n              }\n              let idyR: u32 = u32(dyR);\n              var wC: u32 = 0;\n              if (uniforms.dilations.y == 1) {\n                // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0\n                wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);\n              }\n\n              for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n                if (wC % uniforms.dilations.y != 0) {\n                  continue;\n                }\n                let dyC = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y);\n                let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n                if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[${u}]) ||\n                    fract(dyC) > 0.0 || wCPerm < 0) {\n                  continue;\n                }\n                let idyC: u32 = u32(dyC);\n                var inputChannel = groupId * uniforms.input_channels_per_group;\n                for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + ${c}) {\n                  let xValue = ${s?m.getByOffset(`${m.indicesToOffset(`${m.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${c}`):m.get("batch","inputChannel","idyR","idyC")};\n                  ${(()=>{let e="";if(1===c)e+=`\n        let w_offset = ${f.indicesToOffset(`${f.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};\n        let wValue = ${f.getByOffset(`w_offset / ${p}`)};\n        dotProd = dotProd + xValue * wValue;`;else if(1===l)e+=`\n          let wValue = ${f.getByOffset(`${f.indicesToOffset(`${f.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${p}`)};\n          dotProd = dotProd + dot(xValue, wValue);`;else for(let t=0;t<c;t++)e+=`\n            let wValue${t} = ${f.getByOffset(`${f.indicesToOffset(`${f.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${t}, wOutChannel)`)} / ${p}`)};\n            dotProd = dotProd + xValue[${t}] * wValue${t};`;return e})()}\n                  inputChannel = inputChannel + ${c};\n                }\n                wC = wC + uniforms.strides.y - 1;\n              }\n              wR = wR + uniforms.strides[0] - 1;\n            }\n            let value = dotProd${r?` + bias[d1 / ${d}]`:""};\n            ${v.setByOffset("global_idx","value")};\n          `;return`\n    ${t.registerUniforms(n).declareVariables(...b,v)}\n      ${t.mainStart()}\n      ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n    ${k}}`}}}})),Sl=z((()=>{kl(),hl(),nl(),ts=(e,t,n,r,a,s)=>(e-1)*t+n+(r-1)*a+1-s,ns=(e,t,n,r,a)=>{let s=Math.floor(e/2);"SAME_UPPER"===t?(n[r]=s,n[a]=e-s):"SAME_LOWER"===t&&(n[r]=e-s,n[a]=s)},rs=(e,t,n,r,a,s,i,o,u,l)=>{let c=e.length-2,d=0===l.length;u.length<c&&u.push(...Array(c-u.length).fill(0));let p=e[0],h=t[o?3:1]*a;for(let f=0,m=e.length-c-(o?1:0);f<c;++f,++m){let a=e[m],o=d?a*i[f]:l[f],p=ts(a,i[f],s[f],t[m],n[f],o);ns(p,r,s,f,f+c),d&&l.push(i[f]*(a-1)+u[f]+(t[m]-1)*n[f]+1-s[f]-s[f+c])}l.splice(0,0,p),l.splice(o?3:1,0,h)},as=(e,t)=>{let n=e.kernelShape.slice();if(0===e.kernelShape.length||0===e.kernelShape.reduce(((e,t)=>e*t),1)){n.length=0;for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e])}let r="NHWC"===e.format;n.splice(0,0,t[1].dims[0]),n.splice(r?3:1,0,t[1].dims[1]);let a=e.pads.slice(),s=e.outputShape.slice(),i=e.outputPadding.slice(),o=t[0].dims,u=e.dilations.slice();if(0===u.reduce(((e,t)=>e+t),0)){let e=t[0].dims.length-2;u=new Array(e).fill(1)}let l=e.strides.slice();if(0===l.reduce(((e,t)=>e+t),0)){let e=t[0].dims.length-2;l=new Array(e).fill(1)}rs(o,n,u,e.autoPad,e.group,a,l,r,i,s);let c=Object.assign({},e);return Object.assign(c,{kernelShape:n,pads:a,outputPadding:i,outputShape:s,dilations:u,strides:l}),c},ss=e=>{let t=xa(e),n=e.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],a=e.dilations,s=e.group,i=e.kernelShape,o=e.pads,u=e.strides,l=e.wIsConst();return{autoPad:r,format:n,dilations:a,group:s,kernelShape:i,outputPadding:e.outputPadding,outputShape:e.outputShape,pads:o,strides:u,wIsConst:l,...t,cacheKey:`${e.format};${t.activation};`}},is=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length&&3!==e[0].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(3===e.length&&(1!==e[2].dims.length||e[2].dims[0]!==n))throw new Error("invalid bias");let r=e[0].dims.length-2;if(t.dilations.reduce(((e,t)=>e+t),0)>0&&t.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(t.strides.reduce(((e,t)=>e+t),0)>0&&t.strides.length!==r)throw new Error(`strides should be ${r}D`);if(t.pads.reduce(((e,t)=>e+t),0)>0&&t.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(t.outputPadding.length!==r&&0!==t.outputPadding.length)throw new Error(`output_padding should be ${r}D`);if(t.kernelShape.reduce(((e,t)=>e+t),0)>0&&0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==t.outputShape.length&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},os=(e,t,n,r)=>{let a=e.kernelCustomData.wT??e.compute(Wt(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=a);let s=[t[0],a];3===t.length&&s.push(t[2]),e.compute(es(s,n,r),{inputs:s})},us=(e,t)=>{let n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];3===e.inputs.length&&r.push(e.inputs[2]);let a=t.kernelShape;(0===a.length||0===a[0])&&(a=[e.inputs[1].dims[2]]);let s=t.dilations;(0===s.length||0===s[0])&&(s=[1]);let i=t.strides;(0===i.length||0===i[0])&&(i=[1]);let o=t.pads;0===o.length&&(o=[0,0]),o=[0,o[0],0,o[1]],i=[1].concat(i),s=[1].concat(s),a=[1].concat(a);let u=t.outputPadding;u=[0].concat(u);let l=as({...t,pads:o,strides:i,dilations:s,kernelShape:a,outputPadding:u},r);os(e,r,l,(e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]]))},ls=(e,t)=>{if(is(e.inputs,t),3===e.inputs[0].dims.length)us(e,t);else{let n=as(t,e.inputs);os(e,e.inputs,n)}}})),_l=z((()=>{qu(),el(),Ju(),tl(),cs=(e,t,n,r)=>{let a=ht.size(t),s=t.length,i=Nt("input",e,s),o=Et("output",e,s),u=6===n.dataType?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),l=ht.normalizeAxis(u,s);return{name:"CumSum",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},{type:12,data:l},...kt(t,t)]}),getShaderSource:e=>{let t=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,n=$t("uniforms.input_shape","uniforms.axis",s),a=r.reverse?t+(r.exclusive?" + 1":""):"0",u=r.reverse?n:t+(r.exclusive?"":" + 1");return`\n                ${e.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,o)}\n                ${e.mainStart()}\n                  ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n                  var inputIndices = ${o.offsetToIndices("global_idx")};\n                  var sum = ${o.type.value}(0);\n                  let first : i32 = ${a};\n                  let last : i32 = ${u};\n                  for (var i : i32 = first; i < last; i++) {\n                    ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n                    sum = sum + ${i.getByIndices("inputIndices")};\n                  }\n                  ${o.setByOffset("global_idx","sum")};\n                }`}}},ds=(e,t)=>{let n=e.inputs[0].dims,r=e.inputs[0].dataType,a=e.inputs[1];e.compute(cs(r,n,a,t),{inputs:[0]})},ps=e=>{let t=1===e.exclusive,n=1===e.reverse;return ct({exclusive:t,reverse:n})}})),Il=z((()=>{qu(),el(),Ju(),tl(),hs=e=>{if(!e||1!==e.length)throw new Error("DepthToSpace requires 1 input.");if(4!==e[0].dims.length)throw new Error("DepthToSpace requires 4D input.")},fs=(e,t,n,r)=>{let a=[];a.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {\n    var a: ${n.type.indices};`);for(let s=0;s<t;++s)a.push(n.indicesSet("a",e[s],`i[${s}]`));return a.push("return a;}"),a.join("\n")},ms=(e,t)=>{let n,r,a,s,i,o,u="NHWC"===t.format,l=t.blocksize,c="DCR"===t.mode;u?([n,r,a,s]=e.dims,i=c?[n,r,a,l,l,s/l**2]:[n,r,a,s/l**2,l,l],o=c?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,r,a,s]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=c?[n,l,l,s/l**2,r,a]:[n,s/l**2,l,l,r,a],o=c?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),p=d.dims.length,h=e.dataType,f=Nt("a",h,p),m=Et("output",h,p);return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:e=>{let t=u?[n,r*l,a*l,s/l**2]:[n,s/l**2,r*l,a*l],i=ht.size(t),c=d.dims,p=ht.sortBasedOnPerm(c,o);return{outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...kt(c,p)]}},getShaderSource:e=>`\n  ${e.registerUniform("output_size","u32").declareVariables(f,m)}\n\n  ${fs(o,p,f,m)}\n\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n    let indices = ${m.offsetToIndices("global_idx")};\n    let aIndices = perm(indices);\n\n    ${m.setByOffset("global_idx",f.getByIndices("aIndices"))}\n  }`}},gs=(e,t)=>{hs(e.inputs),e.compute(ms(e.inputs[0],t))},ys=e=>ct({blocksize:e.blocksize,mode:e.mode,format:e.format})})),Tl=z((()=>{qu(),el(),Ju(),tl(),ws="^"+(xs="("+(bs="[a-zA-Z]|\\.\\.\\.")+")+")+"$",vs="^"+("("+xs+",)*"+xs)+"$",ks=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);void 0===n?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},Ss=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,r]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(vs)))throw new Error("Invalid LHS term");if(n.split(",").forEach(((t,n)=>{let r=e[n].dims.slice();if(!t.match(RegExp(ws)))throw new Error("Invalid LHS term");let a=this.processTerm(t,!0,r,n);this.lhs.push(a)})),""===r)r+=[...this.symbolToInfo.entries()].filter((([e,t])=>1===t.count||"..."===e)).map((([e])=>e)).join("");else if(!r.match(RegExp(xs)))throw new Error("Invalid RHS");r.match(RegExp(bs,"g"))?.forEach((e=>{if("..."===e)this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let t=this.symbolToInfo.get(e);if(void 0===t)throw new Error("Invalid RHS symbol");this.outputDims.push(t.dimValue)}})),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(e,t,n){let r=this.symbolToInfo.get(e);if(void 0!==r){if(r.dimValue!==t&&1!==r.count)throw new Error("Dimension mismatch");r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,r)}processTerm(e,t,n,r=-1){let a=n.length,s=!1,i=[],o=0;if(!e.match(RegExp(ws))&&!t&&""!==e)throw new Error("Invalid LHS term");let u=e.match(RegExp(bs,"g")),l=new ks(r);return u?.forEach(((e,c)=>{if("..."===e){if(s)throw new Error("Only one ellipsis is allowed per input term");s=!0;let e=a-u.length+1;if(e<0)throw new Error("Ellipsis out of bounds");if(i=n.slice(o,o+e),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else{if(!t)throw new Error("Ellipsis must be specified in the LHS");this.hasEllipsis=!0,this.ellipsisDims=i}for(let t=0;t<i.length;t++){let e=String.fromCharCode(48+t);l.addSymbol(e,c+t),this.addSymbol(e,n[o++],r)}}else l.addSymbol(e,c+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(e,n[o++],r)})),l}},_s=e=>e+"_max",Is=(e,t,n,r)=>{let a=e.map((e=>e.length)).map(((e,n)=>Nt(`input${n}`,t,e))),s=ht.size(r),i=Et("output",t,r.length),o=[...n.symbolToInfo.keys()].filter((e=>!n.rhs.symbolToIndices.has(e)));return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map((()=>"rank"))},getRunData:()=>{let a=o.filter((e=>n.symbolToInfo.has(e))).map((e=>({type:12,data:n.symbolToInfo.get(e)?.dimValue||0})));a.push({type:12,data:s});let i=e.map(((e,t)=>[...kt(e)])).reduce(((e,t)=>e.concat(t)),a);return i.push(...kt(r)),{outputs:[{dims:r,dataType:t}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:i}},getShaderSource:e=>{let t=[],r=[],s=[],u=[],l=[],c=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach(((e,o)=>{if(n.rhs.symbolToIndices.has(o)){let r=n.rhs.symbolToIndices.get(o)?.[0];void 0!==r&&n.lhs.forEach(((n,s)=>{if(e.inputIndices.includes(s)){let e=n.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach((e=>{t.push(`${a[s].indicesSet(`input${s}Indices`,e,i.indicesGet("outputIndices",r))}`)}))}}))}else n.lhs.forEach(((t,n)=>{if(e.inputIndices.includes(n)){let e=t.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach((e=>{r.push(`${a[n].indicesSet(`input${n}Indices`,e,`${o}`)}`)})),l.push(`prod *= ${a[n].getByIndices(`input${n}Indices`)};`)}})),s.push(`for(var ${o}: u32 = 0; ${o} < uniforms.${_s(o)}; ${o}++) {`),u.push("}")}));let d=c?[...t,`let sum = ${a.map(((e,t)=>e.getByIndices(`input${t}Indices`))).join(" * ")};`]:[...t,"var sum = 0.0;",...s,...r,"var prod = 1.0;",...l,"sum += prod;",...u];return`\n            ${e.registerUniforms(o.map((e=>({name:`${_s(e)}`,type:"u32"})))).registerUniform("outputSize","u32").declareVariables(...a,i)}\n\n            ${e.mainStart()}\n            ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n            var outputIndices = ${i.offsetToIndices("global_idx")};\n            ${a.map(((e,t)=>`var input${t}Indices: ${a[t].type.indices};`)).join("\n")}\n            ${d.join("\n")};\n            ${i.setByOffset("global_idx","sum")};\n          }`}}},Ts=(e,t)=>{let n=new Ss(e.inputs,t.equation),r=n.outputDims,a=e.inputs.map(((e,t)=>e.dims));e.compute(Is(a,e.inputs[0].dataType,n,r))},$s=e=>{let t=e.equation.replace(/\s+/g,"");return ct({equation:t})}})),$l=z((()=>{qu(),el(),tl(),Cs=e=>{if(!e||2!==e.length)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=n.length<t.length?0:n.length-t.length,a=t.length<n.length?0:t.length-n.length;for(;r<n.length&&a<t.length;++r,++a)if(n[r]!==t[a]&&1!==n[r]&&1!==t[a])throw new Error("Expand requires shape to be broadcastable to input")},Ns=(e,t)=>{let n=e.length-t.length,r=[];for(let a=0;a<n;++a)r.push(e[a]);for(let a=0;a<t.length;++a)r.push(1===t[a]?e[a+n]:t[a]);return r},Es=(e,t)=>e.length>t.length?Ns(e,t):Ns(t,e),As=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=Es(t,n),a=e[0].dataType,s=9===a||1===ht.size(t),i=9===a||t.length>0&&t[t.length-1]%4===0?4:1,o=s||r.length>0&&r[r.length-1]%4===0?4:1,u=Math.ceil(ht.size(r)/o),l=[{type:12,data:u},...kt(t,r)];return{name:"Expand",shaderCache:{hint:`${r.length};${i}${o}`,inputDependencies:["rank"]},getShaderSource:e=>{let n,s=Nt("input",a,t.length,i),u=Et("output",a,r.length,o);if(9===a){let e=(e,t,n="")=>`\n          let outputIndices${t} = ${u.offsetToIndices(`outputOffset + ${t}u`)};\n          let offset${t} = ${s.broadcastedIndicesToOffset(`outputIndices${t}`,u)};\n          let index${t} = offset${t} / 4u;\n          let component${t} = offset${t} % 4u;\n          ${e}[${t}] = ${n}(${s.getByOffset(`index${t}`)}[component${t}]);\n        `;n=`\n        let outputOffset = global_idx * ${o};\n        var data = vec4<u32>(0);\n        ${e("data",0,"u32")}\n        ${e("data",1,"u32")}\n        ${e("data",2,"u32")}\n        ${e("data",3,"u32")}\n        ${u.setByOffset("global_idx","data")}\n      }`}else n=`\n        let outputIndices = ${u.offsetToIndices(`global_idx * ${o}`)};\n        let inputOffset = ${s.broadcastedIndicesToOffset("outputIndices",u)};\n        let data = ${u.type.value}(${s.getByOffset(`inputOffset / ${i}`)});\n        ${u.setByOffset("global_idx","data")}\n      }`;return`\n    ${e.registerUniform("vec_size","u32").declareVariables(s,u)}\n    ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n    ${n}`},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l})}},Rs=e=>{Cs(e.inputs),e.compute(As(e.inputs),{inputs:[0]})}})),Cl=z((()=>{qu(),el(),tl(),ll(),Ds=e=>{let t=e[0].dataType,n=ht.size(e[0].dims),r=ht.size(e[1].dims),a=r%4===0;return{name:"FastGeluWithBias",shaderCache:{hint:`${a}`,inputDependencies:["type","type"]},getShaderSource:e=>{let n=Nt("x",t,[1],4),r=Nt("bias",t,[1],4),s=Et("y",t,[1],4),i=e=>`\n      let bias${e}_offset: u32 = (global_idx * 4 + ${e}) % uniforms.bias_size;\n      let bias${e} = ${r.getByOffset(`bias${e}_offset / 4`)}[bias${e}_offset % 4];`,o=a?`\n      let bias = ${r.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${i(0)}${i(1)}${i(2)}${i(3)}\n      let bias = ${n.type.value}(bias0, bias1, bias2, bias3);`;return`${e.registerUniforms([{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}]).declareVariables(n,r,s)}\n\n    ${Br(vt(t))}\n\n    ${e.mainStart(bt)}\n      ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n      let x = ${n.getByOffset("global_idx")};\n      ${o}\n      let x_in = x + bias;\n      ${s.setByOffset("global_idx",Wr("x_in"))}\n    }`},getRunData:e=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(n/bt/4)}})}},Fs=e=>{e.inputs.length<2||0===ht.size(e.inputs[1].dims)?Vr(e):e.compute(Ds(e.inputs))}})),Nl=z((()=>{qu(),el(),Ju(),tl(),Ms=e=>{if(!e||2!==e.length)throw new Error("Gather requires 2 inputs.")},Os=(e,t)=>{let n=e[0].dims,r=e[1].dims,a=n.length,s=ht.normalizeAxis(t.axis,a),i=n.slice(0);i.splice(s,1,...r);let o=n[s],u=9===e[0].dataType?4:1,l=Math.ceil(ht.size(i)/u),c=[{type:12,data:l},{type:6,data:o},{type:12,data:s},...kt(e[0].dims,e[1].dims,i)];return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:t=>{let n,o=Nt("data",e[0].dataType,e[0].dims.length,u),l=Nt("inputIndices",e[1].dataType,e[1].dims.length),c=Et("output",e[0].dataType,i.length,u),d=e=>{let t=r.length,n=`var indicesIndices${e}  = ${l.type.indices}(0);`;for(let r=0;r<t;r++)n+=`${t>1?`indicesIndices${e}[${r}]`:`indicesIndices${e}`} = ${i.length>1?`outputIndices${e}[uniforms.axis + ${r}]`:`outputIndices${e}`};`;n+=`\n          var idx${e} = ${l.getByIndices(`indicesIndices${e}`)};\n          if (idx${e} < 0) {\n            idx${e} = idx${e} + uniforms.axisDimLimit;\n          }\n          var dataIndices${e} : ${o.type.indices};\n        `;for(let r=0,o=0;r<a;r++)r===s?(n+=`${a>1?`dataIndices${e}[${r}]`:`dataIndices${e}`} = u32(idx${e});`,o+=t):(n+=`${a>1?`dataIndices${e}[${r}]`:`dataIndices${e}`} = ${i.length>1?`outputIndices${e}[${o}]`:`outputIndices${e}`};`,o++);return n};if(9===e[0].dataType){let e=(e,t,n="")=>`\n          let outputIndices${t} = ${c.offsetToIndices(`outputOffset + ${t}u`)};\n          ${d(t)};\n          let offset${t} = ${o.indicesToOffset(`dataIndices${t}`)};\n          let index${t} = offset${t} / 4u;\n          let component${t} = offset${t} % 4u;\n          ${e}[${t}] = ${n}(${o.getByOffset(`index${t}`)}[component${t}]);\n        `;n=`\n        let outputOffset = global_idx * ${u};\n        var value = vec4<u32>(0);\n        ${e("value",0,"u32")}\n        ${e("value",1,"u32")}\n        ${e("value",2,"u32")}\n        ${e("value",3,"u32")}\n        ${c.setByOffset("global_idx","value")}\n      `}else n=`\n      let outputIndices = ${c.offsetToIndices("global_idx")};\n      ${d("")};\n      let value = ${o.getByIndices("dataIndices")};\n      ${c.setByOffset("global_idx","value")};\n      `;return`\n      ${t.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(o,l,c)}\n      ${t.mainStart()}\n        ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n        ${n}\n      }`}}},zs=e=>ct({axis:e.axis}),Ls=(e,t)=>{let n=e.inputs;Ms(n),e.compute(Os(e.inputs,t))}})),El=z((()=>{qu(),el(),tl(),Ps=(e,t,n,r,a,s,i,o,u)=>{let l=[{type:12,data:s},{type:12,data:r},{type:12,data:a},{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:12,data:u}],c=[s];l.push(...kt(t.dims,c));return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${a.length}_${n.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:l}),getShaderSource:e=>{let r=[Nt("indices_data",t.dataType,t.dims.length),Et("input_slice_offsets_data",12,1,1)],s=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:a.length},{name:"sizes_from_slice_dims_data",type:"u32",length:n.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`\n  ${e.registerUniforms(s).declareVariables(...r)}\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n    let batch_idx = global_idx / uniforms.num_slices_per_batch;\n    let base_offset = batch_idx * uniforms.input_batch_stride;\n\n    let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;\n    var relative_slice_offset = 0;\n    for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {\n      var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);\n      let input_dim_idx = uniforms.batch_dims + dim_idx;\n      if (index < 0) {\n        ${1===a.length?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"}\n      }\n      ${1===n.length?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"}\n    }\n\n    input_slice_offsets_data[global_idx] =  base_offset + u32(relative_slice_offset);\n  }`}},{inputs:[t],outputs:[-1]})[0]},Bs=(e,t)=>{let n=e.inputs,r=n[0].dims,a=n[0].dataType,s=n[1].dims,i=s[s.length-1],o=ht.sizeToDimension(s,s.length-1),u=ht.sizeFromDimension(r,t.batchDims+i),l=ht.sizeToDimension(r,t.batchDims),c=ht.sizeFromDimension(r,t.batchDims),d=o/l,p=new Array(i),h=u;for(let x=0;x<i;++x)p[i-1-x]=h,h*=r[t.batchDims+i-1-x];let f=Ps(e,n[1],p,t.batchDims,r,o,d,c,i),m=t.batchDims+i;if(m>r.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let g=s.slice(0,-1).concat(r.slice(m)),y=ht.size(g),b=[{type:12,data:y},{type:12,data:u},...kt(n[0].dims,f.dims,g)];e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:g,dataType:a}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:b}),getShaderSource:e=>{let t=Nt("data",n[0].dataType,n[0].dims.length),r=Nt("slice_offsets",12,f.dims.length),a=Et("output",n[0].dataType,g.length);return`\n          ${e.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(t,r,a)}\n            ${e.mainStart()}\n            ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n          let slice_offset = slice_offsets[global_idx / uniforms.slice_size];\n          output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];\n        }`}},{inputs:[n[0],f]})},Ws=e=>({batchDims:e.batch_dims,cacheKey:""})})),Al=z((()=>{qu(),el(),Ju(),tl(),Vs=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=ht.normalizeAxis(t.quantizeAxis,e[0].dims.length),r=t.blockSize,a=e[0],s=e[2],i=4===e.length?e[3]:void 0;if(s.dims.length!==a.dims.length||!a.dims.map(((e,t)=>t===n?Math.ceil(e/r)===s.dims[t]:e===s.dims[t])).reduce(((e,t)=>e&&t),!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==a.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==s.dims.length||!i.dims.map(((e,t)=>e===s.dims[t])).reduce(((e,t)=>e&&t),!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Us=(e,t)=>{let n=e[0].dims,r=e[1].dims,a=n.length,s=ht.normalizeAxis(t.gatherAxis,a),i=ht.normalizeAxis(t.quantizeAxis,a),o=n.slice(0);o.splice(s,1,...r);let u=ht.size(o),l=e[2].dataType,c=22===e[0].dataType,d=[{type:12,data:u},{type:12,data:i},{type:12,data:s},{type:12,data:t.blockSize},...kt(...e.map(((e,t)=>e.dims)),o)];return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter(((e,t)=>1!==t)).map((e=>e.dims.join("_"))).join(";")}`,inputDependencies:Array.from({length:e.length},((e,t)=>"rank"))},getRunData:()=>({outputs:[{dims:o,dataType:l}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:t=>{let a=Nt("data",e[0].dataType,e[0].dims.length),i=Nt("inputIndices",e[1].dataType,e[1].dims.length),u=Nt("scales",e[2].dataType,e[2].dims.length),d=e.length>3?Nt("zeroPoint",e[3].dataType,e[3].dims.length):void 0,p=Et("output",l,o.length),h=[a,i,u];d&&h.push(d);return`\n        ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...h,p)}\n        ${t.mainStart()}\n        let output_indices = ${p.offsetToIndices("global_idx")};\n        var indices_indices = ${i.type.indices}(0);\n        ${r.length>1?`\n          for (var i: u32 = 0; i < ${r.length}; i++) {\n            let index = ${p.indicesGet("output_indices","uniforms.gather_axis + i")};\n            ${i.indicesSet("indices_indices","i","index")};\n          }`:`indices_indices = ${p.indicesGet("output_indices","uniforms.gather_axis")};`};\n        var data_indices = ${a.type.indices}(0);\n        for (var i: u32 = 0; i < uniforms.gather_axis; i++) {\n          let index = ${p.indicesGet("output_indices","i")};\n          ${a.indicesSet("data_indices","i","index")};\n        }\n        var index_from_indices = ${i.getByIndices("indices_indices")};\n        if (index_from_indices < 0) {\n          index_from_indices += ${n[s]};\n        }\n        ${a.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};\n        for (var i = uniforms.gather_axis + 1; i < ${o.length}; i++) {\n          let index = ${p.indicesGet("output_indices",`i + ${r.length} - 1`)};\n          ${a.indicesSet("data_indices","i","index")};\n        }\n        let data_offset = ${a.indicesToOffset("data_indices")};\n        let data_index = data_offset % 8;\n        // Convert 4-bit packed data to 8-bit packed data.\n        let packed_4bit_quantized_data = ${a.getByOffset("data_offset / 8")};\n        let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;\n        let quantized_data_vec = ${c?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));\n        let quantized_data = quantized_data_vec[data_index / 2];\n        var scale_indices = data_indices;\n        let quantize_axis_index = ${u.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;\n        ${u.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};\n        var scale = ${u.getByIndices("scale_indices")};\n        ${d?`\n              let zero_point_indices = scale_indices;\n              let zero_point_offset = ${d.indicesToOffset("zero_point_indices")};\n              let zero_point_index = zero_point_offset % 8;\n              let packed_4bit_zero_points = ${d.getByOffset("zero_point_offset / 8")};\n              let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;\n              let zero_point_vec = ${c?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));\n              let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};\n        let dequantized_data = ${vt(l)}(quantized_data - zero_point) * scale;\n        ${p.setByOffset("global_idx","dequantized_data")};\n    }`}}},Gs=(e,t)=>{let n=e.inputs;Vs(n,t),e.compute(Us(e.inputs,t))},Hs=e=>ct({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})})),Rl=z((()=>{qu(),el(),Ju(),tl(),js=e=>{if(!e||2!==e.length)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error("GatherElements requires that the data input and\n                     indices input tensors be of same rank.")},qs=(e,t)=>{let n=e[0].dims,r=e[0].dataType,a=n.length,s=e[1].dims,i=e[1].dataType,o=ht.normalizeAxis(t.axis,a),u=n[o],l=s.slice(0),c=ht.size(l),d=Nt("input",r,a),p=Nt("indicesInput",i,s.length),h=Et("output",r,l.length),f=[{type:12,data:c},{type:6,data:u},{type:12,data:o}];return f.push(...kt(n,s,l)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:f}),getShaderSource:e=>`\n      ${e.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,p,h)}\n      ${e.mainStart()}\n      ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n      let outputIndices = ${h.offsetToIndices("global_idx")};\n\n      var idx = ${p.getByOffset("global_idx")};\n      if (idx < 0) {\n        idx = idx + uniforms.axisDimLimit;\n      }\n      var inputIndices = ${d.type.indices}(outputIndices);\n      ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n      let value = ${d.getByIndices("inputIndices")};\n\n      ${h.setByOffset("global_idx","value")};\n  }`}},Zs=e=>ct({axis:e.axis}),Ks=(e,t)=>{let n=e.inputs;js(n),e.compute(qs(e.inputs,t))}})),Dl=z((()=>{qu(),el(),tl(),Ys=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(3===e.length&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Qs=(e,t)=>{let n=e[0].dims.slice(),r=e[1].dims.slice(),[a,s,i]=mt.getShapeOfGemmResult(n,t.transA,r,t.transB,3===e.length?e[2].dims:void 0),o=[a,s];if(!o)throw new Error("Can't use gemm on the given tensors");let u=16,l=Math.ceil(s/u),c=Math.ceil(a/u),d=(ht.size(o),[{type:12,data:l},{type:12,data:a},{type:12,data:s},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}]),p=["type","type"];3===e.length&&(d.push(...kt(e[2].dims)),p.push("rank")),d.push(...kt(o));return{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:l*c},programUniforms:d}),getShaderSource:n=>{let r=Nt("a",e[0].dataType,e[0].dims),a=Nt("b",e[1].dataType,e[1].dims),s=null,i=[r,a];3===e.length&&(s=Nt("c",e[2].dataType,e[2].dims.length),i.push(s));let l=Et("output",e[0].dataType,o.length);i.push(l);let c="",d="";t.transA&&t.transB?(d=`\n      var col = tile_row_start + local_id.x;\n      var row = k_start + local_id.y;\n      if (col < uniforms.M && row < uniforms.K) {\n        tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n      } else {\n        tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n      }\n\n      col = k_start + local_id.x;\n      row = tile_col_start + local_id.y;\n      if (col < uniforms.K && row < uniforms.N) {\n        tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n      } else {\n        tile_b[local_id.y][local_id.x] = ${a.type.value}(0);\n      }\n      `,c="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(d=`\n      var col = tile_row_start + local_id.x;\n      var row = k_start + local_id.y;\n      if (col < uniforms.M && row < uniforms.K) {\n        tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n      } else {\n        tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n      }\n\n      col = tile_col_start + local_id.x;\n      row = k_start + local_id.y;\n      if (col < uniforms.N && row < uniforms.K) {\n        tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n      } else {\n        tile_b[local_id.y][local_id.x] = ${a.type.value}(0);\n      }\n      `,c="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(d=`\n      var col = k_start + local_id.x;\n      var row = tile_row_start + local_id.y;\n      if (col < uniforms.K && row < uniforms.M) {\n        tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n      } else {\n        tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n      }\n\n      col = k_start + local_id.x;\n      row = tile_col_start + local_id.y;\n      if (col < uniforms.K && row < uniforms.N) {\n        tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n      } else {\n        tile_b[local_id.y][local_id.x] = ${a.type.value}(0);\n      }\n      `,c="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(d=`\n      var col = k_start + local_id.x;\n      var row = tile_row_start + local_id.y;\n      if (col < uniforms.K && row < uniforms.M) {\n        tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n      } else {\n        tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n      }\n\n      col = tile_col_start + local_id.x;\n      row = k_start + local_id.y;\n      if (col < uniforms.N && row < uniforms.K) {\n        tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n      } else {\n        tile_b[local_id.y][local_id.x] = ${a.type.value}(0);\n      }\n      `,c="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let p=1===t.alpha?"":"value *= uniforms.alpha;";return`\n  ${n.registerUniforms([{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}]).declareVariables(...i)}\n  var<workgroup> tile_a: array<array<${r.type.storage}, 16>, 16>;\n  var<workgroup> tile_b: array<array<${a.type.storage}, 16>, 16>;\n  ${n.mainStart([u,u,1])}\n    let tile_col_start = (workgroup_index % uniforms.num_tile_n) * 16;\n    let tile_row_start = (workgroup_index / uniforms.num_tile_n) * 16;\n    let num_tiles = (uniforms.K - 1) / 16 + 1;\n    var k_start = 0u;\n    var value = ${l.type.value}(0);\n    for (var t: u32 = 0u; t < num_tiles; t++) {\n      ${d}\n      k_start = k_start + 16;\n      workgroupBarrier();\n\n      for (var k: u32 = 0u; k < 16; k++) {\n        ${c}\n      }\n      workgroupBarrier();\n    }\n\n    ${p}\n    let m = tile_row_start + local_id.y;\n    let n = tile_col_start + local_id.x;\n    ${null!=s?`let cOffset = ${s.broadcastedIndicesToOffset("vec2(m, n)",l)}; value += ${l.type.value}(uniforms.beta) * ${s.getByOffset("cOffset")};`:""}\n    if (m < uniforms.M && n < uniforms.N) {\n      output[m * uniforms.N + n] = value;\n    }\n  }`}}},Xs=e=>({transA:e.transA,transB:e.transB,alpha:e.alpha,beta:e.beta,cacheKey:`${e.transA};${e.transB};${1===e.alpha}`}),Js=(e,t)=>{Ys(e.inputs),e.compute(Qs(e.inputs,t))}})),Fl=z((()=>{qu(),el(),Ju(),tl(),[ei,ti,ni,ri]=[0,1,2,3],ai=e=>{if(4!==e[0].dims.length)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error("last dimension of grid must be equal to "+(e[0].dims.length-2));if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},si=e=>`\n  fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {\n    var v: vec4<f32>;\n    var coeffs = gs_get_cubic_coeffs(x);\n    for (var i = 0; i < 4; i++) {\n      v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];\n    }\n    coeffs = gs_get_cubic_coeffs(y);\n    let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);\n    return pixel;\n  }\n`,ii=e=>`\n  fn gs_denormalize(n: f32, length: i32) -> f32 {\n    ${0===e.alignCorners?"\n    // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]\n    return ((n + 1.0) * f32(length) - 1.0) / 2.0;\n    ":"\n    // alignCorners: true => [-1, 1] to [0, length - 1]\n    return (n + 1.0) / 2.0 * (f32(length - 1));\n    "}\n  }\n`,oi=e=>`\n  ${"reflection"===e.paddingMode?"\n      fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {\n        var dx = 0.0;\n        var fx = f32(x);\n        let range = x_max - x_min;\n        if (fx < x_min) {\n          dx = x_min - fx;\n          let n = u32(dx / range);\n          let r = dx - f32(n) * range;\n          if (n % 2 == 0) {\n            fx = x_min + r;\n          } else {\n            fx = x_max - r;\n          }\n        } else if (fx > x_max) {\n          dx = fx - x_max;\n          let n = u32(dx / range);\n          let r = dx - f32(n) * range;\n          if (n % 2 == 0) {\n            fx = x_max - r;\n          } else {\n            fx = x_min + r;\n          }\n        }\n        return u32(fx);\n      }":""}\n`,ui=(e,t,n)=>`\n  fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${t} {\n     var pixel = ${t}(0);\n     var indices = vec4<u32>(0);\n     indices[${ei}] = batch;\n     indices[${ti}] = channel;`+(()=>{switch(n.paddingMode){case"zeros":return`\n          if (r >= 0 && r < H && c >=0 && c < W) {\n            indices[${ni}] = u32(r);\n            indices[${ri}] = u32(c);\n          }\n        `;case"border":return`\n          indices[${ni}] = u32(clamp(r, 0, H - 1));\n          indices[${ri}] = u32(clamp(c, 0, W - 1));\n        `;case"reflection":return`\n          indices[${ni}] = gs_reflect(r, border[1], border[3]);\n          indices[${ri}] = gs_reflect(c, border[0], border[2]);\n        `;default:throw new Error(`padding mode ${n.paddingMode} is not supported`)}})()+`\n    return ${e.getByIndices("indices")};\n  }\n`,li=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return`\n          let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ei}], indices[${ti}], border);\n        `;case"bilinear":return`\n          let x1 = i32(floor(x));\n          let y1 = i32(floor(y));\n          let x2 = x1 + 1;\n          let y2 = y1 + 1;\n\n          let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ei}], indices[${ti}], border);\n          let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ei}], indices[${ti}], border);\n          let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ei}], indices[${ti}], border);\n          let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ei}], indices[${ti}], border);\n\n          let dx2 = ${t}(f32(x2) - x);\n          let dx1 = ${t}(x - f32(x1));\n          let dy2 = ${t}(f32(y2) - y);\n          let dy1 = ${t}(y - f32(y1));\n          let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);\n        `;case"bicubic":return`\n          let x0 = i32(floor(x)) - 1;\n          let y0 = i32(floor(y)) - 1;\n          var p: mat4x4<${t}>;\n          for (var h = 0; h < 4; h++) {\n            for (var w = 0; w < 4; w++) {\n              p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ei}], indices[${ti}], border);\n            }\n          }\n\n          let dx = x - f32(x0 + 1);\n          let dy = y - f32(y0 + 1);\n          let result = gs_bicubic_interpolate(p, dx, dy);\n        `;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,ci=(e,t)=>{let n=Nt("x",e[0].dataType,e[0].dims.length),r=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],a=Nt("grid",e[1].dataType,r.length,2),s=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];"NHWC"===t.format&&(s=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[ei,ti,ni,ri]=[0,3,1,2]);let i=Et("output",e[0].dataType,s.length),o=n.type.value,u=[{type:12,data:ht.size(s)},...kt(e[0].dims,r,s)];return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:e=>{let t=ht.size(s);return{outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:u}},getShaderSource:e=>`\n  ${e.registerUniform("output_size","u32").declareVariables(n,a,i)}\n  \n  fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {\n    let cubic_alpha = -0.75f;\n    let x_abs = abs(x);\n    var coeffs: vec4<f32>;\n    coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);\n    coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);\n    coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);\n    coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);\n    return coeffs;\n  }\n\n  ${si(o)}\n  ${ii(t)}\n  ${oi(t)}\n  ${ui(n,o,t)}\n\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n      let H_in = i32(uniforms.x_shape[${ni}]);\n      let W_in = i32(uniforms.x_shape[${ri}]);\n\n      ${0===t.alignCorners?"\n      let x_min = -0.5;\n      let x_max = f32(W_in) - 0.5;\n      let y_min = -0.5;\n      let y_max = f32(H_in) - 0.5;\n      ":"\n      let x_min = 0.0;\n      let x_max = f32(W_in) - 1.0;\n      let y_min = 0.0;\n      let y_max = f32(H_in) - 1.0;\n      "};\n      let border = vec4<f32>(x_min, y_min, x_max, y_max);\n\n      let indices = ${i.offsetToIndices("global_idx")};\n      var grid_indices = vec3<u32>(indices[${ei}], indices[${ni}], indices[${ri}]);\n      let nxy = ${a.getByIndices("grid_indices")};\n      var x = gs_denormalize(f32(nxy[0]), W_in);\n      var y = gs_denormalize(f32(nxy[1]), H_in);\n\n      ${li(i,o,t)}\n  }`}},di=(e,t)=>{ai(e.inputs),e.compute(ci(e.inputs,t))},pi=e=>ct({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})})),Ml=z((()=>{qu(),el(),Ju(),Qu(),il(),tl(),nl(),hi=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,fi=(e,t)=>{let n=e[0],r=hi(e,1),a=hi(e,2),s=hi(e,3),i=hi(e,4),o=hi(e,5),u=hi(e,6),l=hi(e,7);if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let c,d=n.dims[0],p=n.dims[1],h=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],f=p,m=0,g=0,y=Math.floor(h/t.numHeads);if(u&&l&&ht.size(u.dims)&&ht.size(l.dims)){if(4!==u.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==t.numHeads||u.dims[3]!==y)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[0]!==d||l.dims[1]!==t.numHeads||l.dims[3]!==y)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[2]!==l.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(4!==l.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');m=u.dims[2],g=u.dims[2]}else if(u&&ht.size(u.dims)||l&&ht.size(l.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');if(r&&ht.size(r.dims)>0){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===r.dims.length){if(r.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');c=2,f=r.dims[1]}else if(5===r.dims.length){if(r.dims[2]!==t.numHeads||2!==r.dims[3]||r.dims[4]!==y)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');c=5,f=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==y)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');c=0,f=r.dims[2]}}else{if(5!==n.dims.length)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(n.dims[2]!==t.numHeads||3!==n.dims[3])throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');c=3}if(s&&ht.size(s.dims)>0){if(1!==s.dims.length)throw new Error('Input "bias" is expected to have 1 dimension');if(r&&5===r.dims.length&&2===r.dims[3])throw new Error("bias is not allowed for packed kv.")}let b=m+f,x=0;if(i&&ht.size(i.dims)>0){x=8;let e=i.dims;throw 1===e.length?e[0]===d?x=1:e[0]===3*d+2&&(x=3):2===e.length&&e[0]===d&&e[1]===b&&(x=5),8===x?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let w=!1,v=h;if(a&&ht.size(a.dims)>0){if(3!==a.dims.length&&4!==a.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==a.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===a.dims.length){if(f!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');v=a.dims[2]}else{if(f!==a.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');v=a.dims[1]*a.dims[3],w=!0}}if(i&&ht.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(o&&ht.size(o.dims)>0){if(4!==o.dims.length)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(o.dims[0]!==d||o.dims[1]!==t.numHeads||o.dims[2]!==p||o.dims[3]!==b)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:p,pastSequenceLength:m,kvSequenceLength:f,totalSequenceLength:b,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:v,headSize:y,vHeadSize:Math.floor(v/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:w,qkvFormat:c}},mi=e=>ct({...e}),gi=ct({perm:[0,2,1,3]}),yi=(e,t,n,r,a,s,i)=>{let o=[r,a,s],u=ht.size(o),l=[{type:12,data:u},{type:12,data:i},{type:12,data:s}];return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l}),getShaderSource:e=>{let r=Et("qkv_with_bias",t.dataType,o),a=Nt("qkv",t.dataType,o),s=Nt("bias",n.dataType,o);return`\n  ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}]).declareVariables(a,s,r)}\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n    let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n    qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n  }`}},{inputs:[t,n],outputs:[-1]})[0]},bi=(e,t,n,r,a,s,i,o)=>{let u=s;if(i&&ht.size(i.dims)>0){if(1===r)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return u=yi(e,s,i,t,r,n*a,o),u=u.reshape([t,r,n,a]),1===n||1===r?u:e.compute(Wt(u,gi.perm),{inputs:[u],outputs:[-1]})[0]}return 3===s.dims.length&&(u=s.reshape([t,r,n,a])),1===n||1===r?u:e.compute(Wt(u,gi.perm),{inputs:[u],outputs:[-1]})[0]},xi=(e,t)=>{let n=fi(e.inputs,t),r=e.inputs[0],a=hi(e.inputs,1),s=hi(e.inputs,2),i=hi(e.inputs,3),o=hi(e.inputs,4),u=hi(e.inputs,5),l=hi(e.inputs,6),c=hi(e.inputs,7);if(5===r.dims.length)throw new Error("Packed QKV is not implemented");if(5===a?.dims.length)throw new Error("Packed KV is not implemented");let d=a&&s&&4===a.dims.length&&4===s.dims.length,p=bi(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,r,i,0);if(d)return qn(e,p,a,s,o,void 0,l,c,u,n);if(!a||!s)throw new Error("key and value must be provided");let h=bi(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,a,i,n.hiddenSize),f=bi(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,s,i,2*n.hiddenSize);qn(e,p,h,f,o,void 0,l,c,u,n)}})),Ol=z((()=>{qu(),el(),Ju(),tl(),wi=e=>{if(!e||e.length<1)throw new Error("too few inputs")},vi=(e,t)=>{let n=[],r=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach((e=>n.push(Number(e)))),r=n.length),ct({numOutputs:r,axis:t.axis,splitSizes:n})},ki=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n    for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n    if (index < ${$t("uniforms.size_in_split_axis","i",e)}) {\n        return i;\n    }\n    }\n    return ${e}u;\n}`,Si=e=>{let t=e.length,n=[];for(let r=0;r<t;++r){let a=e[r].setByIndices("indices","input[global_idx]");1===t?n.push(a):0===r?n.push(`if (output_number == ${r}u) { ${a} }`):r===t-1?n.push(`else { ${a} }`):n.push(`else if (output_number == ${r}) { ${a} }`)}return`\n      fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {\n        ${n.join("\n")}\n      }`},_i=(e,t)=>{let n=e[0].dims,r=ht.size(n),a=e[0].dataType,s=ht.normalizeAxis(t.axis,n.length),i=new Array(t.numOutputs),o=Nt("input",a,n.length),u=new Array(t.numOutputs),l=[],c=[],d=0,p=[{type:12,data:r}];for(let h=0;h<t.numOutputs;h++){d+=t.splitSizes[h],u[h]=d;let r=n.slice();r[s]=t.splitSizes[h],c.push(r),i[h]=Et(`output${h}`,a,r.length),l.push({dims:c[h],dataType:e[0].dataType})}p.push({type:12,data:u},...kt(n,...c));return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:e=>`\n  ${e.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",u.length).declareVariables(o,...i)}\n  ${ki(u.length)}\n  ${Si(i)}\n\n  ${e.mainStart()}\n    ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n    var indices = ${o.offsetToIndices("global_idx")};\n    var index = ${o.indicesGet("indices",s)};\n    let output_number = calculateOutputIndex(index);\n    if (output_number != 0) {\n      index -= ${$t("uniforms.size_in_split_axis","output_number - 1u",u.length)};\n      ${o.indicesSet("indices",s,"index")};\n    }\n    writeBufferData(output_number, indices, global_idx);\n  }`,getRunData:()=>({outputs:l,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:p})}},Ii=(e,t)=>{wi(e.inputs);let n=1===e.inputs.length?t:vi(e.inputs,t);e.compute(_i(e.inputs,n),{inputs:[0]})},Ti=e=>{let t=e.axis,n=e.splitSizes,r=e.numOutputs<0?n.length:e.numOutputs;if(r!==n.length)throw new Error("numOutputs and splitSizes lengh must be equal");return ct({axis:t,numOutputs:r,splitSizes:n})}})),zl=z((()=>{Ju(),il(),Ml(),Ol(),nl(),$i=(e,t)=>{if(t.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let n=e[0],r=e[1],a=e[2],s=e[3],i=e[4];if(-1!==t.localWindowSize)throw new Error("Local attention is not supported");if(0!==t.softcap)throw new Error("Softcap is not supported");if(0!==t.rotaryInterleaved)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let o=n.dims[0],u=n.dims[1],l=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],c=u,d=0,p=!r||0===r.dims.length,h=Math.floor(p?l/(t.numHeads+2*t.kvNumHeads):l/t.numHeads);p&&(l=h*t.numHeads);let f=s&&0!==s.dims.length,m=i&&0!==i.dims.length;if(f&&4===s.dims.length&&s.dims[0]===o&&s.dims[1]!==t.kvNumHeads&&s.dims[2]===t.kvNumHeads&&s.dims[3]===h)throw new Error("BSNH pastKey/pastValue is not supported");if(f&&m){if(4!==s.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(4!==i.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');d=s.dims[2]}else if(f||m)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g=1;if(r&&r.dims.length>0){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===r.dims.length){if(n.dims[2]%r.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');c=r.dims[1]}else if(5===r.dims.length){if(r.dims[2]!==t.numHeads||2!==r.dims[3]||r.dims[4]!==h)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(a)throw new Error('Expect "value" be none when "key" has packed kv format.');c=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==h)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');c=r.dims[2]}}else{if(3!==n.dims.length&&5!==n.dims.length)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(5===n.dims.length&&(n.dims[2]!==t.numHeads||3!==n.dims[3]))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');g=3}let y=!1,b=t.kvNumHeads?h*t.kvNumHeads:l;if(a&&a.dims.length>0){if(3!==a.dims.length&&4!==a.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==a.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===a.dims.length){if(c!==a.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');b=a.dims[2]}else{if(c!==a.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');b=a.dims[1]*a.dims[3],y=!0}}let x=e.length>4?e[5]:void 0;if(x&&1!==x.dims.length&&x.dims[0]!==o)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:o,sequenceLength:u,pastSequenceLength:d,kvSequenceLength:c,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:l,vHiddenSize:b,headSize:h,vHeadSize:Math.floor(b/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:y,qkvFormat:g}},Ci=ct({perm:[0,2,1,3]}),Ni=(e,t,n)=>{let r=t,a=n.kvNumHeads;return 3===t.dims.length&&0!==n.kvSequenceLength&&(r=t.reshape([n.batchSize,n.kvSequenceLength,a,n.headSize]),r=e.compute(Wt(r,Ci.perm),{inputs:[r],outputs:[-1]})[0]),r},Ei=(e,t)=>{let n=$i(e.inputs,t);if(5===e.inputs[0].dims.length)throw new Error("Packed QKV is not implemented");if(5===e.inputs[1]?.dims.length)throw new Error("Packed KV is not implemented");let r=e.inputs[0],a=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,s=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&0!==e.inputs[3].dims.length?e.inputs[3]:void 0,o=e.inputs[4]&&0!==e.inputs[4].dims.length?e.inputs[4]:void 0,u=e.inputs.length>4?e.inputs[5]:void 0,l=e.inputs.length>5?e.inputs[6]:void 0,c=n.kvNumHeads?n.kvNumHeads:n.numHeads,d=ct({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,c*n.headSize,c*n.headSize]}),[p,h,f]=a||s?[r,a,s]:e.compute(_i([r],d),{inputs:[r],outputs:[-1,-1,-1]}),m=bi(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,p,void 0,0);qn(e,m,Ni(e,h,n),Ni(e,f,n),void 0,void 0,i,o,void 0,n,u,l)}})),Ll=z((()=>{qu(),el(),nl(),tl(),Ai=(e,t,n,r,a,s,i,o)=>{let u=St(s),l=1===u?"f32":`vec${u}f`,c=1===u?"vec2f":`mat2x${u}f`,d=a*i,p=64;1===d&&(p=256);let h=[a,i,s/u],f=[a,i,2],m=[];m.push(...kt(h,f));return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${u};${o};${p}`,inputDependencies:["rank","type","type"]},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:d},programUniforms:m}),getShaderSource:e=>{let a=Nt("x",t.dataType,3,u),s=[a,Nt("scale",n.dataType,n.dims),Nt("bias",r.dataType,r.dims),Et("output",1,3,2)];return`\n  var<workgroup> workgroup_shared : array<${c}, ${p}>;\n  const workgroup_size = ${p}u;\n  ${e.declareVariables(...s)}\n  ${e.mainStart(p)}\n    let batch = workgroup_index / uniforms.x_shape[1];\n    let channel = workgroup_index % uniforms.x_shape[1];\n    let hight = uniforms.x_shape[2];\n    // initialize workgroup memory\n    var sum = ${l}(0);\n    var squared_sum = ${l}(0);\n    for (var h = local_idx; h < hight; h += workgroup_size) {\n      let value = ${l}(${a.get("batch","channel","h")});\n      sum += value;\n      squared_sum += value * value;\n    }\n    workgroup_shared[local_idx] = ${c}(sum, squared_sum);\n    workgroupBarrier();\n\n    for (var currSize = workgroup_size >> 1;  currSize > 0; currSize = currSize >> 1) {\n      if (local_idx < currSize) {\n        workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];\n      }\n      workgroupBarrier();\n    }\n    if (local_idx == 0) {\n      let sum_final = ${Tt("workgroup_shared[0][0]",u)} / f32(hight * ${u});\n      let squared_sum_final = ${Tt("workgroup_shared[0][1]",u)} / f32(hight * ${u});\n\n      let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${o}));\n      let channel_scale = inv_std_dev * f32(scale[channel]);\n      let channel_shift = f32(bias[channel]) - sum_final * channel_scale;\n      output[workgroup_index] = vec2f(channel_scale, channel_shift);\n    }\n  }`}},{inputs:[t,n,r],outputs:[-1]})[0]},Ri=(e,t,n)=>{let r=t[0].dims,a=r,s=r[0],i=r[1],o=ht.sizeFromDimension(r,2),u=St(o),l=ht.size(a)/u,c=Ai(e,t[0],t[1],t[2],s,o,i,n.epsilon),d=[s,i,o/u],p=[s,i];e.compute({name:"InstanceNormalization",shaderCache:{hint:`${u}`,inputDependencies:["type","none"]},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...kt(d,p,d)]}),getShaderSource:e=>{let n=Nt("x",t[0].dataType,d.length,u),r=Nt("scale_shift",1,p.length,2),a=Et("output",t[0].dataType,d.length,u),s=[n,r,a];return`\n  ${e.registerUniform("output_size","u32").declareVariables(...s)}\n  ${e.mainStart()}\n  ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n      let outputIndices = ${a.offsetToIndices("global_idx")};\n      let batch = outputIndices[0];\n      let channel = outputIndices[1];\n      let scale_shift = ${r.getByIndices("vec2<u32>(batch, channel)")};\n      let value = ${n.getByOffset("global_idx")} * ${a.type.value}(scale_shift.x) + ${a.type.value}(scale_shift.y);\n      ${a.setByOffset("global_idx","value")};\n  }`}},{inputs:[t[0],c]})},Di=(e,t,n)=>{let r=t[0].dims,a=r,s=r[0],i=r[r.length-1],o=ht.sizeFromDimension(r,1)/i,u=St(i),l=ht.size(a)/u,c=[{type:12,data:o},{type:12,data:Math.floor(i/u)}],d=!1,p=[0,r.length-1];for(let m=0;m<r.length-2;m++)d=d||1!==r[m+1],p.push(m+1);d=d&&1!==r[r.length-1];let h=d?e.compute(Wt(e.inputs[0],p),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:r.length},((e,t)=>r[p[t]]))),f=Ai(e,h,t[1],t[2],s,o,i,n.epsilon);e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${u}`,inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:e=>{let n=wt(t[0].dataType),r=1===u?"vec2f":`mat${u}x2f`,s=e=>{let t=0===e?"x":"y",r=1===u?"f32":`vec${u}f`;switch(u){case 1:return`${n}(${r}(scale.${t}))`;case 2:return`vec2<${n}>(${r}(scale[0].${t}, scale[1].${t}))`;case 4:return`vec4<${n}>(${r}(scale[0].${t}, scale[1].${t}, scale[2].${t}, scale[3].${t}))`;default:throw new Error(`Not supported compoents ${u}`)}},i=Nt("input",t[0].dataType,t[0].dims,u),o=Et("output",t[0].dataType,a,u);return`\n  @group(0) @binding(0) var<storage, read> input : array<${i.type.storage}>;\n  @group(0) @binding(1) var<storage, read> scale_input : array<${r}>;\n  @group(0) @binding(2) var<storage, read_write> output : array<${o.type.storage}>;\n  struct Uniforms {H: u32, C : u32};\n  @group(0) @binding(3) var<uniform> uniforms: Uniforms;\n\n  ${e.mainStart()}\n    let current_image_number = global_idx / (uniforms.C * uniforms.H);\n    let current_channel_number = global_idx % uniforms.C;\n\n    let scale_offset = current_image_number * uniforms.C + current_channel_number;\n    let scale = scale_input[scale_offset];\n    output[global_idx] = fma(input[global_idx], ${s(0)}, ${s(1)});\n  }`}},{inputs:[t[0],f]})},Fi=(e,t)=>{"NHWC"===t.format?Di(e,e.inputs,t):Ri(e,e.inputs,t)}})),Pl=z((()=>{qu(),el(),tl(),Mi=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Oi=(e,t,n)=>{let r=t.simplified,a=e[0].dims,s=e[1],i=!r&&e[2],o=a,u=ht.normalizeAxis(t.axis,a.length),l=ht.sizeToDimension(a,u),c=ht.sizeFromDimension(a,u),d=ht.size(s.dims),p=i?ht.size(i.dims):0;if(d!==c||i&&p!==c)throw new Error(`Size of X.shape()[axis:] == ${c}.\n       Size of scale and bias (if provided) must match this.\n       Got scale size of ${d} and bias size of ${p}`);let h=[];for(let w=0;w<a.length;++w)w<u?h.push(a[w]):h.push(1);let f=St(c),m=["type","type"],g=[{type:12,data:l},{type:1,data:c},{type:12,data:Math.floor(c/f)},{type:1,data:t.epsilon}];i&&m.push("type");let y=n>1,b=n>2,x=[{dims:o,dataType:e[0].dataType}];return y&&x.push({dims:h,dataType:1}),b&&x.push({dims:h,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${n};${r}`,inputDependencies:m},getRunData:()=>({outputs:x,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:g}),getShaderSource:t=>{let n=wt(e[0].dataType),a=[Nt("x",e[0].dataType,e[0].dims,f),Nt("scale",s.dataType,s.dims,f)];i&&a.push(Nt("bias",i.dataType,i.dims,f)),a.push(Et("output",e[0].dataType,o,f)),y&&a.push(Et("mean_data_output",1,h)),b&&a.push(Et("inv_std_output",1,h));return`\n  ${t.registerUniforms([{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...a)}\n  ${t.mainStart()}\n    ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n    let offset = global_idx * uniforms.norm_size_vectorized;\n    var mean_vector = ${_t("f32",f)};\n    var mean_square_vector = ${_t("f32",f)};\n\n    for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n      let value = ${It(n,f,"x[h + offset]")};\n      mean_vector += value;\n      mean_square_vector += value * value;\n    }\n    let mean = ${Tt("mean_vector",f)} / uniforms.norm_size;\n    let inv_std_dev = inverseSqrt(${Tt("mean_square_vector",f)} / uniforms.norm_size ${r?"":"- mean * mean"} + uniforms.epsilon);\n\n    for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n      let f32input = ${It(n,f,"x[j + offset]")};\n      let f32scale = ${It(n,f,"scale[j]")};\n      output[j + offset] = ${a[0].type.value}((f32input ${r?"":"- mean"}) * inv_std_dev * f32scale\n        ${i?`+ ${It(n,f,"bias[j]")}`:""}\n      );\n    }\n\n    ${y?"mean_data_output[global_idx] = mean":""};\n    ${b?"inv_std_output[global_idx] = inv_std_dev":""};\n  }`}}},zi=(e,t)=>{Mi(e.inputs),e.compute(Oi(e.inputs,t,e.outputCount))}})),Bl=z((()=>{el(),gl(),yl(),Li=e=>{if(!e||2!==e.length)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Pi=e=>{Li(e.inputs);let t=pt.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],r=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&r<8)e.compute(_a(e.inputs,{activation:""},t));else{let a=t[t.length-2],s=ht.size(e.inputs[0].dims.slice(0,-2)),i=ht.size(e.inputs[1].dims.slice(0,-2));if(1!==s&&1===a&&1===i){let a=[1,s,n],i=[e.inputs[0].reshape([1,s,r]),e.inputs[1].reshape([1,r,n])];e.compute(Ra(i,{activation:""},t,a),{inputs:i})}else e.compute(Ra(e.inputs,{activation:""},t))}}})),Wl=z((()=>{qu(),el(),Ju(),tl(),Bi=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],r=n.dims.length;if(n.dims[r-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let a=Math.floor((t.k+t.blockSize-1)/t.blockSize),s=t.blockSize/8*t.bits,i=e[1];if(!ht.areEqual(i.dims,[t.n,a,s]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=e[2].dims;if(ht.size(o)!==t.n*a)throw new Error("scales input size error.");if(4===e.length){let n=e[3].dims,r=t.bits>4?t.n*a:t.n*Math.floor((a+1)/2);if(ht.size(n)!==r)throw new Error("zeroPoints input size error.")}},Wi=(e,t)=>{let n=e[0].dims,r=n.length,a=n[r-2],s=t.k,i=t.n,o=n.slice(0,r-2),u=ht.size(o),l=e[1].dims[2]/4,c=e[0].dataType,d=St(t.k),p=St(l),h=St(i),f=o.concat([a,i]),m=a>1&&i/h%2===0?2:1,g=ht.size(f)/h/m,y=64,b=[],x=[u,a,s/d],w=ht.convertShape(e[1].dims).slice();w.splice(-1,1,l/p),b.push(...kt(x)),b.push(...kt(w)),b.push(...kt(e[2].dims)),4===e.length&&b.push(...kt(ht.convertShape(e[3].dims)));let v=[u,a,i/h];b.push(...kt(v));return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${d};${p};${h};${m};64`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:c}],dispatchGroup:{x:g},programUniforms:b}),getShaderSource:n=>{let r=x.length,a=Nt("a",e[0].dataType,r,d),s=Nt("b",12,w.length,p),i=Nt("scales",e[2].dataType,e[2].dims.length),o=[a,s,i],u=4===e.length?Nt("zero_points",12,e[3].dims.length):void 0;u&&o.push(u);let c=v.length,f=Et("output",e[0].dataType,c,h),g=wt(e[0].dataType),b=(()=>{switch(d){case 1:return`array<${g}, 8>`;case 2:return`mat4x2<${g}>`;case 4:return`mat2x4<${g}>`;default:throw new Error(`${d}-component is not supported.`)}})();return`\n        var<workgroup> workgroup_shared: array<${f.type.value}, ${m*y}>;\n        ${n.declareVariables(...o,f)}\n        ${n.mainStart([y,1,1])}\n          let output_indices = ${f.offsetToIndices(`(global_idx / 64) * ${m}`)};\n          let col = output_indices[2];\n          let row = output_indices[1];\n          let batch = output_indices[0];\n          let nBlocksPerCol = uniforms.b_shape[1];\n\n          for (var block = local_id.x; block < nBlocksPerCol; block += 64) {\n            //process one block\n            var word_offset: u32 = block * ${t.blockSize/d};\n            ${(()=>{let e=`\n            var col_index = col * ${h};\n            ${u?"\n            let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;\n            var zero_point_byte_count: u32;\n            var zero_point_word_index: u32;\n            var zero_point_byte_offset: u32;\n            let zero_point_nibble_offset: u32 = block & 0x1u;\n            var zero_point_bits_offset: u32;\n            var zero_point_word: u32;":`\n            // The default zero point is 8 for unsigned 4-bit quantization.\n            let zero_point = ${g}(8);`}\n            `;for(let t=0;t<h*m;t++)e+=`\n            let scale${t} = ${i.getByOffset("col_index * nBlocksPerCol + block")};\n            ${u?`\n            zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u);\n            zero_point_word_index = zero_point_byte_count >> 0x2u;\n            zero_point_byte_offset = zero_point_byte_count & 0x3u;\n            zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n            zero_point_word = ${u.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;\n            let zero_point${t} = ${g}((zero_point_word) & 0xFu);`:""}\n            col_index += 1;`;return e})()}\n            for (var word: u32 = 0; word < ${l}; word += ${p}) {\n              ${(()=>{let e=`col_index = col * ${h};`;for(let t=0;t<h*m;t++)e+=`\n            let b${t}_data = ${s.getByIndices(`${s.type.indices}(col_index, block, word)`)};\n            col_index += 1;`;return e+=`\n            var b_value: u32;\n            let b_mask: u32 = 0x0F0F0F0Fu;\n            var b_value_lower: vec4<u32>;\n            var b_value_upper: vec4<u32>;\n            var b_quantized_values: ${b};\n            var b_dequantized_values: ${b};`,e})()}\n              for (var i: u32 = 0; i < ${p}; i++) {\n                ${(()=>{let e=`\n          // reuse a data\n            var input_offset = ${a.indicesToOffset(`${a.type.indices}(batch, row, word_offset)`)};\n            var a_data: ${b};\n            for (var j: u32 = 0; j < ${8/d}; j++) {\n              a_data[j] = ${a.getByOffset("input_offset")};\n              input_offset++;\n            }\n          `;for(let t=0;t<h*m;t++)e+=`\n            b_value = ${1===p?`b${t}_data`:`b${t}_data[i]`};\n            b_value_lower = unpack4xU8(b_value & b_mask);\n            b_value_upper = unpack4xU8((b_value >> 4) & b_mask);\n            b_quantized_values = ${b}(${Array.from({length:4},((e,t)=>`${g}(b_value_lower[${t}]), ${g}(b_value_upper[${t}])`)).join(", ")});\n            b_dequantized_values = ${1===d?`${b}(${Array.from({length:8},((e,n)=>`(b_quantized_values[${n}] - ${u?`zero_point${t}`:"zero_point"}) * scale${t}`)).join(", ")});`:`(b_quantized_values - ${b}(${Array(8).fill(""+(u?`zero_point${t}`:"zero_point")).join(",")})) * scale${t};`};\n            workgroup_shared[local_id.x * ${m} + ${Math.floor(t/h)}]${h>1?`[${t%h}]`:""} += ${Array.from({length:8/d},((e,t)=>""+(1===d?`a_data[${t}] * b_dequantized_values[${t}]`:`dot(a_data[${t}], b_dequantized_values[${t}])`))).join(" + ")};\n          `;return e})()}\n                word_offset += ${8/d};\n              }\n            }\n          }\n          workgroupBarrier();\n\n          if (local_id.x < ${m}) {\n            var output_value: ${f.type.value} = ${f.type.value}(0);\n            var workgroup_shared_offset: u32 = local_id.x;\n            for (var b: u32 = 0u; b < 64u; b++) {\n              output_value += workgroup_shared[workgroup_shared_offset];\n              workgroup_shared_offset += ${m};\n            }\n            ${f.setByIndices(`${f.type.indices}(batch, row, col + local_id.x)`,"output_value")};\n          }\n        }`}}},Vi=(e,t)=>{let n=e[0].dims,r=n.length,a=n[r-2],s=t.k,i=t.n,o=n.slice(0,r-2),u=ht.size(o),l=e[1].dims[2]/4,c=e[0].dataType,d=St(t.k),p=St(l),h=o.concat([a,i]),f=i%8===0?8:i%4===0?4:1,m=128/f,g=m*p*8,y=g/d,b=g/t.blockSize,x=ht.size(h)/f,w=[],v=[u,a,s/d],k=ht.convertShape(e[1].dims).slice();k.splice(-1,1,l/p),w.push(...kt(v)),w.push(...kt(k)),w.push(...kt(e[2].dims)),4===e.length&&w.push(...kt(ht.convertShape(e[3].dims)));let S=[u,a,i];w.push(...kt(S));return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${d};${p};${m};${f}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:h,dataType:c}],dispatchGroup:{x:x},programUniforms:w}),getShaderSource:n=>{let r=v.length,a=Nt("a",e[0].dataType,r,d),s=Nt("b",12,k.length,p),i=Nt("scales",e[2].dataType,e[2].dims.length),o=[a,s,i],u=4===e.length?Nt("zero_points",12,e[3].dims.length):void 0;u&&o.push(u);let l=S.length,c=Et("output",e[0].dataType,l),h=wt(e[0].dataType);return`\n        var<workgroup> sub_a: array<${a.type.value}, ${y}>;\n        var<workgroup> inter_results: array<array<${c.type.value}, ${m}>, ${f}>;\n        ${n.declareVariables(...o,c)}\n        ${n.mainStart([m,f,1])}\n          let output_indices = ${c.offsetToIndices(`workgroup_index * ${f}`)};\n          let col = output_indices[2];\n          let row = output_indices[1];\n          let batch = output_indices[0];\n          let n_blocks_per_col = uniforms.b_shape[1];\n          let num_tiles =  (n_blocks_per_col - 1) / ${b} + 1;\n\n          // Loop over shared dimension.\n          for (var tile: u32 = 0; tile < num_tiles; tile += 1) {\n            let a_col_start = tile * ${y};\n            // load one tile A data into shared memory.\n            for (var a_offset = local_idx; a_offset < ${y}; a_offset += 128)\n            {\n              let a_col = a_col_start + a_offset;\n              if (a_col < uniforms.a_shape[2])\n              {\n                sub_a[a_offset] = ${a.getByIndices(`${a.type.indices}(batch, row, a_col)`)};\n              } else {\n                sub_a[a_offset] = ${a.type.value}(0);\n              }\n            }\n            workgroupBarrier();\n\n            // each thread process one block\n            let b_row = col + local_id.y;\n            let block = tile * ${b} + local_id.x;\n            ${u?`\n            let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;\n            let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);\n            let zero_point_word_index = zero_point_byte_count >> 0x2u;\n            let zero_point_byte_offset = zero_point_byte_count & 0x3u;\n            let zero_point_nibble_offset: u32 = block & 0x1u;\n            let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n            let zero_point_word = ${u.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;\n            let zero_point = ${h}((zero_point_word) & 0xFu);`:`\n            // The default zero point is 8 for unsigned 4-bit quantization.\n            let zero_point = ${h}(8);`}\n            let scale = ${i.getByOffset("b_row * n_blocks_per_col + block")};\n            let b_data = ${s.getByIndices(`${s.type.indices}(b_row, block, 0)`)};\n            var word_offset = local_id.x * ${t.blockSize/d};\n            for (var i: u32 = 0; i < ${p}; i++) {\n              ${(()=>{switch(d){case 1:return`\n          let a_data0 = vec4<${h}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);\n          let a_data1 = vec4<${h}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`\n          let a_data0 = vec4<${h}>(sub_a[word_offset], sub_a[word_offset + 1]);\n          let a_data1 = vec4<${h}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return"\n          let a_data0 = sub_a[word_offset];\n          let a_data1 = sub_a[word_offset + 1];";default:throw new Error(`${d}-component is not supported.`)}})()}\n              let b_value = ${1===p?"b_data":"b_data[i]"};\n              let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);\n              let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);\n              let b_quantized_values = mat2x4<${h}>(${Array.from({length:4},((e,t)=>`${h}(b_value_lower[${t}]), ${h}(b_value_upper[${t}])`)).join(", ")});\n              let b_dequantized_values = (b_quantized_values - mat2x4<${h}>(${Array(8).fill("zero_point").join(",")})) * scale;\n              inter_results[local_id.y][local_id.x] += ${Array.from({length:2},((e,t)=>`dot(a_data${t}, b_dequantized_values[${t}])`)).join(" + ")};\n              word_offset += ${8/d};\n            }\n            workgroupBarrier();\n          }\n\n          if (local_idx < ${f}) {\n            var output_value: ${c.type.value} = ${c.type.value}(0);\n            for (var b = 0u; b < ${m}; b++) {\n              output_value += inter_results[local_idx][b];\n            }\n            if (col + local_idx < uniforms.output_shape[2])\n            {\n              ${c.setByIndices(`${c.type.indices}(batch, row, col + local_idx)`,"output_value")}\n            }\n          }\n        }`}}},Ui=(e,t)=>{Bi(e.inputs,t),32===t.blockSize&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Vi(e.inputs,t)):e.compute(Wi(e.inputs,t))},Gi=e=>ct(e)})),Vl=z((()=>{qu(),el(),tl(),Hi=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(1!==e[0].dataType&&10!==e[0].dataType)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=2*e[0].dims.length===e[1].dims[0];if(4===e.length&&(t=2*e[3].dims[0]===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},ji=(e,t,n)=>{let r="";for(let a=t-1;a>=0;--a)r+=`\n            k = i32(${e.indicesGet("indices",a)}) - ${$t("uniforms.pads",a,n)};\n            if (k < 0) {\n              break;\n            }\n            if (k >= i32(${$t("uniforms.x_shape",a,t)})) {\n              break;\n            }\n            offset += k * i32(${$t("uniforms.x_strides",a,t)});\n        `;return`\n          value = ${e.type.value}(uniforms.constant_value);\n          for (var i = 0; i < 1; i++) {\n            var offset = 0;\n            var k = 0;\n            ${r}\n            value = x[offset];\n          }\n      `},qi=(e,t,n)=>{let r="";for(let a=t-1;a>=0;--a)r+=`\n                k = i32(${e.indicesGet("indices",a)}) - ${$t("uniforms.pads",a,n)};\n                if (k < 0) {\n                  k = -k;\n                }\n                {\n                  let _2n_1 = 2 * (i32(${$t("uniforms.x_shape",a,t)}) - 1);\n                  k = k % _2n_1;\n                  if(k >= i32(${$t("uniforms.x_shape",a,t)})) {\n                    k = _2n_1 - k;\n                  }\n                }\n                offset += k * i32(${$t("uniforms.x_strides",a,t)});\n            `;return`\n              var offset = 0;\n              var k = 0;\n              ${r}\n              value = x[offset];\n          `},Zi=(e,t,n)=>{let r="";for(let a=t-1;a>=0;--a)r+=`\n                k = i32(${e.indicesGet("indices",a)}) - ${$t("uniforms.pads",a,n)};\n                if (k < 0) {\n                  k = 0;\n                }\n                if (k >= i32(${$t("uniforms.x_shape",a,t)})) {\n                  k = i32(${$t("uniforms.x_shape",a,t)}) - 1;\n                }\n                offset += k * i32(${$t("uniforms.x_strides",a,t)});\n            `;return`\n              var offset = 0;\n              var k = 0;\n              ${r}\n              value = x[offset];\n          `},Ki=(e,t,n)=>{let r="";for(let a=t-1;a>=0;--a)r+=`\n                k = i32(${e.indicesGet("indices",a)}) - ${$t("uniforms.pads",a,n)};\n                if (k < 0)  {\n                  k += i32(${$t("uniforms.x_shape",a,t)}]);\n                }\n                if (k >= i32(${$t("uniforms.x_shape",a,t)})) {\n                  k -= i32(${$t("uniforms.x_shape",a,t)});\n                }\n                offset += k * i32(${$t("uniforms.x_strides",a,t)});\n            `;return`\n              var offset = 0;\n              var k = 0;\n              ${r}\n              value = x[offset];\n          `},Yi=(e,t,n)=>{switch(n.mode){case 0:return ji(e,t,n.pads.length);case 1:return qi(e,t,n.pads.length);case 2:return Zi(e,t,n.pads.length);case 3:return Ki(e,t,n.pads.length);default:throw new Error("Invalid mode")}},Qi=(e,t)=>{let n=ht.padShape(e[0].dims.slice(),t.pads),r=e[0].dims,a=[{type:12,data:ht.size(n)},{type:6,data:t.pads}],s=e.length>=3&&e[2].data;0===t.mode&&a.push({type:s?e[2].dataType:1,data:t.value}),a.push(...kt(e[0].dims,n));return{name:"Pad",shaderCache:{hint:`${t.mode}${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ht.size(n)/64)},programUniforms:a}),getShaderSource:a=>{let i=Et("output",e[0].dataType,n.length),o=Nt("x",e[0].dataType,r.length),u=o.type.value,l=Yi(i,r.length,t),c=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return 0===t.mode&&c.push({name:"constant_value",type:s?u:"f32"}),`\n            ${a.registerUniforms(c).declareVariables(o,i)}\n            ${a.mainStart()}\n            ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n            let indices = ${i.offsetToIndices("global_idx")};\n\n            var value = ${u}(0);\n            ${l}\n            output[global_idx] = value;\n        }`}}},Xi=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?10===e[2].dataType?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,a=e[0].dims.length,s=new Int32Array(2*a).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;e<t.length;e++)s[Number(t[e])]=Number(n[e]),s[Number(t[e])+a]=Number(n[e+t.length])}else n.forEach(((e,t)=>s[Number(t)]=Number(e)));let i=[];return s.forEach((e=>i.push(e))),{mode:t.mode,value:r,pads:i}}return t},Ji=(e,t)=>{Hi(e.inputs);let n=Xi(e.inputs,t);e.compute(Qi(e.inputs,n),{inputs:[0]})}})),Ul=z((()=>{se(),qu(),el(),tl(),eo=e=>{if(l.webgpu.validateInputContent&&(!e||1!==e.length))throw new Error("Pool ops requires 1 input.")},to=(e,t,n)=>{let r="NHWC"===t.format,a=e.dims.slice();r&&a.splice(1,0,a.pop());let s=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),o=t.strides.slice(),u=s?t.dilations.slice():[],l=t.pads.slice();ft.adjustPoolAttributes(n,a,i,o,u,l);let c=ft.computePoolOutputShape(n,a,o,u,i,l,t.autoPad),d=Object.assign({},t);s?Object.assign(d,{kernelShape:i,strides:o,pads:l,dilations:u,cacheKey:t.cacheKey}):Object.assign(d,{kernelShape:i,strides:o,pads:l,cacheKey:t.cacheKey});let p=c.slice();return p.push(p.splice(1,1)[0]),[d,r?p:c]},no=(e,t)=>{let n="NHWC"===t.format,r=[{type:12,data:ht.size(e)},{type:12,data:ht.size(t.kernelShape)}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let e=t.kernelShape[t.kernelShape.length-1],n=t.strides[t.strides.length-1],s=t.pads[t.pads.length/2-1],i=t.pads[t.pads.length-1],o=!!(s+i);r.push({type:12,data:e},{type:12,data:n},{type:12,data:s},{type:12,data:i}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(2===t.kernelShape.length){let e=t.kernelShape[t.kernelShape.length-2],n=t.strides[t.strides.length-2],s=t.pads[t.pads.length/2-2],i=t.pads[t.pads.length-2];u=!!(s+i),r.push({type:12,data:e},{type:12,data:n},{type:12,data:s},{type:12,data:i}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[r,a,!0,o,u]}{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let e=ht.computeStrides(t.kernelShape);return r.push({type:12,data:e},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:e.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length}),[r,a,!!t.pads.reduce(((e,t)=>e+t)),!1,!1]}},ro=(e,t,n,r,a,s,i,o,u,l,c,d)=>{let p="NHWC"===a.format,h=t.type.value,f=Et("output",t.type.tensor,r);if(a.kernelShape.length<=2){let r="",l="",m="",g=n-(p?2:1);if(r=c?`\n                for (var i: u32 = 0u; i < uniforms.kw; i++) {\n                  xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n                  if (xIndices[${g}] < 0 || xIndices[${g}]\n                      >= uniforms.x_shape[${g}]) {\n                    pad++;\n                    continue;\n                  }\n                  let x_val = x[${t.indicesToOffset("xIndices")}];\n                  ${s}\n                }`:`\n                for (var i: u32 = 0u; i < uniforms.kw; i++) {\n                  xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n                  let x_val = x[${t.indicesToOffset("xIndices")}];\n                  ${s}\n                }`,2===a.kernelShape.length){let e=n-(p?3:2);l=d?`\n                for (var j: u32 = 0u; j < uniforms.kh; j++) {\n                  xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n                  if (xIndices[${e}] < 0 || xIndices[${e}] >= uniforms.x_shape[${e}]) {\n                    pad += i32(uniforms.kw);\n                    continue;\n                  }\n              `:`\n                for (var j: u32 = 0u; j < uniforms.kh; j++) {\n                  xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n                `,m="\n              }\n            "}return`\n            ${e.registerUniforms(u).declareVariables(t,f)}\n\n            ${e.mainStart()}\n              ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n              let indices = ${f.offsetToIndices("global_idx")};\n              var xIndices = ${f.offsetToIndices("global_idx")};\n\n              var value = ${h}(${o});\n              var pad = 0;\n              ${l}\n              ${r}\n              ${m}\n              ${i}\n\n              output[global_idx] = value;\n            }`}{if(p)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let r=a.kernelShape.length,c=a.pads.length,d="";return d=l?`\n                if (xIndices[j] >= uniforms.x_shape[j]) {\n                  pad++;\n                  isPad = true;\n                  break;\n                }\n              }\n              if (!isPad) {\n                let x_val = x[${t.indicesToOffset("xIndices")}];\n                ${s}\n              }`:`\n              }\n              let x_val = x[${t.indicesToOffset("xIndices")}];\n              ${s}\n            `,`\n            ${e.registerUniforms(u).declareVariables(t,f)}\n\n            ${e.mainStart()}\n              ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n              let indices = ${f.offsetToIndices("global_idx")};\n              var xIndices = ${f.offsetToIndices("global_idx")};\n\n              var offsets: array<u32, ${r}>;\n\n              var value = ${h}(${o});\n              var pad = 0;\n              var isPad = false;\n\n              for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n                var offset = i;\n                for (var j = 0u; j < ${r-1}u; j++) {\n                  offsets[j] = offset / ${$t("uniforms.kernelStrides","j",r)};\n                  offset -= offsets[j] * ${$t("uniforms.kernelStrides","j",r)};\n                }\n                offsets[${r-1}] = offset;\n\n                isPad = false;\n                for (var j = ${n-r}u; j < ${n}u; j++) {\n                  xIndices[j] = indices[j] * ${$t("uniforms.strides",`j - ${n-r}u`,r)}\n                    + offsets[j - ${n-r}u] - ${$t("uniforms.pads","j - 2u",c)};\n                  ${d}\n              }\n              ${i}\n\n              output[global_idx] = value;\n            }`}},ao=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,so=e=>`${ao(e)};${e.countIncludePad}`,io=e=>`${ao(e)};${e.storageOrder};${e.dilations}`,oo=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),uo=(e,t,n,r)=>{let[a,s]=to(t,r,n),i=Nt("x",t.dataType,t.dims.length),o=i.type.value,u="";a.countIncludePad?u+=`value /= ${o}(uniforms.kernelSize);`:u+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[l,c,d,p,h]=no(s,a);l.push(...kt(t.dims,s));return{name:e,shaderCache:{hint:`${r.cacheKey};${d};${p};${h}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ht.size(s)/64)},programUniforms:l}),getShaderSource:e=>ro(e,i,t.dims.length,s.length,a,"value += x_val;",u,0,c,d,p,h)}},lo=e=>{let t=0!==e.count_include_pad,n=oo(e);if(0!==n.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let r={countIncludePad:t,...n,cacheKey:""};return{...r,cacheKey:so(r)}},co=(e,t)=>{eo(e.inputs),e.compute(uo("AveragePool",e.inputs[0],!1,t))},po={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ho=e=>{let t=e.format;return{format:t,...po,cacheKey:t}},fo=(e,t)=>{eo(e.inputs),e.compute(uo("GlobalAveragePool",e.inputs[0],!0,t))},mo=(e,t,n,r)=>{let[a,s]=to(t,r,n),i=Nt("x",t.dataType,t.dims.length),[o,u,l,c,d]=no(s,a);return o.push(...kt(t.dims,s)),{name:e,shaderCache:{hint:`${r.cacheKey};${l};${c};${d}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ht.size(s)/64)},programUniforms:o}),getShaderSource:e=>ro(e,i,t.dims.length,s.length,a,"\n      value = max(x_val, value);\n    ","",10===t.dataType?-65504:-1e5,u,l,c,d)}},go=(e,t)=>{eo(e.inputs),e.compute(mo("MaxPool",e.inputs[0],!1,t))},yo=e=>{let t=e.storage_order,n=e.dilations,r=oo(e);if(0!==t)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==r.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let a={storageOrder:t,dilations:n,...r,cacheKey:""};return{...a,cacheKey:io(a)}},bo=e=>{let t=e.format;return{format:t,...po,cacheKey:t}},xo=(e,t)=>{eo(e.inputs),e.compute(mo("GlobalMaxPool",e.inputs[0],!0,t))}})),Gl=z((()=>{qu(),el(),Ju(),tl(),wo=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(3===e.length&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(6===e[0].dataType&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(0!==e[1].dims.length&&1!==e[1].dims.length&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map(((t,n)=>t===e[2].dims[n])).reduce(((e,t)=>e&&t),!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(0===e[1].dims.length||1===e[1].dims.length&&1===e[1].dims[0])throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map(((n,r)=>r===t.axis||n===e[0].dims[r])).reduce(((e,t)=>e&&t),!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let n=e[0].dims[t.axis],r=e[1].dims[t.axis];if(t.blockSize<Math.ceil(n/r)||t.blockSize>Math.ceil(n/(r-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},vo=(e,t)=>{let n=ht.normalizeAxis(t.axis,e[0].dims.length),r=e[0].dataType,a=3===r,s=e[0].dims,i=e[1].dataType,o=ht.size(s),u=3===r||2===r,l=u?[Math.ceil(ht.size(e[0].dims)/4)]:e[0].dims,c=e[1].dims,d=e.length>2?e[2]:void 0,p=d?u?[Math.ceil(ht.size(d.dims)/4)]:d.dims:void 0,h=0===c.length||1===c.length&&1===c[0],f=!1===h&&1===c.length,m=St(o),g=h&&(!u||4===m),y=g?m:1,b=g&&!u?m:1,x=Nt("input",u?12:r,l.length,b),w=Nt("scale",i,c.length),v=d?Nt("zero_point",u?12:r,p.length):void 0,k=Et("output",i,s.length,y),S=[x,w];v&&S.push(v);let _=[l,c];d&&_.push(p);let I=[{type:12,data:o/y},{type:12,data:n},{type:12,data:t.blockSize},...kt(..._,s)];return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:v?["rank","rank","rank"]:["rank","rank"]},getShaderSource:e=>`\n      ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...S,k)}\n      ${e.mainStart()}\n          ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n          let output_indices = ${k.offsetToIndices("global_idx")};\n\n          // Set input x\n          ${u?`\n            let input = ${x.getByOffset("global_idx / 4")};\n            let x_vec = ${a?"unpack4xI8(input)":"unpack4xU8(input)"};\n            let x_value = ${1===y?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${x.getByOffset("global_idx")};`};\n\n          // Set scale input\n          ${h?`let scale_value= ${w.getByOffset("0")}`:f?`\n            let scale_index = ${k.indicesGet("output_indices","uniforms.axis")};\n            let scale_value= ${w.getByOffset("scale_index")};`:`\n            var scale_indices: ${w.type.indices} = output_indices;\n            let index = ${w.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;\n            ${w.indicesSet("scale_indices","uniforms.axis","index")};\n            let scale_value= ${w.getByIndices("scale_indices")};`};\n\n          // Set zero-point input\n          ${v?h?u?`\n                let zero_point_input = ${v.getByOffset("0")};\n                let zero_point_vec =  ${a?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n                let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${v.getByOffset("0")}`:f?u?`\n                let zero_point_index = ${k.indicesGet("output_indices","uniforms.axis")};\n                let zero_point_input = ${v.getByOffset("zero_point_index / 4")};\n                let zero_point_vec =  ${a?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n                let zero_point_value = zero_point_vec[zero_point_index % 4]`:`\n                let zero_point_index = ${k.indicesGet("output_indices","uniforms.axis")};\n                let zero_point_value = ${v.getByOffset("zero_point_index")};`:u?`\n                let zero_point_offset = ${w.indicesToOffset("scale_indices")};\n                let zero_point_input = ${v.getByOffset("zero_point_offset / 4")};\n                let zero_point_vec = ${a?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n                let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${v.getByIndices("scale_indices")};`:`let zero_point_value = ${u?a?"i32":"u32":x.type.value}(0);`};\n      // Compute and write output\n      ${k.setByOffset("global_idx",`${k.type.value}(x_value - zero_point_value) * scale_value`)};\n      }`,getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(o/y/64),y:1,z:1},programUniforms:I})}},ko=(e,t)=>{wo(e.inputs,t),e.compute(vo(e.inputs,t))},So=e=>ct({axis:e.axis,blockSize:e.blockSize})})),Hl=z((()=>{se(),qu(),tl(),_o=(e,t,n)=>{if(e===t||e<t&&n<0||e>t&&n>0)throw new Error("Range these inputs' contents are invalid.")},Io=(e,t,n,r)=>{let a=Math.abs(Math.ceil((t-e)/n)),s=[a],i=a,o=[{type:12,data:i},{type:r,data:e},{type:r,data:n},...kt(s)];return{name:"Range",shaderCache:{hint:`${r}`},getShaderSource:e=>{let t=Et("output",r,s.length),n=t.type.value,a=[{name:"outputSize",type:"u32"},{name:"start",type:n},{name:"delta",type:n}];return`\n        ${e.registerUniforms(a).declareVariables(t)}\n        ${e.mainStart()}\n        ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n        output[global_idx] = uniforms.start + ${n}(global_idx) * uniforms.delta;\n      }`},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:o})}},To=e=>{let t=0,n=0,r=0;6===e.inputs[0].dataType?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],r=e.inputs[2].getInt32Array()[0]):1===e.inputs[0].dataType&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],r=e.inputs[2].getFloat32Array()[0]),l.webgpu.validateInputContent&&_o(t,n,r),e.compute(Io(t,n,r,e.inputs[0].dataType),{inputs:[]})}})),jl=z((()=>{qu(),el(),Ju(),tl(),$o=(e,t,n,r)=>{if("none"!==e&&"i32"!==r&&"u32"!==r&&"f32"!==r)throw new Error(`Input ${r} is not supported with reduction ${e}.`);let a="{\n                var oldValue = 0;\n                loop {\n                  let newValueF32 =",s=`;\n                  let newValue = bitcast<i32>(newValueF32);\n                  let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);\n                  if res.exchanged {\n                    break;\n                  }\n                  oldValue = res.old_value;\n                }\n              }`;switch(e){case"none":return`${t}=${n};`;case"add":return"i32"===r||"u32"===r?`atomicAdd(&${t}, bitcast<${r}>(${n}));`:`\n              ${a}bitcast<${r}>(oldValue) + (${n})${s}`;case"max":return"i32"===r||"u32"===r?`atomicMax(&${t}, bitcast<${r}>(${n}));`:`\n                ${a}max(bitcast<f32>(oldValue), (${n}))${s}`;case"min":return"i32"===r||"u32"===r?`atomicMin(&${t}, bitcast<${r}>(${n}));`:`${a}min(bitcast<${r}>(oldValue), (${n}))${s}`;case"mul":return`${a}(bitcast<${r}>(oldValue) * (${n}))${s}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Co=(e,t)=>{let n=e[0].dims,r=e[1].dims,a=n,s=Math.ceil(ht.size(r)/1),i=r[r.length-1],o=ht.sizeFromDimension(n,i),u=[{type:12,data:s},{type:12,data:i},{type:12,data:o},...kt(e[1].dims,e[2].dims,a)];return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u}),getShaderSource:n=>{let s=Nt("indices",e[1].dataType,e[1].dims.length),i=Nt("updates",e[2].dataType,e[2].dims.length,1),o="none"!==t.reduction&&""!==t.reduction?At("output",e[0].dataType,a.length):Et("output",e[0].dataType,a.length,1);return`\n      ${n.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(s,i,o)}\n      ${n.mainStart()}\n        ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n  var hasDuplicates = false;\n  if (${"none"===t.reduction}) {\n    let n = ${ht.size(r)};\n    for (var i = 0; i < n; i = i + 1) {\n      for (var j = i + 1; j < n; j = j + 1) {\n        var index_i = i32(indices[i].x);\n        var index_j = i32(indices[j].x);\n        if (index_i == index_j) {\n          hasDuplicates = true;\n          break;\n        }\n      }\n      if (hasDuplicates) {\n        break;\n      }\n    }\n  }\n\n  var data_offset = 0u;\n  var indices_start = uniforms.last_index_dimension * global_idx;\n  if (${"none"===t.reduction} && hasDuplicates) {\n    if (global_idx != 0u) {\n      return;\n    }\n    indices_start = 0u;\n  }\n  let indices_end = indices_start + uniforms.last_index_dimension;\n  for (var i = indices_start; i < indices_end; i++) {\n    var index = i32(indices[i].x);\n    ${1===e[0].dims.length?"\n    let element_count_dim = uniforms.output_strides;\n    let dim_value = uniforms.output_shape;":"\n    let element_count_dim = uniforms.output_strides[i - indices_start];\n    let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];"}\n    if (index >= 0) {\n      if (index >= i32(dim_value)) {\n        index = i32(dim_value - 1);\n      }\n    } else {\n      if (index < -i32(dim_value)) {\n        index = 0;\n      } else {\n        index += i32(dim_value);\n      }\n    }\n    data_offset += u32((u32(index) * element_count_dim));\n  }\n\n  for (var i = 0u; i < uniforms.num_updates_elements; i++) {\n    let value = updates[uniforms.num_updates_elements * global_idx + i];\n    ${$o(t.reduction,"output[data_offset + i]","value",o.type.value)}\n  }\n\n      }`}}},No=e=>ct({reduction:e.reduction}),Eo=(e,t)=>{e.compute(Co(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}})),ql=z((()=>{qu(),el(),Ju(),tl(),Ao=(e,t)=>{if(e.every((e=>e>0||(()=>{throw new Error("Resize requires scales input values to be positive")}))),e.length>0)if("linear"===t.mode){if(!(2===e.length||3===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]||5===e.length&&1===e[0]&&1===e[1]))throw new Error("For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n            one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1")}else if("cubic"===t.mode&&!(2===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")},Ro=(e,t,n)=>{t.every((e=>e>=0&&e<n||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")})));let r=new Array(n).fill(1);return t.forEach(((t,n)=>r[t]=e[n])),r},Do=(e,t,n,r,a,s)=>{let[i,o,u]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],l=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach((e=>s.push(e)));else if("tf_crop_and_resize"===t.coordinateTransformMode)throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(o>0&&e.length>o&&1===e[o].dims.length&&e[o].dims[0]>0){if(e[o].getFloat32Array().forEach((e=>r.push(e))),0!==r.length&&r.length!==l&&n>=18&&r.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Ao(r,t),t.axes.length>0&&Ro(r,t.axes,l).forEach(((e,t)=>r[t]=e))}if(u>0&&e.length>u&&1===e[u].dims.length&&e[u].dims[0]>0&&(e[u].getBigInt64Array().forEach((e=>a.push(Number(e)))),0!==a.length&&a.length!==l&&n>=18&&a.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(0!==r.length&&r.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(0!==a.length&&a.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof r<"u"&&typeof a<"u"&&r.length>0&&a.length>l)throw new Error("Resize requires only of scales or sizes to be specified")},Fo=(e,t,n,r)=>`\n  // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n  // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n  // offset-by-one error later in floor().\n  let big = (${e}) * (${t});\n  let whole = ${r}(big / (${n}));\n  let fract = ${r}(big % (${n})) / ${r}(${n});\n  return whole + fract;\n`,Mo=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n     lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`\n          if (xScale < 1.0 || floor(xScale) != xScale) {\n            return ${t}(xResized) / ${t}(xScale);\n          } else {\n            ${Fo("xResized","lengthOriginal","lengthResized",t)}\n          }\n        `;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n                    return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n                  } else {\n                    return 0.0;\n                  }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n                    return 0.0;\n                  } else {\n                    ${Fo("xResized","lengthOriginal - 1","lengthResized - 1",t)}\n                  }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n                    return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n                        (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n                        ${t}(lengthResized - 1);\n                  } else {\n                    return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n                  }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n                  const adjustment = ${t}(lengthResized) / outputWidth;\n                  const center = ${t}(lengthOriginal) / 2;\n                  const offset = center * (1 - adjustment);\n                  return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Oo=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) {             return ceil(xOriginal);           } else {             return round(xOriginal);           }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) {                     return floor(xOriginal);                   } else {                     return round(xOriginal);                   }";default:if(t<11)return"if (isDownSample)                     {                       return ceil(xOriginal);                     } else {                       return xOriginal;                     }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",zo=(e,t,n)=>{let r=new Array(n).fill(0).concat(new Array(n).fill(1)),a=0===e.length?r:e.slice();return t.length>0?(t.forEach(((e,s)=>{r[e]=a[s],r[s+n]=a[t.length+s]})),r):a},Lo=(e,t,n,r)=>{let a=[];if(n.length>0)if(r.length>0){if(e.forEach((e=>a.push(e))),Math.max(...r)>e.length)throw new Error("axes is out of bound");r.forEach(((e,t)=>a[e]=n[t]))}else n.forEach((e=>a.push(e)));else{if(0===t.length)throw new Error("Resize requires either scales or sizes.");a=e.map(((e,n)=>Math.round(e*t[n])))}return a},Po=(e,t,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map((e=>t[e])),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map((e=>t[e])),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let a=e.slice();return n.axes.length>0?(n.axes.forEach((e=>t[e]=r)),n.axes.forEach((n=>a[n]=Math.round(e[n]*t[n])))):(t.fill(r,0,t.length),a.forEach(((e,n)=>a[n]=Math.round(e*t[n])))),a},Bo=(e,t,n,r,a)=>`\n    fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {\n      var original_indices: array<${e.type.value}, ${n.length}>;\n      for (var i:u32 = 0; i < ${n.length}; i++) {\n        var output_index = ${e.indicesGet("output_indices","i")};\n        var scale = ${$t("uniforms.scales","i",r)};\n        var roi_low = ${$t("uniforms.roi","i",a)};\n        var roi_hi = ${$t("uniforms.roi",`i + ${t.length}`,a)};\n        if (scale == 1.0) {\n          original_indices[i] = ${e.type.value}(output_index);\n        } else {\n          var input_shape_i = ${$t("uniforms.input_shape","i",t.length)};\n          var output_shape_i = ${$t("uniforms.output_shape","i",n.length)};\n          original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n                                                                           input_shape_i, roi_low, roi_hi);\n        }\n      }\n      return original_indices;\n    }`,Wo=(e,t,n,r,a,s,i)=>`\n    fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n      var input_indices: ${e.type.indices};\n      for (var i:u32 = 0; i < ${r.length}; i++) {\n        var output_index = ${t.indicesGet("output_indices","i")};\n        var input_index: u32;\n        var scale = ${$t("uniforms.scales","i",a)};\n        if (scale == 1.0) {\n          input_index = output_index;\n        } else {\n          var roi_low = ${$t("uniforms.roi","i",s)};\n          var roi_hi = ${$t("uniforms.roi",`i + ${n.length}`,s)};\n          var input_shape_i = ${$t("uniforms.input_shape","i",n.length)};\n          var output_shape_i = ${$t("uniforms.output_shape","i",r.length)};\n          var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n                                                                        input_shape_i, roi_low, roi_hi);\n          if (!${i} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n            if (original_idx < 0) {\n              input_index = 0;\n            } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n              input_index = input_shape_i - 1;\n            } else {\n              input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n            }\n          } else {\n            input_index = u32(original_idx);\n          }\n        }\n        ${e.indicesSet("input_indices","i","input_index")}\n      }\n      return input_indices;\n    }`,Vo=(e,t)=>`\n    fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n      for (var i:u32 = 0; i < ${t.length}; i++) {\n        var input_index = ${e.indicesGet("input_indices","i")};\n        if (input_index < 0 || input_index >= ${$t("uniforms.input_shape","i",t.length)}) {\n          return false;\n        }\n      }\n      return true;\n    }`,Uo=(e,t,n,r)=>e.rank>r?`\n    ${e.indicesSet("input_indices",t,"channel")};\n    ${e.indicesSet("input_indices",n,"batch")};\n`:"",Go=(e,t,n,r,a)=>{let[s,i,o,u]=2===n.length?[-1,0,1,-1]:[0,2,3,1],l=e.type.value;return`\n    fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${l} {\n      var input_indices: ${e.type.indices};\n      ${e.indicesSet("input_indices",i,`max(0, min(row, ${n[i]} - 1))`)};\n      ${e.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)};\n      ${Uo(e,u,s,2)}\n      return ${e.getByIndices("input_indices")};\n    }\n\n    fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${l} {\n      var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n      var row:${l} = originalIndices[${i}];\n      var col:${l} = originalIndices[${o}];\n      ${r?`if (row < 0 || row > (${n[i]} - 1) || col < 0 || col > (${n[o]} - 1)) {\n        return ${a};\n      }`:""};\n      row = max(0, min(row, ${n[i]} - 1));\n      col = max(0, min(col, ${n[o]} - 1));\n      var row1: u32 = u32(row);\n      var col1: u32 = u32(col);\n      var row2: u32 = u32(row + 1);\n      var col2: u32 = u32(col + 1);\n      var channel: u32 = ${n.length>2?`u32(originalIndices[${u}])`:"0"};\n      var batch: u32 =  ${n.length>2?`u32(originalIndices[${s}])`:"0"};\n      var x11: ${l} = getInputValue(batch, channel, row1, col1);\n      var x12: ${l} = getInputValue(batch, channel, row1, col2);\n      var x21: ${l} = getInputValue(batch, channel, row2, col1);\n      var x22: ${l} = getInputValue(batch, channel, row2, col2);\n      var dx1: ${l} = abs(row - ${l}(row1));\n      var dx2: ${l} = abs(${l}(row2) - row);\n      var dy1: ${l} = abs(col - ${l}(col1));\n      var dy2: ${l} = abs(${l}(col2) - col);\n      if (row1 == row2) {\n        dx1 = 0.5;\n        dx2 = 0.5;\n      }\n      if (col1 == col2) {\n        dy1 = 0.5;\n        dy2 = 0.5;\n      }\n      return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n    }`},Ho=(e,t,n,r,a,s,i,o,u,l)=>{let c=2===n.length,[d,p]=c?[0,1]:[2,3],h=e.type.value,f=i=>{let c=i===d?"row":"col";return`\n      fn ${c}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${h} {\n        var output_index = ${t.indicesGet("output_indices",i)};\n        var originalIdx: ${h} = getOriginalCoordinateFromResizedCoordinate(output_index, ${a[i]},\n        ${r[i]}, ${n[i]}, ${s[i]}, ${s[i]} + ${n.length});\n        var fractOriginalIdx: ${h} = originalIdx - floor(originalIdx);\n        var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n        if (${o} && (originalIdx < 0 || originalIdx > (${n[i]} - 1))) {\n          return ${u};\n        }\n        var data: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0);\n        for (var i: i32 = -1; i < 3; i++) {\n          var ${c}: ${h} = originalIdx + ${h}(i);\n          if (${c} < 0 || ${c} >= ${n[i]}) {\n            ${l?"coefs[i + 1] = 0.0;\n                        continue;":o?`return ${u};`:`${c} = max(0, min(${c}, ${n[i]} - 1));`};\n          }\n        var input_indices_copy: ${e.type.indices} = input_indices;\n          ${e.indicesSet("input_indices_copy",i,`u32(${c})`)};\n          data[i + 1] = ${i===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n        }\n        return cubicInterpolation1D(data, coefs);\n      }`};return`\n    ${f(d)};\n    ${f(p)};\n  fn getCubicInterpolationCoefs(s: ${h}) -> array<${h}, 4> {\n    var absS = abs(s);\n    var coeffs: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0);\n    var oneMinusAbsS: ${h} = 1.0 - absS;\n    var twoMinusAbsS: ${h} = 2.0 - absS;\n    var onePlusAbsS: ${h} = 1.0 + absS;\n    coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i};\n    coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1;\n    coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n    coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i};\n    return coeffs;\n  }\n\n  fn cubicInterpolation1D(x: array<${h}, 4>, coefs: array<${h}, 4>) -> ${h} {\n    var coefsSum: ${h} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n    return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n  }\n\n  fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${h} {\n    var input_indices: ${e.type.indices} = output_indices;\n    return colCubicInterpolation(input_indices, output_indices);\n  }\n    `},jo=(e,t,n,r,a)=>{let[s,i,o,u,l]=3===n.length?[-1,0,1,2,-1]:[0,2,3,4,1],c=e.type.value;return`\n    fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${c} {\n      var input_indices: ${e.type.indices};\n      ${e.indicesSet("input_indices",i,`max(0, min(depth, ${n[i]} - 1))`)};\n      ${e.indicesSet("input_indices",o,`max(0, min(height, ${n[o]} - 1))`)};\n      ${e.indicesSet("input_indices",u,`max(0, min(width, ${n[u]} - 1))`)};\n      ${Uo(e,l,s,3)}\n      return ${e.getByIndices("input_indices")};\n    }\n\n    fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${c} {\n      var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n      var depth:${c} = originalIndices[${i}];\n      var height:${c} = originalIndices[${o}];\n      var width:${c} = originalIndices[${u}];\n      ${r?`if (depth < 0 || depth > (${n[i]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[u]} - 1)) {\n      return ${a};\n        }`:""};\n\n    depth = max(0, min(depth, ${n[i]} - 1));\n      height = max(0, min(height, ${n[o]} - 1));\n      width = max(0, min(width, ${n[u]} - 1));\n      var depth1: u32 = u32(depth);\n      var height1: u32 = u32(height);\n      var width1: u32 = u32(width);\n      var depth2: u32 = u32(depth + 1);\n      var height2: u32 = u32(height + 1);\n      var width2: u32 = u32(width + 1);\n      var channel: u32 = ${n.length>3?`u32(originalIndices[${l}])`:"0"};\n      var batch: u32 =  ${n.length>3?`u32(originalIndices[${s}])`:"0"};\n\n      var x111: ${c} = getInputValue(batch, channel, depth1, height1, width1);\n      var x112: ${c} = getInputValue(batch, channel, depth1, height1, width2);\n      var x121: ${c} = getInputValue(batch, channel, depth1, height2, width1);\n      var x122: ${c} = getInputValue(batch, channel, depth1, height2, width2);\n      var x211: ${c} = getInputValue(batch, channel, depth2, height1, width1);\n      var x212: ${c} = getInputValue(batch, channel, depth2, height1, width2);\n      var x221: ${c} = getInputValue(batch, channel, depth2, height2, width1);\n      var x222: ${c} = getInputValue(batch, channel, depth2, height2, width2);\n      var dx1: ${c} = abs(depth - ${c}(depth1));\n      var dx2: ${c} = abs(${c}(depth2) - depth);\n      var dy1: ${c} = abs(height - ${c}(height1));\n      var dy2: ${c} = abs(${c}(height2) - height);\n      var dz1: ${c} = abs(width - ${c}(width1));\n      var dz2: ${c} = abs(${c}(width2) - width);\n      if (depth1 == depth2) {\n        dx1 = 0.5;\n        dx2 = 0.5;\n      }\n      if (height1 == height2) {\n        dy1 = 0.5;\n        dy2 = 0.5;\n      }\n      if (width1 == width2) {\n        dz1 = 0.5;\n        dz2 = 0.5;\n      }\n      return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n              x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n    }`},qo=(e,t,n,r,a,s)=>{let i=e.dims,o=zo(s,t.axes,i.length),u=Lo(i,r,a,t.axes),l=r.slice();0===r.length&&(l=i.map(((e,t)=>0===e?1:u[t]/e)),"stretch"!==t.keepAspectRatioPolicy&&(u=Po(i,l,t)));let c=Et("output",e.dataType,u.length),d=Nt("input",e.dataType,i.length),p=ht.size(u),h=i.length===u.length&&i.every(((e,t)=>e===u[t])),f="tf_crop_and_resize"===t.coordinateTransformMode,m=t.extrapolationValue,g=d.type.value;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${l.length>0?"cubic"===t.mode?l:l.length:""}|${a.length>0?a:""}|${o.length>0?o:""}|${h}|${"nearest"===t.mode?i.length:i}`,inputDependencies:["rank"]},getShaderSource:e=>`\n      ${h?"":`\n      ${Mo(t.coordinateTransformMode,g)};\n      ${(()=>{switch(t.mode){case"nearest":return`\n              ${Vo(d,i)};\n              ${Oo(t.nearestMode,n,g)};\n              ${Wo(d,c,i,u,l.length,o.length,f)};\n              `;case"linear":return`\n              ${Bo(c,i,u,l.length,o.length)};\n              ${(()=>{if(2===i.length||4===i.length)return`${Go(d,c,i,f,m)}`;if(3===i.length||5===i.length)return`${jo(d,c,i,f,m)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n            `;case"cubic":return`\n            ${(()=>{if(2===i.length||4===i.length)return`${Ho(d,c,i,u,l,o,t.cubicCoeffA,f,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n            `;default:throw Error("Invalid resize mode")}})()};\n      `}\n      ${e.registerUniform("output_size","u32").registerUniform("scales","f32",l.length).registerUniform("roi","f32",o.length).declareVariables(d,c)}\n      ${e.mainStart()}\n        ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n        ${h?"output[global_idx] = input[global_idx];":`\n        let output_indices = ${c.offsetToIndices("global_idx")};\n        var input_indices: ${d.type.indices};\n        ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n                if (checkInputIndices(input_indices)) {\n                  output[global_idx] = ${d.getByIndices("input_indices")};\n                } else {\n                  output[global_idx] = ${t.extrapolationValue};\n                }`;case"linear":return`output[global_idx] = ${2===i.length||4===i.length?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n      }`,getRunData:()=>({outputs:[{dims:u,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},{type:1,data:l},{type:1,data:o},...kt(i,u)]})}},Zo=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Ko=(e,t)=>{let n=[],r=[],a=[],s=Zo(e);if(0!==t.antialias)throw Error("Only default value (0) for Antialias attribute is supported");Do(e.inputs,t,s,n,r,a),e.compute(qo(e.inputs[0],t,s,n,r,a),{inputs:[0]})},Yo=e=>{let t=e.antialias,n=e.axes,r=e.coordinateTransformMode,a=e.cubicCoeffA,s=0!==e.excludeOutside,i=e.extrapolationValue,o=e.keepAspectRatioPolicy,u=e.mode,l=""===e.nearestMode?"simple":e.nearestMode;return ct({antialias:t,axes:n,coordinateTransformMode:r,cubicCoeffA:a,excludeOutside:s,extrapolationValue:i,keepAspectRatioPolicy:o,mode:u,nearestMode:l})}})),Zl=z((()=>{qu(),el(),Ju(),tl(),Qo=(e,t)=>{let[n,r,a,s]=e,{numHeads:i,rotaryEmbeddingDim:o}=t;if(3!==n.dims.length&&4!==n.dims.length)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!ht.areEqual(r.dims,[])&&!ht.areEqual(r.dims,[1])&&2!==r.dims.length)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${r.dims.length}`);if(2!==a.dims.length)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(2!==s.dims.length)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(!ht.areEqual(a.dims,s.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(o>0&&0===i)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let u=n.dims[0],l=n.dims[n.dims.length-2],c=a.dims[0],d=ht.sizeFromDimension(n.dims,1)/l,p=0===o?2*a.dims[1]:d/i;if(o>p)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(2===r.dims.length){if(u!==r.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${r.dims[0]}`);if(l!==r.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${r.dims[1]}`)}if(p/2!==a.dims[1]&&o/2!==a.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${a.dims[1]}`);if(l>c)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Xo=(e,t)=>{let{interleaved:n,numHeads:r,rotaryEmbeddingDim:a,scale:s}=t,i=e[0].dims[0],o=ht.sizeFromDimension(e[0].dims,1),u=e[0].dims[e[0].dims.length-2],l=o/u,c=e[2].dims[1],d=0===a?2*c:l/r,p=new Array(i,u,l/d,d-c),h=ht.computeStrides(p),f=[{type:1,data:s},{type:12,data:p},{type:12,data:h},...3===e[0].dims.length?new Array({type:12,data:[o,l,d,1]}):[],...4===e[0].dims.length?new Array({type:12,data:[o,d,u*d,1]}):[],...kt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)];return{name:"RotaryEmbedding",shaderCache:{hint:ct({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:t=>{let r=Nt("input",e[0].dataType,e[0].dims.length),a=Nt("position_ids",e[1].dataType,e[1].dims.length),s=Nt("cos_cache",e[2].dataType,e[2].dims.length),i=Nt("sin_cache",e[3].dataType,e[3].dims.length),o=Et("output",e[0].dataType,e[0].dims.length);return t.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:p.length},{name:"global_strides",type:"u32",length:h.length},{name:"input_output_strides",type:"u32",length:h.length}]),`\n        ${t.declareVariables(r,a,s,i,o)}\n\n        ${t.mainStart(bt)}\n          let half_rotary_emb_dim = uniforms.${s.name}_shape[1];\n          let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n          let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n          ${t.guardAgainstOutOfBoundsWorkgroupSizes("size")}\n\n          if (bsnh[3] < half_rotary_emb_dim) {\n            let position_ids_idx =\n                ${a.broadcastedIndicesToOffset("bsnh.xy",Et("",a.type.tensor,2))};\n            let position_id =\n                u32(${a.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);\n            let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${n});\n            let j = i + select(half_rotary_emb_dim, 1, ${n});\n            let re = ${r.getByOffset("i")} * ${s.get("position_id","bsnh[3]")} -\n                ${r.getByOffset("j")} * ${i.get("position_id","bsnh[3]")};\n            ${o.setByOffset("i","re")}\n            let im = ${r.getByOffset("i")} * ${i.get("position_id","bsnh[3]")} +\n                ${r.getByOffset("j")} * ${s.get("position_id","bsnh[3]")};\n            ${o.setByOffset("j","im")}\n          } else {\n            let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n            ${o.setByOffset("k",r.getByOffset("k"))}\n          }\n        }`},getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ht.size(p)/bt)},programUniforms:f})}},Jo=(e,t)=>{Qo(e.inputs,t),e.compute(Xo(e.inputs,t))}})),Kl=z((()=>{qu(),el(),tl(),eu=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],r=e[2];if(t.dataType!==n.dataType||t.dataType!==r.dataType)throw new Error("All inputs must have the same data type");if(3!==t.dims.length&&2!==t.dims.length)throw new Error("Input must be 2D or 3D");if(3!==n.dims.length&&2!==n.dims.length)throw new Error("Skip must be 2D or 3D");let a=t.dims[t.dims.length-1],s=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==a)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==s)throw new Error("Skip must have the same sequence length as input");if(1!==r.dims.length)throw new Error("Gamma must be 1D");if(r.dims[r.dims.length-1]!==a)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let t=e[3];if(1!==t.dims.length)throw new Error("Beta must be 1D");if(t.dims[t.dims.length-1]!==a)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let t=e[4];if(1!==t.dims.length)throw new Error("Bias must be 1D");if(t.dims[t.dims.length-1]!==a)throw new Error("Bias must have the same hidden size as input")}},tu=(e,t,n,r)=>{let a=t.simplified,s=e[0].dims,i=ht.size(s),o=s,u=i,l=s.slice(-1)[0],c=r?s.slice(0,-1).concat(1):[],d=!a&&e.length>3,p=e.length>4,h=r&&n>1,f=r&&n>2,m=n>3,g=64,y=St(l),b=[{type:12,data:u},{type:12,data:y},{type:12,data:l},{type:1,data:t.epsilon}],x=[{dims:o,dataType:e[0].dataType}];return n>1&&x.push({dims:c,dataType:1}),n>2&&x.push({dims:c,dataType:1}),n>3&&x.push({dims:s,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${y};${h};${f};${m}`,inputDependencies:e.map(((e,t)=>"type"))},getShaderSource:t=>{let n=[Nt("x",e[0].dataType,e[0].dims,y),Nt("skip",e[1].dataType,e[1].dims,y),Nt("gamma",e[2].dataType,e[2].dims,y)];d&&n.push(Nt("beta",e[3].dataType,e[3].dims,y)),p&&n.push(Nt("bias",e[4].dataType,e[4].dims,y)),n.push(Et("output",e[0].dataType,o,y)),h&&n.push(Et("mean_output",1,c)),f&&n.push(Et("inv_std_output",1,c)),m&&n.push(Et("input_skip_bias_sum",e[0].dataType,o,y));let r=wt(e[0].dataType),s=wt(1,y);return`\n\n      ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...n)}\n      var<workgroup> sum_shared : array<${s}, 64>;\n      var<workgroup> sum_squared_shared : array<${s}, 64>;\n\n      ${t.mainStart([g,1,1])}\n        let ix = local_id.x;\n        let iy = global_id.x / 64;\n\n        let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n        var stride = hidden_size_vectorized / 64;\n        let offset = ix * stride + iy * hidden_size_vectorized;\n        let offset1d = stride * ix;\n        if (ix == 63) {\n          stride = hidden_size_vectorized - stride * ix;\n        }\n        for (var i: u32 = 0; i < stride; i++) {\n          let skip_value = skip[offset + i];\n          let bias_value = ${p?"bias[offset1d + i]":r+"(0.0)"};\n          let input_value = x[offset + i];\n          let value = input_value + skip_value + bias_value;\n          ${m?"input_skip_bias_sum[offset + i] = value;":""}\n          output[offset + i] = value;\n          let f32_value = ${It(r,y,"value")};\n          sum_shared[ix] += f32_value;\n          sum_squared_shared[ix] += f32_value * f32_value;\n        }\n        workgroupBarrier();\n\n        var reduce_size : u32 = 64;\n        for (var curr_size = reduce_size >> 1;  curr_size > 0; curr_size = reduce_size >> 1) {\n          reduce_size = curr_size + (reduce_size & 1);\n          if (ix < curr_size) {\n            sum_shared[ix] += sum_shared[ix + reduce_size];\n            sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];\n          }\n          workgroupBarrier();\n        }\n\n        let sum = sum_shared[0];\n        let square_sum = sum_squared_shared[0];\n        let mean = ${Tt("sum",y)} / f32(uniforms.hidden_size);\n        let inv_std_dev = inverseSqrt(${Tt("square_sum",y)} / f32(uniforms.hidden_size) ${a?"":"- mean * mean"} + uniforms.epsilon);\n        ${h?"mean_output[global_idx] = mean;":""}\n        ${f?"inv_std_output[global_idx] = inv_std_dev;":""}\n\n        for (var i: u32 = 0; i < stride; i++) {\n          output[offset + i] = (output[offset + i] ${a?"":`- ${r}(mean)`}) *\n            ${r}(inv_std_dev) * gamma[offset1d + i]\n            ${d?"+ beta[offset1d + i]":""};\n        }\n      }`},getRunData:()=>({outputs:x,dispatchGroup:{x:Math.ceil(u/l)},programUniforms:b})}},nu=(e,t)=>{eu(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(tu(e.inputs,t,e.outputCount,!1),{outputs:n})}})),Yl=z((()=>{qu(),el(),Ju(),tl(),ru=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(0!==t.axes.length){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach(((t,n)=>{if(6!==e[n+1].dataType&&7!==e[n+1].dataType)throw new Error(`Input ${n} must be an array of int32 or int64`)}))},au=(e,t)=>{let n=[];if(e.length>t)if(7===e[t].dataType)e[t].getBigInt64Array().forEach((e=>n.push(Number(e))));else{if(6!==e[t].dataType)throw new Error(`Input ${t} must be an array of int32 or int64`);e[t].getInt32Array().forEach((e=>n.push(Number(e))))}return n},su=(e,t)=>{if(e.length>1){let t=au(e,1),n=au(e,2),r=au(e,3);return 0===r.length&&(r=[...Array(e[0].dims.length).keys()]),ct({starts:t,ends:n,axes:r})}return t},iu=(e,t,n,r,a)=>{let s=e;return e<0&&(s+=n[r[t]]),a[t]<0?Math.max(0,Math.min(s,n[r[t]]-1)):Math.max(0,Math.min(s,n[r[t]]))},ou=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n          var input_indices: ${e.type.indices};\n          var carry = 0u;\n          for (var i = ${n.length}; i >= 0; i--) {\n            let input_shape_i = ${$t("uniforms.input_shape","i",n.length)};\n            let steps_i = ${$t("uniforms.steps","i",n.length)};\n            let signs_i = ${$t("uniforms.signs","i",n.length)};\n            let starts_i = ${$t("uniforms.starts","i",n.length)};\n            var output_index = ${t.indicesGet("output_indices","i")};\n            var input_index = output_index * steps_i + starts_i + carry;\n            carry = input_index / input_shape_i;\n            input_index = input_index % input_shape_i;\n            if (signs_i < 0) {\n              input_index = input_shape_i - input_index - 1u + starts_i;\n            }\n            ${e.indicesSet("input_indices","i","input_index")};\n          }\n          return input_indices;\n      }`,uu=(e,t)=>{let n=e[0].dims,r=ht.size(n),a=t.axes.length>0?ht.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],s=au(e,4);s.forEach((e=>0!==e||(()=>{throw new Error("step cannot be 0")}))),0===s.length&&(s=Array(a.length).fill(1));let i=t.starts.map(((e,t)=>iu(e,t,n,a,s))),o=t.ends.map(((e,t)=>iu(e,t,n,a,s)));if(a.length!==i.length||a.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(a.length!==n.length)for(let g=0;g<n.length;++g)a.includes(g)||(i.splice(g,0,0),o.splice(g,0,n[g]),s.splice(g,0,1));let u=s.map((e=>Math.sign(e)));s.forEach(((e,t,n)=>{if(e<0){let r=(o[t]-i[t])/e,a=i[t],u=a+r*s[t];i[t]=u,o[t]=a,n[t]=-e}}));let l=n.slice(0);a.forEach(((e,t)=>{l[e]=Math.ceil((o[e]-i[e])/s[e])}));let c={dims:l,dataType:e[0].dataType},d=Et("output",e[0].dataType,l.length),p=Nt("input",e[0].dataType,e[0].dims.length),h=ht.size(l),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:u.length},{name:"steps",type:"u32",length:s.length}],m=[{type:12,data:h},{type:12,data:i},{type:6,data:u},{type:12,data:s},...kt(e[0].dims,l)];return{name:"Slice",shaderCache:{hint:`${u.length}_${i.length}_${s.length}`,inputDependencies:["rank"]},getShaderSource:e=>`\n      ${e.registerUniforms(f).declareVariables(p,d)}\n        ${ou(p,d,n)}\n        ${e.mainStart()}\n          ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n          let output_indices = ${d.offsetToIndices("global_idx")};\n          let input_indices = calculateInputIndices(output_indices);\n          ${d.setByOffset("global_idx",p.getByIndices("input_indices"))}\n      }`,getRunData:()=>({outputs:[c],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:m})}},lu=(e,t)=>{ru(e.inputs,t);let n=su(e.inputs,t);e.compute(uu(e.inputs,n),{inputs:[0]})},cu=e=>{let t=e.starts,n=e.ends,r=e.axes;return ct({starts:t,ends:n,axes:r})}})),Ql=z((()=>{qu(),el(),Ju(),nl(),tl(),du=e=>{if(!e||1!==e.length)throw new Error("Softmax op requires 1 input.")},pu=(e,t)=>{let n,r=e.inputs[0],a=r.dims,s=ht.size(a),i=a.length,o=ht.normalizeAxis(t.axis,i),u=o<a.length-1,l=[];u?(l=Array.from({length:i},((e,t)=>t)),l[o]=i-1,l[i-1]=o,n=e.compute(Wt(r,l),{inputs:[r],outputs:[-1]})[0]):n=r;let c=n.dims,d=c[i-1],p=s/d,h=St(d),f=d/h,m=64;1===p&&(m=256);let g=Nt("x",n.dataType,n.dims,h),y=Et("result",n.dataType,n.dims,h),b=g.type.value,x="f32"===wt(n.dataType)?`var threadMax = ${b}(-3.402823e+38f);`:`var threadMax = ${b}(-65504.0h);`,w=e.compute({name:"Softmax",shaderCache:{hint:`${h};${m}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:c,dataType:n.dataType}],dispatchGroup:{x:p},programUniforms:[{type:6,data:f}]}),getShaderSource:e=>`\n      var<workgroup> rowMaxShared : ${b};\n      var<workgroup> rowSumShared : ${b};\n      var<workgroup> threadShared : array<${b}, ${m}>;\n\n      fn getValue(row: i32, col: i32, row_stride: i32) -> ${b} {\n        let index = row * row_stride + col;\n        return x[index];\n      }\n\n      fn setValue(row: i32, col: i32, row_stride: i32, value: ${b}) {\n        let index = row * row_stride + col;\n        result[index] = value;\n      }\n      ${e.registerUniform("packedCols","i32").declareVariables(g,y)}\n      ${e.mainStart(m)}\n        let gindex = i32(global_idx);\n        let lindex = i32(local_idx);\n        const wg = ${m};\n        let row = gindex / wg;\n        let cols = uniforms.packedCols;\n        let row_stride : i32 = uniforms.packedCols;\n\n        // find the rows max\n        ${x}\n        for (var col = lindex; col < cols; col += wg) {\n          let value = getValue(row, col, row_stride);\n          threadMax = max(threadMax, value);\n        }\n        if (lindex < cols) {\n          threadShared[lindex] = threadMax;\n        }\n        workgroupBarrier();\n\n        var reduceSize = min(cols, wg);\n        for (var currSize = reduceSize >> 1;  currSize > 0; currSize = reduceSize >> 1) {\n          reduceSize = currSize + (reduceSize & 1);\n          if (lindex < currSize) {\n            threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n          }\n          workgroupBarrier();\n        }\n        if (lindex == 0) {\n          rowMaxShared = ${b}(${((e,t)=>4===t?`max(max(${e}.x, ${e}.y), max(${e}.z, ${e}.w))`:2===t?`max(${e}.x, ${e}.y)`:3===t?`max(max(${e}.x, ${e}.y), ${e}.z)`:e)("threadShared[0]",h)});\n        }\n        workgroupBarrier();\n\n        // find the rows sum\n        var threadSum = ${b}(0.0);\n        for (var col = lindex; col < cols; col += wg) {\n          let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n          threadSum += subExp;\n        }\n        threadShared[lindex] = threadSum;\n        workgroupBarrier();\n\n        for (var currSize = wg >> 1;  currSize > 0; currSize = currSize >> 1) {\n          if (lindex < currSize) {\n            threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n          }\n          workgroupBarrier();\n        }\n        if (lindex == 0) {\n          rowSumShared = ${b}(${Tt("threadShared[0]",h)});\n        }\n        workgroupBarrier();\n\n        // calculate final value for each element in the row\n        for (var col = lindex; col < cols; col += wg) {\n          let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n          setValue(row, col, row_stride, value);\n        }\n      }`},{inputs:[n],outputs:[u?-1:0]})[0];u&&e.compute(Wt(w,l),{inputs:[w]})},hu=(e,t)=>{du(e.inputs),pu(e,t)},fu=e=>ct({axis:e.axis})})),Xl=z((()=>{qu(),el(),tl(),mu=e=>Array.from(e.getBigInt64Array(),Number),gu=e=>{if(!e||2!==e.length)throw new Error("Tile requires 2 inputs.");if(1!==e[0].dataType&&10!==e[0].dataType&&6!==e[0].dataType&&12!==e[0].dataType)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(7!==e[1].dataType)throw new Error("Tile `repeats` input should be of int64 data type");if(1!==e[1].dims.length)throw new Error("Tile `repeats` input should be 1-D");if(mu(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},yu=(e,t)=>{let n=[];for(let r=0;r<e.length;++r)n.push(e[r]*t[r]);return n},bu=(e,t)=>{let n=e[0].dims,r=t??mu(e[1]),a=yu(n,r),s=ht.size(a),i=e[0].dataType,o=Nt("input",i,n.length),u=Et("output",i,a.length);return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},...kt(e[0].dims,a)]}),getShaderSource:e=>`\n      const inputShape = ${o.indices(...n)};\n      ${e.registerUniform("output_size","u32").declareVariables(o,u)}\n      ${e.mainStart()}\n      ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n      let output_indices = ${u.offsetToIndices("global_idx")};\n      var input_indices: ${o.type.indices};\n      for (var i = 0; i < ${n.length}; i++) {\n        let input_dim_i = ${o.indicesGet("uniforms.input_shape","i")};\n        let input_dim_value = ${u.indicesGet("output_indices","i")}  % input_dim_i;\n\n        ${o.indicesSet("input_indices","i","input_dim_value")}\n      }\n      ${u.setByOffset("global_idx",o.getByIndices("input_indices"))}\n    }`}},xu=e=>{gu(e.inputs),e.compute(bu(e.inputs),{inputs:[0]})}})),Jl=z((()=>{qu(),el(),tl(),wu=(e,t,n,r,a)=>{let s,i=Et("output_data",a,n.length,4),o=Nt("a_data",t[1].dataType,t[1].dims.length,4),u=Nt("b_data",t[2].dataType,t[2].dims.length,4),l=Nt("c_data",t[0].dataType,t[0].dims.length,4),c=(e,t,n)=>`select(${t}, ${e}, ${n})`;if(r){let e=(e,t,n="")=>{let r=`a_data[index_a${t}][component_a${t}]`,a=`b_data[index_b${t}][component_b${t}]`,s=`bool(c_data[index_c${t}] & (0xffu << (component_c${t} * 8)))`;return`\n            let output_indices${t} = ${i.offsetToIndices(`global_idx * 4u + ${t}u`)};\n            let offset_a${t} = ${o.broadcastedIndicesToOffset(`output_indices${t}`,i)};\n            let offset_b${t} = ${u.broadcastedIndicesToOffset(`output_indices${t}`,i)};\n            let offset_c${t} = ${l.broadcastedIndicesToOffset(`output_indices${t}`,i)};\n            let index_a${t} = offset_a${t} / 4u;\n            let index_b${t} = offset_b${t} / 4u;\n            let index_c${t} = offset_c${t} / 4u;\n            let component_a${t} = offset_a${t} % 4u;\n            let component_b${t} = offset_b${t} % 4u;\n            let component_c${t} = offset_c${t} % 4u;\n            ${e}[${t}] = ${n}(${c(r,a,s)});\n          `};s=9===a?`\n            var data = vec4<u32>(0);\n            ${e("data",0,"u32")}\n            ${e("data",1,"u32")}\n            ${e("data",2,"u32")}\n            ${e("data",3,"u32")}\n            output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:`\n            ${e("output_data[global_idx]",0)}\n            ${e("output_data[global_idx]",1)}\n            ${e("output_data[global_idx]",2)}\n            ${e("output_data[global_idx]",3)}\n          `}else s=i.setByOffset("global_idx",c(o.getByOffset("global_idx"),u.getByOffset("global_idx"),l.getByOffset("global_idx")));return`\n        ${e.registerUniform("vec_size","u32").declareVariables(l,o,u,i)}\n        ${e.mainStart()}\n        ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n        ${s}\n      }`},vu=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,a=e[1].dataType,s=!(ht.areEqual(t,n)&&ht.areEqual(n,r)),i=t,o=ht.size(t);if(s){let e=pt.calcShape(pt.calcShape(t,n,!1),r,!1);if(!e)throw new Error("Can't perform where op on the given tensors");i=e,o=ht.size(i)}let u=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:t=>wu(t,e,i,s,a),getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:u},...kt(r,t,n,i)]})}},ku=e=>{e.compute(vu(e.inputs))}})),ec=z((()=>{sl(),il(),ol(),ul(),cl(),dl(),pl(),vl(),Sl(),_l(),Il(),Tl(),$l(),Cl(),Nl(),El(),Al(),Rl(),Dl(),Fl(),zl(),Ll(),Pl(),Bl(),Wl(),Ml(),Vl(),Ul(),Gl(),Hl(),jl(),al(),ql(),Zl(),Kl(),Yl(),Ql(),Ol(),Xl(),nl(),ll(),Jl(),Su=new Map([["Abs",[sr]],["Acos",[ir]],["Acosh",[or]],["Add",[ea]],["ArgMax",[Bn,Wn]],["ArgMin",[Pn,Wn]],["Asin",[ur]],["Asinh",[lr]],["Atan",[cr]],["Atanh",[dr]],["Attention",[Kn]],["AveragePool",[co,lo]],["BatchNormalization",[Jn]],["BiasAdd",[nr]],["BiasSplitGelu",[Yr]],["Cast",[hr,pr]],["Ceil",[gr]],["Clip",[mr]],["Concat",[fa,ma]],["Conv",[Ja,Ka]],["ConvTranspose",[ls,ss]],["Cos",[yr]],["Cosh",[br]],["CumSum",[ds,ps]],["DepthToSpace",[gs,ys]],["DequantizeLinear",[ko,So]],["Div",[ta]],["Einsum",[Ts,$s]],["Elu",[wr,xr]],["Equal",[na]],["Erf",[kr]],["Exp",[Sr]],["Expand",[Rs]],["FastGelu",[Fs]],["Floor",[_r]],["FusedConv",[Ja,Ka]],["Gather",[Ls,zs]],["GatherElements",[Ks,Zs]],["GatherBlockQuantized",[Gs,Hs]],["GatherND",[Bs,Ws]],["Gelu",[Ir]],["Gemm",[Js,Xs]],["GlobalAveragePool",[fo,ho]],["GlobalMaxPool",[xo,bo]],["Greater",[ia]],["GreaterOrEqual",[ua]],["GridSample",[di,pi]],["GroupQueryAttention",[Ei]],["HardSigmoid",[Dr,Rr]],["InstanceNormalization",[Fi]],["LayerNormalization",[zi]],["LeakyRelu",[Tr,xr]],["Less",[oa]],["LessOrEqual",[la]],["Log",[Gr]],["MatMul",[Pi]],["MatMulNBits",[Ui,Gi]],["MaxPool",[go,yo]],["Mul",[ra]],["MultiHeadAttention",[xi,mi]],["Neg",[Cr]],["Not",[$r]],["Pad",[Ji]],["Pow",[aa]],["QuickGelu",[qr,xr]],["Range",[To]],["Reciprocal",[Nr]],["ReduceMin",[Dn]],["ReduceMean",[Cn]],["ReduceMax",[Rn]],["ReduceSum",[Mn]],["ReduceProd",[Fn]],["ReduceL1",[Nn]],["ReduceL2",[En]],["ReduceLogSum",[zn]],["ReduceLogSumExp",[An]],["ReduceSumSquare",[On]],["Relu",[Er]],["Resize",[Ko,Yo]],["RotaryEmbedding",[Jo]],["ScatterND",[Eo,No]],["Sigmoid",[Ar]],["Sin",[Fr]],["Sinh",[Mr]],["Slice",[lu,cu]],["SkipLayerNormalization",[nu]],["Split",[Ii,Ti]],["Sqrt",[Or]],["Softmax",[hu,fu]],["Sub",[sa]],["Tan",[zr]],["Tanh",[Pr]],["ThresholdedRelu",[Ur,xr]],["Tile",[xu]],["Transpose",[Vt,Ut]],["Where",[ku]]])})),tc=z((()=>{se(),Ku(),tl(),_u=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r,a){C(e.programInfo.name);let s=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber);let o=[];for(let l of t)o.push({binding:o.length,resource:{buffer:l.buffer}});for(let l of n)o.push({binding:o.length,resource:{buffer:l.buffer}});a&&o.push({binding:o.length,resource:a});let u=s.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:o,label:e.programInfo.name});if("capturing"===this.backend.sessionStatus){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:u,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}i.setPipeline(e.computePipeline),i.setBindGroup(0,u),i.dispatchWorkgroups(...r),this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||"at-passes"===this.backend.queryType)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),N(e.programInfo.name)}dispose(){}build(e,t){C(e.name);let n=this.backend.device,r=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach((e=>{n.features.has(e.feature)&&r.push(`enable ${e.extension};`)}));let a=Ft(t,this.backend.device.limits),s=e.getShaderSource(a),i=`${r.join("\n")}\n${a.additionalImplementations}\n${s}`,o=n.createShaderModule({code:i,label:e.name});Xe("verbose",(()=>`[WebGPU] ${e.name} shader code: ${i}`));let u=n.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:e.name});return N(e.name),{programInfo:e,computePipeline:u,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(e){let t="number"==typeof e?e:e.x,n="number"==typeof e?1:e.y||1,r="number"==typeof e?1:e.z||1,a=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=a&&n<=a&&r<=a)return[t,n,r];let s=t*n*r,i=Math.ceil(Math.sqrt(s));if(i>a){if(i=Math.ceil(Math.cbrt(s)),i>a)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}return[i,i,1]}}})),nc=z((()=>{se(),qu(),Ku(),Yu(),Xu(),ec(),tc(),Iu=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r<e.length;++r){let a=e[r].dataType;switch(t[r]){case"none":n.push("");break;case"type":n.push(`${a}`);break;case"rank":{let t=e[r].dims.length;n.push(`${a};${t}`);break}case"dims":{let t=e[r].dims.join(",");n.push(`${a};${t}`);break}default:throw new Error(`unsupported input dependency: ${t[r]}`)}}return n.join("|")},Tu=(e,t,n)=>{let r=e.name;return e.shaderCache?.hint&&(r+="["+e.shaderCache.hint+"]"),r+=":"+n+`:${Iu(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,r},$u=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Cu=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;this.subgroupsSupported&&t.minSubgroupSize&&t.maxSubgroupSize?this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]:this.subgroupSizeRange=void 0}},Nu=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(null===this.currentKernelId)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},a=e=>t.features.has(e)&&n.push(e)&&!0;a("chromium-experimental-timestamp-query-inside-passes")||a("timestamp-query"),a("shader-f16"),a("subgroups")&&a("subgroups-f16"),this.device=await t.requestDevice(r),this.deviceInfo=new Cu(this.device),this.adapterInfo=new $u(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ut(this),this.programManager=new _u(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ye(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error,GPUValidationError},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};"at-passes"===this.queryType&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:2*this.pendingDispatchNumber,endOfPassWriteIndex:2*this.pendingDispatchNumber+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;let e;C(),this.endComputePass(),"none"!==this.queryType&&(this.commandEncoder.resolveQuerySet(this.querySet,0,2*this.pendingDispatchNumber,this.queryResolveBuffer,0),e=this.device.createBuffer({size:2*this.pendingDispatchNumber*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,2*this.pendingDispatchNumber*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,"none"!==this.queryType&&e.mapAsync(GPUMapMode.READ).then((()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e<t.length/2;e++){let r=n[e],a=r.kernelId,s=this.kernels.get(a),i=s.kernelType,o=s.kernelName,u=r.programName,l=r.inputTensorViews,c=r.outputTensorViews,d=t[2*e],p=t[2*e+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=d);let h=Number(d-this.queryTimeBase),f=Number(p-this.queryTimeBase);if(!Number.isSafeInteger(h)||!Number.isSafeInteger(f))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:l.map((e=>({dims:e.dims,dataType:Be(e.dataType)}))),outputsMetadata:c.map((e=>({dims:e.dims,dataType:Be(e.dataType)}))),kernelId:a,kernelType:i,kernelName:o,programName:u,startTime:h,endTime:f});else{let e="";l.forEach(((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${Be(t.dataType)}, `}));let t="";c.forEach(((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${Be(e.dataType)}, `}))}T("GPU",`${u}::${d}::${p}`)}e.unmap(),this.pendingQueries.delete(e)})),N()}run(e,t,n,r,a,s){C(e.name);let i=[];for(let b=0;b<t.length;++b){let e=t[b].data;if(0===e)continue;let n=this.gpuDataManager.get(e);if(!n)throw new Error(`no GPU data for input: ${e}`);i.push(n)}let{outputs:o,dispatchGroup:u,programUniforms:l}=e.getRunData(t),c=0===n.length?o.map(((e,t)=>t)):n;if(c.length!==o.length)throw new Error(`Output size ${c.length} must be equal to ${o.length}.`);let d,p=[],h=[];for(let b=0;b<o.length;++b){if(!Number.isInteger(c[b])||c[b]<-3||c[b]>=s)throw new Error(`Invalid output index: ${c[b]}`);if(-3===c[b])continue;let e=-1===c[b],t=-2===c[b],n=e||t?a(o[b].dataType,o[b].dims):r(c[b],o[b].dataType,o[b].dims);if(p.push(n),0===n.data)continue;let i=this.gpuDataManager.get(n.data);if(!i)throw new Error(`no GPU data for output: ${n.data}`);if(e&&this.temporaryData.push(i),t){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(i)}h.push(i)}if(i.length!==t.length||h.length!==p.length){if(0===h.length)return N(e.name),p;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}if(l){let e=0,t=[];l.forEach((n=>{let r="number"==typeof n.data?[n.data]:n.data;if(0===r.length)return;let a,s,i=10===n.type?2:4;10===n.type?(s=r.length>4?16:r.length>2?8:r.length*i,a=r.length>4?16:i*r.length):(s=r.length<=2?r.length*i:16,a=16),e=Math.ceil(e/s)*s,t.push(e);let o=10===n.type?8:4;e+=r.length>4?Math.ceil(r.length/o)*a:r.length*i}));let n=16;e=Math.ceil(e/n)*n;let r=new ArrayBuffer(e);l.forEach(((e,n)=>{let a=t[n],s="number"==typeof e.data?[e.data]:e.data;if(6===e.type)new Int32Array(r,a,s.length).set(s);else if(12===e.type)new Uint32Array(r,a,s.length).set(s);else if(10===e.type)new Uint16Array(r,a,s.length).set(s);else{if(1!==e.type)throw new Error(`Unsupported uniform type: ${Be(e.type)}`);new Float32Array(r,a,s.length).set(s)}}));let a=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(a.buffer,0,r,0,e),this.gpuDataManager.release(a.id),d={offset:0,size:e,buffer:a.buffer}}let f=this.programManager.normalizeDispatchGroupSize(u),m=1===f[1]&&1===f[2],g=Tu(e,t,m),y=this.programManager.getArtifact(g);if(y||(y=this.programManager.build(e,f),this.programManager.setArtifact(g,y),Xe("info",(()=>`[artifact] key: ${g}, programName: ${e.name}`))),l&&y.uniformVariablesInfo){if(l.length!==y.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${y.uniformVariablesInfo.length}, got ${l.length} in program "${y.programInfo.name}".`);for(let e=0;e<l.length;e++){let t=l[e],n=t.type,r="number"==typeof t.data?1:t.data.length,[a,s]=y.uniformVariablesInfo[e];if(n!==a||r!==s)throw new Error(`Uniform variable ${e} mismatch: expect type ${a} with size ${s}, got type ${n} with size ${r} in program "${y.programInfo.name}".`)}}if(Xe("info",(()=>`[ProgramManager] run "${e.name}" (key=${g}) with ${f[0]}x${f[1]}x${f[2]}`)),"none"!==this.queryType||"capturing"===this.sessionStatus){let e={kernelId:this.currentKernelId,programName:y.programInfo.name,inputTensorViews:t,outputTensorViews:p};this.pendingKernels.push(e),"capturing"===this.sessionStatus&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(y,i,h,f,d),N(e.name),p}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let a=Su.get(e);if(!a)throw new Error(`kernel not implemented: ${e}`);let s={kernelType:e,kernelName:r,kernelEntry:a[0],attributes:[a[1],n]};this.kernels.set(t,s)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw new Error(`kernel not created: ${e}`);let a=r.kernelType,s=r.kernelName,i=r.kernelEntry,o=r.attributes;if(null!==this.currentKernelId)throw new Error(`kernel "[${a}] ${s}" is not allowed to be called recursively`);this.currentKernelId=e,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),Xe("info",(()=>`[WebGPU] Start to run kernel "[${a}] ${s}"...`));let u=this.env.debug;this.temporaryData=[];try{return u&&this.device.pushErrorScope("validation"),i(t,o[1]),0}catch(l){return n.push(Promise.resolve(`[WebGPU] Kernel "[${a}] ${s}" failed. ${l}`)),1}finally{u&&n.push(this.device.popErrorScope().then((e=>e?`GPU validation error for kernel "[${a}] ${s}": ${e.message}`:null)));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let a=this.sessionExternalDataMapping.get(e);a||(a=new Map,this.sessionExternalDataMapping.set(e,a));let s=a.get(t),i=this.gpuDataManager.registerExternalBuffer(n,r,s);return a.set(t,[i,n]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach((e=>this.gpuDataManager.unregisterExternalBuffer(e[0]))),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await it(this,e,t);return Je(r.buffer,n)}}writeTimestamp(e){"inside-passes"===this.queryType&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",("default"===this.env.webgpu.profiling?.mode||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),"none"!==this.queryType&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2*this.maxDispatchNumber}),this.queryResolveBuffer=this.device.createBuffer({size:2*this.maxDispatchNumber*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Xe("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Xe("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Xe("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r<n;r++){let n=this.getComputePassEncoder(),a=e[r];this.writeTimestamp(2*this.pendingDispatchNumber),n.setPipeline(a.computePipeline),n.setBindGroup(0,a.bindGroup),n.dispatchWorkgroups(...a.dispatchGroup),this.writeTimestamp(2*this.pendingDispatchNumber+1),this.pendingDispatchNumber++,"none"!==this.queryType&&this.pendingKernels.push(t[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||"at-passes"===this.queryType)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}})),rc=z((()=>{Ku(),Eu=1,Au=()=>Eu++,Ru=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Du=(e,t)=>{let n=Ru.get(e);if(!n)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce(((e,t)=>e*t))*n/8):0},Fu=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Du(this.dataType,this.tensorShape)}destroy(){Xe("verbose",(()=>"[WebNN] TensorWrapper.destroy")),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every(((e,t)=>e===n[t]))}},Mu=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let a=this.tensorManager.getMLContext(e);if(this.wrapper){if(this.wrapper.canReuseTensor(a,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==Du(t,n))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper){if(e.byteLength===this.wrapper.byteLength)return void this.wrapper.write(e);Xe("verbose",(()=>"Data size does not match tensor size. Releasing tensor.")),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)return e?void(e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload)):this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Ou=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}reserveTensorId(){let e=Au();return this.tensorTrackersById.set(e,new Mu(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,a){Xe("verbose",(()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${a}}`));let s=this.tensorTrackersById.get(t);if(!s)throw new Error("Tensor not found.");return s.ensureTensor(e,n,r,a)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){Xe("verbose",(()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`));let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter((t=>t.sessionId!==e))}registerTensor(e,t,n,r){let a=this.getMLContext(e),s=Au(),i=new Fu({sessionId:e,context:a,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(s,new Mu(this,i)),this.externalTensors.add(i),s}async getCachedTensor(e,t,n,r,a,s){let i=this.getMLContext(e);for(let[u,l]of this.freeTensors.entries())if(l.canReuseTensor(i,t,n)){Xe("verbose",(()=>`[WebNN] Reusing tensor {dataType: ${t}, shape: ${n}}`));let r=this.freeTensors.splice(u,1)[0];return r.sessionId=e,r}Xe("verbose",(()=>`[WebNN] MLContext.createTensor {dataType: ${t}, shape: ${n}}`));let o=await i.createTensor({dataType:t,shape:n,dimensions:n,usage:r,writable:a,readable:s});return new Fu({sessionId:e,context:i,tensor:o,dataType:t,shape:n})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},zu=(...e)=>new Ou(...e)})),ac=z((()=>{qu(),Uu(),Yu(),rc(),Ku(),Lu=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Pu=(e,t)=>{if(e===t)return!0;if(void 0===e||void 0===t)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every(((n,a)=>n===r[a]&&e[n]===t[n]))},Bu=class{constructor(e){this.tensorManager=zu(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ye(e.logLevel,!!e.debug)}get currentSessionId(){if(void 0===this.activeSessionId)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Xe("verbose",(()=>`[WebNN] onRunStart {sessionId: ${e}}`)),this.activeSessionId=e}onRunEnd(e){Xe("verbose",(()=>`[WebNN] onRunEnd {sessionId: ${e}}`));let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Xe("verbose",(()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`)),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex((t=>t.gpuDevice===e));if(-1!==t)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(void 0===e){let e=this.mlContextCache.findIndex((e=>void 0===e.options&&void 0===e.gpuDevice));if(-1!==e)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex((t=>Pu(t.options,e)));if(-1!==t)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),0===n.size){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex((e=>e.mlContext===t));-1!==e&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Xe("verbose",(()=>`[WebNN] releaseTensorId {tensorId: ${e}}`)),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,a){let s=Lu.get(n);if(!s)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,s,r,a)}async createTemporaryTensor(e,t,n){Xe("verbose",(()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`));let r=Lu.get(t);if(!r)throw new Error(`Unsupported ONNX data type: ${t}`);let a=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,a,r,n,!1);let s=this.temporarySessionTensorIds.get(e);return s?s.push(a):this.temporarySessionTensorIds.set(e,[a]),a}uploadTensor(e,t){if(!Ne().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Xe("verbose",(()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`)),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return Je(n,t)}}registerMLTensor(e,t,n,r){let a=Lu.get(n);if(!a)throw new Error(`Unsupported ONNX data type: ${n}`);let s=this.tensorManager.registerTensor(e,t,a,r);return Xe("verbose",(()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${a}, dimensions: ${r}} -> {tensorId: ${s}}`)),s}registerMLConstant(e,t,n,r,a,s){if(!s)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let o=s.get(i);if(!o)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+n>o.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u,l=o.slice(t,t+n).buffer;switch(a.dataType){case"float32":u=new Float32Array(l);break;case"float16":u=new Uint16Array(l);break;case"int32":u=new Int32Array(l);break;case"uint32":u=new Uint32Array(l);break;case"int64":u=new BigInt64Array(l);break;case"uint64":u=new BigUint64Array(l);break;case"int8":u=new Int8Array(l);break;case"int4":case"uint4":case"uint8":u=new Uint8Array(l);break;default:throw new Error(`Unsupported data type: ${a.dataType} in creating WebNN Constant from external data.`)}return Xe("verbose",(()=>`[WebNN] registerMLConstant {dataType: ${a.dataType}, shape: ${a.shape}}}`)),r.constant(a,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return!!n&&n.includes(t)}flush(){}}})),sc={};L(sc,{init:()=>uc});var ic,oc,uc,lc,cc,dc,pc,hc,fc,mc,gc,yc,bc,xc,wc,vc,kc,Sc,_c,Ic,Tc,$c,Cc,Nc,Ec,Ac,Rc,Dc,Fc,Mc,Oc,zc,Lc,Pc,Bc,Wc,Vc=z((()=>{qu(),nc(),Ku(),el(),ac(),ic=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(1!==this.dataType)throw new Error("Invalid data type");let e=ht.size(this.dims);return 0===e?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(7!==this.dataType)throw new Error("Invalid data type");let e=ht.size(this.dims);return 0===e?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(6!==this.dataType)throw new Error("Invalid data type");let e=ht.size(this.dims);return 0===e?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(10!==this.dataType&&4!==this.dataType)throw new Error("Invalid data type");let e=ht.size(this.dims);return 0===e?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(ht.size(t)!==ht.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},oc=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let r=e.PTR_SIZE,a=n/e.PTR_SIZE,s=4===r?"i32":"i64";this.opKernelContext=Number(e.getValue(r*a++,s));let i=Number(e.getValue(r*a++,s));this.outputCount=Number(e.getValue(r*a++,s)),this.customDataOffset=Number(e.getValue(r*a++,"*")),this.customDataSize=Number(e.getValue(r*a++,s));let o=[];for(let u=0;u<i;u++){let t=Number(e.getValue(r*a++,s)),n=Number(e.getValue(r*a++,"*")),i=Number(e.getValue(r*a++,s)),u=[];for(let o=0;o<i;o++)u.push(Number(e.getValue(r*a++,s)));o.push(new ic(e,t,n,u))}this.inputs=o}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map((e=>"number"==typeof e?this.inputs[e]:e))??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,((e,t,n)=>new ic(this.module,t,this.output(e,n),n)),((e,t)=>{let n=We(e,t);if(!n)throw new Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new ic(this.module,e,r,t)}),this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=4===n?"i32":"i64",a=this.module.stackAlloc((1+t.length)*n);this.module.setValue(a,t.length,r);for(let e=0;e<t.length;e++)this.module.setValue(a+n*(e+1),t[e],r);return this.module._JsepOutput(this.opKernelContext,e,a)}catch(r){throw new Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${r}`)}finally{this.module.stackRestore(n)}}},uc=async(e,t,n,r)=>{let a=t.jsepInit;if(!a)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if("webgpu"===e){let e=new Nu;await e.initialize(n,r),a("webgpu",[e,t=>e.alloc(Number(t)),t=>e.free(t),(n,r,a,s=!1)=>{if(s)Xe("verbose",(()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(n)}, dst=${Number(r)}, size=${Number(a)}`)),e.memcpy(Number(n),Number(r));else{Xe("verbose",(()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(n)}, gpuDataId=${Number(r)}, size=${Number(a)}`));let s=t.HEAPU8.subarray(Number(n>>>0),Number(n>>>0)+Number(a));e.upload(Number(r),s)}},async(n,r,a)=>{Xe("verbose",(()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${n}, dataOffset=${r}, size=${a}`)),await e.download(Number(n),(()=>t.HEAPU8.subarray(Number(r)>>>0,Number(r+a)>>>0)))},(n,r,a)=>e.createKernel(n,Number(r),a,t.UTF8ToString(t._JsepGetNodeName(Number(r)))),t=>e.releaseKernel(t),(n,r,a,s)=>{Xe("verbose",(()=>`[WebGPU] jsepRun: sessionHandle=${a}, kernel=${n}, contextDataOffset=${r}`));let i=new oc(t,e,Number(r));return e.computeKernel(Number(n),i,s)},()=>e.captureBegin(),()=>e.captureEnd(),()=>e.replay()])}else{let e=new Bu(n);a("webnn",[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,a,s)=>e.ensureTensor(t,n,r,a,s),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n)])}}})),Uc=z((()=>{Hu(),ju(),qu(),Uu(),Gu(),Zu(),lc=(e,t)=>{0!==Ne()._OrtInit(e,t)&&Re("Can't initialize onnxruntime.")},cc=async e=>{lc(e.wasm.numThreads,Ue(e.logLevel))},dc=async(e,t)=>{{let n=(Vc(),P(sc)).init;if("webgpu"===t){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let t=e.webgpu.adapter;if(t){if("object"!=typeof t.limits||"object"!=typeof t.features||"function"!=typeof t.requestDevice)throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(void 0!==n&&"low-power"!==n&&"high-performance"!==n)throw new Error(`Invalid powerPreference setting: "${n}"`);let r=e.webgpu.forceFallbackAdapter;if(void 0!==r&&"boolean"!=typeof r)throw new Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:r}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await n("webgpu",Ne(),e,t)}if("webnn"===t){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await n("webnn",Ne(),e)}}},pc=new Map,hc=e=>{let t=Ne(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);0!==t._OrtGetInputOutputCount(e,r,r+n)&&Re("Can't get session input/output count.");let a=4===n?"i32":"i64";return[Number(t.getValue(r,a)),Number(t.getValue(r+n,a))]}finally{t.stackRestore(n)}},fc=e=>{let t=Ne(),n=t._malloc(e.byteLength);if(0===n)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},mc=async(e,t)=>{let n,r,a=Ne();Array.isArray(e)?[n,r]=e:e.buffer===a.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=fc(e);let s=0,i=0,o=0,u=[],l=[],c=[];try{if([i,u]=Le(t),t?.externalData&&a.mountExternalData){let e=[];for(let n of t.externalData){let t="string"==typeof n?n:n.path;e.push(qe("string"==typeof n?n:n.data).then((e=>{a.mountExternalData(t,e)})))}await Promise.all(e)}for(let n of t?.executionProviders??[])if("webnn"===("string"==typeof n?n:n.name)){if(a.shouldTransferToMLTensor=!1,"string"!=typeof n){let e=n,t=e?.context,r=e?.gpuDevice,s=e?.deviceType,i=e?.powerPreference;a.currentContext=t||(r?await a.jsepCreateMLContext(r):await a.jsepCreateMLContext({deviceType:s,powerPreference:i}))}else a.currentContext=await a.jsepCreateMLContext();break}s=await a._OrtCreateSession(n,r,i),0===s&&Re("Can't create a session."),a.jsepOnCreateSession?.(),a.currentContext&&(a.jsepRegisterMLContext(s,a.currentContext),a.currentContext=void 0,a.shouldTransferToMLTensor=!0);let[e,d]=hc(s),p=!!t?.enableGraphCapture,h=[],f=[],m=[];for(let t=0;t<e;t++){let e=a._OrtGetInputName(s,t);0===e&&Re("Can't get an input name."),l.push(e),h.push(a.UTF8ToString(e))}for(let n=0;n<d;n++){let e=a._OrtGetOutputName(s,n);0===e&&Re("Can't get an output name."),c.push(e);let r=a.UTF8ToString(e);f.push(r);{if(p&&void 0===t?.preferredOutputLocation){m.push("gpu-buffer");continue}let e="string"==typeof t?.preferredOutputLocation?t.preferredOutputLocation:t?.preferredOutputLocation?.[r]??"cpu";if("cpu"!==e&&"cpu-pinned"!==e&&"gpu-buffer"!==e&&"ml-tensor"!==e)throw new Error(`Not supported preferred output location: ${e}.`);if(p&&"gpu-buffer"!==e)throw new Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);m.push(e)}}let g=null;return m.some((e=>"gpu-buffer"===e||"ml-tensor"===e))&&(o=a._OrtCreateBinding(s),0===o&&Re("Can't create IO binding."),g={handle:o,outputPreferredLocations:m,outputPreferredLocationsEncoded:m.map((e=>je(e)))}),pc.set(s,[s,l,c,g,p,!1]),[s,h,f]}catch(d){throw l.forEach((e=>a._OrtFree(e))),c.forEach((e=>a._OrtFree(e))),0!==o&&0!==a._OrtReleaseBinding(o)&&Re("Can't release IO binding."),0!==s&&0!==a._OrtReleaseSession(s)&&Re("Can't release session."),d}finally{a._free(n),0!==i&&0!==a._OrtReleaseSessionOptions(i)&&Re("Can't release session options."),u.forEach((e=>a._free(e))),a.unmountExternalData?.()}},gc=e=>{let t=Ne(),n=pc.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[r,a,s,i,o]=n;i&&(o&&0!==t._OrtClearBoundOutputs(i.handle)&&Re("Can't clear bound outputs."),0!==t._OrtReleaseBinding(i.handle)&&Re("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),a.forEach((e=>t._OrtFree(e))),s.forEach((e=>t._OrtFree(e))),0!==t._OrtReleaseSession(r)&&Re("Can't release session."),pc.delete(e)},yc=async(e,t,n,r,a,s=!1)=>{if(!e)return void t.push(0);let i,o,u=Ne(),l=u.PTR_SIZE,c=e[0],d=e[1],p=e[3],h=p;if("string"===c&&("gpu-buffer"===p||"ml-tensor"===p))throw new Error("String tensor is not supported on GPU.");if(s&&"gpu-buffer"!==p)throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if("gpu-buffer"===p){let t=e[2].gpuBuffer;o=We(Pe(c),d);let n=u.jsepRegisterBuffer;if(!n)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');i=n(r,a,t,o)}else if("ml-tensor"===p){let t=e[2].mlTensor;o=We(Pe(c),d);let n=u.jsepRegisterMLTensor;if(!n)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');i=n(r,t,Pe(c),d)}else{let t=e[2];if(Array.isArray(t)){o=l*t.length,i=u._malloc(o),n.push(i);for(let e=0;e<t.length;e++){if("string"!=typeof t[e])throw new TypeError(`tensor data at index ${e} is not a string`);u.setValue(i+e*l,Ee(t[e],n),"*")}}else{let e=u.jsepIsGraphInput;if("string"!==c&&e){let s=u._OrtGetInputName(r,a);if(e(r,u.UTF8ToString(s))){let e=Pe(c);o=We(e,d),h="ml-tensor";let n=u.jsepCreateTemporaryTensor,a=u.jsepUploadTensor;if(!n||!a)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let s=await n(r,e,d);a(s,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),i=s}else o=t.byteLength,i=u._malloc(o),n.push(i),u.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),i)}else o=t.byteLength,i=u._malloc(o),n.push(i),u.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),i)}}let f=u.stackSave(),m=u.stackAlloc(4*d.length);try{d.forEach(((e,t)=>u.setValue(m+t*l,e,4===l?"i32":"i64")));let e=u._OrtCreateTensor(Pe(c),i,o,m,d.length,je(h));0===e&&Re(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{u.stackRestore(f)}},bc=async(e,t,n,r,a,s)=>{let i=Ne(),o=i.PTR_SIZE,u=pc.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let l=u[0],c=u[1],d=u[2],p=u[3],h=u[4],f=u[5],m=t.length,g=r.length,y=0,b=[],x=[],w=[],v=[],k=i.stackSave(),S=i.stackAlloc(m*o),_=i.stackAlloc(m*o),I=i.stackAlloc(g*o),T=i.stackAlloc(g*o);try{[y,b]=De(s);for(let r=0;r<m;r++)await yc(n[r],x,v,e,t[r],h);for(let t=0;t<g;t++)await yc(a[t],w,v,e,m+r[t],h);for(let e=0;e<m;e++)i.setValue(S+e*o,x[e],"*"),i.setValue(_+e*o,c[t[e]],"*");for(let e=0;e<g;e++)i.setValue(I+e*o,w[e],"*"),i.setValue(T+e*o,d[r[e]],"*");if(p&&!f){let{handle:n,outputPreferredLocations:s,outputPreferredLocationsEncoded:o}=p;if(c.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${c.length}).`);for(let r=0;r<m;r++){let a=t[r];0!==await i._OrtBindInput(n,c[a],x[r])&&Re(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let u=r[t];a[t]?.[3]?0!==i._OrtBindOutput(n,d[u],w[t],0)&&Re(`Can't bind pre-allocated output[${t}] for session=${e}.`):0!==i._OrtBindOutput(n,d[u],0,o[u])&&Re(`Can't bind output[${t}] to ${s[t]} for session=${e}.`)}pc.set(e,[l,c,d,p,h,!0])}let u;i.jsepOnRunStart?.(l),u=p?await i._OrtRunWithBinding(l,p.handle,g,I,y):await i._OrtRun(l,_,S,m,T,g,I,y),0!==u&&Re("failed to call OrtRun().");let k=[];for(let t=0;t<g;t++){let n=Number(i.getValue(I+t*o,"*"));if(n===w[t]){k.push(a[t]);continue}let s,u=i.stackSave(),c=i.stackAlloc(4*o),d=!1,h=0;try{0!==i._OrtGetTensorData(n,c,c+o,c+2*o,c+3*o)&&Re(`Can't access output tensor data on index ${t}.`);let a=4===o?"i32":"i64",u=Number(i.getValue(c,a));h=i.getValue(c+o,"*");let l=i.getValue(c+2*o,"*"),f=Number(i.getValue(c+3*o,a)),m=[];for(let e=0;e<f;e++)m.push(Number(i.getValue(l+e*o,a)));0!==i._OrtFree(l)&&Re("Can't free memory for tensor dims.");let g=m.reduce(((e,t)=>e*t),1);s=Be(u);let y=p?.outputPreferredLocations[r[t]];if("string"===s){if("gpu-buffer"===y||"ml-tensor"===y)throw new Error("String tensor is not supported on GPU.");let e=[];for(let t=0;t<g;t++){let n=i.getValue(h+t*o,"*"),r=i.getValue(h+(t+1)*o,"*"),a=t===g-1?void 0:r-n;e.push(i.UTF8ToString(n,a))}k.push([s,m,e,"cpu"])}else if("gpu-buffer"===y&&g>0){let e=i.jsepGetBuffer;if(!e)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let t=e(h),r=We(u,g);if(void 0===r||!Ge(s))throw new Error(`Unsupported data type: ${s}`);d=!0,k.push([s,m,{gpuBuffer:t,download:i.jsepCreateDownloader(t,r,s),dispose:()=>{0!==i._OrtReleaseTensor(n)&&Re("Can't release tensor.")}},"gpu-buffer"])}else if("ml-tensor"===y&&g>0){let t=i.jsepEnsureTensor;if(!t)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(void 0===We(u,g)||!He(s))throw new Error(`Unsupported data type: ${s}`);let r=await t(e,h,u,m,!1);d=!0,k.push([s,m,{mlTensor:r,download:i.jsepCreateMLTensorDownloader(h,s),dispose:()=>{i.jsepReleaseTensorId(h),i._OrtReleaseTensor(n)}},"ml-tensor"])}else{let e=new(Ve(s))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(i.HEAPU8.subarray(h,h+e.byteLength)),k.push([s,m,e,"cpu"])}}finally{i.stackRestore(u),"string"===s&&h&&i._free(h),d||i._OrtReleaseTensor(n),i.jsepOnRunEnd?.(l)}}return p&&!h&&(0!==i._OrtClearBoundOutputs(p.handle)&&Re("Can't clear bound outputs."),pc.set(e,[l,c,d,p,h,!1])),k}finally{i.stackRestore(k),x.forEach((e=>i._OrtReleaseTensor(e))),w.forEach((e=>i._OrtReleaseTensor(e))),v.forEach((e=>i._free(e))),0!==y&&i._OrtReleaseRunOptions(y),b.forEach((e=>i._free(e)))}},xc=e=>{let t=Ne(),n=pc.get(e);if(!n)throw new Error("invalid session id");let r=n[0],a=t._OrtEndProfiling(r);0===a&&Re("Can't get an profile file name."),t._OrtFree(a)},wc=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&"buffer"in e&&t.push(e.buffer)}return t}})),Gc=z((()=>{se(),Uc(),Uu(),Vu(),vc=()=>!!l.wasm.proxy&&typeof document<"u",Sc=!1,_c=!1,Ic=!1,Cc=new Map,Nc=(e,t)=>{let n=Cc.get(e);n?n.push(t):Cc.set(e,[t])},Ec=()=>{if(Sc||!_c||Ic||!kc)throw new Error("worker not ready")},Ac=e=>{switch(e.data.type){case"init-wasm":Sc=!1,e.data.err?(Ic=!0,$c[1](e.data.err)):(_c=!0,$c[0]()),Tc&&(URL.revokeObjectURL(Tc),Tc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Cc.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Rc=async()=>{if(!_c){if(Sc)throw new Error("multiple calls to 'initWasm()' detected.");if(Ic)throw new Error("previous call to 'initWasm()' failed.");if(Sc=!0,vc())return new Promise(((e,t)=>{kc?.terminate(),we().then((([n,r])=>{try{(kc=r).onerror=e=>t(e),kc.onmessage=Ac,$c=[e,t];let a={type:"init-wasm",in:l};if(!a.in.wasm.wasmPaths&&n){let e=he();e&&(a.in.wasm.wasmPaths=e)}kc.postMessage(a),Tc=n}catch(a){t(a)}}),t)}));try{await Ce(l.wasm),await cc(l),_c=!0}catch(e){throw Ic=!0,e}finally{Sc=!1}}},Dc=async e=>{if(vc())return Ec(),new Promise(((t,n)=>{Nc("init-ep",[t,n]);let r={type:"init-ep",in:{epName:e,env:l}};kc.postMessage(r)}));await dc(l,e)},Fc=async e=>vc()?(Ec(),new Promise(((t,n)=>{Nc("copy-from",[t,n]);let r={type:"copy-from",in:{buffer:e}};kc.postMessage(r,[e.buffer])}))):fc(e),Mc=async(e,t)=>{if(vc()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ec(),new Promise(((n,r)=>{Nc("create",[n,r]);let a={type:"create",in:{model:e,options:{...t}}},s=[];e instanceof Uint8Array&&s.push(e.buffer),kc.postMessage(a,s)}))}return mc(e,t)},Oc=async e=>{if(vc())return Ec(),new Promise(((t,n)=>{Nc("release",[t,n]);let r={type:"release",in:e};kc.postMessage(r)}));gc(e)},zc=async(e,t,n,r,a,s)=>{if(vc()){if(n.some((e=>"cpu"!==e[3])))throw new Error("input tensor on GPU is not supported for proxy.");if(a.some((e=>e)))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ec(),new Promise(((a,i)=>{Nc("run",[a,i]);let o=n,u={type:"run",in:{sessionId:e,inputIndices:t,inputs:o,outputIndices:r,options:s}};kc.postMessage(u,wc(o))}))}return bc(e,t,n,r,a,s)},Lc=async e=>{if(vc())return Ec(),new Promise(((t,n)=>{Nc("end-profiling",[t,n]);let r={type:"end-profiling",in:e};kc.postMessage(r)}));xc(e)}})),Hc=z((()=>{se(),Gc(),qu(),ie(),Zu(),Pc=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Bc=e=>{switch(e[3]){case"cpu":return new I(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Ge(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:a}=e[2];return I.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:a})}case"ml-tensor":{let t=e[0];if(!He(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:a}=e[2];return I.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:a})}default:throw new Error(`invalid data location: ${e[3]}`)}},Wc=class{async fetchModelAndCopyToWasmMemory(e){return Fc(await qe(e))}async loadModel(e,t){let n;C(),n="string"==typeof e?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames]=await Mc(n,t),N()}async dispose(){return Oc(this.sessionId)}async run(e,t,n){C();let r=[],a=[];Object.entries(e).forEach((e=>{let t=e[0],n=e[1],s=this.inputNames.indexOf(t);if(-1===s)throw new Error(`invalid input '${t}'`);r.push(n),a.push(s)}));let s=[],i=[];Object.entries(t).forEach((e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(-1===r)throw new Error(`invalid output '${t}'`);s.push(n),i.push(r)}));let o=r.map(((e,t)=>Pc(e,(()=>`input "${this.inputNames[a[t]]}"`)))),u=s.map(((e,t)=>e?Pc(e,(()=>`output "${this.outputNames[i[t]]}"`)):null)),l=await zc(this.sessionId,a,o,i,u,n),c={};for(let d=0;d<l.length;d++)c[this.outputNames[i[d]]]=s[d]??Bc(l[d]);return N(),c}startProfiling(){}endProfiling(){Lc(this.sessionId)}}})),jc={};L(jc,{OnnxruntimeWebAssemblyBackend:()=>Zc,initializeFlags:()=>qc,wasmBackend:()=>Kc});var qc,Zc,Kc,Yc=z((()=>{se(),Gc(),Hc(),qc=()=>{if(("number"!=typeof l.wasm.initTimeout||l.wasm.initTimeout<0)&&(l.wasm.initTimeout=0),l.wasm.simd,"boolean"!=typeof l.wasm.proxy&&(l.wasm.proxy=!1),"boolean"!=typeof l.wasm.trace&&(l.wasm.trace=!1),"number"!=typeof l.wasm.numThreads||!Number.isInteger(l.wasm.numThreads)||l.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)l.wasm.numThreads=1;else{let e=typeof navigator>"u"?O("node:os").cpus().length:navigator.hardwareConcurrency;l.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Kc=new(Zc=class{async init(e){qc(),await Rc(),await Dc(e)}async createInferenceSessionHandler(e,t){let n=new Wc;return await n.loadModel(e,t),Promise.resolve(n)}})})),Qc={};L(Qc,{InferenceSession:()=>A,TRACE:()=>T,TRACE_FUNC_BEGIN:()=>C,TRACE_FUNC_END:()=>N,Tensor:()=>I,default:()=>Xc,env:()=>l,registerBackend:()=>r}),se(),se(),se();var Xc=ae;{let e=(Yc(),P(jc)).wasmBackend;r("webgpu",e,5),r("webnn",e,5),r("cpu",e,10),r("wasm",e,10)}return Object.defineProperty(l.versions,"web",{value:"1.21.0",enumerable:!0}),P(Qc)})();e.exports=r},1743:(e,t,n)=>{"use strict";let r;function a(){if(null==r){let e;if("undefined"!==typeof window)e=window;else if("undefined"!==typeof n.g)e=n.g;else if("undefined"!==typeof process)e=process;else{if("undefined"===typeof self)throw new Error("Could not find a global object");e=self}r=e}return r}function s(e,t){const n=function(){const e=a();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)}}n.d(t,{L:()=>a,m:()=>s})},1760:(e,t,n)=>{"use strict";n.d(t,{M:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({oneHot_:function(e,t,n=1,i=0,o="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const u={indices:(0,s.YT)(e,"indices","oneHot","int32")},l={dtype:o,depth:t,onValue:n,offValue:i};return r.T2.runKernel(a.urI,u,l)}})},1830:(e,t,n)=>{"use strict";n.d(t,{Dv:()=>o,_X:()=>p,jY:()=>l,mu:()=>c,ok:()=>u,y7:()=>d});var r=n(1585),a=n(259),s=n(8189),i=n(5119);function o(e){return i.vA(i.Tn(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const a=(0,s.YT)(t,"x","tf.grad","string_or_numeric"),o=null!=n?(0,s.YT)(n,"dy","tf.grad"):null;return r.T2.tidy((()=>{const{value:t,grads:n}=r.T2.gradients((()=>e(a)),[a],o);return null!=o&&i.O3(t.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),h(n),n[0]}))}}function u(e){return i.vA(i.Tn(e),(()=>"The f passed in grads(f) must be a function")),(t,n)=>{i.vA(Array.isArray(t),(()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"));const a=(0,s.j1)(t,"args","tf.grads","string_or_numeric"),o=null!=n?(0,s.YT)(n,"dy","tf.grads"):null;return r.T2.tidy((()=>{const{value:t,grads:n}=r.T2.gradients((()=>e(...a)),a,o);return null!=o&&i.O3(t.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),h(n),n}))}}function l(e){return i.vA(i.Tn(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{i.vA(t instanceof a.qY,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),i.vA(null==n||n instanceof a.qY,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:s,value:o}=r.T2.gradients((()=>e(t)),[t],n);return h(s),{grad:s[0],value:o}}}function c(e){return i.vA(i.Tn(e),(()=>"The f passed in valueAndGrads(f) must be a function")),(t,n)=>{i.vA(Array.isArray(t)&&t.every((e=>e instanceof a.qY)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),i.vA(null==n||n instanceof a.qY,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const s=r.T2.gradients((()=>e(...t)),t,n);return null!=n&&i.O3(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),h(s.grads),s}}function d(e,t){i.vA(i.Tn(e),(()=>"The f passed in variableGrads(f) must be a function")),i.vA(null==t||Array.isArray(t)&&t.every((e=>e instanceof a.rT)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in r.T2.registeredVariables)t.push(r.T2.registeredVariables[e])}const s=n?t.filter((e=>!e.trainable)):null,o=t.length;t=t.filter((e=>e.trainable)),i.vA(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`));const{value:u,grads:l}=r.T2.gradients(e,t,null,!0);i.vA(l.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.vA(0===u.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${u.rank} tensor`));const c={};return t.forEach(((e,t)=>{null!=l[t]&&(c[e.name]=l[t])})),null!=s&&s.forEach((e=>c[e.name]=null)),{value:u,grads:c}}function p(e){return r.T2.customGrad(e)}function h(e){if(e.filter((e=>null==e)).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n    the f you passed encloses all operations that lead from x to y.")}},1890:(e,t,n)=>{"use strict";n.d(t,{x:()=>o});var r=n(1585),a=n(5441),s=n(929),i=n(2302);const o=(0,s.op)({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,s,o,u=[1,1],l){let c=e;3===e.rank&&(c=(0,i.t)(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let d=t;3===d.rank&&(d=(0,i.t)(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const p={x:c,dy:d},h={strides:s,pad:o,dimRoundingMode:l,dilations:u,filterShape:n};return r.T2.runKernel(a.X$8,p,h)}})},1895:(e,t,n)=>{"use strict";n.d(t,{c:()=>u});var r=n(1585),a=n(5441),s=n(5119),i=n(929),o=n(2302);const u=(0,i.op)({conv3DBackpropInput_:function(e,t,n,i,u){s.vA(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let l=e,c=t,d=!1;4===t.rank&&(d=!0,c=(0,o.t)(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),l=[1,e[0],e[1],e[2],e[3]]);const p=l[4],h=c.shape[4];s.vA(5===l.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${l.length}.`)),s.vA(5===c.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${c.rank}`)),s.vA(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),s.vA(p===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${p}) must match input depth for filter ${n.shape[3]}.`)),s.vA(h===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[4]}.`));const f={dy:c,filter:n},m={pad:u,strides:i,inputShape:l},g=r.T2.runKernel(a.gC7,f,m);return d?(0,o.t)(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}})},1902:(e,t,n)=>{"use strict";n.d(t,{x:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({real_:function(e){const t={input:(0,s.YT)(e,"input","real")};return r.T2.runKernel(a.LRy,t)}})},1938:(e,t,n)=>{"use strict";n.d(t,{T:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({max_:function(e,t=null,n=!1){const i={x:(0,s.YT)(e,"x","max")},o={reductionIndices:t,keepDims:n};return r.T2.runKernel(a.VAI,i,o)}})},2015:(e,t,n)=>{"use strict";n.d(t,{K:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({log1p_:function(e){const t={x:(0,s.YT)(e,"x","log1p")};return r.T2.runKernel(a.Cg$,t)}})},2046:(e,t,n)=>{"use strict";var r,a,s,i,o;n.d(t,{Nw:()=>p,Oj:()=>d,Tu:()=>l,ch:()=>c,rg:()=>r}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(r||(r={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(a||(a={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(s||(s={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(i||(i={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(o||(o={}));const u={float32:i,int32:a,bool:s,complex64:o};function l(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return u[e][t]}function c(e){return l(e,"int32")}function d(e){return null!=e&&"object"===typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function p(e){return"undefined"!==typeof GPUBuffer&&null!=e&&"object"===typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}},2058:(e,t,n)=>{"use strict";n.d(t,{r:()=>u});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198);const u=(0,n(929).op)({greater_:function(e,t){let n=(0,i.YT)(e,"a","greater","string_or_numeric"),u=(0,i.YT)(t,"b","greater","string_or_numeric");[n,u]=(0,s.makeTypesMatch)(n,u),(0,o.assertAndGetBroadcastShape)(n.shape,u.shape);const l={a:n,b:u};return r.T2.runKernel(a.XhZ,l)}})},2118:(e,t,n)=>{"use strict";n.d(t,{E:()=>u});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198);const u=(0,n(929).op)({notEqual_:function(e,t){let n=(0,i.YT)(e,"a","notEqual","string_or_numeric"),u=(0,i.YT)(t,"b","notEqual","string_or_numeric");[n,u]=(0,s.makeTypesMatch)(n,u),(0,o.assertAndGetBroadcastShape)(n.shape,u.shape);const l={a:n,b:u};return r.T2.runKernel(a.ylV,l)}})},2151:(e,t,n)=>{"use strict";n.d(t,{_:()=>u});var r=n(1585),a=n(5441),s=n(8189),i=n(3567),o=n(2198);const u=(0,n(929).op)({where_:function(e,t,n){const u=(0,s.YT)(t,"a","where"),l=(0,s.YT)(n,"b","where"),c=(0,s.YT)(e,"condition","where","bool"),d=(0,o.assertAndGetBroadcastShape)((0,o.assertAndGetBroadcastShape)(c.shape,u.shape),l.shape),p={condition:(0,i.h)(c,d),t:(0,i.h)(u,d),e:(0,i.h)(l,d)};return r.T2.runKernel(a.l6P,p)}})},2198:(e,t,n)=>{"use strict";function r(e,t){const n=e.length,r=[];for(let a=0;a<n;a++){const s=n-1-a,i=e[s]||1;(t[t.length-1-a]||1)>1&&1===i&&r.unshift(s)}return r}function a(e,t){const n=[];for(let r=0;r<t.length;r++){const a=e[e.length-r-1],s=t.length-r-1,i=t[s];(null==a||1===a&&i>1)&&n.unshift(s)}return n}function s(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 i=t[t.length-a-1];if(null==i&&(i=1),1===s)r[n-a-1]=i;else if(1===i)r[n-a-1]=s;else{if(s!==i){throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`)}r[n-a-1]=s}}return r}n.r(t),n.d(t,{assertAndGetBroadcastShape:()=>s,getBroadcastDims:()=>r,getReductionAxes:()=>a})},2292:(e,t,n)=>{"use strict";n.d(t,{g:()=>f});var r=n(7148),a=n(5030),s=n(5040),i=n(9258),o=n(929),u=n(1902),l=n(2302),c=n(3262),d=n(5702),p=n(7986),h=n(3108);const f=(0,o.op)({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let o;if(t<=2){const r=(0,l.t)(e,[n,t]);o=(0,h.K)(r)}else{const f=[n,2*(t-1)],m=(0,l.t)((0,u.x)(e),[n,t]),g=(0,l.t)((0,s.n)(e),[n,t]),y=(0,c.B)((0,p.d)(m,[0,1],[n,t-2]),1),b=(0,i.l)((0,c.B)((0,p.d)(g,[0,1],[n,t-2]),1),(0,d.d)(-1)),x=(0,a.x)([m,y],1),w=(0,a.x)([g,b],1),v=(0,l.t)((0,r.f)(x,w),[f[0],f[1]]);o=(0,h.K)(v)}if(o=(0,u.x)(o),3===e.rank&&0!==e.shape[0]){const t=o,n=e.shape[0];o=(0,l.t)(o,[n,o.shape[0]/n,o.shape[1]]),t.dispose()}return o}})},2302:(e,t,n)=>{"use strict";n.d(t,{t:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({reshape_:function(e,t){const n={x:(0,s.YT)(e,"x","reshape","string_or_numeric")},i={shape:t};return r.T2.runKernel(a.R23,n,i)}})},2307:(e,t,n)=>{"use strict";n.d(t,{Q:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({all_:function(e,t=null,n=!1){const i={x:(0,s.YT)(e,"x","all","bool")},o={axis:t,keepDims:n};return r.T2.runKernel(a.u8Z,i,o)}})},2596:(e,t,n)=>{"use strict";n.d(t,{x:()=>y});var r=n(8189),a=n(5119),s=n(4888),i=n(1078),o=n(1938),u=n(7436),l=n(929),c=n(8990),d=n(2302),p=n(5702),h=n(9348),f=n(5793),m=n(3791);function g(e,t,n=null){if(0===e.rank)return(0,s.t)(e);if(1!==e.rank&&null===n)return g((0,d.t)(e,[-1]),t,n);if(1===e.rank||"number"===typeof n||Array.isArray(n)&&1===n.length){if(1===t)return(0,m.c)((0,s.t)(e),n);if(t===1/0)return(0,o.T)((0,s.t)(e),n);if(t===-1/0)return(0,u.j)((0,s.t)(e),n);if("euclidean"===t||2===t)return(0,h.R)((0,m.c)((0,c.n)((0,s.t)(e),(0,p.d)(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return(0,o.T)((0,m.c)((0,s.t)(e),n[0]),n[1]-1);if(t===1/0)return(0,o.T)((0,m.c)((0,s.t)(e),n[1]),n[0]);if(t===-1/0)return(0,u.j)((0,m.c)((0,s.t)(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return(0,h.R)((0,m.c)((0,f.E)(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const y=(0,l.op)({norm_:function(e,t="euclidean",n=null,s=!1){const o=g(e=(0,r.YT)(e,"x","norm"),t,n);let u=o.shape;if(s){const t=(0,a.Y6)(n,e.shape);u=i.SM(o.shape,t)}return(0,d.t)(o,u)}})},2610:(e,t,n)=>{"use strict";n.d(t,{q:()=>a});var r=n(5838);function a(e,t,n,a){if(e===t||e<t&&n<0||t<e&&n>1)return r.ZSL.makeZerosTypedArray(0,a);const s=Math.abs(Math.ceil((t-e)/n)),i=r.ZSL.makeZerosTypedArray(s,a);t<e&&1===n&&(n=-1),i[0]=e;for(let r=1;r<i.length;r++)i[r]=i[r-1]+n;return i}},2611:(e,t,n)=>{"use strict";n.d(t,{i:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({mean_:function(e,t=null,n=!1){const i={x:(0,s.YT)(e,"x","mean")},o={axis:t,keepDims:n};return r.T2.runKernel(a.g5A,i,o)}})},2644:(e,t,n)=>{"use strict";n.d(t,{B:()=>l});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198),u=n(9809);const l=(0,n(929).op)({minimum_:function(e,t){let n=(0,i.YT)(e,"a","minimum"),l=(0,i.YT)(t,"b","minimum");[n,l]=(0,s.makeTypesMatch)(n,l),"bool"===n.dtype&&(n=(0,u.w)(n,"int32"),l=(0,u.w)(l,"int32")),(0,o.assertAndGetBroadcastShape)(n.shape,l.shape);const c={a:n,b:l};return r.T2.runKernel(a.LG0,c)}})},2750:(e,t,n)=>{"use strict";n.d(t,{w:()=>a});var r=n(5838);function a(e,t,n,a){const s=r.ZSL.parseAxisParam(t,n)[0],i=[1,n[0],1];for(let r=0;r<s;r++)i[0]*=n[r];i[1]=n[s];for(let r=s+1;r<n.length;r++)i[2]*=n[r];const o=new Map,u=new Int32Array(n[s]),l=new r.ylz(i,a,e),c=[],d=1===i[0]&&1===i[2];for(let r=0;r<n[s];r++){let t;if(d)t=e[r].toString();else{const e=[];for(let t=0;t<i[0];t++)for(let n=0;n<i[2];n++)e.push(l.get(t,r,n));t=e.join(",")}const n=o.get(t);if(null!=n)u[r]=n;else{const e=o.size;o.set(t,e),u[r]=e,c.push(r)}}const p=i.slice();p[1]=o.size;const h=new r.ylz(p,a);c.forEach(((e,t)=>{for(let n=0;n<i[0];n++)for(let r=0;r<i[2];r++)h.set(l.get(n,e,r),n,t,r)}));const f=n.slice();return f[s]=p[1],{outputValues:h.values,outputShape:f,indices:u}}},2768:(e,t,n)=>{"use strict";n.d(t,{$:()=>i});var r=n(8189),a=n(5119),s=n(9171);function i(e,t,n){if((0,a.HO)(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const i=(0,r.MZ)(e,n);if(3!==i.length&&1!==i.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===i.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return(0,s.Q)(e,t,i,n)}},2804:(e,t,n)=>{"use strict";n.d(t,{H:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({acos_:function(e){const t={x:(0,s.YT)(e,"x","acos")};return r.T2.runKernel(a.Vvy,t)}})},2855:(e,t,n)=>{"use strict";n.d(t,{U:()=>i});var r=n(1585),a=n(5119),s=n(7148);function i(e,t="float32"){if((0,a.SA)(e),"complex64"===t){const t=i(e,"float32"),n=i(e,"float32");return(0,s.f)(t,n)}const n=(0,a.Ty)((0,a.Ze)(e),t);return r.T2.makeTensor(n,e,t)}},2948:(e,t,n)=>{"use strict";n.d(t,{S:()=>s});var r=n(5838);function a(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 s(e,t,n){const s=e.length,i=[];let o=0,u=0;const l=new Array(s);for(let r=0;r<s;++r){const s=i.length;a(e[r],t,n,i);const c=i.length-s;l[r]=c,o+=c,u=Math.max(u,c)}const c=r.ZSL.getArrayFromDType("int32",2*o),d=new Array(o),p=[s,u];let h=0;for(let r=0;r<s;++r)for(let e=0;e<l[r];++e)c[2*h]=r,c[2*h+1]=e,d[h]=i[h],++h;return[c,d,p]}},2954:(e,t,n)=>{"use strict";n.d(t,{b:()=>l});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(929),u=n(2302);const l=(0,o.op)({resizeNearestNeighbor_:function(e,t,n=!1,o=!1){const l=(0,s.YT)(e,"images","resizeNearestNeighbor");i.vA(3===l.rank||4===l.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${l.rank}.`)),i.vA(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),i.vA("float32"===l.dtype||"int32"===l.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),i.vA(!1===o||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let c=l,d=!1;3===l.rank&&(d=!0,c=(0,u.t)(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const[]=t,p={images:c},h={alignCorners:n,halfPixelCenters:o,size:t},f=r.T2.runKernel(a.jOE,p,h);return d?(0,u.t)(f,[f.shape[1],f.shape[2],f.shape[3]]):f}})},3002:(e,t,n)=>{"use strict";n.d(t,{X:()=>l});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(929),u=n(2302);const l=(0,o.op)({dilation2d_:function(e,t,n,o,l=[1,1],c="NHWC"){const d=(0,s.YT)(e,"x","dilation2d"),p=(0,s.YT)(t,"filter","dilation2d");i.vA(3===d.rank||4===d.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${d.rank}.`)),i.vA(3===p.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${p.rank}.`)),i.vA("NHWC"===c,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${c}`));let h=d,f=!1;3===d.rank&&(h=(0,u.t)(d,[1,d.shape[0],d.shape[1],d.shape[2]]),f=!0),i.vA(h.shape[3]===p.shape[2],(()=>`Error in dilation2d:  input and filter must have the same depth: ${h.shape[3]} vs ${p.shape[2]}`));const m={x:h,filter:p},g={strides:n,pad:o,dilations:l},y=r.T2.runKernel(a.jxD,m,g);return f?(0,u.t)(y,[y.shape[1],y.shape[2],y.shape[3]]):y}})},3020:(e,t,n)=>{"use strict";n.d(t,{L:()=>u});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198);const u=(0,n(929).op)({equal_:function(e,t){let n=(0,i.YT)(e,"a","equal","string_or_numeric"),u=(0,i.YT)(t,"b","equal","string_or_numeric");[n,u]=(0,s.makeTypesMatch)(n,u),(0,o.assertAndGetBroadcastShape)(n.shape,u.shape);const l={a:n,b:u};return r.T2.runKernel(a.BRl,l)}})},3031:function(e,t,n){var r;!function(e,a){function s(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 i(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 o(e,t){var n=new s(e),r=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&("object"==typeof r&&i(r,n),a.state=function(){return i(n,{})}),a}a&&a.exports?a.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,a))||(a.exports=r):this.xorwow=o}(0,e=n.nmd(e),n.amdD)},3108:(e,t,n)=>{"use strict";n.d(t,{K:()=>i});var r=n(1585),a=n(5441),s=n(5119);const i=(0,n(929).op)({ifft_:function(e){(0,s.vA)("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return r.T2.runKernel(a.OAQ,t)}})},3134:(e,t,n)=>{"use strict";n.d(t,{l:()=>o});var r=n(1585),a=n(5441),s=n(929),i=n(2302);const o=(0,s.op)({depthwiseConv2dNativeBackpropInput_:function(e,t,n,s,o,u=[1,1],l){let c=t,d=!1;3===t.rank&&(d=!0,c=(0,i.t)(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const p={dy:c,filter:n},h={strides:s,pad:o,dimRoundingMode:l,dilations:u,inputShape:e},f=r.T2.runKernel(a.nVu,p,h);return d?(0,i.t)(f,[f.shape[1],f.shape[2],f.shape[3]]):f}})},3181:function(e,t,n){var r;!function(e,a){function s(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 i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function o(e,t){var n=new s(e),r=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&("object"==typeof r&&i(r,n),a.state=function(){return i(n,{})}),a}a&&a.exports?a.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,a))||(a.exports=r):this.xor128=o}(0,e=n.nmd(e),n.amdD)},3262:(e,t,n)=>{"use strict";n.d(t,{B:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({reverse_:function(e,t){const n={x:(0,s.YT)(e,"x","reverse")},i={dims:t};return r.T2.runKernel(a.D7i,n,i)}})},3330:(e,t,n)=>{"use strict";n.d(t,{V:()=>f});var r=n(8189),a=n(5119),s=n(7523),i=n(1078),o=n(8631),u=n(4010),l=n(1938),c=n(929),d=n(2302),p=n(7126),h=n(3791);const f=(0,c.op)({logSumExp_:function(e,t=null,n=!1){const c=(0,r.YT)(e,"x","logSumExp"),f=(0,a.Y6)(t,c.shape),m=(0,l.T)(c,f,!0),g=(0,p.j)(c,m),y=(0,o.o)(g),b=(0,h.c)(y,f),x=(0,u.R)(b),w=(0,s.W)((0,d.t)(m,x.shape),x);if(n){const e=(0,i.SM)(w.shape,f);return(0,d.t)(w,e)}return w}})},3337:(e,t,n)=>{"use strict";n.d(t,{D:()=>u});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198);const u=(0,n(929).op)({greaterEqual_:function(e,t){let n=(0,i.YT)(e,"a","greaterEqual","string_or_numeric"),u=(0,i.YT)(t,"b","greaterEqual","string_or_numeric");[n,u]=(0,s.makeTypesMatch)(n,u),(0,o.assertAndGetBroadcastShape)(n.shape,u.shape);const l={a:n,b:u};return r.T2.runKernel(a.lLS,l)}})},3416:(e,t,n)=>{"use strict";n.d(t,{P:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({elu_:function(e){const t={x:(0,s.YT)(e,"x","elu","float32")};return r.T2.runKernel(a.Pah,t)}})},3427:(e,t,n)=>{"use strict";n.d(t,{P:()=>u});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198);const u=(0,n(929).op)({squaredDifference_:function(e,t){let n=(0,i.YT)(e,"a","squaredDifference"),u=(0,i.YT)(t,"b","squaredDifference");[n,u]=(0,s.makeTypesMatch)(n,u),(0,o.assertAndGetBroadcastShape)(n.shape,u.shape);const l={a:n,b:u};return r.T2.runKernel(a.Ddj,l,{})}})},3454:(e,t,n)=>{"use strict";n.d(t,{E:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({isInf_:function(e){const t={x:(0,s.YT)(e,"x","isInf")};return r.T2.runKernel(a.E3$,t)}})},3514:(e,t,n)=>{"use strict";n.d(t,{G:()=>s});var r=n(5838);class a{constructor(e,t,n,a,s,i){this.separator=r.ZSL.encodeString(e),this.nGramWidths=t,this.leftPad=r.ZSL.encodeString(n),this.rightPad=r.ZSL.encodeString(a),this.padWidth=s,this.preserveShort=i}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 i=0;i<a;++i){const o=this.getPadWidth(s),u=Math.max(0,o-i),l=Math.max(0,o-(a-(i+1))),c=s-(u+l),d=t+(u>0?0:i-o);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+i]=new Uint8Array(p);const h=n[r+i];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,a=t.length;if(a>0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let r=1;r<a;++r){let a=t[r]>=e;if(a=a&&t[r]<=n,!a)throw new Error(`Invalid split value ${t[r]}, must be in [${e}, ${n}]`);e=t[r]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const s=a-1,i=r.ZSL.getArrayFromDType("int32",a);if(0===n||0===a){const e=new Array(n);for(let t=0;t<=s;++t)i[t]=0;return[e,i]}i[0]=0;for(let r=1;r<=s;++r){const e=t[r]-t[r-1];let n=0;this.nGramWidths.forEach((t=>{n+=this.getNumNGrams(e,t)})),this.preserveShort&&e>0&&0===n&&(n=1),i[r]=i[r-1]+n}const o=new Array(i[s]);for(let r=0;r<s;++r){const n=t[r];let a=i[r];if(this.nGramWidths.forEach((s=>{const i=t[r+1]-t[r],u=this.getNumNGrams(i,s);this.createNGrams(e,n,o,a,u,s),a+=u})),this.preserveShort&&a===i[r]){const s=t[r+1]-t[r];if(0===s)continue;const i=s+2*this.padWidth,u=1;this.createNGrams(e,n,o,a,u,i)}}return[o,i]}}function s(e,t,n,r,s,i,o,u){return new a(n,r,s,i,o,u).compute(e,t)}},3531:(e,t,n)=>{"use strict";n.d(t,{K:()=>l});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(929),u=n(2302);const l=(0,o.op)({localResponseNormalization_:function(e,t=5,n=1,o=1,l=.5){const c=(0,s.YT)(e,"x","localResponseNormalization");i.vA(4===c.rank||3===c.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank ${c.rank}.`)),i.vA(i.E6(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let d=c,p=!1;3===c.rank&&(p=!0,d=(0,u.t)(c,[1,c.shape[0],c.shape[1],c.shape[2]]));const h={x:d},f={depthRadius:t,bias:n,alpha:o,beta:l},m=r.T2.runKernel(a.jM4,h,f);return p?(0,u.t)(m,[m.shape[1],m.shape[2],m.shape[3]]):m}})},3556:()=>{},3567:(e,t,n)=>{"use strict";n.d(t,{h:()=>c});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(125),u=n(929),l=n(2302);const c=(0,u.op)({broadcastTo_:function(e,t){let n=(0,s.YT)(e,"broadcastTo","x");const u=n.shape;if((0,i.SA)(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=(0,l.t)(n,e)}const c=n.shape,d=Array.from(t);for(let r=t.length-1;r>=0;r--)if(c[r]===t[r])d[r]=1;else if(1!==n.shape[r])throw new Error(`broadcastTo(): [${u}] cannot be broadcast to [${t}].`);if(0===d.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return(0,o.o)(n);const p={x:n},h={reps:d};return r.T2.runKernel(a.FAs,p,h)}})},3673:(e,t,n)=>{"use strict";n.d(t,{R:()=>s,i:()=>a});var r=n(6574);function a(...e){!(0,r._K)().getBool("IS_TEST")&&(0,r._K)().getBool("PROD")}function s(...e){!(0,r._K)().getBool("IS_TEST")&&(0,r._K)().getBool("PROD")}},3701:(e,t,n)=>{"use strict";n.d(t,{k:()=>l});var r=n(8189),a=n(5119),s=n(8794),i=n(7195),o=n(929),u=n(2302);const l=(0,o.op)({conv1d_:function(e,t,n,o,l="NWC",c=1,d){const p=(0,r.YT)(e,"x","conv1d"),h=(0,r.YT)(t,"filter","conv1d");let f=p,m=!1;2===p.rank&&(m=!0,f=(0,u.t)(p,[1,p.shape[0],p.shape[1]])),a.vA(3===f.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${f.rank}.`)),a.vA(3===h.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${h.rank}.`)),i.s_("conv1d",o,d),a.vA(f.shape[2]===h.shape[1],(()=>`Error in conv1d: depth of input (${f.shape[2]}) must match input depth for filter ${h.shape[1]}.`)),a.vA(i.G0(n,c),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${c}'`)),a.vA(i.qk(c),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),a.vA(i.qk(n),(()=>"Error in conv1D: Stride should be larger than 0.")),a.vA("NWC"===l,(()=>`Error in conv1d: got dataFormat of ${l} but only NWC is currently supported.`));const g=(0,u.t)(h,[1,h.shape[0],h.shape[1],h.shape[2]]),y=(0,u.t)(f,[f.shape[0],1,f.shape[1],f.shape[2]]),b=[1,n],x=[1,c],w=(0,s.X)(y,g,b,o,"NHWC",x,d);return m?(0,u.t)(w,[w.shape[2],w.shape[3]]):(0,u.t)(w,[w.shape[0],w.shape[2],w.shape[3]])}})},3717:function(e,t,n){var r;!function(e,a){function s(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 i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function o(e,t){var n=new s(e),r=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&("object"==typeof r&&i(r,n),a.state=function(){return i(n,{})}),a}a&&a.exports?a.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,a))||(a.exports=r):this.tychei=o}(0,e=n.nmd(e),n.amdD)},3726:(e,t,n)=>{"use strict";n.d(t,{F:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({sin_:function(e){const t={x:(0,s.YT)(e,"x","sin","float32")};return r.T2.runKernel(a.hql,t)}})},3732:(e,t,n)=>{"use strict";n.d(t,{j:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({relu6_:function(e){const t={x:(0,s.YT)(e,"x","relu6")};return r.T2.runKernel(a.P_L,t)}})},3774:(e,t,n)=>{"use strict";n.d(t,{r:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({atanh_:function(e){const t={x:(0,s.YT)(e,"x","atanh")};return r.T2.runKernel(a.zP9,t)}})},3789:(e,t,n)=>{"use strict";n.d(t,{n:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(2198);const o=(0,n(929).op)({logicalAnd_:function(e,t){const n=(0,s.YT)(e,"a","logicalAnd","bool"),o=(0,s.YT)(t,"b","logicalAnd","bool");(0,i.assertAndGetBroadcastShape)(n.shape,o.shape);const u={a:n,b:o};return r.T2.runKernel(a.RUm,u)}})},3791:(e,t,n)=>{"use strict";n.d(t,{c:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(9809);const o=(0,n(929).op)({sum_:function(e,t=null,n=!1){let o=(0,s.YT)(e,"x","sum");"bool"===o.dtype&&(o=(0,i.w)(o,"int32"));const u={x:o},l={axis:t,keepDims:n};return r.T2.runKernel(a.WuN,u,l)}})},3805:(e,t,n)=>{var r=(()=>{var e="undefined"!==typeof document&&document.currentScript?document.currentScript.src:void 0;return e=e||"/index.js",function(t){var r,a,s,i="undefined"!=typeof(t=t||{})?t:{};i.ready=new Promise((function(e,t){r=e,a=t})),"undefined"!==typeof process&&process.listeners&&(s={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var o,u,l,c=Object.assign({},i),d=[],p="object"==typeof window,h="function"==typeof importScripts,f="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";if(f){var g=n(9893),y=n(5281);m=h?y.dirname(m)+"/":"//",o=(e,t)=>(e=V(e)?new URL(e):y.normalize(e),g.readFileSync(e,t?void 0:"utf8")),l=e=>{var t=o(e,!0);return t.buffer||(t=new Uint8Array(t)),t},u=(e,t,n)=>{e=V(e)?new URL(e):y.normalize(e),g.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),d=process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof G))throw e})),process.on("unhandledRejection",(function(e){throw e})),i.inspect=function(){return"[Emscripten Module object]"}}else(p||h)&&(h?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),e&&(m=e),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},h&&(l=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),u=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)},e=>document.title=e);var b=i.print||function(){}.bind(),x=i.printErr||function(){}.bind();Object.assign(i,c),c=null,i.arguments&&(d=i.arguments),i.thisProgram&&i.thisProgram,i.quit&&i.quit;var w;i.wasmBinary&&(w=i.wasmBinary);var v,k=i.noExitRuntime||!0;"object"!=typeof WebAssembly&&L("no native wasm support detected");var S=!1;var _,I,T,$,C="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function N(e,t,n){for(var r=(t>>>=0)+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.buffer&&C)return C.decode(e.subarray(t,a));for(var s="";t<a;){var i=e[t++];if(128&i){var o=63&e[t++];if(192!=(224&i)){var u=63&e[t++];if((i=224==(240&i)?(15&i)<<12|o<<6|u:(7&i)<<18|o<<12|u<<6|63&e[t++])<65536)s+=String.fromCharCode(i);else{var l=i-65536;s+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else s+=String.fromCharCode((31&i)<<6|o)}else s+=String.fromCharCode(i)}return s}function E(e,t){return(e>>>=0)?N(T,e,t):""}function A(e){_=e,i.HEAP8=I=new Int8Array(e),i.HEAP16=new Int16Array(e),i.HEAP32=new Int32Array(e),i.HEAPU8=T=new Uint8Array(e),i.HEAPU16=new Uint16Array(e),i.HEAPU32=$=new Uint32Array(e),i.HEAPF32=new Float32Array(e),i.HEAPF64=new Float64Array(e)}i.INITIAL_MEMORY;var R=[],D=[],F=[];var M=0,O=null,z=null;function L(e){i.onAbort&&i.onAbort(e),x(e="Aborted("+e+")"),S=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw a(t),t}var P,B;function W(e){return e.startsWith("data:application/octet-stream;base64,")}function V(e){return e.startsWith("file://")}function U(e){try{if(e==P&&w)return new Uint8Array(w);if(l)return l(e);throw"both async and sync fetching of the wasm failed"}catch(x){L(x)}}function G(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function H(e){for(;e.length>0;)e.shift()(i)}function j(e){try{return v.grow(e-_.byteLength+65535>>>16),A(v.buffer),1}catch(t){}}W(P="tfjs-backend-wasm.wasm")||(B=P,P=i.locateFile?i.locateFile(B,m):m+B);var q=[null,[],[]];function Z(e,t){var n=q[e];0===t||10===t?((1===e?b:x)(N(n,0)),n.length=0):n.push(t)}function K(e){return i["_"+e]}function Y(e,t,n,r,a){var s={string:e=>{var t=0;if(null!==e&&void 0!==e&&0!==e){var n=1+(e.length<<2);(function(e,t,n){(function(e,t,n,r){if(!(r>0))return 0;for(var a=n>>>=0,s=n+r-1,i=0;i<e.length;++i){var o=e.charCodeAt(i);if(o>=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++i)),o<=127){if(n>=s)break;t[n++>>>0]=o}else if(o<=2047){if(n+1>=s)break;t[n++>>>0]=192|o>>6,t[n++>>>0]=128|63&o}else if(o<=65535){if(n+2>=s)break;t[n++>>>0]=224|o>>12,t[n++>>>0]=128|o>>6&63,t[n++>>>0]=128|63&o}else{if(n+3>=s)break;t[n++>>>0]=240|o>>18,t[n++>>>0]=128|o>>12&63,t[n++>>>0]=128|o>>6&63,t[n++>>>0]=128|63&o}}t[n>>>0]=0})(e,T,t,n)})(e,t=re(n),n)}return t},array:e=>{var t=re(e.length);return function(e,t){I.set(e,t>>>0)}(e,t),t}};var i=K(e),o=[],u=0;if(r)for(var l=0;l<r.length;l++){var c=s[n[l]];c?(0===u&&(u=te()),o[l]=c(r[l])):o[l]=r[l]}var d=i.apply(null,o);return d=function(e){return 0!==u&&ne(u),function(e){return"string"===t?E(e):"boolean"===t?Boolean(e):e}(e)}(d)}var Q,X,J,ee={abort:function(){L("")},emscripten_get_heap_max:function(){return 4294901760},emscripten_memcpy_big:function(e,t,n){T.copyWithin(e>>>0,t>>>0,t+n>>>0)},emscripten_resize_heap:function(e){var t,n,r=T.length,a=4294901760;if((e>>>=0)>a)return!1;for(var s=1;s<=4;s*=2){var i=r*(1+.2/s);if(i=Math.min(i,e+100663296),j(Math.min(a,(t=Math.max(e,i))+((n=65536)-t%n)%n)))return!0}return!1},fd_close:function(e){return 52},fd_seek:function(e,t,n,r,a){return 70},fd_write:function(e,t,n,r){for(var a=0,s=0;s<n;s++){var i=$[t>>>2],o=$[t+4>>>2];t+=8;for(var u=0;u<o;u++)Z(e,T[i+u>>>0]);a+=o}return $[r>>>2]=a,0}},te=(function(){var e={env:ee,wasi_snapshot_preview1:ee};function t(e,t){var n,r=e.exports;i.asm=r,A((v=i.asm.memory).buffer),i.asm.__indirect_function_table,n=i.asm.__wasm_call_ctors,D.unshift(n),function(){if(M--,i.monitorRunDependencies&&i.monitorRunDependencies(M),0==M&&(null!==O&&(clearInterval(O),O=null),z)){var e=z;z=null,e()}}()}function n(e){t(e.instance)}function r(t){return function(){if(!w&&(p||h)){if("function"==typeof fetch&&!V(P))return fetch(P,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+P+"'";return e.arrayBuffer()})).catch((function(){return U(P)}));if(u)return new Promise((function(e,t){u(P,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return U(P)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){x("failed to asynchronously prepare wasm: "+e),L(e)}))}if(M++,i.monitorRunDependencies&&i.monitorRunDependencies(M),i.instantiateWasm)try{return i.instantiateWasm(e,t)}catch(s){x("Module.instantiateWasm callback failed with error: "+s),a(s)}(w||"function"!=typeof WebAssembly.instantiateStreaming||W(P)||V(P)||f||"function"!=typeof fetch?r(n):fetch(P,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return x("wasm streaming compile failed: "+e),x("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),i.___wasm_call_ctors=function(){return(i.___wasm_call_ctors=i.asm.__wasm_call_ctors).apply(null,arguments)},i._init=function(){return(i._init=i.asm.init).apply(null,arguments)},i._init_with_threads_count=function(){return(i._init_with_threads_count=i.asm.init_with_threads_count).apply(null,arguments)},i._get_threads_count=function(){return(i._get_threads_count=i.asm.get_threads_count).apply(null,arguments)},i._register_tensor=function(){return(i._register_tensor=i.asm.register_tensor).apply(null,arguments)},i._dispose_data=function(){return(i._dispose_data=i.asm.dispose_data).apply(null,arguments)},i._dispose=function(){return(i._dispose=i.asm.dispose).apply(null,arguments)},i._Abs=function(){return(i._Abs=i.asm.Abs).apply(null,arguments)},i._Acos=function(){return(i._Acos=i.asm.Acos).apply(null,arguments)},i._Acosh=function(){return(i._Acosh=i.asm.Acosh).apply(null,arguments)},i._Add=function(){return(i._Add=i.asm.Add).apply(null,arguments)},i._AddN=function(){return(i._AddN=i.asm.AddN).apply(null,arguments)},i._All=function(){return(i._All=i.asm.All).apply(null,arguments)},i._Any=function(){return(i._Any=i.asm.Any).apply(null,arguments)},i._ArgMax=function(){return(i._ArgMax=i.asm.ArgMax).apply(null,arguments)},i._ArgMin=function(){return(i._ArgMin=i.asm.ArgMin).apply(null,arguments)},i._Asin=function(){return(i._Asin=i.asm.Asin).apply(null,arguments)},i._Asinh=function(){return(i._Asinh=i.asm.Asinh).apply(null,arguments)},i._Atan=function(){return(i._Atan=i.asm.Atan).apply(null,arguments)},i._Atan2=function(){return(i._Atan2=i.asm.Atan2).apply(null,arguments)},i._Atanh=function(){return(i._Atanh=i.asm.Atanh).apply(null,arguments)},i._AvgPool=function(){return(i._AvgPool=i.asm.AvgPool).apply(null,arguments)},i._AvgPool3D=function(){return(i._AvgPool3D=i.asm.AvgPool3D).apply(null,arguments)},i._AvgPool3DGrad=function(){return(i._AvgPool3DGrad=i.asm.AvgPool3DGrad).apply(null,arguments)},i._AvgPoolGrad=function(){return(i._AvgPoolGrad=i.asm.AvgPoolGrad).apply(null,arguments)},i._BatchMatMul=function(){return(i._BatchMatMul=i.asm.BatchMatMul).apply(null,arguments)},i._Bincount=function(){return(i._Bincount=i.asm.Bincount).apply(null,arguments)},i._BitwiseAnd=function(){return(i._BitwiseAnd=i.asm.BitwiseAnd).apply(null,arguments)},i._Ceil=function(){return(i._Ceil=i.asm.Ceil).apply(null,arguments)},i._ClipByValue=function(){return(i._ClipByValue=i.asm.ClipByValue).apply(null,arguments)},i._Conv2D=function(){return(i._Conv2D=i.asm.Conv2D).apply(null,arguments)},i._Conv2DBackpropInput=function(){return(i._Conv2DBackpropInput=i.asm.Conv2DBackpropInput).apply(null,arguments)},i._Conv3D=function(){return(i._Conv3D=i.asm.Conv3D).apply(null,arguments)},i._Conv3DBackpropFilterV2=function(){return(i._Conv3DBackpropFilterV2=i.asm.Conv3DBackpropFilterV2).apply(null,arguments)},i._Conv3DBackpropInputV2=function(){return(i._Conv3DBackpropInputV2=i.asm.Conv3DBackpropInputV2).apply(null,arguments)},i._Cos=function(){return(i._Cos=i.asm.Cos).apply(null,arguments)},i._Cosh=function(){return(i._Cosh=i.asm.Cosh).apply(null,arguments)},i._CropAndResize=function(){return(i._CropAndResize=i.asm.CropAndResize).apply(null,arguments)},i._Cumprod=function(){return(i._Cumprod=i.asm.Cumprod).apply(null,arguments)},i._Cumsum=function(){return(i._Cumsum=i.asm.Cumsum).apply(null,arguments)},i._DenseBincount=function(){return(i._DenseBincount=i.asm.DenseBincount).apply(null,arguments)},i._DepthToSpace=function(){return(i._DepthToSpace=i.asm.DepthToSpace).apply(null,arguments)},i._DepthwiseConv2dNative=function(){return(i._DepthwiseConv2dNative=i.asm.DepthwiseConv2dNative).apply(null,arguments)},i._Diag=function(){return(i._Diag=i.asm.Diag).apply(null,arguments)},i._Dilation2D=function(){return(i._Dilation2D=i.asm.Dilation2D).apply(null,arguments)},i._Dilation2DBackpropFilter=function(){return(i._Dilation2DBackpropFilter=i.asm.Dilation2DBackpropFilter).apply(null,arguments)},i._Dilation2DBackpropInput=function(){return(i._Dilation2DBackpropInput=i.asm.Dilation2DBackpropInput).apply(null,arguments)},i._Elu=function(){return(i._Elu=i.asm.Elu).apply(null,arguments)},i._EluGrad=function(){return(i._EluGrad=i.asm.EluGrad).apply(null,arguments)},i._Equal=function(){return(i._Equal=i.asm.Equal).apply(null,arguments)},i._Erf=function(){return(i._Erf=i.asm.Erf).apply(null,arguments)},i._Exp=function(){return(i._Exp=i.asm.Exp).apply(null,arguments)},i._Expm1=function(){return(i._Expm1=i.asm.Expm1).apply(null,arguments)},i._FlipLeftRight=function(){return(i._FlipLeftRight=i.asm.FlipLeftRight).apply(null,arguments)},i._Floor=function(){return(i._Floor=i.asm.Floor).apply(null,arguments)},i._FloorDiv=function(){return(i._FloorDiv=i.asm.FloorDiv).apply(null,arguments)},i._FusedBatchNorm=function(){return(i._FusedBatchNorm=i.asm.FusedBatchNorm).apply(null,arguments)},i._FusedConv2D=function(){return(i._FusedConv2D=i.asm.FusedConv2D).apply(null,arguments)},i._FusedDepthwiseConv2D=function(){return(i._FusedDepthwiseConv2D=i.asm.FusedDepthwiseConv2D).apply(null,arguments)},i._Gather=function(){return(i._Gather=i.asm.Gather).apply(null,arguments)},i._GatherNd=function(){return(i._GatherNd=i.asm.GatherNd).apply(null,arguments)},i._Greater=function(){return(i._Greater=i.asm.Greater).apply(null,arguments)},i._GreaterEqual=function(){return(i._GreaterEqual=i.asm.GreaterEqual).apply(null,arguments)},i._IsFinite=function(){return(i._IsFinite=i.asm.IsFinite).apply(null,arguments)},i._IsInf=function(){return(i._IsInf=i.asm.IsInf).apply(null,arguments)},i._IsNan=function(){return(i._IsNan=i.asm.IsNan).apply(null,arguments)},i._LRN=function(){return(i._LRN=i.asm.LRN).apply(null,arguments)},i._LRNGrad=function(){return(i._LRNGrad=i.asm.LRNGrad).apply(null,arguments)},i._LeakyRelu=function(){return(i._LeakyRelu=i.asm.LeakyRelu).apply(null,arguments)},i._Less=function(){return(i._Less=i.asm.Less).apply(null,arguments)},i._LessEqual=function(){return(i._LessEqual=i.asm.LessEqual).apply(null,arguments)},i._LinSpace=function(){return(i._LinSpace=i.asm.LinSpace).apply(null,arguments)},i._Log=function(){return(i._Log=i.asm.Log).apply(null,arguments)},i._Log1p=function(){return(i._Log1p=i.asm.Log1p).apply(null,arguments)},i._LogicalAnd=function(){return(i._LogicalAnd=i.asm.LogicalAnd).apply(null,arguments)},i._LogicalNot=function(){return(i._LogicalNot=i.asm.LogicalNot).apply(null,arguments)},i._LogicalOr=function(){return(i._LogicalOr=i.asm.LogicalOr).apply(null,arguments)},i._LogicalXor=function(){return(i._LogicalXor=i.asm.LogicalXor).apply(null,arguments)},i._Max=function(){return(i._Max=i.asm.Max).apply(null,arguments)},i._MaxPool=function(){return(i._MaxPool=i.asm.MaxPool).apply(null,arguments)},i._MaxPool3D=function(){return(i._MaxPool3D=i.asm.MaxPool3D).apply(null,arguments)},i._MaxPool3DGrad=function(){return(i._MaxPool3DGrad=i.asm.MaxPool3DGrad).apply(null,arguments)},i._MaxPoolGrad=function(){return(i._MaxPoolGrad=i.asm.MaxPoolGrad).apply(null,arguments)},i._MaxPoolWithArgmax=function(){return(i._MaxPoolWithArgmax=i.asm.MaxPoolWithArgmax).apply(null,arguments)},i._Maximum=function(){return(i._Maximum=i.asm.Maximum).apply(null,arguments)},i._Mean=function(){return(i._Mean=i.asm.Mean).apply(null,arguments)},i._Min=function(){return(i._Min=i.asm.Min).apply(null,arguments)},i._Minimum=function(){return(i._Minimum=i.asm.Minimum).apply(null,arguments)},i._MirrorPad=function(){return(i._MirrorPad=i.asm.MirrorPad).apply(null,arguments)},i._Mod=function(){return(i._Mod=i.asm.Mod).apply(null,arguments)},i._Multinomial=function(){return(i._Multinomial=i.asm.Multinomial).apply(null,arguments)},i._Multiply=function(){return(i._Multiply=i.asm.Multiply).apply(null,arguments)},i._Neg=function(){return(i._Neg=i.asm.Neg).apply(null,arguments)},i._NonMaxSuppressionV3=function(){return(i._NonMaxSuppressionV3=i.asm.NonMaxSuppressionV3).apply(null,arguments)},i._NonMaxSuppressionV4=function(){return(i._NonMaxSuppressionV4=i.asm.NonMaxSuppressionV4).apply(null,arguments)},i._NonMaxSuppressionV5=function(){return(i._NonMaxSuppressionV5=i.asm.NonMaxSuppressionV5).apply(null,arguments)},i._NotEqual=function(){return(i._NotEqual=i.asm.NotEqual).apply(null,arguments)},i._OneHot=function(){return(i._OneHot=i.asm.OneHot).apply(null,arguments)},i._PadV2=function(){return(i._PadV2=i.asm.PadV2).apply(null,arguments)},i._Pow=function(){return(i._Pow=i.asm.Pow).apply(null,arguments)},i._Prelu=function(){return(i._Prelu=i.asm.Prelu).apply(null,arguments)},i._Prod=function(){return(i._Prod=i.asm.Prod).apply(null,arguments)},i._RealDiv=function(){return(i._RealDiv=i.asm.RealDiv).apply(null,arguments)},i._Reciprocal=function(){return(i._Reciprocal=i.asm.Reciprocal).apply(null,arguments)},i._Relu=function(){return(i._Relu=i.asm.Relu).apply(null,arguments)},i._Relu6=function(){return(i._Relu6=i.asm.Relu6).apply(null,arguments)},i._ResizeBilinear=function(){return(i._ResizeBilinear=i.asm.ResizeBilinear).apply(null,arguments)},i._ResizeBilinearGrad=function(){return(i._ResizeBilinearGrad=i.asm.ResizeBilinearGrad).apply(null,arguments)},i._ResizeNearestNeighbor=function(){return(i._ResizeNearestNeighbor=i.asm.ResizeNearestNeighbor).apply(null,arguments)},i._ResizeNearestNeighborGrad=function(){return(i._ResizeNearestNeighborGrad=i.asm.ResizeNearestNeighborGrad).apply(null,arguments)},i._Reverse=function(){return(i._Reverse=i.asm.Reverse).apply(null,arguments)},i._RotateWithOffset=function(){return(i._RotateWithOffset=i.asm.RotateWithOffset).apply(null,arguments)},i._Round=function(){return(i._Round=i.asm.Round).apply(null,arguments)},i._Rsqrt=function(){return(i._Rsqrt=i.asm.Rsqrt).apply(null,arguments)},i._ScatterNd=function(){return(i._ScatterNd=i.asm.ScatterNd).apply(null,arguments)},i._SearchSorted=function(){return(i._SearchSorted=i.asm.SearchSorted).apply(null,arguments)},i._SelectV2=function(){return(i._SelectV2=i.asm.SelectV2).apply(null,arguments)},i._Selu=function(){return(i._Selu=i.asm.Selu).apply(null,arguments)},i._Sigmoid=function(){return(i._Sigmoid=i.asm.Sigmoid).apply(null,arguments)},i._Sign=function(){return(i._Sign=i.asm.Sign).apply(null,arguments)},i._Sin=function(){return(i._Sin=i.asm.Sin).apply(null,arguments)},i._Sinh=function(){return(i._Sinh=i.asm.Sinh).apply(null,arguments)},i._Softmax=function(){return(i._Softmax=i.asm.Softmax).apply(null,arguments)},i._Softplus=function(){return(i._Softplus=i.asm.Softplus).apply(null,arguments)},i._SparseFillEmptyRows=function(){return(i._SparseFillEmptyRows=i.asm.SparseFillEmptyRows).apply(null,arguments)},i._SparseReshape=function(){return(i._SparseReshape=i.asm.SparseReshape).apply(null,arguments)},i._SparseSegmentReduction=function(){return(i._SparseSegmentReduction=i.asm.SparseSegmentReduction).apply(null,arguments)},i._SparseToDense=function(){return(i._SparseToDense=i.asm.SparseToDense).apply(null,arguments)},i._Sqrt=function(){return(i._Sqrt=i.asm.Sqrt).apply(null,arguments)},i._Square=function(){return(i._Square=i.asm.Square).apply(null,arguments)},i._SquaredDifference=function(){return(i._SquaredDifference=i.asm.SquaredDifference).apply(null,arguments)},i._Step=function(){return(i._Step=i.asm.Step).apply(null,arguments)},i._StridedSlice=function(){return(i._StridedSlice=i.asm.StridedSlice).apply(null,arguments)},i._Sub=function(){return(i._Sub=i.asm.Sub).apply(null,arguments)},i._Sum=function(){return(i._Sum=i.asm.Sum).apply(null,arguments)},i._Tan=function(){return(i._Tan=i.asm.Tan).apply(null,arguments)},i._Tanh=function(){return(i._Tanh=i.asm.Tanh).apply(null,arguments)},i._TensorScatterUpdate=function(){return(i._TensorScatterUpdate=i.asm.TensorScatterUpdate).apply(null,arguments)},i._Tile=function(){return(i._Tile=i.asm.Tile).apply(null,arguments)},i._TopK=function(){return(i._TopK=i.asm.TopK).apply(null,arguments)},i._Transform=function(){return(i._Transform=i.asm.Transform).apply(null,arguments)},i._Transpose=function(){return(i._Transpose=i.asm.Transpose).apply(null,arguments)},i.__FusedMatMul=function(){return(i.__FusedMatMul=i.asm._FusedMatMul).apply(null,arguments)},i._malloc=function(){return(i._malloc=i.asm.malloc).apply(null,arguments)},i._free=function(){return(i._free=i.asm.free).apply(null,arguments)},i.___errno_location=function(){return(i.___errno_location=i.asm.__errno_location).apply(null,arguments)},i.stackSave=function(){return(te=i.stackSave=i.asm.stackSave).apply(null,arguments)}),ne=i.stackRestore=function(){return(ne=i.stackRestore=i.asm.stackRestore).apply(null,arguments)},re=i.stackAlloc=function(){return(re=i.stackAlloc=i.asm.stackAlloc).apply(null,arguments)};i.dynCall_iijjiiii=function(){return(i.dynCall_iijjiiii=i.asm.dynCall_iijjiiii).apply(null,arguments)},i.dynCall_jiji=function(){return(i.dynCall_jiji=i.asm.dynCall_jiji).apply(null,arguments)};function ae(e){function t(){Q||(Q=!0,i.calledRun=!0,S||(H(D),r(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for("function"==typeof i.postRun&&(i.postRun=[i.postRun]);i.postRun.length;)e=i.postRun.shift(),F.unshift(e);var e;H(F)}()))}e=e||d,M>0||(!function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)e=i.preRun.shift(),R.unshift(e);var e;H(R)}(),M>0||(i.setStatus?(i.setStatus("Running..."),setTimeout((function(){setTimeout((function(){i.setStatus("")}),1),t()}),1)):t()))}if(i.cwrap=function(e,t,n,r){var a=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&a&&!r?K(e):function(){return Y(e,t,n,arguments)}},z=function e(){Q||ae(),Q||(z=e)},i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();if(ae(),s&&(X={uncaughtException:process.listeners("uncaughtException").filter((function(e){return!s.uncaughtException.indexOf(e)>-1})),unhandledRejection:process.listeners("unhandledRejection").filter((function(e){return!s.unhandledRejection.indexOf(e)>-1}))}),"undefined"!==typeof t)J=t;else{if("undefined"===typeof WasmBackendModuleThreadedSimd)throw new Error("Could not find wasm module in post.js");J=WasmBackendModuleThreadedSimd}if(X){var se=J._dispose;J._dispose=function(){se(),X.uncaughtException.forEach((function(e){process.removeListener("uncaughtException",e)})),X.unhandledRejection.forEach((function(e){process.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=r},3879:(e,t,n)=>{"use strict";n.r(t),n.d(t,{arraysEqual:()=>s.r1,arraysEqualWithNull:()=>s.e_,assert:()=>s.vA,assertNonNegativeIntegerDimensions:()=>s.SA,assertNonNull:()=>s.HO,assertShapesMatch:()=>s.O3,bytesFromStringArray:()=>s.SL,bytesPerElement:()=>s.jv,checkConversionForErrors:()=>s.nd,clamp:()=>s.qE,computeStrides:()=>s.Ur,convertBackendValuesAndArrayBuffer:()=>s.o2,createScalarValue:()=>w,createShuffledIndices:()=>s.P8,decodeString:()=>I,distSquared:()=>s.oO,encodeString:()=>_,fetch:()=>S,fingerPrint64:()=>x,flatten:()=>$,getArrayFromDType:()=>s.Ab,getTypedArrayFromDType:()=>s.ce,hasEncodingLoss:()=>s.BE,hexToLong:()=>u,indexToLoc:()=>s._k,inferDtype:()=>s.X$,inferFromImplicitShape:()=>s.XT,isBoolean:()=>s.Lm,isFunction:()=>s.Tn,isInt:()=>s.E6,isNumber:()=>s.Et,isPromise:()=>s.yL,isScalarShape:()=>s.Sf,isString:()=>s.Kg,isTypedArray:()=>T,isValidDtype:()=>s.xn,locToIndex:()=>s.sX,makeOnesTypedArray:()=>s.FZ,makeZerosNestedTypedArray:()=>s.c7,makeZerosTypedArray:()=>s.Ty,nearestDivisor:()=>s.lK,nearestLargerEven:()=>s.eV,now:()=>k,parseAxisParam:()=>s.Y6,randUniform:()=>s.so,repeatedTry:()=>s._q,rightPad:()=>s.av,shuffle:()=>s.k4,shuffleCombo:()=>s.a0,sizeFromShape:()=>s.Ze,sizeToSquarishShape:()=>s.gS,squeezeShape:()=>s.gx,sum:()=>s.cz,swap:()=>s.wg,tanh:()=>s.ym,toNestedArray:()=>s.yw,toTypedArray:()=>v});var r=n(6574),a=n(6448),s=n(5119),i=n(8570);const o=n.n(i)()||i;function u(e){return o.fromString(e,!0,16)}const l=u("c3a5c85c97cb3127"),c=u("b492b66fbe98f273"),d=u("9ae16a3b2f90404f");function p(e){return e.xor(e.shru(47))}function h(e,t,n){const r=e.slice(t,t+n);return o.fromBytes(Array.from(r),!0,!0)}function f(e,t){return h(e,t,8)}function m(e,t){return h(e,t,4)}function g(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function y(e,t,n=u("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 b(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=g(s.add(a).add(r),21);const i=a;return a=(a=a.add(t)).add(n),s=s.add(g(a,44)),[a.add(r),s.add(i)]}(f(e,t),f(e,t+8),f(e,t+16),f(e,t+24),n,r)}function x(e,t=e.length){const n=o.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=d.add(2*t),r=f(e,0).add(d),a=f(e,t-8);return y(g(a,37).mul(n).add(r),g(r,25).add(a).mul(n),n)}if(t>=4){const n=d.add(2*t);return y(m(e,0).shl(3).add(t),m(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return p(d.mul(n).xor(l.mul(r))).mul(d)}return d}(e,t):function(e,t=e.length){const n=d.add(2*t),r=f(e,0).mul(c),a=f(e,8),s=f(e,t-8).mul(n),i=f(e,t-16).mul(d);return y(g(r.add(a),43).add(g(s,30)).add(i),r.add(g(a.add(d),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=d.add(2*t),r=f(e,0).mul(d),a=f(e,8),s=f(e,t-8).mul(n),i=f(e,t-16).mul(d),o=g(r.add(a),43).add(g(s,30)).add(i),u=y(o,r.add(g(a.add(d),18)).add(s),n),l=f(e,16).mul(n),c=f(e,24),p=o.add(f(e,t-32)).mul(n),h=u.add(f(e,t-24)).mul(n);return y(g(l.add(c),43).add(g(p,30)).add(h),l.add(g(c.add(r),18)).add(p),n)}(e,t);let r=n,a=n.mul(c).add(113),s=p(a.mul(d).add(113)).mul(d),i=[o.UZERO,o.UZERO],u=[o.UZERO,o.UZERO];r=r.mul(d).add(f(e,0));let h=0;const x=64*(t-1>>6),w=x+(t-1&63)-63;do{r=g(r.add(a).add(i[0]).add(f(e,h+8)),37).mul(c),a=g(a.add(i[1]).add(f(e,h+48)),42).mul(c),r=r.xor(u[1]),a=a.add(i[0]).add(f(e,h+40)),s=g(s.add(u[0]),33).mul(c),i=b(e,h,i[1].mul(c),r.add(u[0])),u=b(e,h+32,s.add(u[1]),a.add(f(e,h+16))),[s,r]=[r,s],h+=64}while(h!==x);const v=c.add(s.and(255).shl(1));return h=w,u[0]=u[0].add(t-1&63),i[0]=i[0].add(u[0]),u[0]=u[0].add(i[0]),r=g(r.add(a).add(i[0]).add(f(e,h+8)),37).mul(v),a=g(a.add(i[1]).add(f(e,h+48)),42).mul(v),r=r.xor(u[1].mul(9)),a=a.add(i[0].mul(9).add(f(e,h+40))),s=g(s.add(u[0]),33).mul(v),i=b(e,h,i[1].mul(v),r.add(u[0])),u=b(e,h+32,s.add(u[1]),a.add(f(e,h+16))),[s,r]=[r,s],y(y(i[0],u[0],v).add(p(a).mul(l)).add(s),y(i[1],u[1],v).add(r),v)}function w(e,t){return"string"===t?_(e):v([e],t)}function v(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=$(e)),(0,r._K)().getBool("DEBUG")&&s.nd(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 k(){return(0,r._K)().platform.now()}function S(e,t){return(0,r._K)().platform.fetch(e,t)}function _(e,t="utf-8"){return t=t||"utf-8",(0,r._K)().platform.encode(e,t)}function I(e,t="utf-8"){return t=t||"utf-8",(0,r._K)().platform.decode(e,t)}function T(e){return null!=(0,r._K)().platform.isTypedArray?(0,r._K)().platform.isTypedArray(e):(0,a.Y)(e)}function $(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"===typeof e||"number"===typeof e||"string"===typeof e||s.yL(e)||null==e||T(e)&&n)t.push(e);else if(Array.isArray(e)||T(e))for(let r=0;r<e.length;++r)$(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++)$(e[a],t,n)}return t}},3909:(e,t,n)=>{"use strict";n.d(t,{$:()=>d});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(9809),u=n(7195),l=n(929),c=n(2302);const d=(0,l.op)({avgPool_:function(e,t,n,l,d){const p=(0,s.YT)(e,"x","avgPool","float32");i.vA(u.G0(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let h=p,f=!1;3===p.rank&&(f=!0,h=(0,c.t)(p,[1,p.shape[0],p.shape[1],p.shape[2]])),i.vA(4===h.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${h.rank}.`)),u.s_("avgPool",l,d);const m={x:h},g={filterSize:t,strides:n,pad:l,dimRoundingMode:d};let y=r.T2.runKernel(a.ho8,m,g);return y=(0,o.w)(y,p.dtype),f?(0,c.t)(y,[y.shape[1],y.shape[2],y.shape[3]]):y}})},3937:(e,t,n)=>{"use strict";n.d(t,{A:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({unique_:function(e,t=0){const n=(0,s.YT)(e,"x","unique","string_or_numeric");(0,i.vA)(n.rank>0,(()=>"The input tensor must be at least 1D"));const o={x:n},u={axis:t},[l,c]=r.T2.runKernel(a.EwU,o,u);return{values:l,indices:c}}})},4010:(e,t,n)=>{"use strict";n.d(t,{R:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({log_:function(e){const t={x:(0,s.YT)(e,"x","log","float32")};return r.T2.runKernel(a.tG8,t)}})},4027:(e,t,n)=>{"use strict";n.d(t,{O:()=>s});var r=n(8189),a=n(9171);function s(e,t,n){const s=(0,r.MZ)(e,n);return(0,a.Q)(e,t,s,n)}},4268:(e,t,n)=>{"use strict";n.d(t,{t:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({stack_:function(e,t=0){const n=(0,s.j1)(e,"tensors","stack","string_or_numeric");i.vA(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&i.vA(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const o=n,u={axis:t};return r.T2.runKernel(a.mM$,o,u)}})},4339:(e,t,n)=>{"use strict";n.d(t,{X:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({argMin_:function(e,t=0){const n={x:(0,s.YT)(e,"x","argMin")},i={axis:t};return r.T2.runKernel(a.p_m,n,i)}})},4394:(e,t,n)=>{"use strict";n.d(t,{N:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({prelu_:function(e,t){const n={x:(0,s.YT)(e,"x","prelu"),alpha:(0,s.YT)(t,"alpha","prelu")};return r.T2.runKernel(a.Ncv,n)}})},4411:(e,t,n)=>{"use strict";n.d(t,{Y:()=>a});var r=n(448);function a(e,t){const n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(r);const a=(0,r.r)(e,"int32"),s=(0,r.r)([n.length,e.length],"int32");for(let r=0;r<n.length;r++){const t=a.indexToLoc(n[r]),i=r*e.length;s.values.set(t,i)}return s.toTensor()}},4530:()=>{},4687:e=>{function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=4687,e.exports=t},4703:(e,t,n)=>{"use strict";var r;n.d(t,{i:()=>r}),function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(r||(r={}))},4711:(e,t,n)=>{"use strict";n.d(t,{v:()=>l});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(929),u=n(2302);const l=(0,o.op)({resizeBilinear_:function(e,t,n=!1,o=!1){const l=(0,s.YT)(e,"images","resizeBilinear");i.vA(3===l.rank||4===l.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${l.rank}.`)),i.vA(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),i.vA(!1===o||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let c=l,d=!1;3===l.rank&&(d=!0,c=(0,u.t)(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const[]=t,p={images:c},h={alignCorners:n,halfPixelCenters:o,size:t},f=r.T2.runKernel(a.hgw,p,h);return d?(0,u.t)(f,[f.shape[1],f.shape[2],f.shape[3]]):f}})},4801:function(e,t,n){var r;!function(a,s,i){var o,u=256,l=i.pow(u,6),c=i.pow(2,52),d=2*c,p=255;function h(e,t,n){var r=[],p=y(g((t=1==t?{entropy:!0}:t||{}).entropy?[e,b(s)]:null==e?function(){try{var e;return o&&(e=o.randomBytes)?e=e(u):(e=new Uint8Array(u),(a.crypto||a.msCrypto).getRandomValues(e)),b(e)}catch(r){var t=a.navigator,n=t&&t.plugins;return[+new Date,a,n,a.screen,b(s)]}}():e,3),r),h=new f(r),x=function(){for(var e=h.g(6),t=l,n=0;e<c;)e=(e+n)*u,t*=u,n=h.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|h.g(4)},x.quick=function(){return h.g(4)/4294967296},x.double=x,y(b(h.S),s),(t.pass||n||function(e,t,n,r){return r&&(r.S&&m(r,h),e.state=function(){return m(h,{})}),n?(i.random=e,t):e})(x,p,"global"in t?t.global:this==i,t.state)}function f(e){var t,n=e.length,r=this,a=0,s=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);a<u;)i[a]=a++;for(a=0;a<u;a++)i[a]=i[s=p&s+e[a%n]+(t=i[a])],i[s]=t;(r.g=function(e){for(var t,n=0,a=r.i,s=r.j,i=r.S;e--;)t=i[a=p&a+1],n=n*u+i[p&(i[a]=i[s=p&s+t])+(i[s]=t)];return r.i=a,r.j=s,n})(u)}function m(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function g(e,t){var n,r=[],a=typeof e;if(t&&"object"==a)for(n in e)try{r.push(g(e[n],t-1))}catch(s){}return r.length?r:"string"==a?e:e+"\0"}function y(e,t){for(var n,r=e+"",a=0;a<r.length;)t[p&a]=p&(n^=19*t[p&a])+r.charCodeAt(a++);return b(t)}function b(e){return String.fromCharCode.apply(0,e)}if(y(i.random(),s),e.exports){e.exports=h;try{o=n(1234)}catch(x){}}else void 0===(r=function(){return h}.call(t,n,t,e))||(e.exports=r)}("undefined"!==typeof self?self:this,[],Math)},4826:(e,t,n)=>{"use strict";n.d(t,{V:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({tile_:function(e,t){const n=(0,s.YT)(e,"x","tile","string_or_numeric");i.vA(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const o={x:n},u={reps:t};return r.T2.runKernel(a.FAs,o,u)}})},4881:(e,t,n)=>{"use strict";n.d(t,{p:()=>a});var r=n(2596);const a=(0,n(929).op)({euclideanNorm_:function(e,t=null,n=!1){return(0,r.x)(e,"euclidean",t,n)}})},4888:(e,t,n)=>{"use strict";n.d(t,{t:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({abs_:function(e){const t=(0,s.YT)(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return r.T2.runKernel(a.$zE,e)}{const e={x:t};return r.T2.runKernel(a.ljI,e)}}})},4969:(e,t,n)=>{"use strict";n.r(t),n.d(t,{assertParamsValid:()=>i,computeFlatOffset:()=>x,computeOutShape:()=>u,getNormalizedAxes:()=>p,isSliceContinous:()=>b,maskToAxes:()=>o,parseSliceParams:()=>w,sliceInfo:()=>v,startForAxis:()=>g,startIndicesWithElidedDims:()=>h,stopForAxis:()=>y,stopIndicesWithElidedDims:()=>f,stridesForAxis:()=>m,stridesWithElidedDims:()=>l});var r=n(5119);const a=-2,s=-1;function i(e,t,n){const a=e.shape.length;r.vA(a===t.length,(()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`)),r.vA(a===n.length,(()=>`Error in slice${a}D: Length of size ${n} must match the rank of the array (${a}).`));for(let s=0;s<a;++s)r.vA(t[s]+n[s]<=e.shape[s],(()=>`Error in slice${a}D: begin[${s}] + size[${s}] (${t[s]+n[s]}) would overflow input.shape[${s}] (${e.shape[s]})`))}function o(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function u(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 l(e,t,n,r){const a=[...e];for(let s=a.length;s<r.length;s++)a.push(1);for(let s=0;s<n;s++)0===s?a[t]=1:(a.splice(t,0,1),a.pop());return a}function c(e,t,n){return n<=e?n:n-(t-1)}function d(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function p(e,t,n,r,a,s,i,o,u){const c=e.length;let d=new Array(c),p=new Array(c),b=new Array(c);if(t.length&&n>0){const u=t[0],c=n+1;d=h(i,u,c,r,e),p=f(o,u,c,a,e),b=l(s,u,c,e)}else for(let l=0;l<c;l++)d[l]=g(i,r,s,e,l,u),p[l]=y(o,a,s,e,l,u),b[l]=m(s,l,u);return{begin:d,end:p,strides:b}}function h(e,t,n,r,a){const s=[...a],i=d(n,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{const a=c(t,n,o);let i=r[a];e&1<<a&&(i=0),s[o]=i}return s}function f(e,t,n,a,s){const i=[...s],o=d(n,t);for(let r=0;r<i.length;r++)if(o.indexOf(r)>-1)i[r]=Number.MAX_SAFE_INTEGER;else{const s=c(t,n,r);let o=a[s];e&1<<s&&(o=Number.MAX_SAFE_INTEGER),i[r]=o}for(let u=0;u<i.length;u++){const e=s[u];i[u]<0&&(i[u]+=e),i[u]=r.qE(0,i[u],s[u])}return i}function m(e,t,n){let r=e[t];return(n&1<<t||null==r)&&(r=1),r}function g(e,t,n,a,s,i){let o=t[s];const u=n[s]||1;(e&1<<s||i&1<<s||null==o)&&(o=u>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const l=a[s];return o<0&&(o+=l),o=r.qE(0,o,l-1),o}function y(e,t,n,a,s,i){let o=t[s];const u=n[s]||1;(e&1<<s||i&1<<s||null==o)&&(o=u>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const l=a[s];return o<0&&(o+=l),o=u>0?r.qE(0,o,l):r.qE(-1,o,l-1),o}function b(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 x(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 w(e,t,n){let a;const s=e.shape.length;let i;return a="number"===typeof t?[t,...new Array(s-1).fill(0)]:t.length<s?t.concat(new Array(s-t.length).fill(0)):t.slice(),a.forEach((e=>{r.vA(-1!==e,(()=>"slice() does not support negative begin indexing."))})),i=null==n?new Array(s).fill(-1):"number"===typeof n?[n,...new Array(s-1).fill(-1)]:n.length<s?n.concat(new Array(s-n.length).fill(-1)):n,i=i.map(((t,n)=>t>=0?t:(r.vA(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-a[n]))),[a,i]}function v(e,t,n,r,i,o,u,l,c){let d;if(null==r?(d=new Array(t.length),d.fill(1)):d=r,null!=u&&0!==(u&u-1))throw new Error("Multiple ellipses in slice is not allowed.");let p=!1;const h={dims:d.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:d.slice(),beginMask:i,endMask:o,ellipsisMask:u,newAxisMask:l,shrinkAxisMask:c};for(let a=0;a<h.dims;a++)p&&0!==(1<<a&l)&&h.numAddAxisAfterEllipsis++,1<<a&u&&(p=!0);p||(h.ellipsisMask|=1<<h.dims,h.dims++);const f={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(a),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(s),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(r)),t.inputShapeGatherIndicesSparse[n]=r,n++}}(h,f);let m=!0,g=!0,y=!0;const b=[],x=[];for(let a=0;a<e.length;++a){if(0===f.strides[a])throw Error(`strides[${a}] must be non-zero`);const t=!!(f.shrinkAxisMask&1<<a),n=e[a];if(-1===n){b.push(t?1:-1);continue}const r=[f.beginMask&1<<a,f.endMask&1<<a],s=[f.strides[a]>0?0:-1,f.strides[a]>0?n:n-1];if(t&&f.strides[a]<=0)throw Error("only stride 1 allowed on non-range indexing.");y=y&&1===f.strides[a];const i=!!(f.beginMask&1<<a&&f.endMask&1<<a);if(f.beginValid&&f.endValid){if(t){const e=f.begin[a]<0?n+f.begin[a]:f.begin[a];if(f.begin[a]=e,f.end[a]=f.begin[a]+1,e<0||e>=n)throw Error(`slice index ${f.begin[a]} of dimension ${a} out of bounds.`)}else f.begin[a]=k(f.begin[a],0,f.strides[a],n,r,s),f.end[a]=k(f.end[a],1,f.strides[a],n,r,s);const e=1===f.strides[a]&&0===f.begin[a]&&f.end[a]===n;m=m&&e,g=g&&(0===a&&1===f.strides[a]||e)}else m=m&&1===f.strides[a]&&i,g=g&&(0===a&&1===f.strides[a]||i);let o,u=!1;if(f.beginValid&&f.endValid?(o=f.end[a]-f.begin[a],u=!0):t?(o=1,u=!0):i&&n>=0&&(o=f.strides[a]<0?-n:n,u=!0),u){let e;e=0===o||o<0!==f.strides[a]<0?0:Math.trunc(o/f.strides[a])+(o%f.strides[a]!==0?1:0),b.push(e)}else b.push(-1)}for(let s=0;s<f.finalShapeGatherIndices.length;++s){const e=f.finalShapeGatherIndices[s];e>=0?x.push(b[e]):e===a&&x.push(1)}return{finalShapeSparse:x.filter(((e,t)=>f.finalShapeGatherIndices[t]!==a)),finalShape:x,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:f.begin,end:f.end,strides:f.strides}}function k(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}}},5030:(e,t,n)=>{"use strict";n.d(t,{x:()=>u});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(125);const u=(0,n(929).op)({concat_:function(e,t=0){(0,i.vA)(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=(0,s.j1)(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(0,o.o)(n[0]);const u=n,l={axis:t};return r.T2.runKernel(a.$dB,u,l)}})},5040:(e,t,n)=>{"use strict";n.d(t,{n:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({imag_:function(e){const t={input:(0,s.YT)(e,"input","imag")};return r.T2.runKernel(a.dv8,t)}})},5119:(e,t,n)=>{"use strict";function r(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,o(e,t,n)}function a(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,r=0;for(;n>0;)r=Math.random()*n|0,n--,o(e,n,r),o(t,n,r)}function s(e,t,n){return Math.max(e,Math.min(t,n))}function i(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 u(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function l(e,t){const n=Math.random();return t*n+(1-n)*e}function c(e,t){let n=0;for(let r=0;r<e.length;r++){const a=Number(e[r])-Number(t[r]);n+=a*a}return n}function d(e,t){if(!e)throw new Error("string"===typeof t?t:t())}function p(e,t,n=""){d(y(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function h(e){d(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function f(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 m(e){return 0===e.length}function g(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}function y(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 b(e){return e%1===0}function x(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function w(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function v(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return r(t),t}function k(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function S(e,t=e=>0,n,r){return new Promise(((a,s)=>{let i=0;const o=()=>{if(e())return void a();i++;const u=t(i);null!=n&&i>=n?s():null!=r?r(o,u):setTimeout(o,u)};o()}))}function _(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 I(e,t){const n=t.length;return d((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}`)),d(e.every((e=>b(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function T(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:I(t,e).sort();let i=0;for(let o=0;o<e.length;++o){if(null!=s){if(s[i]===o&&1!==e[o])throw new Error(`Can't squeeze axis ${o} since its dim '${e[o]}' is not 1`);(null==s[i]||s[i]>o)&&1===e[o]&&(n.push(e[o]),r.push(o)),s[i]<=o&&i++}1!==e[o]&&(n.push(e[o]),r.push(o))}return{newShape:n,keptDims:r}}function $(e,t){return C(e,t)}function C(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 N(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}.`)}}function E(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function A(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function R(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 D(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}function F(e){return"string"===typeof e||e instanceof String}function M(e){return"boolean"===typeof e}function O(e){return"number"===typeof e}function z(e){return Array.isArray(e)?z(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":O(e)?"float32":F(e)?"string":M(e)?"bool":"float32"}function L(e){return!!(e&&e.constructor&&e.call&&e.apply)}function P(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function B(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 W(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],i=t.slice(1),o=i.reduce(((e,t)=>e*t))*(r?2:1);for(let t=0;t<s;t++)a[t]=W(e+t*o,i,n,r)}return a}function V(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 W(0,e,t,n)}function U(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}`)}function G(e,t){const n=H(e,t);for(let r=0;r<n.length;r++)n[r]=1;return n}function H(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 j(e,t){const n=e.reduce(((e,t)=>e*t),1);if(null==t||"float32"===t)return V(e,new Float32Array(n));if("int32"===t)return V(e,new Int32Array(n));if("bool"===t)return V(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function q(e){e.forEach((t=>{d(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function Z(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 K(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 Y(e){return e&&e.then&&"function"===typeof e.then}n.d(t,{Ab:()=>C,BE:()=>A,E6:()=>b,Et:()=>O,FZ:()=>G,HO:()=>h,Kg:()=>F,Lm:()=>M,O3:()=>p,P8:()=>v,SA:()=>q,SL:()=>D,Sf:()=>m,Tn:()=>L,Ty:()=>H,Ur:()=>B,X$:()=>z,XT:()=>_,Y6:()=>I,Ze:()=>f,_k:()=>K,_q:()=>S,a0:()=>a,av:()=>k,c7:()=>j,ce:()=>$,cz:()=>u,eV:()=>i,e_:()=>g,gS:()=>w,gx:()=>T,jv:()=>R,k4:()=>r,lK:()=>P,nd:()=>N,o2:()=>U,oO:()=>c,qE:()=>s,r1:()=>y,sX:()=>Z,so:()=>l,vA:()=>d,wg:()=>o,xn:()=>E,yL:()=>Y,ym:()=>x,yw:()=>V})},5149:(e,t,n)=>{"use strict";n.d(t,{GJ:()=>r,uI:()=>a});class r{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 a{refCount(e){return s("refCount")}incRef(e){return s("incRef")}timerAvailable(){return!0}time(e){return s("time")}read(e){return s("read")}readSync(e){return s("readSync")}readToGPU(e,t){return s("readToGPU")}numDataIds(){return s("numDataIds")}disposeData(e,t){return s("disposeData")}write(e,t,n){return s("write")}move(e,t,n,r,a){return s("move")}createTensorFromGPUData(e,t,n){return s("createTensorFromGPUData")}memory(){return s("memory")}floatPrecision(){return s("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return s("dispose")}}function s(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`)}},5207:(e,t,n)=>{"use strict";n.d(t,{Y:()=>u});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(9809);const u=(0,n(929).op)({erf_:function(e){let t=(0,s.YT)(e,"x","erf");i.vA("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=(0,o.w)(t,"float32"));const n={x:t};return r.T2.runKernel(a._s9,n)}})},5248:(e,t,n)=>{"use strict";n.d(t,{H:()=>l});var r=n(1585),a=n(5441),s=n(5119),i=n(7195),o=n(929),u=n(2302);const l=(0,o.op)({conv2DBackpropFilter_:function(e,t,n,o,l,c="NHWC",d){let p=e;3===e.rank&&(p=(0,u.t)(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let h=t;3===h.rank&&(h=(0,u.t)(t,[1,t.shape[0],t.shape[1],t.shape[2]])),s.vA(4===p.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${p.shape}.`)),s.vA(4===h.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${h.shape}.`)),s.vA(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const f="NHWC"===c?p.shape[3]:p.shape[1],m="NHWC"===c?h.shape[3]:h.shape[1];s.vA(f===n[2],(()=>`Error in conv2dDerFilter: depth of input ${f}) must match input depth in filter (${n[2]}.`)),s.vA(m===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${m}) must match output depth for filter (${n[3]}).`)),i.s_("conv2dDerFilter",l,d);const g={x:p,dy:h},y={strides:o,pad:l,dataFormat:c,dimRoundingMode:d,filterShape:n};return r.T2.runKernel(a.rFm,g,y)}})},5281:()=>{},5287:(e,t,n)=>{"use strict";n.d(t,{AS:()=>g,DZ:()=>m,Gc:()=>w,Hi:()=>p,Hs:()=>T,IS:()=>l,ME:()=>f,Ok:()=>$,Sm:()=>o,W4:()=>_,aC:()=>y,fL:()=>c,gJ:()=>I,gY:()=>u,go:()=>S,jh:()=>x,jz:()=>v,kB:()=>b,m1:()=>h,rE:()=>k,rm:()=>d});var r=n(1585),a=n(6574),s=n(259),i=n(565);function o(){(0,a._K)().set("PROD",!0)}function u(){(0,a._K)().set("DEBUG",!0)}function l(){(0,a._K)().set("DEPRECATION_WARNINGS_ENABLED",!1)}function c(e){(0,a._K)().getBool("DEPRECATION_WARNINGS_ENABLED")}function d(){r.T2.disposeVariables()}function p(){return r.T2}function h(){return r.T2.memory()}function f(e){return r.T2.profile(e)}function m(e,t){return r.T2.tidy(e,t)}function g(e){(0,i.getTensorsInContainer)(e).forEach((e=>e.dispose()))}function y(e){return r.T2.keep(e)}function b(e){return r.T2.time(e)}function x(e){return r.T2.setBackend(e)}function w(){return r.T2.ready()}function v(){return r.T2.backendName}function k(e){r.T2.removeBackend(e)}function S(e){return r.T2.findBackend(e)}function _(e){return r.T2.findBackendFactory(e)}function I(e,t,n=1){return r.T2.registerBackend(e,t,n)}function T(){return r.T2.backend}function $(e,t){(0,a._K)().setPlatform(e,t)}(0,s.B4)(c)},5295:(e,t,n)=>{"use strict";function r(e,t=!1){}n.d(t,{y:()=>r})},5441:(e,t,n)=>{"use strict";n.d(t,{$dB:()=>R,$jE:()=>nn,$zE:()=>A,A1h:()=>O,A8B:()=>Vt,BK4:()=>bn,BLA:()=>Qe,BRl:()=>se,Blb:()=>Ut,BoJ:()=>jt,BxF:()=>de,C8s:()=>Ht,CQC:()=>ft,Cg$:()=>Ee,CwD:()=>$e,D7i:()=>Tt,Ddj:()=>Yt,Dr:()=>xn,DvZ:()=>Zt,E3$:()=>Se,EkD:()=>o,ElG:()=>he,EwU:()=>dn,FAs:()=>on,FCQ:()=>_t,FSt:()=>l,Fin:()=>Pt,GZp:()=>Xt,HNs:()=>_,Ik2:()=>k,J3C:()=>Ot,JiE:()=>Ft,Jp_:()=>c,KXH:()=>$,L6G:()=>qt,LB5:()=>I,LDN:()=>We,LG0:()=>Ke,LRy:()=>yt,LWX:()=>st,LXA:()=>De,M6A:()=>Qt,MRQ:()=>U,Mn0:()=>P,MnK:()=>B,N4F:()=>S,Ncv:()=>dt,O4G:()=>ge,OAQ:()=>we,ODT:()=>ut,OMN:()=>i,ORI:()=>K,PH8:()=>s,P_L:()=>It,Pah:()=>ne,PbM:()=>rn,Q6t:()=>gt,QDP:()=>C,QKF:()=>p,Qgm:()=>te,R23:()=>wt,RMm:()=>fn,RUm:()=>Ae,RW8:()=>Fe,RXX:()=>Ue,SDM:()=>nt,SQl:()=>ce,T7M:()=>vn,TBb:()=>un,TL8:()=>je,TMz:()=>H,TOR:()=>Ct,ToN:()=>Le,TyE:()=>f,UcO:()=>Jt,VAI:()=>Be,VCH:()=>b,Vvy:()=>a,WRv:()=>Pe,WT3:()=>Xe,WuN:()=>Wt,X$8:()=>q,X0$:()=>Ie,X4r:()=>Et,XQy:()=>kt,XhZ:()=>ye,XmO:()=>J,YAb:()=>en,YVe:()=>zt,ZgB:()=>pe,Zl4:()=>rt,_s9:()=>ae,aAr:()=>wn,awo:()=>yn,bCz:()=>lt,bP9:()=>Q,cHb:()=>He,cS:()=>x,dFH:()=>Bt,dLy:()=>ln,dXR:()=>pn,dv8:()=>ve,e0f:()=>at,epO:()=>h,fUj:()=>xt,g5A:()=>qe,gC7:()=>L,gIW:()=>ke,hVg:()=>$t,hgw:()=>St,ho8:()=>y,hql:()=>Mt,huO:()=>bt,i5R:()=>fe,iGz:()=>z,iPs:()=>_e,iW0:()=>tn,iuW:()=>sn,jAQ:()=>v,jM4:()=>ze,jOE:()=>vt,jfg:()=>M,jgd:()=>Kt,jj_:()=>W,jxD:()=>Y,kdj:()=>pt,l0G:()=>et,l6P:()=>Rt,lLS:()=>be,lNG:()=>Ze,ljI:()=>r,lxb:()=>g,lzr:()=>xe,mH5:()=>mt,mIA:()=>Te,mM$:()=>ot,mnI:()=>Ce,mxL:()=>me,nVu:()=>Z,nY8:()=>V,nZd:()=>Re,oFs:()=>an,oJ2:()=>ht,ox3:()=>ie,p2J:()=>D,pJc:()=>Nt,pPe:()=>hn,p_m:()=>d,pk0:()=>X,pnw:()=>gn,pr3:()=>E,pyJ:()=>ct,rFG:()=>Gt,rFm:()=>F,rGP:()=>le,rsH:()=>re,sDr:()=>ee,t3d:()=>Ve,tG8:()=>Ne,tGH:()=>j,u$b:()=>Dt,u8Z:()=>u,uWl:()=>At,urI:()=>it,vI1:()=>Lt,vaV:()=>N,vj7:()=>T,wNW:()=>G,wwC:()=>w,wx0:()=>cn,x7F:()=>Ye,xJ3:()=>mn,xu7:()=>Je,yPW:()=>Oe,ySp:()=>Ge,ybN:()=>oe,ybj:()=>ue,ylV:()=>tt,zP9:()=>m,zfU:()=>Me});const r="Abs",a="Acos",s="Acosh",i="Add",o="AddN",u="All",l="Any",c="ArgMax",d="ArgMin",p="Asin",h="Asinh",f="Atan",m="Atanh",g="Atan2",y="AvgPool",b="AvgPoolGrad",x="AvgPool3D",w="AvgPool3DGrad",v="BatchMatMul",k="BatchToSpaceND",S="Bincount",_="BitwiseAnd",I="BroadcastTo",T="BroadcastArgs",$="Cast",C="Ceil",N="ClipByValue",E="Complex",A="ComplexAbs",R="Concat",D="Conv2D",F="Conv2DBackpropFilter",M="Conv2DBackpropInput",O="Conv3D",z="Conv3DBackpropFilterV2",L="Conv3DBackpropInputV2",P="Cos",B="Cosh",W="Cumprod",V="Cumsum",U="CropAndResize",G="DenseBincount",H="DepthToSpace",j="DepthwiseConv2dNative",q="DepthwiseConv2dNativeBackpropFilter",Z="DepthwiseConv2dNativeBackpropInput",K="Diag",Y="Dilation2D",Q="Dilation2DBackpropInput",X="Dilation2DBackpropFilter",J="Draw",ee="RealDiv",te="Einsum",ne="Elu",re="EluGrad",ae="Erf",se="Equal",ie="Exp",oe="ExpandDims",ue="Expm1",le="FFT",ce="Fill",de="FlipLeftRight",pe="Floor",he="FloorDiv",fe="FusedBatchNorm",me="GatherV2",ge="GatherNd",ye="Greater",be="GreaterEqual",xe="Identity",we="IFFT",ve="Imag",ke="IsFinite",Se="IsInf",_e="IsNan",Ie="LeakyRelu",Te="Less",$e="LessEqual",Ce="LinSpace",Ne="Log",Ee="Log1p",Ae="LogicalAnd",Re="LogicalNot",De="LogicalOr",Fe="LogicalXor",Me="LogSoftmax",Oe="LowerBound",ze="LRN",Le="LRNGrad",Pe="MatrixBandPart",Be="Max",We="Maximum",Ve="MaxPool",Ue="MaxPoolGrad",Ge="MaxPool3D",He="MaxPool3DGrad",je="MaxPoolWithArgmax",qe="Mean",Ze="Min",Ke="Minimum",Ye="MirrorPad",Qe="Mod",Xe="Multinomial",Je="Multiply",et="Neg",tt="NotEqual",nt="NonMaxSuppressionV3",rt="NonMaxSuppressionV4",at="NonMaxSuppressionV5",st="OnesLike",it="OneHot",ot="Pack",ut="PadV2",lt="Pool",ct="Pow",dt="Prelu",pt="Prod",ht="RaggedGather",ft="RaggedRange",mt="RaggedTensorToTensor",gt="Range",yt="Real",bt="Reciprocal",xt="Relu",wt="Reshape",vt="ResizeNearestNeighbor",kt="ResizeNearestNeighborGrad",St="ResizeBilinear",_t="ResizeBilinearGrad",It="Relu6",Tt="Reverse",$t="Round",Ct="Rsqrt",Nt="ScatterNd",Et="TensorScatterUpdate",At="SearchSorted",Rt="Select",Dt="Selu",Ft="Slice",Mt="Sin",Ot="Sinh",zt="Sign",Lt="Sigmoid",Pt="Softplus",Bt="Sqrt",Wt="Sum",Vt="SpaceToBatchND",Ut="SplitV",Gt="Softmax",Ht="SparseFillEmptyRows",jt="SparseReshape",qt="SparseSegmentMean",Zt="SparseSegmentSum",Kt="SparseToDense",Yt="SquaredDifference",Qt="Square",Xt="StaticRegexReplace",Jt="StridedSlice",en="StringNGrams",tn="StringSplit",nn="StringToHashBucketFast",rn="Sub",an="Tan",sn="Tanh",on="Tile",un="TopK",ln="Transform",cn="Transpose",dn="Unique",pn="Unpack",hn="UnsortedSegmentSum",fn="UpperBound",mn="ZerosLike",gn="Step",yn="FromPixels",bn="RotateWithOffset",xn="_FusedMatMul",wn="FusedConv2D",vn="FusedDepthwiseConv2D"},5535:(e,t,n)=>{"use strict";n.d(t,{f:()=>a});var r=n(5838);function a(e,t){const n=r.ZSL.getArrayFromDType("int32",e.length);for(let a=0;a<e.length;++a)n[a]=r.ZSL.fingerPrint64(e[a]).modulo(t).getLowBitsUnsigned();return n}},5537:(e,t,n)=>{"use strict";n.d(t,{P:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({zerosLike_:function(e){const t={x:(0,s.YT)(e,"x","zerosLike")};return r.T2.runKernel(a.xJ3,t)}})},5545:()=>{},5606:(e,t,n)=>{"use strict";n.d(t,{R:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({floor_:function(e){const t={x:(0,s.YT)(e,"x","floor","float32")};return r.T2.runKernel(a.ZgB,t)}})},5645:(e,t,n)=>{"use strict";n.d(t,{n:()=>c});var r=n(1830),a=n(8189),s=n(9258),i=n(6522),o=n(929),u=n(8968),l=n(6030);const c=(0,o.op)({logSigmoid_:function(e){const t=(0,a.YT)(e,"x","logSigmoid");return(0,r._X)((e=>({value:(0,i.H)((0,l.l)((0,i.H)(e))),gradFunc:t=>(0,s.l)(t,(0,u.r)((0,i.H)(e)))})))(t)}})},5661:(e,t,n)=>{"use strict";n.d(t,{e:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({pad_:function(e,t,n=0){const i=(0,s.YT)(e,"x","pad");if(0===i.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const o={paddings:t,constantValue:n},u={x:i};return r.T2.runKernel(a.ODT,u,o)}})},5685:(e,t,n)=>{"use strict";n.d(t,{i:()=>r});const r={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8}},5702:(e,t,n)=>{"use strict";n.d(t,{d:()=>s});var r=n(3879),a=n(9171);function s(e,t){if(((0,r.isTypedArray)(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&&(0,r.isTypedArray)(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return(0,a.Q)(e,[],[],t)}},5703:(e,t,n)=>{"use strict";n.d(t,{N:()=>o});var r=n(1585),a=n(5441),s=n(565),i=n(8189);const o=(0,n(929).op)({matMul_:function(e,t,n=!1,o=!1){let u=(0,i.YT)(e,"a","matMul"),l=(0,i.YT)(t,"b","matMul");[u,l]=(0,s.makeTypesMatch)(u,l);const c={a:u,b:l},d={transposeA:n,transposeB:o};return r.T2.runKernel(a.jAQ,c,d)}})},5793:(e,t,n)=>{"use strict";n.d(t,{E:()=>s});var r=n(1585),a=n(8189);const s=(0,n(929).op)({square_:function(e){const t=(0,a.YT)(e,"x","square");return r.T2.runKernel("Square",{x:t},{})}})},5817:()=>{},5838:(e,t,n)=>{"use strict";n.d(t,{ljI:()=>yt.ljI,Vvy:()=>yt.Vvy,PH8:()=>yt.PH8,K$F:()=>Ee,ah4:()=>Re,FYc:()=>Me,oC7:()=>Le,OMN:()=>yt.OMN,EkD:()=>yt.EkD,u8Z:()=>yt.u8Z,FSt:()=>yt.FSt,Jp_:()=>yt.Jp_,p_m:()=>yt.p_m,QKF:()=>yt.QKF,epO:()=>yt.epO,TyE:()=>yt.TyE,lxb:()=>yt.lxb,zP9:()=>yt.zP9,ho8:()=>yt.ho8,cS:()=>yt.cS,wwC:()=>yt.wwC,VCH:()=>yt.VCH,jAQ:()=>yt.jAQ,Ik2:()=>yt.Ik2,N4F:()=>yt.N4F,HNs:()=>yt.HNs,vj7:()=>yt.vj7,LB5:()=>yt.LB5,KXH:()=>yt.KXH,QDP:()=>yt.QDP,vaV:()=>yt.vaV,pr3:()=>yt.pr3,$zE:()=>yt.$zE,$dB:()=>yt.$dB,p2J:()=>yt.p2J,rFm:()=>yt.rFm,jfg:()=>yt.jfg,A1h:()=>yt.A1h,iGz:()=>yt.iGz,gC7:()=>yt.gC7,Mn0:()=>yt.Mn0,MnK:()=>yt.MnK,MRQ:()=>yt.MRQ,jj_:()=>yt.jj_,nY8:()=>yt.nY8,GJx:()=>hr.GJ,wNW:()=>yt.wNW,TMz:()=>yt.TMz,tGH:()=>yt.tGH,X$8:()=>yt.X$8,nVu:()=>yt.nVu,ORI:()=>yt.ORI,jxD:()=>yt.jxD,pk0:()=>yt.pk0,bP9:()=>yt.bP9,XmO:()=>yt.XmO,Kmu:()=>b.Km,Qgm:()=>yt.Qgm,Pah:()=>yt.Pah,rsH:()=>yt.rsH,OH$:()=>b.OH,BRl:()=>yt.BRl,_s9:()=>yt._s9,ox3:()=>yt.ox3,ybN:()=>yt.ybN,ybj:()=>yt.ybj,rGP:()=>yt.rGP,SQl:()=>yt.SQl,BxF:()=>yt.BxF,ZgB:()=>yt.ZgB,ElG:()=>yt.ElG,awo:()=>yt.awo,i5R:()=>yt.i5R,aAr:()=>yt.aAr,T7M:()=>yt.T7M,O4G:()=>yt.O4G,mxL:()=>yt.mxL,XhZ:()=>yt.XhZ,lLS:()=>yt.lLS,OAQ:()=>yt.OAQ,lzr:()=>yt.lzr,dv8:()=>yt.dv8,gIW:()=>yt.gIW,E3$:()=>yt.E3$,iPs:()=>yt.iPs,uI_:()=>hr.uI,jM4:()=>yt.jM4,ToN:()=>yt.ToN,X0$:()=>yt.X0$,mIA:()=>yt.mIA,CwD:()=>yt.CwD,mnI:()=>yt.mnI,tG8:()=>yt.tG8,Cg$:()=>yt.Cg$,zfU:()=>yt.zfU,RUm:()=>yt.RUm,nZd:()=>yt.nZd,LXA:()=>yt.LXA,RW8:()=>yt.RW8,yPW:()=>yt.yPW,WRv:()=>yt.WRv,VAI:()=>yt.VAI,t3d:()=>yt.t3d,ySp:()=>yt.ySp,cHb:()=>yt.cHb,RXX:()=>yt.RXX,TL8:()=>yt.TL8,LDN:()=>yt.LDN,g5A:()=>yt.g5A,lNG:()=>yt.lNG,LG0:()=>yt.LG0,x7F:()=>yt.x7F,BLA:()=>yt.BLA,Qu_:()=>Be,WT3:()=>yt.WT3,xu7:()=>yt.xu7,l0G:()=>yt.l0G,SDM:()=>yt.SDM,Zl4:()=>yt.Zl4,e0f:()=>yt.e0f,ylV:()=>yt.ylV,BTT:()=>Qt.BTT,urI:()=>yt.urI,LWX:()=>yt.LWX,ELo:()=>Ne,L5p:()=>Kt,mM$:()=>yt.mM$,ODT:()=>yt.ODT,bCz:()=>yt.bCz,pyJ:()=>yt.pyJ,Ncv:()=>yt.Ncv,kdj:()=>yt.kdj,PS5:()=>We,oJ2:()=>yt.oJ2,CQC:()=>yt.CQC,mH5:()=>yt.mH5,Q6t:()=>yt.Q6t,rgM:()=>Yt.rg,LRy:()=>yt.LRy,sDr:()=>yt.sDr,huO:()=>yt.huO,iDl:()=>Xt.i,fUj:()=>yt.fUj,P_L:()=>yt.P_L,R23:()=>yt.R23,hgw:()=>yt.hgw,FCQ:()=>yt.FCQ,jOE:()=>yt.jOE,XQy:()=>yt.XQy,D7i:()=>yt.D7i,BK4:()=>yt.BK4,hVg:()=>yt.hVg,TOR:()=>yt.TOR,SYI:()=>Pe,pJc:()=>yt.pJc,uWl:()=>yt.uWl,l6P:()=>yt.l6P,u$b:()=>yt.u$b,vI1:()=>yt.vI1,YVe:()=>yt.YVe,hql:()=>yt.hql,J3C:()=>yt.J3C,JiE:()=>yt.JiE,rFG:()=>yt.rFG,Fin:()=>yt.Fin,A8B:()=>yt.A8B,C8s:()=>yt.C8s,BoJ:()=>yt.BoJ,L6G:()=>yt.L6G,DvZ:()=>yt.DvZ,jgd:()=>yt.jgd,Blb:()=>yt.Blb,dFH:()=>yt.dFH,M6A:()=>yt.M6A,Ddj:()=>yt.Ddj,GZp:()=>yt.GZp,pnw:()=>yt.pnw,UcO:()=>yt.UcO,YAb:()=>yt.YAb,iW0:()=>yt.iW0,$jE:()=>yt.$jE,PbM:()=>yt.PbM,WuN:()=>yt.WuN,oFs:()=>yt.oFs,iuW:()=>yt.iuW,qYS:()=>pe.qY,ylz:()=>pe.yl,X4r:()=>yt.X4r,FAs:()=>yt.FAs,TBb:()=>yt.TBb,dLy:()=>yt.dLy,wx0:()=>yt.wx0,EwU:()=>yt.EwU,dXR:()=>yt.dXR,pPe:()=>yt.pPe,RMm:()=>yt.RMm,rTt:()=>pe.rT,xJ3:()=>yt.xJ3,Dr:()=>yt.Dr,tnl:()=>Qt.tnl,HQu:()=>Qt.HQu,FqL:()=>Qt.FqL,WQq:()=>Qt.WQq,QiD:()=>Qt.QiD,Q7R:()=>Qt.Q7R,bzn:()=>Qt.bzn,FLi:()=>Qt.FLi,XRg:()=>Qt.XRg,qRo:()=>Qt.qRo,yHs:()=>Qt.yHs,rYl:()=>Qt.rYl,FPz:()=>Qt.FPz,rfv:()=>Qt.rfv,$jT:()=>Qt.$jT,sub:()=>Qt.sub,Hs:()=>fe.Hs,C0T:()=>d,lZX:()=>Qt.lZX,$v7:()=>Qt.$v7,BFc:()=>Qt.BFc,kSi:()=>Qt.kSi,T5N:()=>Qt.T5N,GTe:()=>Qt.GTe,HbZ:()=>Qt.HbZ,vjT:()=>Qt.vjT,ftb:()=>Qt.ftb,ROE:()=>Qt.ROE,hOW:()=>Qt.hOW,ZEY:()=>gt,TaL:()=>o,ra8:()=>Qt.ra8,wgE:()=>Qt.wgE,mkO:()=>Qt.mkO,zQh:()=>Qt.zQh,o8B:()=>Qt.o8B,faB:()=>Qt.faB,xWs:()=>Qt.xWs,I1m:()=>Qt.I1m,RPU:()=>Qt.RPU,O5O:()=>Qt.O5O,P1l:()=>Qt.P1l,kA9:()=>Qt.kA9,Xtf:()=>Qt.Xtf,wX9:()=>Qt.wX9,IPL:()=>Qt.IPL,jIJ:()=>Qt.jIJ,Cfv:()=>bt.Cf,gnS:()=>Qt.gnS,yIG:()=>Qt.yIG,_jP:()=>Qt._jP,Lp0:()=>Qt.Lp0,rCv:()=>Qt.rCv,_Xg:()=>ve._X,aOp:()=>Qt.aOp,fLc:()=>fe.fL,Rj8:()=>Qt.Rj8,Gl3:()=>Qt.Gl3,eMq:()=>r,smy:()=>Qt.smy,X7t:()=>Qt.X7t,ISJ:()=>fe.IS,ASo:()=>fe.AS,rm6:()=>fe.rm,y4m:()=>Qt.y4m,ek5:()=>Qt.ek5,Omf:()=>Qt.Omf,EZY:()=>Qt.EZY,_3C:()=>Qt._3C,Pqc:()=>Qt.Pqc,gYU:()=>fe.gY,SmG:()=>fe.Sm,FJY:()=>Qt.FJY,Hi9:()=>fe.Hi,QP2:()=>Qt.QP2,_K2:()=>b._K,LCg:()=>Qt.LCg,Y12:()=>Qt.Y12,p4S:()=>Qt.p4S,oNF:()=>Qt.oNF,UG6:()=>Qt.UG6,IYd:()=>Qt.IYd,y5U:()=>Qt.y5U,hVP:()=>Qt.hVP,GSj:()=>Qt.GSj,goy:()=>fe.go,W4C:()=>fe.W4,RIf:()=>Qt.RIf,wh_:()=>Qt.wh_,cZk:()=>Qt.cZk,kgh:()=>Qt.kgh,SY9:()=>Qt.SY9,FJy:()=>u,jz4:()=>fe.jz,vQR:()=>bt.vQ,_5H:()=>bt._5,OpK:()=>bt.Op,Dvk:()=>ve.Dv,ok9:()=>ve.ok,rhj:()=>Qt.rhj,DQN:()=>Qt.DQN,KGM:()=>Qt.KGM,ngS:()=>Qt.ngS,Slp:()=>Qt.Slp,U4u:()=>Qt.U4u,io:()=>s,ggX:()=>Qt.ggX,MIs:()=>Qt.MIs,EN4:()=>Qt.EN4,yrW:()=>Qt.yrW,aCs:()=>fe.aC,kpo:()=>p,H8d:()=>Qt.H8d,M7h:()=>Qt.M7h,InN:()=>Qt.InN,mPL:()=>Qt.mPL,mT8:()=>Qt.mT8,Kgs:()=>Qt.Kgs,Rm2:()=>Qt.Rm2,Kko:()=>Qt.Kko,nqI:()=>Qt.nqI,HPB:()=>Qt.HPB,VZ:()=>Qt.VZ,n76:()=>Qt.n76,NSZ:()=>Qt.NSZ,ztW:()=>Qt.ztW,rxB:()=>Qt.rxB,YYh:()=>Qt.YYh,yzS:()=>Qt.yzS,NoW:()=>Qt.NoW,DyF:()=>i,T9B:()=>Qt.T9B,jgi:()=>Qt.jgi,NYV:()=>Qt.NYV,RO:()=>Qt.RO,PhQ:()=>Qt.PhQ,i2o:()=>Qt.i2o,m1Z:()=>fe.m1,OYQ:()=>Qt.OYQ,jkA:()=>Qt.jkA,BpO:()=>Qt.BpO,FFZ:()=>Qt.FFZ,ziu:()=>Qt.ziu,Clk:()=>Qt.Clk,CRk:()=>Qt.CRk,lKK:()=>Qt.lKK,YDF:()=>Qt.YDF,OjQ:()=>Qt.OjQ,HZy:()=>Qt.HZy,dA1:()=>tn,xbf:()=>Qt.xbf,Ec:()=>Qt.Ec,Mw0:()=>Qt.Mw0,SaS:()=>Qt.SaS,P61:()=>Qt.P61,op:()=>Qt.op,X4o:()=>Qt.X4o,eVF:()=>Qt.eVF,BZs:()=>Qt.BZs,grY:()=>Qt.grY,XHu:()=>Qt.XHu,WLX:()=>Qt.WLX,dzn:()=>Qt.dzn,n7C:()=>Qt.n7C,NsG:()=>Qt.NsG,yyV:()=>Qt.yyV,_eU:()=>Qt._eU,MEE:()=>fe.ME,whe:()=>Qt.whe,iyU:()=>Qt.iyU,Q0_:()=>Qt.Q0_,_9M:()=>Qt._9M,pR9:()=>Qt.pR9,FE$:()=>Qt.FE$,m0H:()=>Qt.m0H,YeY:()=>Qt.YeY,HYA:()=>Qt.HYA,y17:()=>Qt.y17,Gc4:()=>fe.Gc,xav:()=>Qt.xav,VOZ:()=>Qt.VOZ,gJX:()=>fe.gJ,krJ:()=>bt.kr,tAK:()=>bt.tA,VVh:()=>Qt.VVh,j__:()=>Qt.j__,rEj:()=>fe.rE,tQQ:()=>Qt.tQQ,BEg:()=>Qt.BEg,QD2:()=>Qt.QD2,LMr:()=>Qt.LMr,I2l:()=>Qt.I2l,JYU:()=>Qt.JYU,z8$:()=>Qt.z8$,LIG:()=>Qt.LIG,Z$r:()=>Qt.Z$r,d_2:()=>Qt.d_2,NFr:()=>Qt.NFr,g23:()=>Et,sZg:()=>Qt.sZg,WfX:()=>Qt.WfX,wdz:()=>Qt.wdz,JFn:()=>a,jh6:()=>fe.jh,OkC:()=>fe.Ok,F12:()=>Qt.F12,ry7:()=>Qt.ry7,_SZ:()=>Qt._SZ,vPA:()=>Qt.vPA,F8e:()=>Qt.F8e,L0l:()=>Qt.L0l,dik:()=>Qt.dik,Q$M:()=>Qt.Q$M,zAd:()=>Qt.zAd,wck:()=>Qt.wck,R0O:()=>Qt.R0O,Kro:()=>At,Vs9:()=>Qt.Vs9,lw0:()=>Qt.lw0,eDJ:()=>Qt.eDJ,lMo:()=>Qt.lMo,Zhr:()=>Qt.Zhr,lOn:()=>Qt.lOn,lDo:()=>Qt.lDo,RZD:()=>Qt.RZD,EwI:()=>Qt.EwI,Pbu:()=>Qt.Pbu,r2V:()=>Qt.r2V,t$z:()=>Qt.t$z,PMw:()=>Qt.PMw,Ym9:()=>Qt.Ym9,YjP:()=>Qt.YjP,jbE:()=>Qt.jbE,czq:()=>Qt.czq,chL:()=>Yt.ch,Mlm:()=>Qt.Mlm,ymU:()=>Qt.ymU,OEK:()=>Qt.OEK,tGX:()=>Qt.tGX,KtR:()=>Qt.KtR,$_$:()=>Qt.$_$,g9W:()=>Qt.g9W,Lpo:()=>Qt.Lpo,yxw:()=>Qt.yxw,NNh:()=>Qt.NNh,d_S:()=>Rt,Obs:()=>l,DZQ:()=>fe.DZ,Vsq:()=>Qt.Vsq,kBw:()=>fe.kB,rfw:()=>Qt.rfw,BaG:()=>Jt,mgz:()=>Qt.mgz,efE:()=>Qt.efE,AmM:()=>Qt.AmM,rYx:()=>bt.rY,iPt:()=>bt.iP,zAU:()=>Qt.zAU,K$i:()=>Qt.K$i,TuY:()=>Yt.Tu,rni:()=>Qt.rni,ZSL:()=>Dt,jYt:()=>ve.jY,muS:()=>ve.mu,bvq:()=>Qt.bvq,y7e:()=>ve.y7,bgA:()=>Zt,_M9:()=>Qt._M9,YJN:()=>Qt.YJN,Ul9:()=>Qt.Ul9,POl:()=>Qt.POl});var r={};n.r(r),n.d(r,{isBrowser:()=>y,isMobile:()=>g,mockIsMobile:()=>m});var a={};n.r(a),n.d(a,{Serializable:()=>Ie,SerializationMap:()=>Te,getRegisteredName:()=>Ce,registerClass:()=>$e});var s={};n.r(s),n.d(s,{CompositeArrayBuffer:()=>T.D,browserFiles:()=>je,browserHTTPRequest:()=>nt,concatenateArrayBuffers:()=>w.AQ,copyModel:()=>te,decodeWeights:()=>w.CY,decodeWeightsStream:()=>w.s5,encodeWeights:()=>w.aG,fromMemory:()=>it,fromMemorySync:()=>ot,getLoadHandlers:()=>I,getModelArtifactsForJSON:()=>w.Ej,getModelArtifactsForJSONSync:()=>w.Rl,getModelArtifactsInfoForJSON:()=>w.oR,getSaveHandlers:()=>_,getWeightSpecs:()=>w.Xf,http:()=>tt,isHTTPScheme:()=>Je,listModels:()=>J,loadWeights:()=>Ye,moveModel:()=>ne,registerLoadRouter:()=>S,registerSaveRouter:()=>k,removeModel:()=>ee,weightsLoaderFactory:()=>Qe,withSaveHandler:()=>ut,withSaveHandlerSync:()=>lt});var i={};n.r(i),n.d(i,{confusionMatrix:()=>mt});var o={};n.r(o),n.d(o,{draw:()=>$t,fromPixels:()=>Ct,fromPixelsAsync:()=>_t,toPixels:()=>Tt});var u={};n.r(u),n.d(u,{prepareAndValidate:()=>Nt});var l={};n.r(l),n.d(l,{TEST_EPSILON_FLOAT16:()=>Mt,createVideoElement:()=>jt,encodeStrings:()=>Ht,expectArrayBuffersEqual:()=>Gt,expectArraysClose:()=>Ot,expectArraysEqual:()=>Bt,expectNumbersClose:()=>Wt,expectPromiseToFail:()=>Pt,expectValuesInRange:()=>Ut,play:()=>qt,testEpsilon:()=>zt});var c={};n.r(c),n.d(c,{collectGatherOpShapeInfo:()=>ur,computeOutShape:()=>or,segOpComputeOptimalWindowSize:()=>ir});var d={};n.r(d),n.d(d,{ERF_A1:()=>Sn,ERF_A2:()=>_n,ERF_A3:()=>In,ERF_A4:()=>Tn,ERF_A5:()=>$n,ERF_P:()=>kn,PARALLELIZE_THRESHOLD:()=>hn,RowPartitionType:()=>sn,SELU_SCALE:()=>vn.X,SELU_SCALEALPHA:()=>vn.j,applyActivation:()=>un.f2,assertAndGetBroadcastShape:()=>gt.assertAndGetBroadcastShape,assertAxesAreInnerMostDims:()=>nn.WC,assertParamsConsistent:()=>rn,assignToTypedArray:()=>Fn,axesAreInnerMostDims:()=>nn.WH,calculateShapes:()=>Et.calculateShapes,checkEinsumDimSizes:()=>Un,checkPadOnDimRoundingMode:()=>on.s_,combineLocations:()=>nn.aF,combineRaggedTensorToTensorShapes:()=>ln,complexWithEvenIndex:()=>An,complexWithOddIndex:()=>Rn,computeConv2DInfo:()=>on.uf,computeConv3DInfo:()=>on.p$,computeDefaultPad:()=>on.G8,computeDilation2DInfo:()=>on.YQ,computeOptimalWindowSize:()=>fn,computeOutAndReduceShapes:()=>nn.lb,computeOutShape:()=>an,computePool2DInfo:()=>on.E6,computePool3DInfo:()=>on.l5,convertConv2DDataFormat:()=>on.$Q,decodeEinsumEquation:()=>Wn,eitherStridesOrDilationsAreOne:()=>on.G0,expandShapeToKeepDim:()=>nn.SM,exponent:()=>On,exponents:()=>Mn,fromStringArrayToUint8:()=>cr,fromUint8ToStringArray:()=>lr,getAxesPermutation:()=>nn.Em,getBroadcastDims:()=>gt.getBroadcastDims,getComplexWithIndex:()=>Dn,getEinsumComputePath:()=>Gn,getEinsumPermutation:()=>Vn,getFusedBiasGradient:()=>un.Do,getFusedDyActivation:()=>un.XB,getImageCenter:()=>mn,getInnerMostAxes:()=>nn.fK,getPermuted:()=>yn,getRaggedRank:()=>dn,getReductionAxes:()=>gt.getReductionAxes,getReshaped:()=>gn,getReshapedPermuted:()=>bn,getRowPartitionTypesHelper:()=>cn,getSliceBeginCoords:()=>xn,getSliceSize:()=>wn,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>Zn,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>Kn,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>Yn,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>Jn,getSparseReshapeInputOutputMismatchErrorMessage:()=>tr,getSparseReshapeInputOutputMultipleErrorMessage:()=>er,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>Qn,getSparseReshapeNegativeOutputDimErrorMessage:()=>Xn,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>sr,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>nr,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>rr,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>ar,getUndoAxesPermutation:()=>nn.gx,isIdentityPermutation:()=>Hn,log:()=>Cn.R,mergeRealAndImagArrays:()=>Nn,prepareAndValidate:()=>Nt,prepareSplitSize:()=>qn,segment_util:()=>c,shouldFuse:()=>un.zE,slice_util:()=>At,splitRealAndImagArrays:()=>En,stridesOrDilationsArePositive:()=>on.qk,tupleValuesAreOne:()=>on.Dh,upcastType:()=>Yt.Tu,validateDefaultValueShape:()=>pn,validateInput:()=>Et.validateInput,validateUpdateShape:()=>Et.validateUpdateShape,warn:()=>Cn.i});var p={};n.r(p),n.d(p,{nonMaxSuppressionV3Impl:()=>dr.c7,nonMaxSuppressionV4Impl:()=>dr.ZS,nonMaxSuppressionV5Impl:()=>dr.ut,whereImpl:()=>pr.Y});var h=n(1585);let f;function m(e){f=e}function g(e){if(void 0!==f)return f;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 y(){return"undefined"!==typeof window&&null!=window.document||"undefined"!==typeof WorkerGlobalScope}var b=n(6574);const x=(0,b._K)();x.registerFlag("DEBUG",(()=>!1),(e=>{})),x.registerFlag("IS_BROWSER",(()=>y())),x.registerFlag("IS_NODE",(()=>"undefined"!==typeof process&&"undefined"!==typeof process.versions&&"undefined"!==typeof process.versions.node)),x.registerFlag("IS_CHROME",(()=>"undefined"!==typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),x.registerFlag("IS_SAFARI",(()=>"undefined"!==typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),x.registerFlag("PROD",(()=>!1)),x.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>x.getBool("DEBUG"))),x.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),x.registerFlag("IS_TEST",(()=>!1)),x.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>x.getBool("DEBUG"))),x.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),x.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),x.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));var w=n(7084);class v{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==v.instance&&(v.instance=new v),v.instance}static registerSaveRouter(e){v.getInstance().saveRouters.push(e)}static registerLoadRouter(e){v.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return v.getHandlers(e,"save")}static getLoadHandlers(e,t){return v.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?v.getInstance().loadRouters:v.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&r.push(a)})),r}}const k=e=>v.registerSaveRouter(e),S=e=>v.registerLoadRouter(e),_=e=>v.getSaveHandlers(e),I=(e,t)=>v.getLoadHandlers(e,t);var T=n(6734);const $="tensorflowjs",C="models_store",N="model_info_store";function E(){if(!(0,b._K)().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 A(e){const t=e.result;t.createObjectStore(C,{keyPath:"modelPath"}),t.createObjectStore(N,{keyPath:"modelPath"})}class R{constructor(e){if(this.indexedDB=E(),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($,1);r.onupgradeneeded=()=>A(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction(C,"readonly"),r=t.objectStore(C).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=T.D.join(t.weightData);const r=(0,w.oR)(t),i=a.transaction(N,"readwrite");let o,u,l=i.objectStore(N);try{o=l.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(s){return n(s)}o.onsuccess=()=>{u=a.transaction(C,"readwrite");const o=u.objectStore(C);let c;try{c=o.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(s){return n(s)}c.onsuccess=()=>e({modelArtifactsInfo:r}),c.onerror=e=>{l=i.objectStore(N);const t=l.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(c.error)),t.onerror=e=>(a.close(),n(c.error))}},o.onerror=e=>(a.close(),n(o.error)),i.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)}))}}R.URL_SCHEME="indexeddb://";const D=e=>{return(0,b._K)().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(R.URL_SCHEME)?(t=e.slice(R.URL_SCHEME.length),new R(t)):null;var t};v.registerSaveRouter(D),v.registerLoadRouter(D);class F{constructor(){this.indexedDB=E()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open($,1);n.onupgradeneeded=()=>A(n),n.onsuccess=()=>{const r=n.result,a=r.transaction(N,"readonly"),s=a.objectStore(N).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(R.URL_SCHEME)?t.slice(R.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open($,1);r.onupgradeneeded=()=>A(r),r.onsuccess=()=>{const a=r.result,s=a.transaction(N,"readwrite"),i=s.objectStore(N),o=i.get(e);let u;o.onsuccess=()=>{if(null==o.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=i.delete(e),s=()=>{u=a.transaction(C,"readwrite");const r=u.objectStore(C).delete(e);r.onsuccess=()=>t(o.result.modelArtifactsInfo),r.onerror=e=>n(o.error)};r.onsuccess=s,r.onerror=e=>(s(),a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}},r.onerror=e=>n(r.error)}))}}var M=n(5119);const O="/",z="tensorflowjs_models",L="info",P="model_topology",B="weight_specs",W="weight_data",V="model_metadata";function U(e){return{info:[z,e,L].join(O),topology:[z,e,P].join(O),weightSpecs:[z,e,B].join(O),weightData:[z,e,W].join(O),modelMetadata:[z,e,V].join(O)}}function G(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function H(e){const t=e.split(O);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(O)}class j{constructor(e){if(!(0,b._K)().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=U(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=(0,w.oR)(e),s=T.D.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,(0,w.l3)(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 G(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=(0,w.jf)(s),t}}j.URL_SCHEME="localstorage://";const q=e=>{return(0,b._K)().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(j.URL_SCHEME)?(t=e.slice(j.URL_SCHEME.length),new j(t)):null;var t};v.registerSaveRouter(q),v.registerLoadRouter(q);class Z{constructor(){(0,M.vA)((0,b._K)().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),(0,M.vA)("undefined"===typeof window||"undefined"!==typeof window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=z+O,n=O+L;for(let r=0;r<this.LS.length;++r){const a=this.LS.key(r);if(a.startsWith(t)&&a.endsWith(n)){e[H(a)]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){var t;const n=U(e=(t=e).startsWith(j.URL_SCHEME)?t.slice(j.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 G(n),r}}const K="://";class Y{constructor(){this.managers={}}static getInstance(){return null==Y.instance&&(Y.instance=new Y),Y.instance}static registerManager(e,t){(0,M.vA)(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(K)&&(e=e.slice(0,e.indexOf(K))),(0,M.vA)(e.length>0,(()=>"scheme must not be an empty string."));const n=Y.getInstance();(0,M.vA)(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=Y.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Y.getInstance().managers)}}function Q(e){if(-1===e.indexOf(K))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Y.getSchemes().join(",")}`);return{scheme:e.split(K)[0],path:e.split(K)[1]}}async function X(e,t,n=!1){(0,M.vA)(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=v.getLoadHandlers(e);(0,M.vA)(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),(0,M.vA)(r.length<2,(()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`));const a=r[0],s=v.getSaveHandlers(t);(0,M.vA)(s.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),(0,M.vA)(s.length<2,(()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`));const i=s[0],o=Q(e).scheme,u=Q(e).path,l=o===Q(e).scheme,c=await a.load();n&&l&&await Y.getManager(o).removeModel(u);const d=await i.save(c);return n&&!l&&await Y.getManager(o).removeModel(u),d.modelArtifactsInfo}async function J(){const e=Y.getSchemes(),t={};for(const n of e){const e=await Y.getManager(n).listModels();for(const r in e){t[n+K+r]=e[r]}}return t}async function ee(e){const t=Q(e);return Y.getManager(t.scheme).removeModel(t.path)}async function te(e,t){return X(e,t,!1)}async function ne(e,t){return X(e,t,!0)}var re=n(6448);class ae{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&&(0,b._K)().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(0,re.Y)(e)}}if((0,b._K)().get("IS_BROWSER")){(0,b._K)().setPlatform("browser",new ae);try{Y.registerManager(j.URL_SCHEME,new Z)}catch(fr){}try{Y.registerManager(R.URL_SCHEME,new F)}catch(fr){}}const se=()=>n(5817);let ie;class oe{constructor(){this.util=n(8590),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=(0,b._K)().global.fetch?(0,b._K)().global.fetch(e,t):(null==ie&&(ie=se()),ie(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)}}(0,b._K)().get("IS_NODE")&&!(0,b._K)().get("IS_BROWSER")&&(0,b._K)().setPlatform("node",new oe);var ue=n(448),le=n(9809),ce=n(125),de=n(5295),pe=n(259);(0,h.Ye)();const he={buffer:ue.r,cast:le.w,clone:ce.o,print:de.y};(0,pe.Q5)(he);var fe=n(5287),me=n(7523),ge=n(9359),ye=n(9258),be=n(9348),xe=n(5793),we=n(5537),ve=n(1830),ke=n(5702);const Se=new Map,_e=new Map;class Ie{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Te{constructor(){this.classNameMap={}}static getMap(){return null==Te.instance&&(Te.instance=new Te),Te.instance}static register(e){Te.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function $e(e,t,n){(0,M.vA)(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),(0,M.vA)("string"===typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),(0,M.vA)(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 Te.register(e),Se.set(r,e),_e.set(e,r),e}function Ce(e){return _e.has(e)?_e.get(e):e.className}class Ne extends Ie{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(0,fe.AS)(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(0,ve.y7)(e,t)}dispose(){null!=this.iterations_&&(0,fe.AS)(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:(0,ke.d)(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(Ne,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class Ee extends Ne{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=h.T2.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=h.T2.registeredVariables[t],a=!1;null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:(0,fe.DZ)((()=>(0,we.P)(r).variable(a)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:(0,fe.DZ)((()=>(0,we.P)(r).variable(a)))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;(0,fe.DZ)((()=>{const e=(0,me.W)((0,ye.l)(i,this.rho),(0,ye.l)((0,xe.E)(s),1-this.rho)),t=(0,ye.l)((0,ge.y)((0,be.R)((0,me.W)(o,this.epsilon)),(0,be.R)((0,me.W)(i,this.epsilon))),s),n=(0,me.W)((0,ye.l)(o,this.rho),(0,ye.l)((0,xe.E)(t),1-this.rho));i.assign(e),o.assign(n);const a=(0,me.W)((0,ye.l)(t,-this.learningRate),r);r.assign(a)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&((0,fe.AS)(this.accumulatedGrads.map((e=>e.variable))),(0,fe.AS)(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)}}var Ae=n(6111);class Re extends Ne{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=h.T2.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:(0,fe.DZ)((()=>(0,Ae.G)(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;(0,fe.DZ)((()=>{const e=(0,me.W)(s,(0,xe.E)(a));s.assign(e);const t=(0,me.W)((0,ye.l)((0,ge.y)(a,(0,be.R)((0,me.W)(e,h.T2.backend.epsilon()))),-this.learningRate),r);r.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&(0,fe.AS)(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)}}var De=n(8990),Fe=n(7126);class Me extends Ne{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=[],(0,fe.DZ)((()=>{this.accBeta1=(0,ke.d)(t).variable(),this.accBeta2=(0,ke.d)(n).variable()})),null==r&&(this.epsilon=h.T2.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);(0,fe.DZ)((()=>{const n=(0,Fe.j)(1,this.accBeta1),r=(0,Fe.j)(1,this.accBeta2);t.forEach(((t,a)=>{const s=h.T2.registeredVariables[t],i=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:(0,fe.DZ)((()=>(0,we.P)(s).variable(i)))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:(0,fe.DZ)((()=>(0,we.P)(s).variable(i)))});const o=Array.isArray(e)?e[a].tensor:e[t];if(null==o)return;const u=this.accumulatedFirstMoment[a].variable,l=this.accumulatedSecondMoment[a].variable,c=(0,me.W)((0,ye.l)(u,this.beta1),(0,ye.l)(o,1-this.beta1)),d=(0,me.W)((0,ye.l)(l,this.beta2),(0,ye.l)((0,xe.E)(o),1-this.beta2)),p=(0,ge.y)(c,n),f=(0,ge.y)(d,r);u.assign(c),l.assign(d);const m=(0,me.W)((0,ye.l)((0,ge.y)(p,(0,me.W)((0,be.R)(f),this.epsilon)),-this.learningRate),s);s.assign(m)})),this.accBeta1.assign((0,ye.l)(this.accBeta1,this.beta1)),this.accBeta2.assign((0,ye.l)(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&(0,fe.AS)(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&(0,fe.AS)(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),(0,fe.DZ)((()=>{this.accBeta1.assign((0,De.n)(this.beta1,this.iterations_+1)),this.accBeta2.assign((0,De.n)(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)}}var Oe=n(4888),ze=n(178);class Le extends Ne{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=[],(0,fe.DZ)((()=>{this.iteration=(0,ke.d)(0).variable(),this.accBeta1=(0,ke.d)(t).variable()})),null==r&&(this.epsilon=h.T2.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);(0,fe.DZ)((()=>{const n=(0,Fe.j)(1,this.accBeta1),r=(0,ge.y)(-this.learningRate,(0,me.W)((0,ye.l)(this.iteration,this.decay),1));t.forEach(((t,a)=>{const s=h.T2.registeredVariables[t],i=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:(0,we.P)(s).variable(i)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:(0,we.P)(s).variable(i)});const o=Array.isArray(e)?e[a].tensor:e[t];if(null==o)return;const u=this.accumulatedFirstMoment[a].variable,l=this.accumulatedWeightedInfNorm[a].variable,c=(0,me.W)((0,ye.l)(u,this.beta1),(0,ye.l)(o,1-this.beta1)),d=(0,ye.l)(l,this.beta2),p=(0,Oe.t)(o),f=(0,ze.P)(d,p);u.assign(c),l.assign(f);const m=(0,me.W)((0,ye.l)((0,ge.y)(r,n),(0,ge.y)(c,(0,me.W)(f,this.epsilon))),s);s.assign(m)})),this.iteration.assign((0,me.W)(this.iteration,1)),this.accBeta1.assign((0,ye.l)(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&(0,fe.AS)(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&(0,fe.AS)(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 Pe extends Ne{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=h.T2.registeredVariables[t];(0,fe.DZ)((()=>{const e=(0,me.W)((0,ye.l)(this.c,r),a);a.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=(0,fe.aC)((0,ke.d)(-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 Be extends Pe{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=(0,ke.d)(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=h.T2.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:(0,fe.DZ)((()=>(0,we.P)(r).variable(e)))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&(0,fe.DZ)((()=>{let e;const t=(0,me.W)((0,ye.l)(this.m,a),s);e=this.useNesterov?(0,me.W)((0,ye.l)(this.c,(0,me.W)(s,(0,ye.l)(t,this.m))),r):(0,me.W)((0,ye.l)(this.c,t),r),a.assign(t),r.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&(0,fe.AS)(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 We extends Ne{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=h.T2.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=h.T2.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:(0,fe.DZ)((()=>(0,we.P)(r).variable(a)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:(0,fe.DZ)((()=>(0,we.P)(r).variable(a)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:(0,fe.DZ)((()=>(0,we.P)(r).variable(a)))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;(0,fe.DZ)((()=>{const e=(0,me.W)((0,ye.l)(i,this.decay),(0,ye.l)((0,xe.E)(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=(0,me.W)((0,ye.l)(t,this.decay),(0,ye.l)(s,1-this.decay)),u=(0,ge.y)((0,ye.l)(s,this.learningRate),(0,be.R)((0,Fe.j)(e,(0,me.W)((0,xe.E)(a),this.epsilon)))),l=(0,me.W)((0,ye.l)(o,this.momentum),u);i.assign(e),t.assign(a),o.assign(l);const c=(0,Fe.j)(r,l);r.assign(c)}else{const e=(0,me.W)((0,ye.l)(i,this.decay),(0,ye.l)((0,xe.E)(s),1-this.decay)),t=(0,me.W)((0,ye.l)(o,this.momentum),(0,ge.y)((0,ye.l)(s,this.learningRate),(0,be.R)((0,me.W)(e,this.epsilon))));i.assign(e),o.assign(t);const n=(0,Fe.j)(r,t);r.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&(0,fe.AS)(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&(0,fe.AS)(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&(0,fe.AS)(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 Ve=[Ee,Re,Me,Le,Be,We,Pe];function Ue(e){return new Promise((e=>setTimeout(e))).then(e)}class Ge{constructor(e){if(!(0,b._K)().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Ge.URL_SCHEME)&&(e=e.slice(Ge.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=T.D.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=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r=(0,w.zV)(e,t),a=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),s=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=a,await Ue((()=>s.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 Ue((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:(0,w.oR)(e)}}}}Ge.URL_SCHEME="downloads://";class He{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=(0,w.Ej)(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=>(0,w.P8)(e.name))),r={};for(const a of e)a.paths.forEach((e=>{const a=(0,w.P8)(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 je(e){return new He(e)}function qe(e,t,n,r){!function(e){(0,M.vA)(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){(0,M.vA)(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),(0,M.vA)(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),(0,M.vA)(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,r=null==r?1:r);let a=0;return Promise.all(e.map((s=>(s.then((s=>{const i=n+ ++a/e.length*(r-n);return t(i),s})),s))))}v.registerSaveRouter((e=>(0,b._K)().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ge.URL_SCHEME)?function(e="model"){return new Ge(e)}(e.slice(Ge.URL_SCHEME.length)):null));var Ze=n(5685);async function Ke(e,t){null==t&&(t={});const n=null==t.fetchFunc?(0,b._K)().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),a=(null==t.onProgress?await Promise.all(r):await qe(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(a):await qe(a,t.onProgress,.5,1)}async function Ye(e,t="",n,r){return Qe((e=>Ke(e,{requestInit:r})))(e,t,n)}function Qe(e){return async(t,n="",r)=>{const a=t.map((()=>!1)),s={},i=null!=r?r.map((()=>!1)):[],o=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=Ze.i[u]*M.Ze(e.shape),c=()=>{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&&(c(),i[n]=!0)})):c(),o.push(e.name),n+=l}))})),!i.every((e=>e))){const e=r.filter(((e,t)=>!i[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${o.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 c=await e(l),d={};let p=0;return u.forEach((e=>{const n=t[e].paths.length,r=new T.D(c.slice(p,p+n));s[e].forEach((e=>{const t=r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),n=(0,w.CY)(t,[e.manifestEntry]);for(const r in n)d[r]=n[r]})),p+=n})),d}}class Xe{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?((0,M.vA)("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=(0,b._K)().platform.fetch,(0,M.vA)(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&(0,M.vA)(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=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=(0,w.zV)(e,n);if(t.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=T.D.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const a=await this.fetch(this.path,t);if(a.ok)return{modelArtifactsInfo:(0,w.oR)(e),responses:[a]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${a.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();const e=await this.loadModelJSON();return(0,w.Ej)(e,(e=>this.loadWeights(e)))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=(0,w.Xf)(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?(0,b._K)().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 i;s<e.length;){if(!a){const n=(await r(e[s],t.requestInit,{isBinary:!0})).body;a=n.getReader()}const{done:o,value:u}=await a.read();if(!o)return void n.enqueue(u);s++,a=void 0,null===(i=t.onProgress)||void 0===i||i.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=[],i=[];for(const o of e)for(const e of o.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):s.push(a+e+r);return this.weightUrlConverter&&s.push(...await Promise.all(i)),s}async loadWeights(e){const t=await this.getWeightUrls(e);return[(0,w.Xf)(e),await Ke(t,this.loadOptions)]}}function Je(e){return null!=e.match(Xe.URL_SCHEME_REGEX)}Xe.URL_SCHEME_REGEX=/^https?:\/\//;const et=(e,t)=>{if("undefined"===typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Je(e))):Je(e),n)return tt(e,t)}return null};function tt(e,t){return new Xe(e,t)}function nt(e,t){return tt(e,t)}v.registerSaveRouter(et),v.registerLoadRouter(et);class rt{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class at{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class st{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function it(e,t,n,r){return new st(ot(...arguments))}function ot(e,t,n,r){if(1===arguments.length){const t=null!=e.modelTopology||null!=e.weightSpecs;return new rt(t?e:{modelTopology:e})}return new rt({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}function ut(e){return new at(e)}function lt(e){return new at(e)}var ct=n(8189),dt=n(5703),pt=n(1760),ht=n(929),ft=n(7703);const mt=(0,ht.op)({confusionMatrix_:function(e,t,n){const r=(0,ct.YT)(e,"labels","confusionMatrix"),a=(0,ct.YT)(t,"predictions","confusionMatrix");M.vA(null==n||n>0&&Number.isInteger(n),(()=>`If provided, numClasses must be a positive integer, but got ${n}`)),M.vA(1===r.rank,(()=>`Expected the rank of labels to be 1, but got ${r.rank}`)),M.vA(1===a.rank,(()=>`Expected the rank of predictions to be 1, but got ${a.rank}`)),M.vA(r.shape[0]===a.shape[0],(()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${a.shape[0]}. Labels and predictions should have the same number of elements.`)),M.vA(n>0&&Number.isInteger(n),(()=>`numClasses is required to be a positive integer, but got ${n}`));const s=(0,pt.M)((0,le.w)(r,"int32"),n),i=(0,pt.M)((0,le.w)(a,"int32"),n),o=(0,ft.m)(s),u=(0,dt.N)(o,i);return(0,le.w)(u,"int32")}});var gt=n(2198),yt=n(5441),bt=n(7074),xt=n(2768);let wt,vt=!1;function kt(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,i=!1,o=!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)i=!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}`);o=!0}if(null!=(0,bt._5)(yt.awo,h.T2.backendName)){const n={pixels:e},r={numChannels:t};return h.T2.runKernel(yt.awo,n,r)}const[u,l]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,d;if(i)c=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)c=e.data;else if(s||a||o){if(null==wt)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.");wt=new OffscreenCanvas(1,1).getContext("2d")}else wt=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});wt.canvas.width=u,wt.canvas.height=l,wt.drawImage(e,0,0,u,l),c=wt.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]}const p=[l,u,t];return(0,xt.$)(d,p,"int32")}function St(e){return"undefined"!==typeof window&&"undefined"!==typeof ImageBitmap&&window.hasOwnProperty("createImageBitmap")&&!(e instanceof ImageBitmap)&&function(e){return null!=e&&0!==e.width&&0!==e.height}(e)&&!function(e){return null!=e&&e.data instanceof Uint8Array}(e)}async function _t(e,t=3){let n=null;if((0,b._K)().getBool("WRAP_TO_IMAGEBITMAP")&&St(e)){let t;try{t=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(r){t=null}n=null!=t&&t.width===e.width&&t.height===e.height?t:e}else n=e;return kt(n,t)}function It(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.`)}async function Tt(e,t){let n=(0,ct.YT)(e,"img","toPixels");if(!(e instanceof pe.qY)){const e=n;n=(0,le.w)(e,"int32"),e.dispose()}It(n);const[r,a]=n.shape.slice(0,2),s=2===n.rank?1:n.shape[2],i=await n.data(),o="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=i[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*o,e[1]=t*o,e[2]=t*o):e[r]=t*o}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(!vt){null!=(0,bt._5)(yt.XmO,h.T2.backendName)&&(vt=!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}function $t(e,t,n){let r=(0,ct.YT)(e,"img","draw");if(!(e instanceof pe.qY)){const e=r;r=(0,le.w)(e,"int32"),e.dispose()}It(r),function(e){const t=(null===e||void 0===e?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}(null===n||void 0===n?void 0:n.imageOptions);const a={image:r},s={canvas:t,options:n};h.T2.runKernel(yt.XmO,a,s)}const Ct=(0,ht.op)({fromPixels_:kt});function Nt(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===(0,M.Ze)(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 i=1;for(let d=0;d<a.length-1;++d)i*=a[d];const o=e.shape,u=a.slice();u.pop();let l=1;for(let d=s;d<n;++d)l*=o[d],u.push(o[d]);const c=[...(0,M.Ur)(e.shape).map((e=>e/l)),1].slice(0,s);return[u,i,l,c]}var Et=n(6170),At=n(4969),Rt=n(565),Dt=n(3879);const Ft=.001,Mt=.1;function Ot(e,t,n){return null==n&&(n=zt()),Lt(e,t,((e,t)=>Vt(e,t,n)))}function zt(){return 32===h.T2.backend.floatPrecision()?Ft:Mt}function Lt(e,t,n){let r=!0;if(((0,Dt.isTypedArray)(e)||(0,Dt.isTypedArray)(t))&&(r=!1),(0,Dt.isTypedArray)(e)&&(0,Dt.isTypedArray)(t)&&(r=!0),r){const n=e.constructor.name,r=t.constructor.name;if(n!==r)throw new Error(`Arrays are of different type. Actual: ${n}. Expected: ${r}`)}if(Array.isArray(e)&&Array.isArray(t)){const n=(0,ct.MZ)(e),r=(0,ct.MZ)(t);if(!(0,M.r1)(n,r))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${r}]`)}const a=(0,Dt.isTypedArray)(e)?e:(0,Dt.flatten)(e),s=(0,Dt.isTypedArray)(t)?t:(0,Dt.flatten)(t);if(a.length!==s.length)throw new Error(`Arrays have different lengths actual: ${a.length} vs expected: ${s.length}.\nActual:   ${a}.\nExpected: ${s}.`);for(let i=0;i<s.length;++i){const e=a[i],t=s[i];if(!n(e,t))throw new Error(`Arrays differ: actual[${i}] = ${e}, expected[${i}] = ${t}.\nActual:   ${a}.\nExpected: ${s}.`)}"undefined"!==typeof expect&&expect().nothing()}function Pt(e,t){e().then((()=>t.fail()),(()=>t())),"undefined"!==typeof expect&&expect().nothing()}function Bt(e,t){const n="string"===typeof t||"number"===typeof t||"boolean"===typeof t?[t]:t;return(0,M.Kg)(e)||(0,M.Kg)(e[0])||(0,M.Kg)(t)||(0,M.Kg)(t[0])?Lt(e,n,((e,t)=>e==t)):Lt(e,t,((e,t)=>Vt(e,t,0)))}function Wt(e,t,n){if(null==n&&(n=zt()),!Vt(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);"undefined"!==typeof expect&&expect().nothing()}function Vt(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function Ut(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function Gt(e,t){const n=new Float32Array(e),r=new Float32Array(t);if(n.length!==r.length)throw new Error(`Expected ArrayBuffer to be of length ${r.length}, but it was ${n.length}`);for(let a=0;a<r.length;a++)if(n[a]!==r[a])throw new Error(`Expected ArrayBuffer value at ${a} to be ${r[a]} but got ${n[a]} instead`)}function Ht(e){for(let t=0;t<e.length;t++){const n=e[t];Array.isArray(n)?Ht(n):e[t]=(0,Dt.encodeString)(n)}return e}function jt(e){const t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise((e=>{t.addEventListener("loadeddata",(n=>e(t))),t.load()}))}async function qt(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise((t=>{e.requestVideoFrameCallback(t)}))}const Zt="4.22.0";class Kt{static sgd(e){return new Pe(e)}static momentum(e,t,n=!1){return new Be(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,a=!1){return new We(e,t,n,r,a)}static adam(e=.001,t=.9,n=.999,r=null){return new Me(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new Ee(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,a=0){return new Le(e,t,n,r,a)}static adagrad(e,t=.1){return new Re(e,t)}}var Yt=n(2046),Qt=n(7270),Xt=n(4703);const Jt=Kt,en="undefined"!==typeof requestAnimationFrame?requestAnimationFrame:"undefined"!==typeof setImmediate?setImmediate:e=>e();function tn(){return new Promise((e=>en((()=>e()))))}var nn=n(1078);function rn(e,t){const n=e[0].length;e.forEach(((e,t)=>{M.vA(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),M.vA(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++)M.vA(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 an(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var sn,on=n(7195),un=n(8646);function ln(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],i=r[r.length-n.length+a],o=r[i];if(s>=0)if(o>=0){if(o!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${a+e}] = ${s} but shape[${a+e}] = ${o}`)}else r[i]=s}return r}function cn(e){const t={FIRST_DIM_SIZE:sn.FIRST_DIM_SIZE,VALUE_ROWIDS:sn.VALUE_ROWIDS,ROW_LENGTHS:sn.ROW_LENGTHS,ROW_SPLITS:sn.ROW_SPLITS,ROW_LIMITS:sn.ROW_LIMITS,ROW_STARTS:sn.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function dn(e){return 0===e.length?0:e[0]===sn.FIRST_DIM_SIZE?e.length-1:e.length}function pn(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}`)}}!function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"}(sn||(sn={}));const hn=30;function fn(e){return e<=hn?e:(0,M.lK)(e,Math.floor(Math.sqrt(e)))}function mn(e,t,n){return[n*("number"===typeof e?e:e[0]),t*("number"===typeof e?e:e[1])]}function gn(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 yn(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 bn(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 xn(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function wn(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}var vn=n(8576);const kn=.3275911,Sn=.254829592,_n=-.284496736,In=1.421413741,Tn=-1.453152027,$n=1.061405429;var Cn=n(3673);function Nn(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 En(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 An(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 Rn(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 Dn(e,t){return{real:e[2*t],imag:e[2*t+1]}}function Fn(e,t,n,r){e[2*r]=t,e[2*r+1]=n}function Mn(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 On(e,t,n){const r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}}const zn="->",Ln=/->/g,Pn=",",Bn="...";function Wn(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(Ln,"").length)/zn.length;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 ("${zn}").`);const[r,a]=e.split(zn);(0,M.vA)(-1===r.indexOf(Bn),(()=>`The ellipsis notation ("${Bn}") is not supported yet.`));const s=r.split(Pn),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const o=[];for(let d=0;d<a.length;++d){const e=a[d];if(!s.some((t=>-1!==t.indexOf(e))))throw new Error(`Output subscripts contain the label ${e} not present in the input subscripts.`);-1===o.indexOf(e)&&o.push(e)}for(let d=0;d<r.length;++d){const e=r[d];-1===o.indexOf(e)&&e!==Pn&&o.push(e)}const u=new Array(s.length);for(let d=0;d<i;++d){if(new Set(s[d].split("")).size!==s[d].length)throw new Error(`Found duplicate axes in input component ${s[d]}. Support for duplicate axes in input is not implemented yet.`);u[d]=[];for(let e=0;e<s[d].length;++e)u[d].push(o.indexOf(s[d][e]))}const l=o.length,c=[];for(let d=a.length;d<l;++d)c.push(d);return{allDims:o,summedDims:c,idDims:u}}function Vn(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 Un(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]:(0,M.vA)(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 Gn(e,t){const n=e,r=[];let a=0;0===e.length&&n.push(-1),a=e.length+1;for(let i=0;i<a;++i)r.push([]);const s=[];for(let i=0;i<n.length;++i){const e=jn(t,n[i]);for(const t of e)-1===s.indexOf(t)&&(r[i].push(t),s.push(t))}return{path:n,steps:r}}function Hn(e){return e.every(((e,t)=>e===t))}function jn(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 qn(e,t,n=0){let r=[];if("number"===typeof t)(0,M.vA)(e.shape[n]%t===0,(()=>"Number of splits must evenly divide the axis.")),r=new Array(t).fill(e.shape[n]/t);else{const a=t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0);(0,M.vA)(a<=1,(()=>"There should be only one negative value in split array."));const s=t.indexOf(-1);if(-1!==s){const r=t.reduce(((e,t)=>t>0?e+t:e));t[s]=e.shape[n]-r}(0,M.vA)(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 Zn(e){return`Received SparseTensor with denseShape[0] = 0 but\n  indices.shape[0] = ${e}`}function Kn(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Yn(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Qn(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Xn(e,t){return`size ${e} must be non-negative, not ${t}`}function Jn(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function er(e,t){return`Input to reshape is a SparseTensor with ${(0,M.Ze)(e)}\n  dense values, but the requested shape requires a multiple of ${(0,M.Ze)(t)}. inputShape=${e} outputShape= ${t}`}function tr(e,t){return`Input to reshape is a tensor with ${(0,M.Ze)(e)} dense values, but the requested shape has ${(0,M.Ze)(t)}. inputShape=${e} outputShape=${t}`}function nr(){return"segment ids must be >= 0"}function rr(){return"segment ids are not increasing"}function ar(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function sr(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function ir(e,t){let n,r=!1;for(e<=hn?(n=e,r=!0):n=(0,M.lK)(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=(0,M.lK)(e,n+1);return n}function or(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}function ur(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 i=e.shape[n],o=[];let u=1,l=1,c=1;for(let d=0;d<r;++d)o.push(e.shape[d]),u*=e.shape[d];for(let d=r;d<n;d++)o.push(e.shape[d]),l*=e.shape[d];for(let d=r;d<a;d++)o.push(t.shape[d]);for(let d=n+1;d<s;d++)o.push(e.shape[d]),c*=e.shape[d];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:i,outputShape:o}}function lr(e){try{return e.map((e=>(0,Dt.decodeString)(e)))}catch(fr){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${fr}`)}}function cr(e){return e.map((e=>(0,Dt.encodeString)(e)))}var dr=n(8360),pr=n(4411),hr=n(5149);!function(){for(const e of Ve)$e(e)}()},5894:(e,t,n)=>{"use strict";n.d(t,{Y:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({stridedSlice_:function(e,t,n,i,o=0,u=0,l=0,c=0,d=0){const p={x:(0,s.YT)(e,"x","stridedSlice","string_or_numeric")},h={begin:t,end:n,strides:i,beginMask:o,endMask:u,ellipsisMask:l,newAxisMask:c,shrinkAxisMask:d};return r.T2.runKernel(a.UcO,p,h)}})},5912:(e,t,n)=>{"use strict";n.d(t,{L:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({round_:function(e){const t={x:(0,s.YT)(e,"x","round")};return r.T2.runKernel(a.hVg,t)}})},5932:(e,t,n)=>{"use strict";n.d(t,{r:()=>o});var r=n(8189),a=n(5119),s=n(929),i=n(2302);const o=(0,s.op)({squeeze_:function(e,t){const n=(0,r.YT)(e,"x","squeeze","string_or_numeric");return(0,i.t)(n,(0,a.gx)(n.shape,t).newShape)}})},6030:(e,t,n)=>{"use strict";n.d(t,{l:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({softplus_:function(e){const t={x:(0,s.YT)(e,"x","softplus")};return r.T2.runKernel(a.Fin,t)}})},6111:(e,t,n)=>{"use strict";n.d(t,{G:()=>i});var r=n(1585),a=n(5441),s=n(5119);function i(e,t,n){(0,s.SA)(e);const i={shape:e,value:t,dtype:n=n||(0,s.X$)(t)};return r.T2.runKernel(a.SQl,{},i)}},6170:(e,t,n)=>{"use strict";n.r(t),n.d(t,{calculateShapes:()=>i,validateInput:()=>s,validateUpdateShape:()=>a});var r=n(5119);function a(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 i=0;i<a;++i)if(n.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${n.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<n.rank-a;++i)if(n.shape[i+a]!==e[i+r])throw new Error(s+` updates.shape[${i+a}] (${n.shape[i+a]}) != shape[${i+a}] (${e[i+a]})`)}function s(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}`)}a(n,t,e)}function i(e,t,n){const a=t.shape.length,s=a>1?t.shape[a-1]:1,i=n.length;let o=1;for(let r=s;r<i;++r)o*=n[r];const u=s<1?1:s;return{sliceRank:s,numUpdates:(0,r.Ze)(t.shape)/u,sliceSize:o,strides:[...(0,r.Ur)(n.slice(0,s)),1],outputSize:(0,r.Ze)(n)}}},6300:(e,t,n)=>{"use strict";n.d(t,{y:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({isNaN_:function(e){const t={x:(0,s.YT)(e,"x","isNaN")};return r.T2.runKernel(a.iPs,t)}})},6325:(e,t,n)=>{"use strict";n.d(t,{W:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({selu_:function(e){const t={x:(0,s.YT)(e,"x","selu")};return r.T2.runKernel(a.u$b,t)}})},6346:(e,t,n)=>{"use strict";n.d(t,{V:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({softmax_:function(e,t=-1){const n=(0,s.YT)(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 i={logits:n},o={dim:t};return r.T2.runKernel(a.rFG,i,o)}})},6448:(e,t,n)=>{"use strict";function r(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}n.d(t,{Y:()=>r})},6508:(e,t,n)=>{"use strict";n.d(t,{I:()=>u});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(2198);const u=(0,n(929).op)({lessEqual_:function(e,t){let n=(0,i.YT)(e,"a","lessEqual","string_or_numeric"),u=(0,i.YT)(t,"b","lessEqual","string_or_numeric");[n,u]=(0,s.makeTypesMatch)(n,u),(0,o.assertAndGetBroadcastShape)(n.shape,u.shape);const l={a:n,b:u};return r.T2.runKernel(a.CwD,l)}})},6512:(e,t,n)=>{"use strict";n.d(t,{l:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({split_:function(e,t,n=0){const i={x:(0,s.YT)(e,"x","split")},o={numOrSizeSplits:t,axis:n};return r.T2.runKernel(a.Blb,i,o)}})},6522:(e,t,n)=>{"use strict";n.d(t,{H:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({neg_:function(e){const t={x:(0,s.YT)(e,"x","neg")};return r.T2.runKernel(a.l0G,t)}})},6554:(e,t,n)=>{"use strict";n.d(t,{zj:()=>fa});var r,a,s=n(5838);let i;!function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"}(r||(r={})),function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"}(a||(a={}));const o={kernelName:s.Dr,backendName:"wasm",setupFunc:function(e){i=e.wasm.cwrap(s.Dr,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:o,b:u,bias:l,preluActivationWeights:c}=t;if("float32"!==o.dtype||"float32"!==u.dtype)throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");const{transposeA:d,transposeB:p,activation:h,leakyreluAlpha:f}=r,m=n.dataIdMap.get(o.dataId).id,g=n.dataIdMap.get(u.dataId).id;let y=0;if(null!=l){const e=n.dataIdMap.get(l.dataId);if(1!==e.shape.length)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${e.shape.length}.`);y=e.id}const b=null==c?0:n.dataIdMap.get(c.dataId).id,x=a[h];if(null==x)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);const w=d?o.shape[2]:o.shape[1],v=p?u.shape[1]:u.shape[2],k=s.ZEY.assertAndGetBroadcastShape(o.shape.slice(0,-2),u.shape.slice(0,-2)),S=n.makeOutput([...k,w,v],o.dtype),_=n.dataIdMap.get(S.dataId).id,I=new Uint8Array(new Int32Array(o.shape).buffer),T=new Uint8Array(new Int32Array(u.shape).buffer);return i(m,I,o.shape.length,g,T,u.shape.length,d,p,x,y,b,f||0,_),S}};function u(e,t){let n;return{kernelName:e,backendName:"wasm",setupFunc:function(t){n=t.wasm.cwrap(e,null,["number","number","number"])},kernelFunc:function(e){const{backend:a,inputs:{x:i}}=e,o=a.dataIdMap.get(i.dataId).id,u=a.makeOutput(i.shape,t||i.dtype),l=a.dataIdMap.get(u.dataId).id;return 0===s.ZSL.sizeFromShape(u.shape)||n(o,r[i.dtype],l),u}}}const l=u(s.ljI),c=u(s.Vvy),d=u(s.PH8);function p(e,t,n){let a;return{kernelName:e,backendName:"wasm",setupFunc:function(t){a=t.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:i}=e,{a:o,b:u}=i,l=t.dataIdMap.get(o.dataId).id,c=t.dataIdMap.get(u.dataId).id,d=null!=n?n:o.dtype,p=s.C0T.assertAndGetBroadcastShape(o.shape,u.shape),h=t.makeOutput(p,d);if(0===s.ZSL.sizeFromShape(p))return h;const f=new Uint8Array(new Int32Array(o.shape).buffer),m=new Uint8Array(new Int32Array(u.shape).buffer),g=t.dataIdMap.get(h.dataId).id;return a(l,f,o.shape.length,c,m,u.shape.length,r[o.dtype],g),h}}}const h=p(s.OMN);let f;const m={kernelName:s.EkD,backendName:"wasm",setupFunc:function(e){f=e.wasm.cwrap(s.EkD,null,["array","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,a=n.makeOutput(t[0].shape,t[0].dtype);if(0===s.ZSL.sizeFromShape(a.shape))return a;const i=t.map((e=>n.dataIdMap.get(e.dataId).id)),o=new Uint8Array(new Int32Array(i).buffer),u=n.dataIdMap.get(a.dataId).id;return f(o,i.length,r[a.dtype],u),a}};function g(e){const{inputs:{x:t},backend:n}=e;if("string"===t.dtype)return(0,s.OEK)(n.readSync(t.dataId),t.shape,t.dtype);const r=n.makeOutput(t.shape,t.dtype),a=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(r).set(a),r}const y={kernelName:s.lzr,backendName:"wasm",kernelFunc:g};let b;function x(e){const{inputs:t,backend:n,attrs:a}=e,[s,i]=function(e,t){const n=[],r=[];for(let a=0;a<e.length;++a)1!==e[a]&&n.push(e[a]),1!==e[t[a]]&&r.push(t[a]);for(let a=0;a<r.length;++a){let e=-1;for(let t=0;t<r.length;++t)r[t]>=a&&(-1===e||r[e]>r[t])&&(e=t);r[e]=a}return[n,r]}(t.x.shape,a.perm);let o=!0;for(let r=0;r<i.length;r++)i[r]!==r&&(o=!1);const u=function(e,t){const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];return n}(t.x.shape,a.perm),l={dataId:t.x.dataId,shape:s,dtype:t.x.dtype};if(o){const e=g({inputs:t,backend:n});return e.shape=u,e}const c=n.makeOutput(u,l.dtype),d=n.dataIdMap.get(l.dataId).id,p=n.dataIdMap.get(c.dataId).id,h=new Uint8Array(new Int32Array(i).buffer),f=new Uint8Array(new Int32Array(l.shape).buffer);return b(d,f,l.shape.length,r[l.dtype],p,h,i.length),c}const w={kernelName:s.wx0,backendName:"wasm",kernelFunc:x,setupFunc:function(e){b=e.wasm.cwrap(s.wx0,null,["number","array","number","number","number","array","number"])}};function v(e,t,n){const r=e.shape,a=e.shape.length,i=s.ZSL.parseAxisParam(t,r);let o=i;const u=s.C0T.getAxesPermutation(o,a);let l=null,c=!1;if(null!=u){const t=new Array(a);for(let e=0;e<t.length;e++)t[e]=r[u[e]];o=s.C0T.getInnerMostAxes(o.length,a),l=x({inputs:{x:e},attrs:{perm:u},backend:n});const i=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(l.dataId).id!==i&&(c=!0)}return{transposed:l,originalAxes:i,axes:o,inputWasTransposed:c}}let k;const S={kernelName:s.u8Z,backendName:"wasm",setupFunc:function(e){k=e.wasm.cwrap(s.u8Z,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:i}=r,{x:o}=n;let u=t.dataIdMap.get(o.dataId).id,l=o;const{transposed:c,axes:d,originalAxes:p,inputWasTransposed:h}=v(o,a,t);if(h){l=c,u=t.dataIdMap.get(c.dataId).id}const f=l.shape.length;s.C0T.assertAxesAreInnerMostDims("all",d,f);const[m,g]=s.C0T.computeOutAndReduceShapes(l.shape,d),y=s.ZSL.sizeFromShape(g),b=t.makeOutput(m,o.dtype);if(0!==s.ZSL.sizeFromShape(l.shape)){const e=t.dataIdMap.get(b.dataId).id;k(u,y,e)}if(h&&t.disposeData(c.dataId),i){const e=s.C0T.expandShapeToKeepDim(b.shape,p);b.shape=e}return b}};let _;const I={kernelName:s.FSt,backendName:"wasm",setupFunc:function(e){_=e.wasm.cwrap(s.FSt,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:i}=r,{x:o}=n;let u=t.dataIdMap.get(o.dataId).id,l=o;const{transposed:c,axes:d,originalAxes:p,inputWasTransposed:h}=v(o,a,t);if(h){l=c,u=t.dataIdMap.get(c.dataId).id}const f=l.shape.length;s.C0T.assertAxesAreInnerMostDims("any",d,f);const[m,g]=s.C0T.computeOutAndReduceShapes(l.shape,d),y=s.ZSL.sizeFromShape(g),b=t.makeOutput(m,o.dtype);if(0!==s.ZSL.sizeFromShape(l.shape)){const e=t.dataIdMap.get(b.dataId).id;_(u,y,e)}if(h&&t.disposeData(c.dataId),i){const e=s.C0T.expandShapeToKeepDim(b.shape,p);b.shape=e}return b}};function T(e){let t;return{kernelName:e,backendName:"wasm",setupFunc:function(n){t=n.wasm.cwrap(e,null,["number","number","number","number","number"])},kernelFunc:function(e){const{backend:n,inputs:a,attrs:i}=e,{axis:o}=i,{x:u}=a,l=n.dataIdMap.get(u.dataId).id;let c=l,d=u;const{transposed:p,axes:h,inputWasTransposed:f}=v(u,o,n);if(f){const e=n.dataIdMap.get(p.dataId).id;e!==l&&(d=p,c=e)}const m=d.shape.slice(0,-1),g=n.makeOutput(m,"int32"),y=n.dataIdMap.get(g.dataId).id,b=s.ZSL.sizeFromShape(g.shape),x=d.shape[h[0]];return t(c,r[d.dtype],b,x,y),f&&n.disposeData(p.dataId),g}}}const $=T(s.Jp_),C=T(s.p_m),N=u(s.QKF),E=u(s.epO),A=u(s.TyE),R=p(s.lxb),D=u(s.zP9);let F;const M={kernelName:s.ho8,backendName:"wasm",setupFunc:function(e){F=e.wasm.cwrap(s.ho8,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,a=t.x,i=r.dataIdMap.get(a.dataId).id,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=n,d=s.C0T.computePool2DInfo(a.shape,o,u,1,l,c),p=d.filterHeight,h=d.filterWidth,f=d.padInfo.top,m=d.padInfo.right,g=d.padInfo.bottom,y=d.padInfo.left,b=d.strideHeight,x=d.strideWidth,w=d.inChannels;if("channelsLast"!==d.dataFormat)throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);if(1!==d.dilationWidth||1!==d.dilationHeight)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${d.dilationHeight}, ${d.dilationWidth}].`);const v=r.makeOutput(d.outShape,"float32"),k=r.dataIdMap.get(v.dataId).id;return F(i,a.shape[0],a.shape[1],a.shape[2],p,h,f,m,g,y,b,x,w,k),v}};let O;const z={kernelName:s.cS,backendName:"wasm",setupFunc:function(e){O=e.wasm.cwrap("AvgPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:i,strides:o,pad:u,dimRoundingMode:l,dataFormat:c}=r,d=s.C0T.computePool3DInfo(a.shape,i,o,1,u,l,c),p=n.makeOutput(d.outShape,a.dtype);return O(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,d.batchSize,d.inChannels,d.inDepth,d.inHeight,d.inWidth,d.outDepth,d.outHeight,d.outWidth,d.strideDepth,d.strideHeight,d.strideWidth,d.dilationDepth,d.dilationHeight,d.dilationWidth,d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.front,d.padInfo.top,d.padInfo.left),p}};let L;const P={kernelName:s.wwC,backendName:"wasm",setupFunc:function(e){L=e.wasm.cwrap("AvgPool3DGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:i}=t,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,d=s.C0T.computePool3DInfo(i.shape,o,u,1,l,c),p=n.makeOutput(i.shape,i.dtype);return L(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,d.batchSize,d.inChannels,d.inDepth,d.inHeight,d.inWidth,d.outDepth,d.outHeight,d.outWidth,d.strideDepth,d.strideHeight,d.strideWidth,d.dilationDepth,d.dilationHeight,d.dilationWidth,d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.front,d.padInfo.top,d.padInfo.left,d.filterDepth,d.filterHeight,d.filterWidth),p}};let B;const W={kernelName:s.VCH,backendName:"wasm",setupFunc:function(e){B=e.wasm.cwrap("AvgPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:i}=t,{filterSize:o,strides:u,pad:l}=r,c=s.C0T.computePool2DInfo(i.shape,o,u,1,l),d=n.makeOutput(i.shape,i.dtype);return B(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(d.dataId).id,c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.top,c.padInfo.left,c.filterHeight,c.filterWidth),d}};function V(e){const{inputs:t,attrs:n}=e,{x:r}=t,{shape:a}=n,i=s.ZSL.sizeFromShape(r.shape),o=s.ZSL.inferFromImplicitShape(a,i);return s.ZSL.assert(i===s.ZSL.sizeFromShape(o),(()=>`new shape: ${o}, old shape: ${r.shape}. New shape and old shape must have the same number of elements.`)),e.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}const U={kernelName:s.R23,backendName:"wasm",kernelFunc:V};let G;const H={kernelName:s.jAQ,backendName:"wasm",setupFunc:function(e){G=e.wasm.cwrap(s.jAQ,null,["number","array","number","number","array","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:i}=t,{transposeA:o,transposeB:u}=r;if("float32"!==a.dtype||"float32"!==i.dtype)throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");const l=a.shape.length,c=i.shape.length,d=o?a.shape[l-2]:a.shape[l-1],p=u?i.shape[c-1]:i.shape[c-2],h=o?a.shape[l-1]:a.shape[l-2],f=u?i.shape[c-2]:i.shape[c-1],m=a.shape.slice(0,-2),g=i.shape.slice(0,-2),y=s.ZSL.sizeFromShape(m),b=s.ZSL.sizeFromShape(g),x=s.ZEY.assertAndGetBroadcastShape(a.shape.slice(0,-2),i.shape.slice(0,-2)).concat([h,f]);s.ZSL.assert(d===p,(()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${a.shape} and ${i.shape} and transposeA=${o} and transposeB=${u} must match.`));const w=u?[b,f,p]:[b,p,f],v=V({inputs:{x:a},backend:n,attrs:{shape:o?[y,d,h]:[y,h,d]}}),k=V({inputs:{x:i},backend:n,attrs:{shape:w}}),S=n.dataIdMap.get(v.dataId).id,_=n.dataIdMap.get(k.dataId).id,I=o?v.shape[2]:v.shape[1],T=u?k.shape[1]:k.shape[2],$=Math.max(y,b),C=n.makeOutput([$,I,T],v.dtype),N=n.dataIdMap.get(C.dataId).id,E=new Uint8Array(new Int32Array(v.shape).buffer),A=new Uint8Array(new Int32Array(k.shape).buffer);return G(S,E,v.shape.length,_,A,k.shape.length,o,u,N),n.disposeData(v.dataId),n.disposeData(k.dataId),C.shape=x,C}};var j=n(7906);function q(e){const{inputs:{x:t},attrs:{begin:n,size:r},backend:a}=e,[i,o]=s.Kro.parseSliceParams(t,n,r),u=s.Kro.isSliceContinous(t.shape,i,o),l=a.readSync(t.dataId),c=a.makeOutput(o,t.dtype),d=s.ZSL.computeStrides(t.shape),p=a.dataIdMap.get(c.dataId);if(u){const e=s.Kro.computeFlatOffset(i,d);if("string"===t.dtype)p.stringBytes=l.slice(e,e+s.ZSL.sizeFromShape(o));else{a.typedArrayFromHeap(c).set(l.subarray(e,e+s.ZSL.sizeFromShape(o)))}return c}if("string"===t.dtype){const e=(0,j.HS)(l,i,o,t.shape,t.dtype);return p.stringBytes=e,c}const h=a.typedArrayFromHeap(c),f=t.shape.length;if(2===f)!function(e,t,n,r,a){let s=0;const i=r[0],o=r[1],u=i+a[0];for(let l=i;l<u;l++){const r=l*t+o;n.set(e.subarray(r,r+a[1]),s),s+=a[1]}}(l,d[0],h,i,o);else if(3===f)!function(e,t,n,r,a,s){let i=0;const o=a[0],u=a[1],l=a[2],c=o+s[0],d=u+s[1];for(let p=o;p<c;p++)for(let a=u;a<d;a++){const o=p*t+a*n+l;r.set(e.subarray(o,o+s[2]),i),i+=s[2]}}(l,d[0],d[1],h,i,o);else if(4===f)!function(e,t,n,r,a,s,i){let o=0;const u=s[0],l=s[1],c=s[2],d=u+i[0],p=l+i[1],h=c+i[2],f=s[3];for(let m=u;m<d;m++)for(let s=l;s<p;s++)for(let u=c;u<h;u++){const l=m*t+s*n+u*r+f;a.set(e.subarray(l,l+i[3]),o),o+=i[3]}}(l,d[0],d[1],d[2],h,i,o);else{const e=(0,j.HS)(l,i,o,t.shape,t.dtype);h.set(e)}return c}const Z={kernelName:s.JiE,backendName:"wasm",kernelFunc:q};const K={kernelName:s.Ik2,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:i,crops:o}=r,u=i.reduce(((e,t)=>e*t)),l=s.C0T.getReshaped(a.shape,i,u),c=s.C0T.getPermuted(l.length,i.length),d=s.C0T.getReshapedPermuted(a.shape,i,u),p=s.C0T.getSliceBeginCoords(o,i.length),h=s.C0T.getSliceSize(d,o,i.length),f=V({inputs:{x:a},backend:n,attrs:{shape:l}}),m=x({inputs:{x:f},backend:n,attrs:{perm:c}}),g=V({inputs:{x:m},backend:n,attrs:{shape:d}}),y=q({inputs:{x:g},backend:n,attrs:{begin:p,size:h}});return n.disposeData(f.dataId),n.disposeData(m.dataId),n.disposeData(g.dataId),y}};let Y;const Q={kernelName:s.N4F,backendName:"wasm",setupFunc:function(e){Y=e.wasm.cwrap(s.N4F,null,["number","number","boolean","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{x:s,weights:i}=n,{size:o}=a,u=0!==i.shape.reduce(((e,t)=>e*t),1),l=1===s.shape.length?[o]:[s.shape[0],o],c=t.makeOutput(l,i.dtype);function d(e){return t.dataIdMap.get(e.dataId).id}return Y(d(s),o,u,d(i),r[i.dtype],d(c)),c}},X=p(s.HNs);const J={kernelName:s.vj7,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:a}=t,i=n.typedArrayFromHeap(r),o=n.typedArrayFromHeap(a),u=s.C0T.assertAndGetBroadcastShape(Array.from(i),Array.from(o));return n.makeOutput([u.length],"int32",void 0,new Int32Array(u))}};function ee(e){const{inputs:{x:t},attrs:{dtype:n},backend:r}=e,a=r.makeOutput(t.shape,n),s=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(a).set(s),a}const te={kernelName:s.KXH,backendName:"wasm",kernelFunc:ee},ne=u(s.QDP);let re;const ae={kernelName:s.vaV,backendName:"wasm",setupFunc:function(e){re=e.wasm.cwrap(s.vaV,null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=r,o=n.dataIdMap.get(a.dataId).id,u=n.makeOutput(a.shape,a.dtype),l=n.dataIdMap.get(u.dataId).id;return re(o,s,i,l),u}};var se=n(7763);function ie(e){const{inputs:t,backend:n}=e,r=s.ZSL.parseAxisParam(e.attrs.axis,t[0].shape)[0],a=t.map((e=>e.shape));s.C0T.assertParamsConsistent(a,r);let i=s.C0T.computeOutShape(t.map((e=>e.shape)),r);const o=t.filter((e=>s.ZSL.sizeFromShape(e.shape)>0));if(1===o.length)return g({inputs:{x:o[0]},backend:n});const u=n.makeOutput(i,t[0].dtype);if(0===s.ZSL.sizeFromShape(i))return u;if("string"===o[0].dtype){const e=o.map((e=>{const t=s.ZSL.sizeFromShape(e.shape.slice(r));return V({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),a=e.map((e=>({vals:n.readSync(e.dataId),shape:e.shape})));i=s.C0T.computeOutShape(e.map((e=>e.shape)),1);const l=1===e[0].shape[0],c=(0,se.h)(a,i,t[0].dtype,l),d=s.C0T.computeOutShape(o.map((e=>e.shape)),r);u.shape=d;return n.dataIdMap.get(u.dataId).stringBytes=s.C0T.fromStringArrayToUint8(c),e.forEach((e=>n.disposeData(e.dataId))),u}const l=s.ZSL.sizeFromShape(o[0].shape.slice(0,r));let c=0;const d=o.map((e=>{const t=s.ZSL.sizeFromShape(e.shape.slice(r));return c+=t,t})),p=o.map((e=>n.typedArrayFromHeap(e))),h=n.typedArrayFromHeap(u);for(let s=0;s<l;s++){let e=s*c;for(let t=0;t<p.length;t++){const n=d[t],r=s*n,a=p[t].subarray(r,r+n);h.set(a,e),e+=n}}return u}const oe={kernelName:s.$dB,backendName:"wasm",kernelFunc:ie};let ue;const le={kernelName:s.p2J,backendName:"wasm",setupFunc:function(e){ue=e.wasm.cwrap(s.p2J,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:i}=t,o=r.dataIdMap.get(a.dataId).id,u=r.dataIdMap.get(i.dataId).id,{strides:l,dilations:c,pad:d,dimRoundingMode:p,dataFormat:h}=n,f=s.C0T.convertConv2DDataFormat(h),m=s.C0T.computeConv2DInfo(a.shape,i.shape,l,c,d,p,!1,f),g=m.filterHeight,y=m.filterWidth,b=m.padInfo.top,x=m.padInfo.right,w=m.padInfo.bottom,v=m.padInfo.left,k=m.dilationHeight,S=m.dilationWidth,_=m.strideHeight,I=m.strideWidth,T=m.inChannels,$=m.outChannels,C="SAME"===m.padInfo.type?1:0;if("channelsLast"!==m.dataFormat)throw new Error(`wasm backend Conv2D does not support dataFormat:'${m.dataFormat}'. Please use 'channelsLast'.`);const N=r.makeOutput(m.outShape,"float32"),E=r.dataIdMap.get(N.dataId).id;return ue(o,a.shape[0],a.shape[1],a.shape[2],u,g,y,b,x,w,v,C,k,S,_,I,T,$,E),N}};let ce;const de={kernelName:s.jfg,backendName:"wasm",setupFunc:function(e){ce=e.wasm.cwrap(s.jfg,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{dy:a,filter:i}=n,{strides:o,pad:u,dataFormat:l,dimRoundingMode:c,inputShape:d}=r,p=s.C0T.convertConv2DDataFormat(l),h=s.C0T.computeConv2DInfo(d,i.shape,o,1,u,c,!1,p),{batchSize:f,filterHeight:m,filterWidth:g,inChannels:y,inHeight:b,inWidth:x,outChannels:w,outHeight:v,outWidth:k,strideHeight:S,strideWidth:_}=h,I=m-1-h.padInfo.top,T=g-1-h.padInfo.left,$="channelsLast"===h.dataFormat,C=s.ZSL.computeStrides(h.inShape),N=s.ZSL.computeStrides(a.shape),[E,A,R]=s.ZSL.computeStrides(i.shape),D=C[0],F=$?C[1]:C[2],M=$?C[2]:1,O=$?1:C[1],z=N[0],L=$?N[1]:N[2],P=$?N[2]:1,B=$?1:N[1],W=t.makeOutput(h.inShape,"float32"),V=t.dataIdMap.get(W.dataId).id,U=t.dataIdMap.get(a.dataId).id,G=t.dataIdMap.get(i.dataId).id;return ce(U,G,f,m,g,b,x,y,v,k,w,S,_,I,T,E,A,R,D,F,M,O,z,L,P,B,V),W}};let pe;const he={kernelName:s.A1h,backendName:"wasm",setupFunc:function(e){pe=e.wasm.cwrap(s.A1h,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:i}=t,{strides:o,pad:u,dilations:l}=r;if("float32"!==a.dtype)throw new Error(`Tensor x must have dtype float32, got ${a.dtype}`);if("float32"!==i.dtype)throw new Error(`Tensor filter must have dtype float32, got ${i.dtype}`);const c=s.C0T.computeConv3DInfo(a.shape,i.shape,o,l,u),d=n.makeOutput(c.outShape,a.dtype);return pe(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,c.batchSize,c.inDepth,c.inHeight,c.inWidth,c.inChannels,c.outDepth,c.outHeight,c.outWidth,c.outChannels,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.filterDepth,c.filterHeight,c.filterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),d}};let fe;const me={kernelName:s.iGz,backendName:"wasm",setupFunc:function(e){fe=e.wasm.cwrap(s.iGz,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:i}=t,{strides:o,pad:u,filterShape:l}=r;if("float32"!==a.dtype)throw new Error(`Tensor dy must have dtype float32, got ${a.dtype}`);if("float32"!==i.dtype)throw new Error(`Tensor filter must have dtype float32, got ${i.dtype}`);const c=s.C0T.computeConv3DInfo(a.shape,l,o,1,u),d=n.makeOutput(c.filterShape,i.dtype);return fe(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,c.batchSize,c.inDepth,c.inHeight,c.inWidth,c.inChannels,c.outDepth,c.outHeight,c.outWidth,c.outChannels,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.filterDepth,c.filterHeight,c.filterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),d}};let ge;const ye={kernelName:s.gC7,backendName:"wasm",setupFunc:function(e){ge=e.wasm.cwrap(s.gC7,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:i}=t,{pad:o,strides:u,inputShape:l}=r;if("float32"!==a.dtype)throw new Error(`Tensor dy must have dtype float32, got ${a.dtype}`);if("float32"!==i.dtype)throw new Error(`Tensor filter must have dtype float32, got ${i.dtype}`);const c=s.C0T.computeConv3DInfo(l,i.shape,u,1,o),d=n.makeOutput(c.inShape,a.dtype);return ge(n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(d.dataId).id,c.batchSize,c.inDepth,c.inHeight,c.inWidth,c.inChannels,c.outDepth,c.outHeight,c.outWidth,c.outChannels,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.filterDepth,c.filterHeight,c.filterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),d}},be=u(s.Mn0),xe=u(s.MnK);var we;let ve;!function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"}(we||(we={}));const ke={kernelName:s.MRQ,backendName:"wasm",setupFunc:function(e){ve=e.wasm.cwrap(s.MRQ,null,["number","number","number","number","array","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{method:a,extrapolationValue:s,cropSize:i}=r,{image:o,boxes:u,boxInd:l}=n,c=u.shape[0],[d,p]=i,h=[c,d,p,o.shape[3]];let f,m=t.dataIdMap.get(o.dataId);"float32"!==o.dtype&&(f=ee({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));const g=m.id,y=t.dataIdMap.get(u.dataId).id,b=t.dataIdMap.get(l.dataId).id,x=t.makeOutput(h,"float32"),w=t.dataIdMap.get(x.dataId).id,v=new Uint8Array(new Int32Array(o.shape).buffer);return ve(g,y,b,c,v,d,p,we[a],s,w),null!=f&&t.disposeData(f.dataId),x}};let Se;const _e={kernelName:s.jj_,backendName:"wasm",setupFunc:function(e){Se=e.wasm.cwrap(s.jj_,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:o,exclusive:u,reverse:l}=a,c=i.shape.length;s.ZSL.assert("float32"===i.dtype||"int32"===i.dtype,(()=>`cumprod does not support ${i.dtype} tensors in the WASM backend`));const d=s.C0T.getAxesPermutation([o],c);let p=i;null!==d&&(p=x({inputs:{x:i},attrs:{perm:d},backend:n}));const h=s.C0T.getInnerMostAxes(1,c)[0];s.C0T.assertAxesAreInnerMostDims("cumprod",[h],c);const f=n.makeOutput(p.shape,p.dtype),m=p.shape[h],g=n.dataIdMap.get(p.dataId).id,y=n.dataIdMap.get(f.dataId).id;Se(g,u?1:0,l?1:0,m,y,r[i.dtype]);let b=f;if(null!==d){b=x({inputs:{x:f},attrs:{perm:s.C0T.getUndoAxesPermutation(d)},backend:n}),n.disposeData(p.dataId),n.disposeData(f.dataId)}return b}};let Ie;const Te={kernelName:s.nY8,backendName:"wasm",setupFunc:function(e){Ie=e.wasm.cwrap(s.nY8,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{axis:o,exclusive:u,reverse:l}=a,c=i.shape.length;s.ZSL.assert("float32"===i.dtype||"int32"===i.dtype,(()=>`cumsum does not support ${i.dtype} tensors in the WASM backend`));const d=s.C0T.getAxesPermutation([o],c);let p=i;null!==d&&(p=x({inputs:{x:i},attrs:{perm:d},backend:n}));const h=s.C0T.getInnerMostAxes(1,c)[0];s.C0T.assertAxesAreInnerMostDims("cumsum",[h],c);const f=n.makeOutput(p.shape,p.dtype),m=p.shape[h],g=n.dataIdMap.get(p.dataId).id,y=n.dataIdMap.get(f.dataId).id;Ie(g,u?1:0,l?1:0,m,y,r[i.dtype]);let b=f;if(null!==d){b=x({inputs:{x:f},attrs:{perm:s.C0T.getUndoAxesPermutation(d)},backend:n}),n.disposeData(p.dataId),n.disposeData(f.dataId)}return b}};let $e;const Ce={kernelName:s.wNW,backendName:"wasm",setupFunc:function(e){$e=e.wasm.cwrap("DenseBincount",null,["number","array","number","number","boolean","number","number","boolean","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{x:s,weights:i}=n,{size:o,binaryOutput:u}=a,l=0!==i.shape.reduce(((e,t)=>e*t),1),c=1===s.shape.length?[o]:[s.shape[0],o],d=t.makeOutput(c,i.dtype);function p(e){return t.dataIdMap.get(e.dataId).id}return $e(p(s),new Uint8Array(new Int32Array(s.shape).buffer),s.shape.length,o,l,p(i),r[i.dtype],u,p(d)),d}};let Ne;const Ee={kernelName:s.TMz,backendName:"wasm",setupFunc:function(e){Ne=e.wasm.cwrap(s.TMz,null,["number","number","number","array","number","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a}=n,{blockSize:i,dataFormat:o}=r,u=a.shape[0],l=("NHWC"===o?a.shape[1]:a.shape[2])*i,c=("NHWC"===o?a.shape[2]:a.shape[3])*i,d=("NHWC"===o?a.shape[3]:a.shape[1])/(i*i),p="NHWC"===o?[u,l,c,d]:[u,d,l,c],h=t.makeOutput(p,"float32"),f=t.dataIdMap.get(a.dataId).id,m=new Uint8Array(new Int32Array(s.ZSL.computeStrides(a.shape)).buffer),g=new Uint8Array(new Int32Array(p).buffer),y=new Uint8Array(new Int32Array(s.ZSL.computeStrides(p)).buffer),b=t.dataIdMap.get(h.dataId).id;return Ne(f,i,"NHWC"===o?1:0,m,a.shape.length-1,g,y,p.length,b),h}};let Ae;const Re={kernelName:s.tGH,backendName:"wasm",setupFunc:function(e){Ae=e.wasm.cwrap(s.tGH,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:i}=t,o=r.dataIdMap.get(a.dataId).id,u=r.dataIdMap.get(i.dataId).id,{strides:l,dilations:c,pad:d,dimRoundingMode:p}=n,h=null==c?[1,1]:c,f=s.C0T.computeConv2DInfo(a.shape,i.shape,l,h,d,p,!0),m=f.filterHeight,g=f.filterWidth,y=f.padInfo.top,b=f.padInfo.right,x=f.padInfo.bottom,w=f.padInfo.left,v=f.dilationHeight,k=f.dilationWidth,S=f.strideHeight,_=f.strideWidth,I=f.inChannels,T=f.outChannels,$="SAME"===f.padInfo.type?1:0;if("channelsLast"!==f.dataFormat)throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);const C=r.makeOutput(f.outShape,"float32"),N=r.dataIdMap.get(C.dataId).id;return Ae(o,a.shape[0],a.shape[1],a.shape[2],u,m,g,y,b,x,w,$,v,k,S,_,I,T,N),C}};let De;const Fe={kernelName:s.ORI,backendName:"wasm",setupFunc:function(e){De=e.wasm.cwrap("Diag",null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:a}=t,i=s.ZSL.sizeFromShape(a.shape),o=n.makeOutput([...a.shape,...a.shape],a.dtype);return De(n.dataIdMap.get(a.dataId).id,r[a.dtype],i,n.dataIdMap.get(o.dataId).id),o}};let Me;const Oe={kernelName:s.jxD,backendName:"wasm",setupFunc:function(e){Me=e.wasm.cwrap(s.jxD,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:o}=t,{strides:u,pad:l,dilations:c}=a;if(i.dtype!==o.dtype)throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${i.dtype} and ${o.dtype}`);const d=s.C0T.computeDilation2DInfo(i.shape,o.shape,u,l,"NHWC",c),p=n.makeOutput(d.outShape,i.dtype);return Me(n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(o.dataId).id,n.dataIdMap.get(p.dataId).id,r[i.dtype],d.batchSize,d.inChannels,d.inHeight,d.inWidth,d.outHeight,d.outWidth,d.strideHeight,d.strideWidth,d.dilationHeight,d.dilationWidth,d.filterHeight,d.filterWidth,d.padInfo.top,d.padInfo.left),p}};let ze;const Le={kernelName:s.pk0,backendName:"wasm",setupFunc:function(e){ze=e.wasm.cwrap(s.pk0,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:o,dy:u}=t,{strides:l,pad:c,dilations:d}=a;if(i.dtype!==o.dtype||i.dtype!==u.dtype)throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${i.dtype}, ${o.dtype}, and ${u.dtype}`);const p=s.C0T.computeDilation2DInfo(i.shape,o.shape,l,c,"NHWC",d),h=n.makeOutput(o.shape,o.dtype);return ze(n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(o.dataId).id,n.dataIdMap.get(u.dataId).id,n.dataIdMap.get(h.dataId).id,r[i.dtype],p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.filterHeight,p.filterWidth,p.padInfo.top,p.padInfo.left),h}};let Pe;const Be={kernelName:s.bP9,backendName:"wasm",setupFunc:function(e){Pe=e.wasm.cwrap(s.bP9,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i,filter:o,dy:u}=t,{strides:l,pad:c,dilations:d}=a;if(i.dtype!==o.dtype||i.dtype!==u.dtype)throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${i.dtype}, ${o.dtype}, and ${u.dtype}`);const p=s.C0T.computeDilation2DInfo(i.shape,o.shape,l,c,"NHWC",d),h=n.makeOutput(i.shape,i.dtype);return Pe(n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(o.dataId).id,n.dataIdMap.get(u.dataId).id,n.dataIdMap.get(h.dataId).id,r[i.dtype],p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.filterHeight,p.filterWidth,p.padInfo.top,p.padInfo.left),h}},We=u(s.Pah);let Ve;const Ue={kernelName:s.rsH,backendName:"wasm",setupFunc:function(e){Ve=e.wasm.cwrap(s.rsH,null,["number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:r,y:a}=t,s=n.makeOutput(a.shape,"float32"),i=e=>n.dataIdMap.get(e.dataId).id;return Ve(i(a),i(r),i(s)),s}},Ge=p(s.BRl,0,"bool"),He=u(s._s9),je=u(s.ox3,"float32");function qe(e){const{inputs:t,attrs:n,backend:r}=e,{input:a}=t,{dim:i}=n,o=a.shape.length,u=a.shape.slice();let l=i;return i<0&&(s.ZSL.assert(-(o+1)<=i,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),l=o+i+1),u.splice(l,0,1),V({inputs:{x:a},backend:r,attrs:{shape:u}})}const Ze={kernelName:s.ybN,backendName:"wasm",kernelFunc:qe},Ke=u(s.ybj,"float32");function Ye(e){const{attrs:{shape:t,value:n},backend:r}=e;let{attrs:{dtype:a}}=e;a=a||s.ZSL.inferDtype(n);const i=r.makeOutput(t,a);return r.typedArrayFromHeap(i).fill(n),i}const Qe={kernelName:s.SQl,backendName:"wasm",kernelFunc:Ye};let Xe;const Je={kernelName:s.BxF,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{image:r}=t,a=n.makeOutput(r.shape,r.dtype),s=n.dataIdMap.get(r.dataId).id,i=n.dataIdMap.get(a.dataId).id,[o,u,l,c]=r.shape;return Xe(s,o,u,l,c,i),a},setupFunc:function(e){Xe=e.wasm.cwrap(s.BxF,null,["number","number","number","number","number","number"])}},et=u(s.ZgB),tt=p(s.ElG);let nt;const rt={kernelName:s.i5R,backendName:"wasm",setupFunc:function(e){nt=e.wasm.cwrap(s.i5R,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{varianceEpsilon:a}=r,{x:i,mean:o,variance:u,offset:l,scale:c}=n,d=t.dataIdMap.get(i.dataId).id,p=t.dataIdMap.get(o.dataId).id,h=t.dataIdMap.get(u.dataId).id,f=null!=l?t.dataIdMap.get(l.dataId).id:0,m=null!=c?t.dataIdMap.get(c.dataId).id:0,g=t.makeOutput(i.shape,i.dtype);if(0===s.ZSL.sizeFromShape(i.shape))return g;const y=t.dataIdMap.get(g.dataId).id;return nt(d,p,h,f,m,a,y),g}};let at;const st={kernelName:s.aAr,backendName:"wasm",setupFunc:function(e){at=e.wasm.cwrap(s.aAr,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:i,filter:o,bias:u,preluActivationWeights:l}=t,{strides:c,pad:d,dilations:p,dataFormat:h,dimRoundingMode:f,activation:m,leakyreluAlpha:g}=n,y=s.C0T.computeConv2DInfo(i.shape,o.shape,c,p,d,f),b=a[m];if(null==b)throw new Error(`${m} activation not yet supported for FusedConv2D in the wasm backend.`);const x=r.dataIdMap.get(i.dataId).id,w=r.dataIdMap.get(o.dataId).id,v=y.outChannels;let k=0;if(null!=u){const e=r.dataIdMap.get(u.dataId);if(1!==e.shape.length)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${e.shape.length}.`);if(e.shape[0]!==v)throw new Error(`FusedConv2D bias shape (${e.shape}) does not match the number of output channels (${v})`);k=e.id}const S=y.filterHeight,_=y.filterWidth,I=y.padInfo.top,T=y.padInfo.right,$=y.padInfo.bottom,C=y.padInfo.left,N=y.dilationHeight,E=y.dilationWidth,A=y.strideHeight,R=y.strideWidth,D=y.inChannels,F="SAME"===y.padInfo.type?1:0,M=y.batchSize,O=y.inHeight,z=y.inWidth;if("NHWC"!==h)throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);const L=r.makeOutput(y.outShape,"float32"),P=r.dataIdMap.get(L.dataId).id,B=null==l?0:r.dataIdMap.get(l.dataId).id;return at(x,M,O,z,w,S,_,k,I,T,$,C,F,N,E,A,R,D,v,b,B,g||0,P),L}};let it;const ot={kernelName:s.T7M,backendName:"wasm",setupFunc:function(e){it=e.wasm.cwrap(s.T7M,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:i,filter:o,bias:u,preluActivationWeights:l}=t,{strides:c,pad:d,dilations:p,dataFormat:h,dimRoundingMode:f,activation:m,leakyreluAlpha:g}=n,y=s.C0T.computeConv2DInfo(i.shape,o.shape,c,p,d,f,!0),b=a[m];if(null==b)throw new Error(`${m} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);const x=r.dataIdMap.get(i.dataId).id,w=r.dataIdMap.get(o.dataId).id,v=y.outChannels;let k=0;if(null!=u){const e=r.dataIdMap.get(u.dataId);if(1!==e.shape.length)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${e.shape.length}.`);if(e.shape[0]!==v)throw new Error(`FusedDepthwiseConv2D bias shape (${e.shape}) does not match the number of output channels (${v})`);k=e.id}const S=y.filterHeight,_=y.filterWidth,I=y.padInfo.top,T=y.padInfo.right,$=y.padInfo.bottom,C=y.padInfo.left,N=y.dilationHeight,E=y.dilationWidth,A=y.strideHeight,R=y.strideWidth,D=y.inChannels,F="SAME"===y.padInfo.type?1:0,M=y.batchSize,O=y.inHeight,z=y.inWidth;if("NHWC"!==h)throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);const L=r.makeOutput(y.outShape,"float32"),P=r.dataIdMap.get(L.dataId).id,B=null==l?0:r.dataIdMap.get(l.dataId).id;return it(x,M,O,z,w,S,_,k,I,T,$,C,F,N,E,A,R,D,v,b,B,g||0,P),L}};let ut;const lt={kernelName:s.O4G,backendName:"wasm",setupFunc:function(e){ut=e.wasm.cwrap(s.O4G,null,["number","number","number","number","number","number","array","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{params:a,indices:i}=n,[o,u,l,c]=s.FJy.prepareAndValidate(a,i),d=t.makeOutput(o,a.dtype);if(0===u)return d;const p=i.shape,h=p[p.length-1],f=t.dataIdMap.get(a.dataId).id,m=t.dataIdMap.get(i.dataId).id,g=new Uint8Array(new Int32Array(c).buffer),y=t.dataIdMap.get(d.dataId).id;return ut(f,r[a.dtype],m,u,h,l,g,y),d}};let ct;const dt={kernelName:s.mxL,backendName:"wasm",setupFunc:function(e){ct=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{x:i,indices:o}=n,{axis:u,batchDims:l}=a,c=s.ZSL.parseAxisParam(u,i.shape)[0],d=t.readSync(o.dataId),p=i.shape[c];for(let r=0;r<d.length;++r){const e=d[r];s.ZSL.assert(e<=p-1&&e>=0,(()=>`GatherV2: the index value ${e} is not in [0, ${p-1}]`))}const h=s.C0T.segment_util.collectGatherOpShapeInfo(i,o,c,l),f=V({inputs:{x:i},attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]},backend:t}),m=s.ZSL.sizeFromShape(o.shape),g=V({inputs:{x:o},attrs:{shape:[h.batchSize,m/h.batchSize]},backend:t}),y=[h.batchSize,h.outerSize,m/h.batchSize,h.sliceSize],b=t.makeOutput(y,i.dtype);if(0===s.ZSL.sizeFromShape(i.shape))return b;const x=f.shape.length-1,w=t.dataIdMap.get(f.dataId).id,v=t.dataIdMap.get(g.dataId).id,k=t.dataIdMap.get(b.dataId).id,S=new Uint8Array(new Int32Array(s.ZSL.computeStrides(f.shape)).buffer),_=new Uint8Array(new Int32Array(s.ZSL.computeStrides(y)).buffer);return ct(w,r[i.dtype],S,x,v,h.batchSize,_,k),t.disposeData(f.dataId),t.disposeData(g.dataId),b.shape=h.outputShape,b}},pt=p(s.XhZ,0,"bool"),ht=p(s.lLS,0,"bool"),ft=u(s.gIW,"bool"),mt=u(s.E3$,"bool"),gt=u(s.iPs,"bool");let yt;const bt={kernelName:s.X0$,backendName:"wasm",setupFunc:function(e){yt=e.wasm.cwrap(s.X0$,null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:{x:t},attrs:{alpha:n},backend:a}=e,i=a.dataIdMap.get(t.dataId).id,o=a.makeOutput(t.shape,"float32");if(0!==s.ZSL.sizeFromShape(t.shape)){const e=a.dataIdMap.get(o.dataId).id;yt(i,r[t.dtype],n,e)}return o}},xt=p(s.mIA,0,"bool"),wt=p(s.CwD,0,"bool");let vt;const kt={kernelName:s.mnI,backendName:"wasm",setupFunc:function(e){vt=e.wasm.cwrap(s.mnI,null,["number","number","number","number"])},kernelFunc:function(e){const{attrs:t,backend:n}=e,{start:r,stop:a,num:s}=t,i=Math.floor(s),o=n.makeOutput([i],"float32");return vt(n.dataIdMap.get(o.dataId).id,r,a,i),o}},St=u(s.tG8),_t=u(s.Cg$),It=p(s.RUm,0,"bool"),Tt=u(s.nZd),$t=p(s.LXA,0,"bool"),Ct=p(s.RW8,0,"bool");let Nt;const Et={kernelName:s.jM4,backendName:"wasm",setupFunc:function(e){Nt=e.wasm.cwrap(s.jM4,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:u}=r;if("float32"!==a.dtype)throw new Error("LRN error: x must have dtype float32");const l=n.makeOutput(a.shape,a.dtype);return Nt(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(l.dataId).id,a.shape[3],s,i,o,u),l}};let At;const Rt={kernelName:s.ToN,backendName:"wasm",setupFunc:function(e){At=e.wasm.cwrap(s.ToN,null,["number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:u,alpha:l,beta:c}=r;if("float32"!==a.dtype||"float32"!==s.dtype||"float32"!==i.dtype)throw new Error("LRNGrad error: x, y, and dy must have dtype float32");const d=n.makeOutput(a.shape,a.dtype);return At(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(d.dataId).id,i.shape[3],o,u,l,c),d}};let Dt;const Ft={kernelName:s.VAI,backendName:"wasm",setupFunc:function(e){Dt=e.wasm.cwrap(s.VAI,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{reductionIndices:i,keepDims:o}=a,{x:u}=n;let l=t.dataIdMap.get(u.dataId).id,c=u;const{transposed:d,axes:p,originalAxes:h,inputWasTransposed:f}=v(u,i,t);if(f){c=d,l=t.dataIdMap.get(d.dataId).id}const m=c.shape.length;s.C0T.assertAxesAreInnerMostDims("max",p,m);const[g,y]=s.C0T.computeOutAndReduceShapes(c.shape,p),b=s.ZSL.sizeFromShape(y),x=t.makeOutput(g,u.dtype);if(0!==s.ZSL.sizeFromShape(c.shape)){const e=t.dataIdMap.get(x.dataId).id;Dt(l,r[u.dtype],b,e)}if(f&&t.disposeData(d.dataId),o){const e=s.C0T.expandShapeToKeepDim(x.shape,h);x.shape=e}return x}},Mt=p(s.LDN);let Ot;const zt={kernelName:s.t3d,backendName:"wasm",setupFunc:function(e){Ot=e.wasm.cwrap(s.t3d,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,a=t.x,i=r.dataIdMap.get(a.dataId).id;s.ZSL.assert("float32"===a.dtype,(()=>`Error in MaxPool: only float32 input is supported. Got ${a.dtype}.`));const{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=n,d=s.C0T.computePool2DInfo(a.shape,o,u,1,l,c),p=d.filterHeight,h=d.filterWidth,f=d.padInfo.top,m=d.padInfo.right,g=d.padInfo.bottom,y=d.padInfo.left,b=d.dilationHeight,x=d.dilationWidth,w=d.strideHeight,v=d.strideWidth,k=d.inChannels,S=d.outChannels;if("channelsLast"!==d.dataFormat)throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);const _=r.makeOutput(d.outShape,"float32"),I=r.dataIdMap.get(_.dataId).id;return Ot(i,a.shape[0],a.shape[1],a.shape[2],p,h,f,m,g,y,b,x,w,v,k,S,I),_}};let Lt;const Pt={kernelName:s.ySp,backendName:"wasm",setupFunc:function(e){Lt=e.wasm.cwrap("MaxPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:i,strides:o,pad:u,dimRoundingMode:l,dataFormat:c}=r,d=s.C0T.computePool3DInfo(a.shape,i,o,1,u,l,c),p=n.makeOutput(d.outShape,a.dtype);return Lt(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,d.batchSize,d.inChannels,d.inDepth,d.inHeight,d.inWidth,d.outDepth,d.outHeight,d.outWidth,d.strideDepth,d.strideHeight,d.strideWidth,d.dilationDepth,d.dilationHeight,d.dilationWidth,d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.front,d.padInfo.top,d.padInfo.left),p}};let Bt;const Wt={kernelName:s.cHb,backendName:"wasm",setupFunc:function(e){Bt=e.wasm.cwrap("MaxPool3DGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:i}=t,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,d=s.C0T.computePool3DInfo(i.shape,o,u,1,l,c),p=n.makeOutput(i.shape,i.dtype);return Bt(n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,d.batchSize,d.inChannels,d.inDepth,d.inHeight,d.inWidth,d.outDepth,d.outHeight,d.outWidth,d.strideDepth,d.strideHeight,d.strideWidth,d.dilationDepth,d.dilationHeight,d.dilationWidth,d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.front,d.padInfo.top,d.padInfo.left),p}};let Vt;const Ut={kernelName:s.RXX,backendName:"wasm",setupFunc:function(e){Vt=e.wasm.cwrap("MaxPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:i}=t,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,d=s.C0T.computePool2DInfo(i.shape,o,u,1,l,c),p=n.makeOutput(i.shape,i.dtype);return Vt(n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,d.batchSize,d.inChannels,d.inHeight,d.inWidth,d.outHeight,d.outWidth,d.strideHeight,d.strideWidth,d.dilationHeight,d.dilationWidth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.top,d.padInfo.left),p}};let Gt;const Ht={kernelName:s.TL8,backendName:"wasm",setupFunc:function(e){Gt=e.wasm.cwrap("MaxPoolWithArgmax",null,["number","number","number","number","boolean","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:i}=t,{filterSize:o,strides:u,pad:l,includeBatchInIndex:c}=a;s.ZSL.assert(4===i.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${i.shape.length}.`));const d=[1,1];s.ZSL.assert(s.C0T.eitherStridesOrDilationsAreOne(u,d),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${u} and dilations '${d}'`));const p=s.C0T.computePool2DInfo(i.shape,o,u,[1,1],l),h=n.makeOutput(p.outShape,i.dtype),f=n.makeOutput(p.outShape,"int32");return Gt(n.dataIdMap.get(i.dataId).id,n.dataIdMap.get(h.dataId).id,n.dataIdMap.get(f.dataId).id,r[i.dtype],c,p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.top,p.padInfo.left),[h,f]}};let jt;const qt={kernelName:s.g5A,backendName:"wasm",setupFunc:function(e){jt=e.wasm.cwrap(s.g5A,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:i}=r,{x:o}=n,u=t.dataIdMap.get(o.dataId).id;let l=u,c=o;const{transposed:d,axes:p,originalAxes:h,inputWasTransposed:f}=v(o,a,t);let m=p;if(f){const e=t.dataIdMap.get(d.dataId).id;e!==u&&(c=d,l=e,m=s.C0T.getInnerMostAxes(m.length,c.shape.length))}s.C0T.assertAxesAreInnerMostDims("mean",m,c.shape.length);const[g,y]=s.C0T.computeOutAndReduceShapes(c.shape,m),b=s.ZSL.sizeFromShape(y);let x=c;"float32"!==c.dtype&&(x=ee({backend:t,inputs:{x:c},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(x.dataId).id);const w=t.makeOutput(g,"float32");if(0!==s.ZSL.sizeFromShape(c.shape)){const e=t.dataIdMap.get(w.dataId).id;jt(l,b,e)}if(f&&t.disposeData(d.dataId),i){const e=s.C0T.expandShapeToKeepDim(w.shape,h);w.shape=e}return"float32"!==c.dtype&&t.disposeData(x.dataId),w}};let Zt;const Kt={kernelName:s.lNG,backendName:"wasm",setupFunc:function(e){Zt=e.wasm.cwrap(s.lNG,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{axis:i,keepDims:o}=a,{x:u}=n,l=t.dataIdMap.get(u.dataId).id;let c=l,d=u;const{transposed:p,axes:h,originalAxes:f,inputWasTransposed:m}=v(u,i,t);if(m){const e=t.dataIdMap.get(p.dataId).id;e!==l&&(d=p,c=e)}const g=d.shape.length;s.C0T.assertAxesAreInnerMostDims("min",h,g);const[y,b]=s.C0T.computeOutAndReduceShapes(d.shape,h),x=s.ZSL.sizeFromShape(b),w=t.makeOutput(y,d.dtype);if(0!==s.ZSL.sizeFromShape(d.shape)){const e=t.dataIdMap.get(w.dataId).id;Zt(c,r[u.dtype],x,e)}if(m&&t.disposeData(p.dataId),o){const e=s.C0T.expandShapeToKeepDim(w.shape,f);w.shape=e}return w}},Yt=p(s.LG0);var Qt;let Xt;!function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"}(Qt||(Qt={}));const Jt={kernelName:s.x7F,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:a,mode:s}}=e,i=a.map(((e,n)=>e[0]+t.shape[n]+e[1])),o=n.dataIdMap.get(t.dataId).id,u=n.makeOutput(i,t.dtype),l=n.dataIdMap.get(u.dataId).id,c=new Uint8Array(new Int32Array(t.shape).buffer),d=a.map((e=>e[0])),p=a.map((e=>e[1])),h=new Uint8Array(new Int32Array(d).buffer),f=new Uint8Array(new Int32Array(p).buffer);return Xt(o,c,t.shape.length,r[t.dtype],h,f,Qt[s],l),u},setupFunc:function(e){Xt=e.wasm.cwrap(s.x7F,null,["number","array","number","number","array","array","number","number"])}};let en;function tn(e){const{backend:t,inputs:{logits:n},attrs:{dim:r}}=e,a=t.dataIdMap.get(n.dataId).id,i=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(i.dataId).id,u=n.shape[r],l=s.ZSL.sizeFromShape(n.shape)/u;return 0===s.ZSL.sizeFromShape(i.shape)||en(a,o,u,l),i}const nn={kernelName:s.rFG,backendName:"wasm",setupFunc:function(e){en=e.wasm.cwrap(s.rFG,null,["number","number","number","number"])},kernelFunc:tn};let rn;const an={kernelName:s.WT3,backendName:"wasm",setupFunc:function(e){rn=e.wasm.cwrap(s.WT3,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=r;if("float32"!==a.dtype)throw new Error(`Tensor logits must have dtype float32, got ${a.dtype}`);const u=o?a:tn({inputs:{logits:a},backend:n,attrs:{dim:a.shape.length-1}}),[l,c]=u.shape,d=n.makeOutput([l,s],"int32");return rn(n.dataIdMap.get(u.dataId).id,l,c,s,i,n.dataIdMap.get(d.dataId).id),o||n.disposeData(u.dataId),d}},sn=p(s.BLA),on=p(s.xu7),un=u(s.l0G);function ln(e,t){const n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),r=n[0],a=n[1],s=n[2],i=n[3];return e.wasm._free(t),{pSelectedIndices:r,selectedSize:a,pSelectedScores:s,pValidOutputs:i}}let cn;const dn={kernelName:s.SDM,backendName:"wasm",setupFunc:function(e){cn=e.wasm.cwrap(s.SDM,"number",["number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i}=r,{boxes:o,scores:u}=n,l=t.dataIdMap.get(o.dataId).id,c=t.dataIdMap.get(u.dataId).id,d=cn(l,c,s,a,i),{pSelectedIndices:p,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=ln(t,d);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",p)}};let pn;const hn={kernelName:s.Zl4,backendName:"wasm",setupFunc:function(e){pn=e.wasm.cwrap(s.Zl4,"number",["number","number","number","number","number","bool"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=r,{boxes:u,scores:l}=n,c=t.dataIdMap.get(u.dataId).id,d=t.dataIdMap.get(l.dataId).id,p=pn(c,d,s,a,i,o),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=ln(t,p);return t.wasm._free(m),[t.makeOutput([f],"int32",h),t.makeOutput([],"int32",g)]}};let fn;const mn={kernelName:s.e0f,backendName:"wasm",setupFunc:function(e){fn=e.wasm.cwrap(s.e0f,"number",["number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=r,{boxes:u,scores:l}=n,c=t.dataIdMap.get(u.dataId).id,d=t.dataIdMap.get(l.dataId).id,p=fn(c,d,s,a,i,o),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=ln(t,p);return t.wasm._free(g),[t.makeOutput([f],"int32",h),t.makeOutput([f],"float32",m)]}},gn=p(s.ylV,0,"bool");let yn;const bn={kernelName:s.urI,backendName:"wasm",setupFunc:function(e){yn=e.wasm.cwrap(s.urI,null,["number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{dtype:s,depth:i,onValue:o,offValue:u}=r,l=n.makeOutput([...a.shape,i],s),c=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(a.dataId).id;return yn(d,i,o,u,c),l}};const xn={kernelName:s.LWX,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(1),r}};const wn={kernelName:s.mM$,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return qe({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const i=t[0].shape,o=t[0].dtype;t.forEach((e=>{s.ZSL.assertShapesMatch(i,e.shape,"All tensors passed to stack must have matching shapes"),s.ZSL.assert(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const u=[],l=ie({inputs:t.map((e=>{const t=qe({inputs:{input:e},backend:n,attrs:{dim:a}});return u.push(t),t})),backend:n,attrs:{axis:a}});return u.forEach((e=>n.disposeData(e.dataId))),l}};let vn;const kn={kernelName:s.ODT,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:a,constantValue:i}}=e,o=a.map(((e,n)=>e[0]+t.shape[n]+e[1]));if(0===s.ZSL.sizeFromShape(t.shape))return Ye({backend:n,attrs:{shape:o,value:i,dtype:t.dtype}});const u=n.dataIdMap.get(t.dataId).id,l=n.makeOutput(o,t.dtype),c=n.dataIdMap.get(l.dataId).id,d=new Uint8Array(new Int32Array(t.shape).buffer),p=a.map((e=>e[0])),h=a.map((e=>e[1])),f=new Uint8Array(new Int32Array(p).buffer),m=new Uint8Array(new Int32Array(h).buffer);return vn(u,d,t.shape.length,r[t.dtype],f,m,i,c),l},setupFunc:function(e){vn=e.wasm.cwrap(s.ODT,null,["number","array","number","number","array","array","number","number"])}},Sn=p(s.pyJ);let _n;const In={kernelName:s.Ncv,backendName:"wasm",setupFunc:function(e){_n=e.wasm.cwrap(s.Ncv,null,["number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t,s=n.dataIdMap.get(r.dataId).id,i=n.dataIdMap.get(a.dataId).id;let o=s;const u=r;let l=u;"float32"!==u.dtype&&(l=ee({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),o=n.dataIdMap.get(l.dataId).id);const c=n.makeOutput(r.shape,"float32"),d=n.dataIdMap.get(c.dataId).id;return _n(o,i,d),"float32"!==u.dtype&&n.disposeData(l.dataId),c}};let Tn;const $n={kernelName:s.kdj,backendName:"wasm",setupFunc:function(e){Tn=e.wasm.cwrap(s.kdj,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{axis:i,keepDims:o}=a,{x:u}=n,l=t.dataIdMap.get(u.dataId).id;let c=l,d=u;const{transposed:p,axes:h,originalAxes:f,inputWasTransposed:m}=v(u,i,t);let g=h;if(m){const e=t.dataIdMap.get(p.dataId).id;e!==l&&(d=p,c=e,g=s.C0T.getInnerMostAxes(g.length,d.shape.length))}s.C0T.assertAxesAreInnerMostDims("prod",g,d.shape.length);const[y,b]=s.C0T.computeOutAndReduceShapes(d.shape,g),x=s.ZSL.sizeFromShape(b),w=t.makeOutput(y,d.dtype);if(0!==s.ZSL.sizeFromShape(d.shape)){const e=t.dataIdMap.get(w.dataId).id;Tn(c,x,r[w.dtype],e)}if(m&&t.disposeData(p.dataId),o){const e=s.C0T.expandShapeToKeepDim(w.shape,f);w.shape=e}return w}};var Cn=n(2610);const Nn={kernelName:s.Q6t,backendName:"wasm",kernelFunc:e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:s,dtype:i}=n,o=(0,Cn.q)(r,a,s,i),u=t.makeOutput([o.length],i);return t.typedArrayFromHeap(u).set(o),u}},En=p(s.sDr),An=u(s.huO),Rn=u(s.fUj),Dn=u(s.P_L);let Fn;const Mn={kernelName:s.hgw,backendName:"wasm",setupFunc:function(e){Fn=e.wasm.cwrap(s.hgw,null,["number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{images:a}=n,{alignCorners:i,halfPixelCenters:o,size:u}=r,[l,c]=u,[d,p,h,f]=a.shape,m=[d,l,c,f];let g,y=t.dataIdMap.get(a.dataId);"float32"!==y.dtype&&(g=ee({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),y=t.dataIdMap.get(g.dataId));const b=y.id,x=t.makeOutput(m,"float32");if(0===s.ZSL.sizeFromShape(a.shape))return x;const w=t.dataIdMap.get(x.dataId).id;return Fn(b,d,p,h,f,l,c,i?1:0,o?1:0,w),null!=g&&t.disposeData(g.dataId),x}};let On;const zn={kernelName:s.FCQ,backendName:"wasm",setupFunc:function(e){On=e.wasm.cwrap(s.FCQ,null,["number","number","number","array","array","boolean"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:i}=r,o=n.makeOutput(a.shape,"float32");let u,l=n.dataIdMap.get(a.dataId);return"float32"!==l.dtype&&(u=ee({backend:n,inputs:{x:a},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),On(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(a.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),null!=u&&n.disposeData(u.dataId),o}};let Ln;const Pn={kernelName:s.jOE,backendName:"wasm",setupFunc:function(e){Ln=e.wasm.cwrap(s.jOE,null,["number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{images:a}=n,{alignCorners:i,halfPixelCenters:o,size:u}=r,[l,c]=u,[d,p,h,f]=a.shape,m=[d,l,c,f],g=t.makeOutput(m,"float32");if(0===s.ZSL.sizeFromShape(a.shape))return g;let y,b=t.dataIdMap.get(a.dataId);"float32"!==b.dtype&&(y=ee({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),b=t.dataIdMap.get(y.dataId));const x=b.id,w=t.dataIdMap.get(g.dataId).id;return Ln(x,d,p,h,f,l,c,i?1:0,o?1:0,w),null!=y&&t.disposeData(y.dataId),g}};let Bn;const Wn={kernelName:s.XQy,backendName:"wasm",setupFunc:function(e){Bn=e.wasm.cwrap(s.XQy,null,["number","number","number","array","array","boolean"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:i}=r,o=n.makeOutput(a.shape,"float32");let u,l=n.dataIdMap.get(a.dataId);return"float32"!==l.dtype&&(u=ee({backend:n,inputs:{x:a},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),Bn(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(a.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),null!=u&&n.disposeData(u.dataId),o}};let Vn;const Un={kernelName:s.D7i,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:i}=r,o=s.ZSL.parseAxisParam(i,a.shape);if(0===a.shape.length)return g({inputs:{x:a},backend:n});const u=n.makeOutput(a.shape,a.dtype),l=n.dataIdMap.get(a.dataId).id,c=n.dataIdMap.get(u.dataId).id,d=new Uint8Array(new Int32Array(o).buffer),p=new Uint8Array(new Int32Array(a.shape).buffer);Vn(l,d,o.length,p,a.shape.length,c);const h=V({inputs:{x:u},attrs:{shape:a.shape},backend:n});return n.disposeData(u.dataId),h},setupFunc:function(e){Vn=e.wasm.cwrap(s.D7i,null,["number","array","number","array","number","number"])}};let Gn;const Hn={kernelName:s.BK4,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a}=t,{radians:i,fillValue:o,center:u}=r,l=n.makeOutput(a.shape,a.dtype),c=n.dataIdMap.get(a.dataId).id,d=n.dataIdMap.get(l.dataId).id,[p,h,f,m]=a.shape,[g,y]=s.C0T.getImageCenter(u,h,f),b="number"===typeof o?[o,o,o,0===o?0:255]:[...o,255],x=new Uint8Array(new Int32Array(b).buffer);return Gn(c,p,h,f,m,i,g,y,x,b.length,d),l},setupFunc:function(e){Gn=e.wasm.cwrap(s.BK4,null,["number","number","number","number","number","number","number","number","array","number","number"])}},jn=u(s.hVg),qn=u(s.TOR);let Zn;const Kn={kernelName:s.pJc,backendName:"wasm",setupFunc:function(e){Zn=e.wasm.cwrap(s.pJc,null,["number","number","number","number","number","number","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{indices:i,updates:o}=n,{shape:u}=a,l=t.makeOutput(u,o.dtype);if(0===s.ZSL.sizeFromShape(u))return l;const{sliceRank:c,numUpdates:d,sliceSize:p,strides:h,outputSize:f}=s.g23.calculateShapes(o,i,u),m=t.dataIdMap.get(i.dataId).id,g=t.dataIdMap.get(o.dataId).id,y=new Uint8Array(new Int32Array(h).buffer),b=t.dataIdMap.get(l.dataId).id;return Zn(m,g,r[o.dtype],c,d,p,y,f,b),l}};let Yn;const Qn={kernelName:s.uWl,backendName:"wasm",setupFunc:function(e){Yn=e.wasm.cwrap(s.uWl,null,["number","number","number","number","number","number","bool","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{sortedSequence:s,values:i}=t,{side:o}=a;if(s.dtype!==i.dtype)throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${s.dtype} and ${i.dtype}`);const u=n.makeOutput(i.shape,"int32");function l(e){return n.dataIdMap.get(e.dataId).id}return Yn(l(s),l(i),s.shape[0],s.shape[1],i.shape[1],r[s.dtype],"left"===o,l(u)),u}};let Xn;const Jn={kernelName:s.l6P,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:i}=t,o=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(a.dataId).id,l=n.dataIdMap.get(i.dataId).id,c=n.makeOutput(a.shape,a.dtype),d=n.dataIdMap.get(c.dataId).id,p=r.shape.length,h=a.shape.length,f=0===p||p>1||1===h?1:s.ZSL.sizeFromShape(a.shape.slice(1));return Xn(o,u,l,f,d),c},setupFunc:function(e){Xn=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}},er=u(s.u$b);let tr;const nr={kernelName:"Sigmoid",backendName:"wasm",setupFunc:function(e){tr=e.wasm.cwrap(s.vI1,null,["number","number"])},kernelFunc:function(e){const{backend:t,inputs:{x:n}}=e,r=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),i=t.dataIdMap.get(a.dataId).id;return 0===s.ZSL.sizeFromShape(a.shape)||tr(r,i),a}},rr=u(s.YVe),ar=u(s.hql),sr=u(s.J3C),ir=u(s.Fin);const or={kernelName:s.A8B,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:i,paddings:o}=r,u=s.ZSL.sizeFromShape(i),l=[[0,0]];l.push(...o);for(let s=1+i.length;s<a.shape.length;++s)l.push([0,0]);const c=kn.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:l,constantValue:0}}),d=s.C0T.getReshaped(c.shape,i,u,!1),p=s.C0T.getPermuted(d.length,i.length,!1),h=s.C0T.getReshapedPermuted(c.shape,i,u,!1),f=V({inputs:{x:c},backend:n,attrs:{shape:d}}),m=x({inputs:{x:f},backend:n,attrs:{perm:p}}),g=V({inputs:{x:m},backend:n,attrs:{shape:h}});return n.disposeData(c.dataId),n.disposeData(f.dataId),n.disposeData(m.dataId),g}};let ur;const lr={kernelName:s.C8s,backendName:"wasm",setupFunc:function(e){ur=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{indices:a,values:i,denseShape:o,defaultValue:u}=n,l=a.shape[0],c=a.shape[1],d=t.readSync(o.dataId)[0],p=[l+d,c],h=t.dataIdMap.get(a.dataId).id,f=t.dataIdMap.get(i.dataId).id,m=t.dataIdMap.get(u.dataId).id,g=t.makeOutput(p,a.dtype),y=t.dataIdMap.get(g.dataId).id,b=t.makeOutput(p.slice(0,1),i.dtype),x=t.dataIdMap.get(b.dataId).id,w=t.makeOutput([d],"bool"),v=t.dataIdMap.get(w.dataId).id,k=t.makeOutput([l],a.dtype),S=t.dataIdMap.get(k.dataId).id,_=t.makeOutput([4],"int32"),I=t.dataIdMap.get(_.dataId).id,T=ur(h,f,r[i.dtype],l,d,c,m,y,x,v,S,I),$=t.readSync(_.dataId);let C;switch($[0]){case 1:C=s.C0T.getSparseFillEmptyRowsIndicesDenseShapeMismatch($[1]);break;case 2:C=s.C0T.getSparseFillEmptyRowsNegativeIndexErrorMessage($[1],$[2]);break;case 3:C=s.C0T.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage($[1],$[2],$[3]);break;default:C=""}if(t.disposeData(_.dataId),C)throw t.disposeData(g.dataId),t.disposeData(b.dataId),t.disposeData(w.dataId),t.disposeData(k.dataId),new Error(C);let N=g,E=b;return T!==p[0]&&(N=q({inputs:{x:g},attrs:{begin:0,size:[T,c]},backend:t}),E=q({inputs:{x:b},attrs:{begin:0,size:T},backend:t}),t.disposeData(g.dataId),t.disposeData(b.dataId)),[N,E,w,k]}};let cr;const dr={kernelName:s.BoJ,backendName:"wasm",setupFunc:function(e){cr=e.wasm.cwrap(s.BoJ,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{inputIndices:r,inputShape:a,newShape:i}=n;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!==i.shape.length)throw new Error(`Target shape should be a vector but received shape ${i.shape}`);const o=t.dataIdMap.get(r.dataId).id,u=t.dataIdMap.get(a.dataId).id,l=t.dataIdMap.get(i.dataId).id,c=r.shape[0],d=s.ZSL.sizeFromShape(i.shape),p=t.makeOutput([c,d],r.dtype),h=t.dataIdMap.get(p.dataId).id,f=t.makeOutput([d],i.dtype),m=t.dataIdMap.get(f.dataId).id,g=t.makeOutput([3],"int32"),y=t.dataIdMap.get(g.dataId).id;cr(o,u,l,c,h,m,y);const b=t.readSync(g.dataId);let x;switch(b[0]){case 0:x=s.C0T.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(b[1],b[2]);break;case 1:x=s.C0T.getSparseReshapeNegativeOutputDimErrorMessage(b[1],b[2]);break;case 2:x=s.C0T.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{const e=Array.from(t.readSync(a.dataId)),n=Array.from(t.readSync(f.dataId));x=s.C0T.getSparseReshapeInputOutputMultipleErrorMessage(e,n);break}case 4:{const e=Array.from(t.readSync(a.dataId)),n=Array.from(t.readSync(f.dataId));x=s.C0T.getSparseReshapeInputOutputMismatchErrorMessage(e,n);break}default:x=""}if(t.disposeData(g.dataId),x)throw t.disposeData(p.dataId),t.disposeData(f.dataId),new Error(x);return[p,f]}};let pr;function hr(e){pr=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function fr(e,t){const{backend:n,inputs:a}=e,{data:i,indices:o,segmentIds:u}=a,l=o.shape[0],c=n.readSync(u.dataId,l-1,l)[0],d=l>0?c+1:0;if(d<0)throw new Error(s.C0T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());const p=i.shape.slice();p[0]=d;const h=n.dataIdMap.get(i.dataId).id,f=n.dataIdMap.get(o.dataId).id,m=n.dataIdMap.get(u.dataId).id,g=n.makeOutput(p,i.dtype),y=n.dataIdMap.get(g.dataId).id,b=n.makeOutput([4],"int32"),x=n.dataIdMap.get(b.dataId).id;pr(h,r[i.dtype],i.shape[0],f,m,y,x,t,0);const w=n.readSync(b.dataId);let v;switch(w[0]){case 0:v=s.C0T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break;case 1:v=s.C0T.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break;case 2:v=s.C0T.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(w[1],w[2]);break;case 3:v=s.C0T.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(w[1],w[2],w[3]);break;default:v=""}if(n.disposeData(b.dataId),v)throw n.disposeData(g.dataId),new Error(v);return g}const mr={kernelName:s.L6G,backendName:"wasm",setupFunc:hr,kernelFunc:function(e){return fr(e,!0)}};const gr={kernelName:s.DvZ,backendName:"wasm",setupFunc:hr,kernelFunc:function(e){return fr(e,!1)}};let yr;const br={kernelName:s.jgd,backendName:"wasm",setupFunc:function(e){yr=e.wasm.cwrap(s.jgd,null,["number","number","number","number","number","number","number","number","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{sparseIndices:i,sparseValues:o,defaultValue:u}=n,{outputShape:l}=a,c=t.makeOutput(l,u.dtype);if(0===s.ZSL.sizeFromShape(l))return c;const{sliceRank:d,numUpdates:p,sliceSize:h,strides:f,outputSize:m}=s.C0T.calculateShapes(o,i,l),g=t.dataIdMap.get(i.dataId).id,y=t.dataIdMap.get(o.dataId).id,b=t.dataIdMap.get(u.dataId).id,x=new Uint8Array(new Int32Array(f).buffer),w=t.dataIdMap.get(c.dataId).id;return yr(g,y,o.shape.length,b,r[u.dtype],d,p,h,x,m,w),c}};const xr={kernelName:s.Blb,backendName:"wasm",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{numOrSizeSplits:i,axis:o}=n,u=s.ZSL.parseAxisParam(o,a.shape)[0],l=s.C0T.prepareSplitSize(a,i,u),c=new Array(a.shape.length).fill(0),d=a.shape.slice();return l.map((e=>{const t=[...d];t[u]=e;const n=q({inputs:{x:a},attrs:{begin:c,size:t},backend:r});return c[u]+=e,n}))}},wr=u(s.dFH),vr=u(s.M6A),kr=p(s.Ddj);let Sr;const _r={kernelName:s.pnw,backendName:"wasm",setupFunc:function(e){Sr=e.wasm.cwrap(s.pnw,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{alpha:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,u=t.makeOutput(i.shape,i.dtype),l=t.dataIdMap.get(u.dataId).id;return Sr(o,s,r[i.dtype],l),u}};let Ir;const Tr={kernelName:s.UcO,backendName:"wasm",setupFunc:function(e){Ir=e.wasm.cwrap(s.UcO,null,["number","array","number","array","array","array","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a}=n,{begin:i,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:w,strides:v}=s.Kro.sliceInfo(a.shape,i,o,u,l,c,d,p,h);let k;if(g)k=V({inputs:{x:a},backend:t,attrs:{shape:m}});else if(y||b){s.ZSL.assert(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=s.Kro.computeOutShape(x,w,v),n=q({inputs:{x:a},backend:t,attrs:{begin:x,size:e}});k=V({inputs:{x:n},backend:t,attrs:{shape:m}}),t.disposeData(n.dataId)}else{const e=t.makeOutput(f,"float32"),n=t.dataIdMap.get(a.dataId).id,r=new Uint8Array(new Int32Array(s.ZSL.computeStrides(a.shape)).buffer),i=new Uint8Array(new Int32Array(x).buffer),o=new Uint8Array(new Int32Array(w).buffer),u=new Uint8Array(new Int32Array(v).buffer),l=new Uint8Array(new Int32Array(f).buffer),c=new Uint8Array(new Int32Array(s.ZSL.computeStrides(f)).buffer),d=t.dataIdMap.get(e.dataId).id;Ir(n,r,a.shape.length,i,o,u,l,c,f.length,d),k=V({inputs:{x:e},backend:t,attrs:{shape:m}}),t.disposeData(e.dataId)}return k}};var $r=n(3514);const Cr={kernelName:s.YAb,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{data:a,dataSplits:s}=n,{separator:i,nGramWidths:o,leftPad:u,rightPad:l,padWidth:c,preserveShortSequences:d}=r,p=t.readSync(a.dataId),h=t.readSync(s.dataId),[f,m]=(0,$r.G)(p,h,i,o,u,l,c,d),g=t.makeOutput([f.length],"string");t.dataIdMap.get(g.dataId).stringBytes=f;const y=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(y).set(m),[g,y]}};var Nr=n(2948);const Er={kernelName:s.iW0,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{input:a,delimiter:s}=n,{skipEmpty:i}=r,o=t.readSync(a.dataId),u=t.readSync(s.dataId),[l,c,d]=(0,Nr.S)(o,u[0],i),p=c.length,h=t.makeOutput([p,2],"int32");t.typedArrayFromHeap(h).set(l);const f=t.makeOutput([p],"string");t.dataIdMap.get(f.dataId).stringBytes=c;const m=t.makeOutput([2],"int32");return t.typedArrayFromHeap(m).set(d),[h,f,m]}};var Ar=n(5535);const Rr={kernelName:s.$jE,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{input:a}=n,{numBuckets:s}=r,i=t.readSync(a.dataId),o=(0,Ar.f)(i,s),u=t.makeOutput(a.shape,"int32");return t.typedArrayFromHeap(u).set(o),u}},Dr=p(s.PbM);let Fr;const Mr={kernelName:s.WuN,backendName:"wasm",setupFunc:function(e){Fr=e.wasm.cwrap(s.WuN,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{axis:i,keepDims:o}=a,{x:u}=n,l=t.dataIdMap.get(u.dataId).id;let c=l,d=u;const{transposed:p,axes:h,originalAxes:f,inputWasTransposed:m}=v(u,i,t);let g=h;if(m){const e=t.dataIdMap.get(p.dataId).id;e!==l&&(d=p,c=e,g=s.C0T.getInnerMostAxes(g.length,d.shape.length))}s.C0T.assertAxesAreInnerMostDims("sum",g,d.shape.length);const[y,b]=s.C0T.computeOutAndReduceShapes(d.shape,g),x=s.ZSL.sizeFromShape(b),w=t.makeOutput(y,d.dtype);if(0!==s.ZSL.sizeFromShape(d.shape)){const e=t.dataIdMap.get(w.dataId).id;Fr(c,x,r[w.dtype],e)}if(m&&t.disposeData(p.dataId),o){const e=s.C0T.expandShapeToKeepDim(w.shape,f);w.shape=e}return w}},Or=u(s.oFs),zr=u(s.iuW);let Lr;const Pr={kernelName:s.X4r,backendName:"wasm",setupFunc:function(e){Lr=e.wasm.cwrap(s.X4r,null,["number","number","number","number","number","number","array","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:a}=e,{tensor:i,indices:o,updates:u}=n,{}=a,l=t.makeOutput(i.shape,i.dtype);if(0===s.ZSL.sizeFromShape(i.shape))return l;const{sliceRank:c,numUpdates:d,sliceSize:p,strides:h,outputSize:f}=s.g23.calculateShapes(u,o,i.shape),m=t.dataIdMap.get(o.dataId).id,g=t.dataIdMap.get(u.dataId).id,y=t.dataIdMap.get(i.dataId).id,b=new Uint8Array(new Int32Array(h).buffer),x=t.dataIdMap.get(l.dataId).id;return Lr(m,g,r[u.dtype],c,d,p,b,f,x,y),l}};let Br;const Wr={kernelName:s.FAs,backendName:"wasm",setupFunc:function(e){Br=e.wasm.cwrap(s.FAs,null,["number","array","number","array","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:a}=e,{x:s}=t,i=n.dataIdMap.get(s.dataId).id,{reps:o}=a,u=new Array(s.shape.length);for(let r=0;r<u.length;r++)u[r]=s.shape[r]*o[r];const l=new Uint8Array(new Int32Array(s.shape).buffer),c=new Uint8Array(new Int32Array(u).buffer),d=n.makeOutput(u,s.dtype),p=n.dataIdMap.get(d.dataId).id;return Br(i,l,s.shape.length,c,u.length,r[d.dtype],p),d}};let Vr;const Ur={kernelName:s.TBb,backendName:"wasm",setupFunc:function(e){Vr=e.wasm.cwrap(s.TBb,null,["number","array","number","number","number","bool","number","number"])},kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:a}=e,{k:s,sorted:i}=n,o=t.dataIdMap.get(a.dataId).id,u=new Uint8Array(new Int32Array(a.shape).buffer),l=a.shape.slice();l[l.length-1]=s;const c=t.makeOutput(l,a.dtype),d=t.dataIdMap.get(c.dataId).id,p=t.makeOutput(l,"int32"),h=t.dataIdMap.get(p.dataId).id;return Vr(o,u,a.shape.length,r[a.dtype],s,i,d,h),[c,p]}};let Gr;const Hr={kernelName:s.dLy,backendName:"wasm",setupFunc:function(e){Gr=e.wasm.cwrap(s.dLy,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{image:a,transforms:i}=n,{interpolation:o,fillMode:u,fillValue:l,outputShape:c}=r,[d,p,h,f]=a.shape,[m,g]=null!=c?c:[p,h],y=[d,m,g,f],b=new Uint8Array(new Int32Array(s.ZSL.computeStrides(a.shape)).buffer),x=new Uint8Array(new Int32Array(s.ZSL.computeStrides(y)).buffer),w=t.makeOutput(y,a.dtype),v=t.dataIdMap.get(w.dataId).id,k=t.dataIdMap.get(a.dataId).id,S=t.dataIdMap.get(i.dataId).id,_="nearest"===o?1:2;let I;switch(u){case"constant":default:I=1;break;case"reflect":I=2;break;case"wrap":I=3;break;case"nearest":I=4}return Gr(k,S,i.shape[0]>1,d,m,g,f,h,p,b,a.shape.length-1,x,y.length-1,_,I,l,v),w}};var jr=n(2750);const qr={kernelName:s.EwU,backendName:"wasm",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:s}=t,{outputValues:i,outputShape:o,indices:u}=(0,jr.w)(r.readSync(s.dataId),a,s.shape,s.dtype);return[r.makeOutput(o,s.dtype,void 0,i),r.makeOutput([u.length],"int32",void 0,u)]}};const Zr={kernelName:s.dXR,backendName:"wasm",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 i=a.shape[s],o=a.shape.length,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(i),d=new Array(o).fill(0),p=a.shape.slice();p[s]=1;for(let h=0;h<c.length;h++)d[s]=h,c[h]=q({inputs:{x:a},attrs:{begin:d,size:p},backend:n});return c.map((({dataId:e,dtype:t})=>({dataId:e,dtype:t,shape:u})))}};const Kr={kernelName:s.xJ3,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(0),r}},Yr=[o,l,c,d,h,m,S,I,$,C,N,E,A,R,D,M,W,z,P,H,K,Q,X,J,te,ne,ae,oe,le,de,he,me,ye,be,xe,ke,_e,Te,Ce,Ee,Re,Fe,Oe,Le,Be,We,Ue,Ge,He,je,Ze,Ke,Qe,Je,et,tt,rt,st,ot,lt,dt,pt,ht,y,ft,mt,gt,bt,xt,wt,kt,_t,St,It,Tt,$t,Ct,Et,Rt,Ft,Mt,zt,Pt,Wt,Ut,Ht,qt,Kt,Yt,Jt,an,sn,on,un,dn,hn,mn,gn,bn,xn,wn,kn,Sn,In,$n,Nn,En,An,Rn,Dn,U,Mn,zn,Pn,Wn,Un,Hn,jn,qn,Kn,Qn,Jn,er,nr,rr,ar,sr,Z,nn,ir,or,lr,dr,mr,gr,br,xr,wr,vr,kr,_r,Tr,Cr,Er,Rr,Dr,Mr,Or,zr,Pr,Wr,Ur,Hr,w,qr,Zr,Kr];for(const ya of Yr)(0,s.tAK)(ya);const Qr=(0,s._K2)();Qr.registerFlag("WASM_HAS_SIMD_SUPPORT",(async()=>{try{return WebAssembly.validate(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]))}catch(e){return!1}})),Qr.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",(async()=>{if(Qr.get("IS_NODE"))return!1;try{return(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(e){return!1}}));var Xr=n(8417),Jr=n.n(Xr),ea=n(9593),ta=n(3805),na=n.n(ta);const ra=Jr()||Xr,aa=na()||ta;class sa extends s.uI_{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(ma),ga=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new s.GJx(this,(0,s.Hi9)())}write(e,t,n){const r={id:this.dataIdNextNumber++};return this.move(r,e,t,n,1),r}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){const t=s.ZSL.now();e();return{kernelMs:s.ZSL.now()-t}}move(e,t,n,r,a){const i=this.dataIdNextNumber++;if("string"===r){const s=t;return void this.dataIdMap.set(e,{id:i,stringBytes:s,shape:n,dtype:r,memoryOffset:null,refCount:a})}const o=s.ZSL.sizeFromShape(n),u=o*s.ZSL.bytesPerElement(r),l=this.wasm._malloc(u)>>>0;this.dataIdMap.set(e,{id:i,memoryOffset:l,shape:n,dtype:r,refCount:a}),this.wasm.tfjs.registerTensor(i,o,l),null!=t&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,u),l)}async read(e){return this.readSync(e)}readSync(e,t,n){const{memoryOffset:r,dtype:a,shape:i,stringBytes:o}=this.dataIdMap.get(e);if("string"===a)return null!=t&&0!==t||!(null==n||n>=o.length)?o.slice(t,n):o;t=t||0,n=n||s.ZSL.sizeFromShape(i);const u=s.ZSL.bytesPerElement(a);return function(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}(this.wasm.HEAPU8.slice(r+t*u,r+n*u).buffer,a)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){const n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){if(this.dataIdMap.has(e)){return this.dataIdMap.get(e).refCount}return 0}incRef(e){const t=this.dataIdMap.get(e);null!=t&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n,r){let a;if(null==n)a=this.write(null!==r&&void 0!==r?r:null,e,t);else{const r=this.dataIdNextNumber++;a={id:r},this.dataIdMap.set(a,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});const i=s.ZSL.sizeFromShape(e);this.wasm.tfjs.registerTensor(r,i,n)}return{dataId:a,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){const r=this.wasm.HEAPU8.buffer,{memoryOffset:a}=this.dataIdMap.get(n),i=s.ZSL.sizeFromShape(e);switch(t){case"float32":return new Float32Array(r,a,i);case"int32":return new Int32Array(r,a,i);case"bool":return new Uint8Array(r,a,i);default:throw new Error(`Unknown dtype ${t}`)}}}function ia(e,t,n){if(null!=la)return la;let r="tfjs-backend-wasm.wasm";return e&&t?r="tfjs-backend-wasm-threaded-simd.wasm":e&&(r="tfjs-backend-wasm-simd.wasm"),null!=da&&null!=da[r]?da[r]:n+r}async function oa(){const[e,t]=await Promise.all([(0,s._K2)().getAsync("WASM_HAS_SIMD_SUPPORT"),(0,s._K2)().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise(((n,r)=>{const a={};var i;a.locateFile=(n,r)=>{if(n.endsWith(".worker.js")){const e=ea.$.replace(/\n/g,"\\n"),t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}return n.endsWith(".wasm")?ia(e,t,null!=ca?ca:r):r+n},ha&&(a.instantiateWasm=(i=ia(e,t,null!=ca?ca:""),(e,t)=>(s.ZSL.fetch(i,{credentials:"same-origin"}).then((n=>{n.ok||e.env.a(`failed to load wasm binary file at '${i}'`),n.arrayBuffer().then((n=>{WebAssembly.instantiate(n,e).then((e=>{t(e.instance,e.module)}))}))})),{})));let o,u=!1;a.onAbort=()=>{if(u)return;if(pa)return;pa=!0;r({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})},t&&e&&null==la?(a.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+ra.toString()],{type:"text/javascript"}),o=ra(a)):o=aa(a),o.then((e=>{u=!0,pa=!1;e.tfjs={init:e.cwrap("init",null,[]),initWithThreadsCount:e.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:e.cwrap("get_threads_count","number",[]),registerTensor:e.cwrap("register_tensor",null,["number","number","number"]),disposeData:e.cwrap("dispose_data",null,["number"]),dispose:e.cwrap("dispose",null,[])},n({wasm:e})})).catch(r)}))}const ua=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let la=null,ca=null,da={},pa=!1,ha=!1;function fa(e,t=!1){if(pa)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if("string"===typeof e)ca=e;else{da=e;const t=ua.filter((e=>null==da[e]));if(t.length>0)throw new Error(`There were no entries found for the following binaries: ${t.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}ha=t}let ma=-1,ga=null;(0,s.gJX)("wasm",(async()=>{const{wasm:e}=await oa();return new sa(e)}),2)},6567:(e,t,n)=>{"use strict";n.d(t,{F:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({mirrorPad_:function(e,t,n){i.vA("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const o=(0,s.YT)(e,"x","mirrorPad");if(0===o.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");i.vA(t.length===o.rank,(()=>`Padding doesn't match input. Must be ${o.rank}. Got ${t.length}.`));const u="reflect"===n?1:0;for(let r=0;r<o.rank;r++)i.vA(2===t[r].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),i.vA(t[r][0]>=0&&t[r][0]<=o.shape[r]-u&&t[r][1]>=0&&t[r][1]<=o.shape[r]-u,(()=>`Padding in dimension ${r} cannot be greater than or equal to ${o.shape[r]-u} or less than 0 for input of shape ${o.shape}`));const l={paddings:t,mode:n},c={x:o};return r.T2.runKernel(a.x7F,c,l)}})},6574:(e,t,n)=>{"use strict";n.d(t,{Km:()=>u,OH:()=>s,_K:()=>o,tj:()=>l});var r=n(5119);const a="tfjsflags";class s{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=i,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&!o().getBool("IS_TEST")&&o().getBool("PROD"),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];!o().getBool("IS_TEST")&&o().getBool("PROD"),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((0,r.yL)(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(a in e){e[a].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 i(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 o(){return u}let u=null;function l(e){u=e}},6734:(e,t,n)=>{"use strict";n.d(t,{D:()=>a});var r=n(3879);class a{static join(e){return new a(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map((e=>r.isTypedArray(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 i=n;i<this.shards.length;i++){const n=this.shards[i],r=e+s-n.start,o=s,u=Math.min(t,n.end)-n.start,l=new Uint8Array(n.buffer,r,u-r);if(a.set(l,o),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)}}},6808:(e,t,n)=>{"use strict";n.d(t,{r:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({cumsum_:function(e,t=0,n=!1,i=!1){const o={x:(0,s.YT)(e,"x","cumsum")},u={axis:t,exclusive:n,reverse:i};return r.T2.runKernel(a.nY8,o,u)}})},6833:function(e,t,n){var r;!function(e,a){function s(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,i,o=[],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&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,s>=0&&(i=i+1640531527|0,a=0==(n=o[127&s]^=r+i)?a+1:0);for(a>=128&&(o[127&(t&&t.length||0)]=-1),a=127,s=512;s>0;--s)r=o[a+34&127],n=o[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,o[a]=r^n;e.w=i,e.X=o,e.i=a}(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function o(e,t){null==e&&(e=+new Date);var n=new s(e),r=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&(r.X&&i(r,n),a.state=function(){return i(n,{})}),a}a&&a.exports?a.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,a))||(a.exports=r):this.xor4096=o}(0,e=n.nmd(e),n.amdD)},6841:(e,t,n)=>{"use strict";n.d(t,{q:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({asin_:function(e){const t={x:(0,s.YT)(e,"x","asin")};return r.T2.runKernel(a.QKF,t)}})},6919:(e,t,n)=>{"use strict";n.d(t,{H:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({leakyRelu_:function(e,t=.2){const n={x:(0,s.YT)(e,"x","leakyRelu")},i={alpha:t};return r.T2.runKernel(a.X0$,n,i)}})},6928:(e,t,n)=>{"use strict";n.d(t,{z:()=>u});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(6111);const u=(0,n(929).op)({clipByValue_:function(e,t,n){const u=(0,s.YT)(e,"x","clipByValue");if(i.vA(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return(0,o.G)(u.shape,t,u.dtype);const l={x:u},c={clipValueMin:t,clipValueMax:n};return r.T2.runKernel(a.vaV,l,c)}})},6999:(e,t,n)=>{"use strict";n.d(t,{j:()=>c});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(7195),u=n(929),l=n(2302);const c=(0,u.op)({maxPool_:function(e,t,n,u,c){const d=(0,s.YT)(e,"x","maxPool");let p=d,h=!1;3===d.rank&&(h=!0,p=(0,l.t)(d,[1,d.shape[0],d.shape[1],d.shape[2]])),i.vA(4===p.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${p.rank}.`)),i.vA(o.G0(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),o.s_("maxPool",u,c);const f={x:p},m={filterSize:t,strides:n,pad:u,dimRoundingMode:c},g=r.T2.runKernel(a.t3d,f,m);return h?(0,l.t)(g,[g.shape[1],g.shape[2],g.shape[3]]):g}})},7074:(e,t,n)=>{"use strict";n.d(t,{Cf:()=>m,Op:()=>c,_5:()=>u,iP:()=>h,kr:()=>p,rY:()=>f,tA:()=>d,vQ:()=>l});var r=n(6574),a=n(1743),s=n(3673);const i=(0,a.m)("kernelRegistry",(()=>new Map)),o=(0,a.m)("gradRegistry",(()=>new Map));function u(e,t){const n=g(e,t);return i.get(n)}function l(e){return o.get(e)}function c(e){const t=i.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[s,i]=a,[o]=s.split("_");o===e&&n.push(i)}return n}function d(e){const{kernelName:t,backendName:n}=e,r=g(t,n);i.has(r)&&s.i(`The kernel '${t}' for backend '${n}' is already registered`),i.set(r,e)}function p(e){const{kernelName:t}=e;o.has(t)&&(0,r._K)().getBool("DEBUG")&&s.i(`Overriding the gradient for '${t}'`),o.set(t,e)}function h(e,t){const n=g(e,t);if(!i.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);i.delete(n)}function f(e){if(!o.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);o.delete(e)}function m(e,t){c(e).forEach((e=>{d(Object.assign({},e,{backendName:t}))}))}function g(e,t){return`${t}_${e}`}},7084:(e,t,n)=>{"use strict";n.d(t,{AQ:()=>S,CY:()=>p,Ej:()=>$,P8:()=>_,Rl:()=>T,Xf:()=>N,aG:()=>d,jf:()=>k,l3:()=>v,oR:()=>C,s5:()=>y,zV:()=>I});var r=n(7148),a=n(4027),s=n(5119),i=n(5685),o=n(6734),u=n(5287),l=n(6574);const c=4;async function d(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 i=a[s],o=Array.isArray(e)?e[s].tensor:e[i];if("float32"!==o.dtype&&"int32"!==o.dtype&&"bool"!==o.dtype&&"string"!==o.dtype&&"complex64"!==o.dtype)throw new Error(`Unsupported dtype in weight '${i}': ${o.dtype}`);const u={name:i,shape:o.shape,dtype:o.dtype};if("string"===o.dtype){const e=new Promise((async e=>{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+c*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+=c,r.set(e,a),a+=e.length}e(r)}));r.push(e)}else r.push(o.data());null!=t&&(u.group=t),n.push(u)}return{data:b(await Promise.all(r)),specs:n}}function p(e,t){const n=new o.D(e),r={};let a=0;for(const s of t){const e=h(s,((e,t)=>n.slice(a+e,a+t)));r[s.name]=m(s,n.slice(a,a+e)),a+=e}return r}function h(e,t){const n=(0,s.Ze)(e.shape);let r;if("quantization"in e){const t=e.quantization;r=i.i[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=c+new Uint32Array(t(e,e+c))[0];return e}r=i.i[e.dtype]}return n*r}async function f(e,t){const n=(0,s.Ze)(e.shape);let r;if("quantization"in e){const t=e.quantization;r=i.i[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=c+new Uint32Array(await t(e,e+c))[0];return e}r=i.i[e.dtype]}return n*r}function m(e,t){const n=e.name,o=e.dtype,u=e.shape,l=(0,s.Ze)(u);let d,p=0;if("quantization"in e){const r=e.quantization;if("uint8"===r.dtype||"uint16"===r.dtype){if(!("min"in r)||!("scale"in r))throw new Error(`Weight ${e.name} with quantization ${r.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==r.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${r.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==o)throw new Error(`Weight ${e.name} is quantized with ${r.dtype} which only supports weights of type float32 not ${o}.`)}const a=i.i[r.dtype],s="uint8"===r.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===o)if("uint8"===r.dtype||"uint16"===r.dtype){d=new Float32Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];d[e]=t*r.scale+r.min}}else{if("float16"!==r.dtype)throw new Error(`Unsupported quantization type ${r.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 i=0;i<r.length;i++){const a=r[i],o=e[n[a>>10]+(1023&a)]+t[a>>10];s[i]=o}return new Float32Array(a)}}();d=e(s)}}else{if("int32"!==o)throw new Error(`Unsupported dtype in weight '${n}': ${o}`);if("uint8"!==r.dtype&&"uint16"!==r.dtype)throw new Error(`Unsupported quantization type ${r.dtype} for weight type int32.`);d=new Int32Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];d[e]=Math.round(t*r.scale+r.min)}}p+=l*a}else if("string"===o){const n=(0,s.Ze)(e.shape);d=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(p,p+c))[0];p+=c;const n=new Uint8Array(t.slice(p,p+e));d.push(n),p+=e}}else{const e=i.i[o];if("float32"===o)d=new Float32Array(t);else if("int32"===o)d=new Int32Array(t);else{if("bool"!==o){if("complex64"===o){d=new Float32Array(t);const e=new Float32Array(d.length/2),n=new Float32Array(d.length/2);for(let t=0;t<e.length;t++)e[t]=d[2*t],n[t]=d[2*t+1];const s=(0,a.O)(e,u,"float32"),i=(0,a.O)(n,u,"float32"),o=(0,r.f)(s,i);return s.dispose(),i.dispose(),o}throw new Error(`Unsupported dtype in weight '${n}': ${o}`)}d=new Uint8Array(t)}p+=l*e}return(0,a.O)(d,u,o)}async function g(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 y(e,t){const n={},r=e.getReader();let a=new ArrayBuffer(0);for(const i of t){const e=await f(i,(async(e,t)=>(a=await g(r,a,t),a.slice(e,t))));a=await g(r,a,e);const t=a.slice(0,e);a=a.slice(e);const o=m(i,t);if(n[i.name]=o,"webgpu"===(0,u.jz)()){const e=(0,u.Hs)();"uploadToGPU"in e&&(0,s.Ze)(o.shape)>=(0,l._K)().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(o.dataId)}}return n}function b(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 x="undefined"!==typeof Buffer&&("undefined"===typeof Blob||"undefined"===typeof atob||"undefined"===typeof btoa);function w(e){return x?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function v(e){if(x)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)}function k(e){if(x){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}function S(e){return o.D.join(e)}function _(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function I(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 T(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 $(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),T(e,n,r)}function C(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:w(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:w(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new o.D(e.weightData).byteLength}}function N(e){const t=[];for(const n of e)t.push(...n.weights);return t}},7126:(e,t,n)=>{"use strict";n.d(t,{j:()=>o});var r=n(1585),a=n(5441),s=n(565),i=n(8189);const o=(0,n(929).op)({sub_:function(e,t){let n=(0,i.YT)(e,"a","sub"),o=(0,i.YT)(t,"b","sub");[n,o]=(0,s.makeTypesMatch)(n,o);const u={a:n,b:o};return r.T2.runKernel(a.PbM,u)}})},7148:(e,t,n)=>{"use strict";n.d(t,{f:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({complex_:function(e,t){const n=(0,s.YT)(e,"real","complex"),o=(0,s.YT)(t,"imag","complex");i.O3(n.shape,o.shape,`real and imag shapes, ${n.shape} and ${o.shape}, must match in call to tf.complex().`);const u={real:n,imag:o};return r.T2.runKernel(a.pr3,u)}})},7180:function(e,t,n){var r;!function(e,a){function s(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 i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function o(e,t){var n=new s(e),r=t&&t.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+11102230246251565e-32*(2097152*a()|0)},a.quick=a,r&&("object"==typeof r&&i(r,n),a.state=function(){return i(n,{})}),a}a&&a.exports?a.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,a))||(a.exports=r):this.alea=o}(0,e=n.nmd(e),n.amdD)},7195:(e,t,n)=>{"use strict";n.d(t,{$Q:()=>y,Dh:()=>f,E6:()=>s,G0:()=>m,G8:()=>l,YQ:()=>a,l5:()=>i,p$:()=>u,qk:()=>g,s_:()=>b,uf:()=>o});var r=n(5119);function a(e,t,n,r,a="NHWC",s){return o(e,[...t,e[3]],n,s,r,null,null,y(a))}function s(e,t,n,r,a,s,i="channelsLast"){const[u,l]=c(t);let d;if("channelsLast"===i)d=[u,l,e[3],e[3]];else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);d=[u,l,e[1],e[1]]}return o(e,d,n,r,a,s,!1,i)}function i(e,t,n,r,a,s,i="NDHWC"){const[o,l,c]=d(t);let p,h;if("NDHWC"===i)h="channelsLast",p=[o,l,c,e[4],e[4]];else{if("NCDHW"!==i)throw new Error(`Unknown dataFormat ${i}`);h="channelsFirst",p=[o,l,c,e[1],e[1]]}return u(e,p,n,r,a,!1,h,s)}function o(e,t,n,r,a,s,i=!1,o="channelsLast"){let[u,d,f,m]=[-1,-1,-1,-1];if("channelsLast"===o)[u,d,f,m]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,m,d,f]=e}const[g,y,,b]=t,[x,w]=c(n),[v,k]=c(r),S=p(g,v),_=p(y,k),{padInfo:I,outHeight:T,outWidth:$}=function(e,t,n,r,a,s,i,o,u){let c,d,p;if("number"===typeof e){c={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,a){null==r&&(r=l(e,t,n));const s=e[0],i=e[1],o=h((s-t+2*r)/n+1,a),u=h((i-t+2*r)/n+1,a);return[o,u]}([t,n],s,r,e,o);d=a[0],p=a[1]}else if("same"===e){d=Math.ceil(t/r),p=Math.ceil(n/a);const e=Math.max(0,(d-1)*r+s-t),o=Math.max(0,(p-1)*a+i-n),u=Math.floor(e/2),l=e-u,h=Math.floor(o/2);c={top:u,bottom:l,left:h,right:o-h,type:"SAME"}}else if("valid"===e)c={top:0,bottom:0,left:0,right:0,type:"VALID"},d=Math.ceil((t-s+1)/r),p=Math.ceil((n-i+1)/a);else{if("object"!==typeof e)throw Error(`Unknown padding parameter: ${e}`);{const l="channelsLast"===u?e[1][0]:e[2][0],f="channelsLast"===u?e[1][1]:e[2][1],m="channelsLast"===u?e[2][0]:e[3][0],g="channelsLast"===u?e[2][1]:e[3][1];c={top:l,bottom:f,left:m,right:g,type:0===l&&0===f&&0===m&&0===g?"VALID":"EXPLICIT"},d=h((t-s+l+f)/r+1,o),p=h((n-i+m+g)/a+1,o)}}return{padInfo:c,outHeight:d,outWidth:p}}(a,d,f,x,w,S,_,s,o),C=i?b*m:b;let N;return"channelsFirst"===o?N=[u,C,T,$]:"channelsLast"===o&&(N=[u,T,$,C]),{batchSize:u,dataFormat:o,inHeight:d,inWidth:f,inChannels:m,outHeight:T,outWidth:$,outChannels:C,padInfo:I,strideHeight:x,strideWidth:w,filterHeight:g,filterWidth:y,effectiveFilterHeight:S,effectiveFilterWidth:_,dilationHeight:v,dilationWidth:k,inShape:e,outShape:N,filterShape:t}}function u(e,t,n,r,a,s=!1,i="channelsLast",o){let[u,c,f,m,g]=[-1,-1,-1,-1,-1];if("channelsLast"===i)[u,c,f,m,g]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,g,c,f,m]=e}const[y,b,x,,w]=t,[v,k,S]=d(n),[_,I,T]=d(r),$=p(y,_),C=p(b,I),N=p(x,T),{padInfo:E,outDepth:A,outHeight:R,outWidth:D}=function(e,t,n,r,a,s,i,o,u,c,d){let p,f,m,g;"valid"===e&&(e=0);if("number"===typeof e){p={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const y=function(e,t,n,r,a,s){null==a&&(a=l(e,t[0],r[0]));const i=[0,0,0,n];for(let o=0;o<3;o++)e[o]+2*a>=t[o]&&(i[o]=h((e[o]-t[o]+2*a)/r[o]+1,s));return i}([t,n,r,1],[o,u,c],1,[a,s,i],e,d);f=y[0],m=y[1],g=y[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{f=Math.ceil(t/a),m=Math.ceil(n/s),g=Math.ceil(r/i);const e=(f-1)*a+o-t,l=(m-1)*s+u-n,d=(g-1)*i+c-r,h=Math.floor(e/2),y=e-h,b=Math.floor(l/2),x=l-b,w=Math.floor(d/2);p={top:b,bottom:x,left:w,right:d-w,front:h,back:y,type:"SAME"}}}return{padInfo:p,outDepth:f,outHeight:m,outWidth:g}}(a,c,f,m,v,k,S,$,C,N,o),F=s?w*g:w;let M;return"channelsFirst"===i?M=[u,F,A,R,D]:"channelsLast"===i&&(M=[u,A,R,D,F]),{batchSize:u,dataFormat:i,inDepth:c,inHeight:f,inWidth:m,inChannels:g,outDepth:A,outHeight:R,outWidth:D,outChannels:F,padInfo:E,strideDepth:v,strideHeight:k,strideWidth:S,filterDepth:y,filterHeight:b,filterWidth:x,effectiveFilterDepth:$,effectiveFilterHeight:C,effectiveFilterWidth:N,dilationDepth:_,dilationHeight:I,dilationWidth:T,inShape:e,outShape:M,filterShape:t}}function l(e,t,n,r=1){const a=p(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function c(e){return"number"===typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function d(e){return"number"===typeof e?[e,e,e]:e}function p(e,t){return t<=1?e:e+(e-1)*(t-1)}function h(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 f(e){const[t,n,r]=c(e);return 1===t&&1===n&&1===r}function m(e,t){return f(e)||f(t)}function g(e){return c(e).every((e=>e>0))}function y(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function b(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)r.vA(r.E6(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=>{r.vA(r.E6(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}},7244:()=>{},7261:(e,t,n)=>{"use strict";n.d(t,{K:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({unstack_:function(e,t=0){const n=(0,s.YT)(e,"x","unstack","string_or_numeric");i.vA(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const o={value:n},u={axis:t};return r.T2.runKernel(a.dXR,o,u)}})},7270:(e,t,n)=>{"use strict";n.d(t,{BTT:()=>p.B,tnl:()=>a.t,HQu:()=>s.H,FqL:()=>i.F,WQq:()=>o.W,QiD:()=>h,Q7R:()=>f.Q,bzn:()=>m.b,FLi:()=>g.F,XRg:()=>y.X,qRo:()=>b.q,yHs:()=>x.y,rYl:()=>w.r,FPz:()=>v.F,rfv:()=>k.r,$jT:()=>S.$,sub:()=>$,lZX:()=>F,$v7:()=>O.$,BFc:()=>z,kSi:()=>L,T5N:()=>P,GTe:()=>M.G,HbZ:()=>B,vjT:()=>W,ftb:()=>nr,ROE:()=>V,hOW:()=>U.h,ra8:()=>G.r,wgE:()=>_.w,mkO:()=>H.m,zQh:()=>j.z,o8B:()=>q.o,faB:()=>Z.f,xWs:()=>C.x,I1m:()=>K,RPU:()=>Y,O5O:()=>Q,P1l:()=>X,kA9:()=>J.k,Xtf:()=>ee.X,wX9:()=>te.w,IPL:()=>ne,jIJ:()=>ae,gnS:()=>se.g,yIG:()=>ie.y,_jP:()=>pr,Lp0:()=>oe.L,rCv:()=>ue.r,aOp:()=>le,Rj8:()=>ce.R,Gl3:()=>de.G,smy:()=>pe,X7t:()=>he.X,y4m:()=>fe.y,ek5:()=>me.e,Omf:()=>ge.O,EZY:()=>cr,_3C:()=>ye,Pqc:()=>be.P,FJY:()=>dr,QP2:()=>xe,LCg:()=>we.L,Y12:()=>ve.Y,p4S:()=>ke.p,oNF:()=>Se.o,UG6:()=>_e.U,IYd:()=>Ie.I,y5U:()=>$e,hVP:()=>vn.h,GSj:()=>Ce.G,RIf:()=>Ne.R,wh_:()=>Ee.w,cZk:()=>r,kgh:()=>Ae.k,SY9:()=>lr,rhj:()=>Re.r,DQN:()=>De.D,KGM:()=>kn.K,ngS:()=>Fe.n,Slp:()=>ga,U4u:()=>hr,ggX:()=>Sn.g,MIs:()=>Me.M,EN4:()=>Oe.E,yrW:()=>ze.y,H8d:()=>Le.H,M7h:()=>Pe.M,InN:()=>Be.I,mPL:()=>ya,mT8:()=>We,Kgs:()=>Ve.K,Rm2:()=>Ue.R,Kko:()=>Ge.K,nqI:()=>He.n,HPB:()=>je.H,VZ:()=>qe.V,n76:()=>Ze.n,NSZ:()=>Ke.N,ztW:()=>Ye.z,rxB:()=>Qe.r,YYh:()=>ba,yzS:()=>et,NoW:()=>N.N,T9B:()=>tt.T,jgi:()=>nt.j,NYV:()=>rt,RO:()=>at,PhQ:()=>st.P,i2o:()=>it.i,OYQ:()=>lt,jkA:()=>ct.j,BpO:()=>dt.B,FFZ:()=>pt.F,ziu:()=>ht.z,Clk:()=>yt,CRk:()=>ir,lKK:()=>E.l,YDF:()=>bt,OjQ:()=>xt,HZy:()=>wt.H,xbf:()=>ar.x,Ec:()=>vt.E,Mw0:()=>kt.M,SaS:()=>ot.S,P61:()=>St.P,op:()=>p.op,X4o:()=>_t,eVF:()=>It.e,BZs:()=>Tt,grY:()=>$t,XHu:()=>Ct,WLX:()=>Nt,dzn:()=>Et.d,n7C:()=>At.n,NsG:()=>Rt.N,yyV:()=>Dt.y,_eU:()=>Ft._,whe:()=>Mt,iyU:()=>Ot,Q0_:()=>zt,_9M:()=>Lt,pR9:()=>Ut,FE$:()=>Gt,m0H:()=>Ht,YeY:()=>jt,HYA:()=>qt,y17:()=>Zt,xav:()=>Kt.x,VOZ:()=>Yt.V,VVh:()=>Qt.V,j__:()=>Xt.j,tQQ:()=>T.t,BEg:()=>Jt.B,QD2:()=>en,LMr:()=>tn,I2l:()=>nn,JYU:()=>rn,z8$:()=>_n.z,LIG:()=>an.L,Z$r:()=>sn.Z,d_2:()=>on.d,NFr:()=>or,sZg:()=>Je,WfX:()=>un.W,wdz:()=>ln.w,F12:()=>cn,ry7:()=>A.r,_SZ:()=>dn._,vPA:()=>ma,F8e:()=>pn.F,L0l:()=>hn.L,dik:()=>R.d,Q$M:()=>fn,zAd:()=>mn,wck:()=>gn,R0O:()=>yn,Vs9:()=>bn.V,lw0:()=>xn.l,eDJ:()=>wn.e,lMo:()=>xa,Zhr:()=>ur,lOn:()=>fa,lDo:()=>In.l,RZD:()=>Tn.R,EwI:()=>mt.E,Pbu:()=>$n.P,r2V:()=>Cn.r,t$z:()=>Nn.t,PMw:()=>En.P,Ym9:()=>An.Y,YjP:()=>wa,jbE:()=>gt.j,czq:()=>Rn.c,Mlm:()=>Dn.M,ymU:()=>D.y,OEK:()=>Fn.O,tGX:()=>On,KtR:()=>zn,$_$:()=>Ln.$,g9W:()=>Pn,Lpo:()=>Bn,yxw:()=>Wn,NNh:()=>Un,Vsq:()=>Te.V,rfw:()=>Gn.r,mgz:()=>rr.m,efE:()=>Hn,AmM:()=>jn.A,zAU:()=>qn.z,K$i:()=>Zn.K,rni:()=>Kn,bvq:()=>Yn,_M9:()=>Qn._,YJN:()=>Jn,Ul9:()=>er.U,POl:()=>tr.P});var r={};n.r(r),n.d(r,{conv2d:()=>xr,depthwiseConv2d:()=>kr,matMul:()=>Sr});var a=n(4888),s=n(2804),i=n(7558),o=n(7523),u=n(1585),l=n(5441),c=n(8189),d=n(5119),p=n(929);const h=(0,p.op)({addN_:function(e){d.vA(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),d.vA(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>(0,c.YT)(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.r1(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return u.T2.runKernel(l.EkD,r)}});var f=n(2307),m=n(9326),g=n(897),y=n(4339),b=n(6841),x=n(269),w=n(9580),v=n(1404),k=n(3774),S=n(3909),_=n(9809),I=n(7195),T=n(2302);const $=(0,p.op)({avgPool3d_:function(e,t,n,r,a,s="NDHWC"){const i=(0,c.YT)(e,"x","avgPool3d","float32");let o=i,p=!1;4===i.rank&&(p=!0,o=(0,T.t)(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),d.vA(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),d.vA("NDHWC"===s,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),d.vA("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}'`)),(0,I.s_)("avgPool3d",r,a);const h={x:o},f={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s};let m=u.T2.runKernel(l.cS,h,f);return m=(0,_.w)(m,o.dtype),p?(0,T.t)(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}});var C=n(5030),N=n(5703),E=n(9258),A=n(8968),R=n(7986),D=n(7311);const F=(0,p.op)({basicLSTMCell_:function(e,t,n,r,a,s){const i=(0,c.YT)(e,"forgetBias","basicLSTMCell"),u=(0,c.YT)(t,"lstmKernel","basicLSTMCell"),l=(0,c.YT)(n,"lstmBias","basicLSTMCell"),d=(0,c.YT)(r,"data","basicLSTMCell"),p=(0,c.YT)(a,"c","basicLSTMCell"),h=(0,c.YT)(s,"h","basicLSTMCell"),f=(0,C.x)([d,h],1),m=(0,N.N)(f,u),g=(0,o.W)(m,l),y=g.shape[0],b=g.shape[1]/4,x=[y,b],w=(0,R.d)(g,[0,0],x),v=(0,R.d)(g,[0,b],x),k=(0,R.d)(g,[0,2*b],x),S=(0,R.d)(g,[0,3*b],x),_=(0,o.W)((0,E.l)((0,A.r)(w),(0,D.y)(v)),(0,E.l)(p,(0,A.r)((0,o.W)(i,k))));return[_,(0,E.l)((0,D.y)(_),(0,A.r)(S))]}});var M=n(9772),O=n(9160);const z=(0,p.op)({batchNorm2d_:function(e,t,n,r,a,s){const i=(0,c.YT)(e,"x","batchNorm"),o=(0,c.YT)(t,"mean","batchNorm"),u=(0,c.YT)(n,"variance","batchNorm");let l,p;return null!=a&&(l=(0,c.YT)(a,"scale","batchNorm")),null!=r&&(p=(0,c.YT)(r,"offset","batchNorm")),d.vA(2===i.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`)),d.vA(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),d.vA(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=l&&d.vA(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=p&&d.vA(2===p.rank||1===p.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`)),(0,O.$)(i,o,u,p,l,s)}});const L=(0,p.op)({batchNorm3d_:function(e,t,n,r,a,s){const i=(0,c.YT)(e,"x","batchNorm"),o=(0,c.YT)(t,"mean","batchNorm"),u=(0,c.YT)(n,"variance","batchNorm");let l,p;return null!=a&&(l=(0,c.YT)(a,"scale","batchNorm")),null!=r&&(p=(0,c.YT)(r,"offset","batchNorm")),d.vA(3===i.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`)),d.vA(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),d.vA(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=l&&d.vA(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=p&&d.vA(3===p.rank||1===p.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`)),(0,O.$)(i,o,u,p,l,s)}});const P=(0,p.op)({batchNorm4d_:function(e,t,n,r,a,s){const i=(0,c.YT)(e,"x","batchNorm"),o=(0,c.YT)(t,"mean","batchNorm"),u=(0,c.YT)(n,"variance","batchNorm");let l,p;return null!=a&&(l=(0,c.YT)(a,"scale","batchNorm")),null!=r&&(p=(0,c.YT)(r,"offset","batchNorm")),d.vA(4===i.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`)),d.vA(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),d.vA(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=l&&d.vA(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=p&&d.vA(4===p.rank||1===p.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`)),(0,O.$)(i,o,u,p,l,s)}});const B=(0,p.op)({bincount_:function(e,t,n){const r=(0,c.YT)(e,"x","bincount"),a=(0,c.YT)(t,"weights","bincount");d.vA("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),d.vA(n>=0,(()=>`size must be non-negative, but got ${n}.`)),d.vA(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},i={size:n};return u.T2.runKernel(l.N4F,s,i)}});const W=(0,p.op)({bitwiseAnd_:function(e,t){const n=(0,c.YT)(e,"x","bitwiseAnd"),r=(0,c.YT)(t,"y","bitwiseAnd");if(!(0,d.r1)(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 u.T2.runKernel(l.HNs,a)}});const V=(0,p.op)({broadcastArgs_:function(e,t){const n=(0,c.YT)(e,"s0","broadcastArgs","int32"),r=(0,c.YT)(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 u.T2.runKernel(l.vj7,a)}});var U=n(3567),G=n(448),H=n(855),j=n(6928),q=n(125),Z=n(7148);const K=(0,p.op)({concat1d_:function(e){return(0,C.x)(e,0)}});const Y=(0,p.op)({concat2d_:function(e,t){return(0,C.x)(e,t)}});const Q=(0,p.op)({concat3d_:function(e,t){return(0,C.x)(e,t)}});const X=(0,p.op)({concat4d_:function(e,t){return(0,C.x)(e,t)}});var J=n(3701),ee=n(8794),te=n(1106);const ne=(0,p.op)({conv3d_:function(e,t,n,r,a="NDHWC",s=[1,1,1]){const i=(0,c.YT)(e,"x","conv3d"),o=(0,c.YT)(t,"filter","conv3d");let p=i,h=!1;4===i.rank&&(h=!0,p=(0,T.t)(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),d.vA(5===p.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${p.rank}.`)),d.vA(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),d.vA(p.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${p.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),d.vA((0,I.G0)(n,s),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),d.vA("NDHWC"===a,(()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`)),d.vA((0,I.qk)(s),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),d.vA((0,I.qk)(n),(()=>"Error in conv3D: Strides should be larger than 0."));const f={x:p,filter:o},m={strides:n,pad:r,dataFormat:a,dilations:s},g=u.T2.runKernel(l.A1h,f,m);return h?(0,T.t)(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}});var re=n(1895);const ae=(0,p.op)({conv3dTranspose_:function(e,t,n,r,a){const s=(0,c.YT)(e,"x","conv3dTranspose"),i=(0,c.YT)(t,"filter","conv3dTranspose");return(0,re.c)(n,s,i,r,a)}});var se=n(9907),ie=n(7451),oe=n(302),ue=n(6808);const le=(0,p.op)({denseBincount_:function(e,t,n,r=!1){const a=(0,c.YT)(e,"x","denseBincount"),s=(0,c.YT)(t,"weights","denseBincount");d.vA("int32"===a.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`)),d.vA(a.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`)),d.vA(n>=0,(()=>`size must be non-negative, but got ${n}.`)),d.vA(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 i={x:a,weights:s},o={size:n,binaryOutput:r};return u.T2.runKernel(l.wNW,i,o)}});var ce=n(1216),de=n(676);const pe=(0,p.op)({diag_:function(e){const t={x:(0,c.YT)(e,"x","diag")};return u.T2.runKernel(l.ORI,t)}});var he=n(3002),fe=n(9359),me=n(919),ge=n(9759);const ye=(0,p.op)({einsum_:function(e,...t){const n=t.map(((e,t)=>(0,c.YT)(e,`tensors${t}`,"einsum"))),r={equation:e};return u.T2.runKernel(l.Qgm,n,r)}});var be=n(3416);const xe=(0,p.op)({ensureShape_:function(e,t){const n=(0,c.YT)(e,"x","ensureShape","string_or_numeric");if(!(0,d.e_)(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}});var we=n(3020),ve=n(5207),ke=n(4881),Se=n(8631),_e=n(8710),Ie=n(517),Te=n(4826);const $e=(0,p.op)({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const a=(0,G.r)([e,t],r),s=e<=t?e:t;for(let o=0;o<s;++o)a.set(1,o,o);const i=(0,T.t)(a.toTensor(),[e,t]);if(null==n)return i;if(1===n.length)return(0,Te.V)((0,_e.U)(i,0),[n[0],1,1]);if(2===n.length)return(0,Te.V)((0,_e.U)((0,_e.U)(i,0),0),[n[0],n[1],1,1]);if(3===n.length)return(0,Te.V)((0,_e.U)((0,_e.U)((0,_e.U)(i,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.`)}});var Ce=n(6111),Ne=n(5606),Ee=n(8991),Ae=n(8229),Re=n(2058),De=n(3337),Fe=n(5040),Me=n(8318),Oe=n(3454),ze=n(6300),Le=n(6919),Pe=n(1303),Be=n(6508);function We(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 u.T2.runKernel(l.mnI,{},r)}var Ve=n(3531),Ue=n(4010),Ge=n(2015),He=n(5645),je=n(7991),qe=n(3330),Ze=n(3789),Ke=n(9881),Ye=n(9879),Qe=n(9925);const Xe=2147483648;const Je=(0,p.op)({searchSorted_:function(e,t,n="left"){const r=(0,c.YT)(e,"sortedSequence","searchSorted"),a=(0,c.YT)(t,"values","searchSorted"),s=r.shape[r.shape.length-1],i=a.shape[a.shape.length-1],o=(0,T.t)(r,[-1,s]),p=(0,T.t)(a,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==p.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if((0,d.Ze)(p.shape)>=Xe)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=Xe)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${o.shape[1]}`);const h={sortedSequence:o,values:p},f={side:n};return u.T2.runKernel(l.uWl,h,f)}});function et(e,t){return Je(e,t,"left")}var tt=n(1938),nt=n(6999);const rt=(0,p.op)({maxPool3d_:function(e,t=[1,1,1],n,r,a,s="NDHWC"){const i=(0,c.YT)(e,"x","maxPool3d");let o=i,p=!1;4===i.rank&&(p=!0,o=(0,T.t)(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),d.vA(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),d.vA("NDHWC"===s,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),(0,I.s_)("maxPool3d",r,a);const h={x:o},f={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s},m=u.T2.runKernel(l.ySp,h,f);return p?(0,T.t)(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}});const at=(0,p.op)({maxPoolWithArgmax_:function(e,t,n,r,a=!1){const s={x:(0,c.YT)(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:a},o=u.T2.runKernel(l.TL8,s,i);return{result:o[0],indexes:o[1]}}});var st=n(178),it=n(2611),ot=n(1411),ut=n(259);function lt(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=(0,c.YT)(e,"x","meshgrid",e instanceof ut.qY?e.dtype:"float32");if(void 0===t)return[r];let a=(0,c.YT)(t,"y","meshgrid",t instanceof ut.qY?t.dtype:"float32");const s=(0,d.Ze)(r.shape),i=(0,d.Ze)(a.shape);return"xy"===n?(r=(0,T.t)(r,[1,-1]),a=(0,T.t)(a,[-1,1]),[(0,N.N)((0,ot.S)([i,1],r.dtype),r),(0,N.N)(a,(0,ot.S)([1,s],a.dtype))]):(r=(0,T.t)(r,[-1,1]),a=(0,T.t)(a,[1,-1]),[(0,N.N)(r,(0,ot.S)([1,i],r.dtype)),(0,N.N)((0,ot.S)([s,1],a.dtype),a)])}var ct=n(7436),dt=n(2644),pt=n(6567),ht=n(152),ft=n(1078),mt=n(5793),gt=n(7126);const yt=(0,p.op)({moments_:function(e,t=null,n=!1){e=(0,c.YT)(e,"x","moments");const r=(0,d.Y6)(t,e.shape),a=(0,it.i)(e,r,n);let s=a.shape;n||(s=(0,ft.SM)(a.shape,r));const i=(0,mt.E)((0,gt.j)((0,_.w)(e,"float32"),(0,T.t)(a,s)));return{mean:a,variance:(0,it.i)(i,r,n)}}});const bt=(0,p.op)({multiRNNCell_:function(e,t,n,r){const a=(0,c.YT)(t,"data","multiRNNCell"),s=(0,c.j1)(n,"c","multiRNNCell"),i=(0,c.j1)(r,"h","multiRNNCell");let o=a;const u=[];for(let c=0;c<e.length;c++){const t=e[c](o,s[c],i[c]);u.push(t[0]),u.push(t[1]),o=t[1]}const l=[],d=[];for(let c=0;c<u.length;c+=2)l.push(u[c]),d.push(u[c+1]);return[l,d]}});const xt=(0,p.op)({multinomial_:function(e,t,n,r=!1){const a=(0,c.YT)(e,"logits","multinomial"),s=a.size,i=a.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();const o={logits:1===i?(0,T.t)(a,[1,-1]):a},d={numSamples:t,seed:n,normalized:r},p=u.T2.runKernel(l.WT3,o,d);return 1===i?(0,T.t)(p,[p.size]):p}});var wt=n(6522),vt=n(2118),kt=n(1760),St=n(9885);const _t=(0,p.op)({outerProduct_:function(e,t){const n=(0,c.YT)(e,"v1","outerProduct"),r=(0,c.YT)(t,"v2","outerProduct");d.vA(1===n.rank&&1===r.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`));const a=(0,T.t)(n,[-1,1]),s=(0,T.t)(r,[1,-1]);return(0,N.N)(a,s)}});var It=n(5661);const Tt=(0,p.op)({pad1d_:function(e,t,n=0){return(0,d.vA)(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),(0,It.e)(e,[t],n)}});const $t=(0,p.op)({pad2d_:function(e,t,n=0){return(0,d.vA)(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),(0,It.e)(e,t,n)}});const Ct=(0,p.op)({pad3d_:function(e,t,n=0){return(0,d.vA)(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.")),(0,It.e)(e,t,n)}});const Nt=(0,p.op)({pad4d_:function(e,t,n=0){return(0,d.vA)(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.")),(0,It.e)(e,t,n)}});var Et=n(7872),At=n(8990),Rt=n(4394),Dt=n(5295),Ft=n(7771);const Mt=(0,p.op)({raggedGather_:function(e,t,n,r){const a={paramsNestedSplits:e.map(((e,t)=>(0,c.YT)(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:(0,c.YT)(t,"paramsDenseValues","raggedGather"),indices:(0,c.YT)(n,"indices","raggedGather","int32")},s={outputRaggedRank:r},i=u.T2.runKernel(l.oJ2,a,s);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}});const Ot=(0,p.op)({raggedRange_:function(e,t,n){const r=(0,c.YT)(e,"starts","raggedRange"),a={starts:r,limits:(0,c.YT)(t,"limits","raggedRange",r.dtype),deltas:(0,c.YT)(n,"deltas","raggedRange",r.dtype)},s=u.T2.runKernel(l.CQC,a);return{rtNestedSplits:s[0],rtDenseValues:s[1]}}});const zt=(0,p.op)({raggedTensorToTensor_:function(e,t,n,r,a){const s=(0,c.YT)(e,"shape","raggedTensorToTensor","int32"),i=(0,c.YT)(t,"values","raggedTensorToTensor"),o={shape:s,values:i,defaultValue:(0,c.YT)(n,"defaultValue","raggedTensorToTensor",i.dtype),rowPartitionTensors:r.map(((e,t)=>(0,c.YT)(e,`tensors${t}`,"raggedTensorToTensor","int32")))},d={rowPartitionTypes:a};return u.T2.runKernel(l.mH5,o,d)}});const Lt=(0,p.op)({rand_:function(e,t,n){(0,d.SA)(e);const r=(0,d.Ze)(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 u.T2.makeTensor(a,e,n)}});var Pt=n(7391);class Bt{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=Pt.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 i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*r*i,t=this.mean+this.stdDev*a*i,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 Wt{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=Pt.alea(a.toString()),this.randn=new Bt(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 Vt{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=Pt.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const Ut=(0,p.op)({randomGamma_:function(e,t,n=1,r="float32",a){if((0,d.SA)(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const s=new Wt(t,n,r,a),i=(0,G.r)(e,r);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}});const Gt=(0,p.op)({randomNormal_:function(e,t=0,n=1,r,a){if((0,d.SA)(e),null!=r&&"bool"===r)throw new Error(`Unsupported data type ${r}`);const s=new Bt(t,n,r,!1,a),i=(0,G.r)(e,r);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}});const Ht=(0,p.op)({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return Gt(e,0,1,t,n)}});const jt=(0,p.op)({randomUniform_:function(e,t=0,n=1,r="float32",a){(0,d.SA)(e);const s=(0,G.r)(e,r),i=new Vt(t,n,null,a);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}});const qt=(0,p.op)({randomUniformInt_:function(e,t,n,r){return jt(e,t,n,"int32",r)}});function Zt(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 u.T2.runKernel(l.Q6t,{},a)}var Kt=n(1902),Yt=n(9870),Qt=n(112),Xt=n(3732),Jt=n(3262);const en=(0,p.op)({reverse1d_:function(e){const t=(0,c.YT)(e,"x","reverse");return d.vA(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),(0,Jt.B)(t,0)}});const tn=(0,p.op)({reverse2d_:function(e,t){const n=(0,c.YT)(e,"x","reverse");return d.vA(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),(0,Jt.B)(n,t)}});const nn=(0,p.op)({reverse3d_:function(e,t){const n=(0,c.YT)(e,"x","reverse");return d.vA(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),(0,Jt.B)(n,t)}});const rn=(0,p.op)({reverse4d_:function(e,t){const n=(0,c.YT)(e,"x","reverse");return d.vA(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),(0,Jt.B)(n,t)}});var an=n(5912),sn=n(7820),on=n(5702),un=n(6325),ln=n(9986);const cn=async function(e,t){const n=(0,c.YT)(e,"x","setdiff1d"),r=(0,c.YT)(t,"y","setdiff1d");d.vA(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),d.vA(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),d.vA(1===r.rank,(()=>`y should be 1D tensor, but got y (${r.shape}).`));const a=await n.data(),s=await r.data(),i=new Set(s);let o=0;for(let c=0;c<a.length;c++)i.has(a[c])||o++;const u=new ut.yl([o],n.dtype),l=new ut.yl([o],"int32");for(let c=0,d=0;c<a.length;c++)i.has(a[c])||(u.values[d]=a[c],l.values[d]=c,d++);return[u.toTensor(),l.toTensor()]};var dn=n(1115),pn=n(3726),hn=n(8276);const fn=(0,p.op)({slice1d_:function(e,t,n){const r=(0,c.YT)(e,"x","slice1d");return d.vA(1===r.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),(0,R.d)(r,[t],[n])}});const mn=(0,p.op)({slice2d_:function(e,t,n){const r=(0,c.YT)(e,"x","slice2d");return d.vA(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),(0,R.d)(r,t,n)}});const gn=(0,p.op)({slice3d_:function(e,t,n){const r=(0,c.YT)(e,"x","slice3d");return d.vA(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),(0,R.d)(r,t,n)}});const yn=(0,p.op)({slice4d_:function(e,t,n){const r=(0,c.YT)(e,"x","slice4d");return d.vA(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),(0,R.d)(r,t,n)}});var bn=n(6346),xn=n(6030),wn=n(776),vn=n(1361),kn=n(3108),Sn=n(2292),_n=n(8775),In=n(6512),Tn=n(9348),$n=n(3427),Cn=n(5932),Nn=n(4268),En=n(700),An=n(5894),Rn=n(3791),Dn=n(7823),Fn=n(4027),Mn=n(9171);function On(e,t){(0,d.HO)(e);const n=(0,c.MZ)(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return(0,Mn.Q)(e,null,n,t)}function zn(e,t,n){if((0,d.HO)(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=(0,c.MZ)(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(0,Mn.Q)(e,t,r,n)}var Ln=n(2768);function Pn(e,t,n){if((0,d.HO)(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=(0,c.MZ)(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(0,Mn.Q)(e,t,r,n)}function Bn(e,t,n){if((0,d.HO)(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=(0,c.MZ)(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(0,Mn.Q)(e,t,r,n)}function Wn(e,t,n){if((0,d.HO)(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=(0,c.MZ)(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 t=t||r,(0,Mn.Q)(e,t,r,n)}var Vn=n(6170);const Un=(0,p.op)({tensorScatterUpdate_:function(e,t,n){const r=(0,c.YT)(e,"tensor","tensorScatterupdate"),a=(0,c.YT)(t,"indices","tensorScatterupdate","int32"),s=(0,c.YT)(n,"updates","tensorScatterupdate");if(Vn.validateInput(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 i={tensor:r,indices:a,updates:s};return u.T2.runKernel(l.X4r,i,{})}});var Gn=n(1190);const Hn=(0,p.op)({truncatedNormal_:function(e,t=0,n=1,r,a){if((0,d.SA)(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const s=new Bt(t,n,r,!0,a),i=(0,G.r)(e,r);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}});var jn=n(3937),qn=n(7706),Zn=n(7261);function Kn(e,t){return Je(e,t,"right")}function Yn(e,t=!0,n,r){return u.T2.makeVariable(e,t,n,r)}var Qn=n(2151),Xn=n(4411);const Jn=async function(e){const t=(0,c.YT)(e,"condition","whereAsync","bool"),n=await t.data(),r=(0,Xn.Y)(t.shape,n);return e!==t&&t.dispose(),r};var er=n(2855),tr=n(5537);const nr=async function(e,t,n){const r=(0,c.YT)(e,"tensor","boolMask"),a=(0,c.YT)(t,"mask","boolMask","bool"),s=null==n?0:n,i=a.rank,o=r.shape;d.vA(i>0,(()=>"mask cannot be scalar")),d.O3(o.slice(s,s+i),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let u=1;for(let c=s;c<s+i;c++)u*=o[c];const l=o.slice(0,s).concat([u],o.slice(s+i)),p=(0,T.t)(r,l),h=(0,T.t)(a,[-1]),f=await Jn(h),m=(0,Cn.r)(f,[1]),g=(0,Ae.k)(p,m,s);return e!==r&&r.dispose(),t!==a&&a.dispose(),m.dispose(),p.dispose(),h.dispose(),f.dispose(),g};var rr=n(7703),ar=n(2596),sr=n(565);const ir=(0,p.op)({movingAverage_:function(e,t,n,r,a=!0){const s=(0,c.YT)(e,"v","movingAverage"),i=(0,c.YT)(t,"x","movingAverage"),u=(0,c.YT)(n,"decay","movingAverage");(0,sr.assertTypesMatch)(s,i),d.vA(d.r1(s.shape,i.shape),(()=>"Shape mismatch in v and x"));const l=(0,on.d)(1),p=(0,gt.j)(l,u);let h=(0,E.l)((0,gt.j)(i,s),p);if(a){d.vA(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=(0,c.YT)(r,"step","movingAverage");h=(0,fe.y)(h,(0,gt.j)(l,(0,At.n)(u,e)))}return(0,o.W)(s,h)}});const or=(0,p.op)({scatterND_:function(e,t,n){(0,d.SA)(n);const r=(0,c.YT)(e,"indices","scatterND","int32"),a=(0,c.YT)(t,"updates","scatterND");Vn.validateInput(a,r,n);const s={indices:r,updates:a},i={shape:n};return u.T2.runKernel(l.pJc,s,i)}});const ur=(0,p.op)({sparseToDense_:function(e,t,n,r=0){(0,d.SA)(n);const a=(0,c.YT)(e,"sparseIndices","sparseToDense","int32"),s=(0,c.YT)(t,"sparseValues","sparseToDense","string_or_numeric"),i=(0,c.YT)(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 i=t.size;if(0!==t.rank&&(1!==t.rank||i!==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,i);const o={sparseIndices:a,sparseValues:s,defaultValue:i},p={outputShape:n};return u.T2.runKernel(l.jgd,o,p)}});const lr=(0,p.op)({gatherND_:function(e,t){const n=(0,c.YT)(t,"indices","gatherND","int32"),r={params:(0,c.YT)(e,"x","gatherND","string_or_numeric"),indices:n};return u.T2.runKernel(l.O4G,r)}});const cr=(0,p.op)({dropout_:function(e,t,n,r){const a=(0,c.YT)(e,"x","dropout");if(d.vA("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.`)),d.vA(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof ut.qY?a.clone():a;const s=function(e,t){if(null==t)return e.shape.slice();if(d.r1(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),i=1-t,u=(0,fe.y)((0,Ne.R)((0,o.W)(jt(s,0,1,"float32",r),i)),i);return(0,E.l)(a,u)}});function dr(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function pr(e,t,n){const r=1-e%2,a=new Float32Array(e);for(let s=0;s<e;++s){const i=2*Math.PI*s/(e+r-1);a[s]=t-n*Math.cos(i)}return On(a,"float32")}const hr=async function(e,t,n=1){const r=(0,c.YT)(e,"predictions","inTopK"),a=(0,c.YT)(t,"targets","inTopK");(0,d.vA)(r.rank>1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),(0,d.vA)(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}`)),(0,d.O3)(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];(0,d.vA)(n>0&&n<=s,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`));const i=await r.data(),o=await a.data(),[u,l]=[i.length/s,s],p=(0,d.ce)("bool",u);for(let c=0;c<u;c++){const e=c*l,t=i.subarray(e,e+l),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[c]=0;for(let a=0;a<n;a++)if(r[a].index===o[c]){p[c]=1;break}}return e!==r&&r.dispose(),t!==a&&a.dispose(),(0,Fn.O)(p,a.shape,"bool")};var fr=n(1830),mr=n(2198),gr=n(5248),yr=n(252),br=n(8646);const xr=(0,p.op)({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:p,activation:h="linear",preluActivationWeights:f,leakyreluAlpha:m}){if(h=h||"linear",!1===(0,br.zE)(u.T2.state.gradientDepth,h)){d.vA("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 u=(0,ee.X)(e,t,n,r,a,s,i);return null!=p&&(u=(0,o.W)(u,p)),(0,br.f2)(u,h,f,m)}const g=(0,c.YT)(e,"x","conv2d","float32"),y=(0,c.YT)(t,"filter","conv2d","float32");let b=g,x=!1;3===g.rank&&(x=!0,b=(0,T.t)(g,[1,g.shape[0],g.shape[1],g.shape[2]])),d.vA(4===b.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${b.rank}.`)),d.vA(4===y.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${y.rank}.`)),I.s_("fused conv2d",r,i);const w="NHWC"===a?b.shape[3]:b.shape[1];d.vA(y.shape[2]===w,(()=>`Error in conv2d: depth of input (${w}) must match input depth for filter ${y.shape[2]}.`)),d.vA(I.G0(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const v=I.uf(b.shape,y.shape,n,s,r,i);let k,S;if(null!=p&&(k=(0,c.YT)(p,"bias","fused conv2d"),[k]=(0,sr.makeTypesMatch)(k,g),"NHWC"===a?mr.assertAndGetBroadcastShape(v.outShape,k.shape):(d.vA(k.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${k.shape.length}.`)),d.vA(0===k.shape.length||k.shape[0]===v.outChannels||1===k.shape[0],(()=>`Error in fused conv2d: bias shape (${k.shape}) is not compatible with the number of output channels (${v.outChannels})`)))),null!=f){const e=f.shape;if(d.vA(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)d.vA(1===e[0]||e[0]===v.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${v.outChannels}).`));else if(3===e.length)try{mr.assertAndGetBroadcastShape(e,v.outShape)}catch(N){const t=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${v.outShape}).`;throw Error(t)}S=(0,c.YT)(f,"prelu weights","fused conv2d")}const _=(e,t)=>{d.vA("NHWC"===a,(()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`));const[i,o,u,l]=t,c=(0,br.XB)(e,u,h);d.vA(I.Dh(s),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const p=[(0,yr.v)(o.shape,c,i,n,r),(0,gr.H)(o,c,i.shape,n,r)];if(null!=l){const e=(0,br.Do)(l,c);p.push(e)}return p},$={x:b,filter:y,bias:k,preluActivationWeights:S},C={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:i,activation:h,leakyreluAlpha:m};if(null==p){const e=(0,fr._X)(((e,t,n)=>{let r=u.T2.runKernel(l.aAr,$,C);return n([t,e,r]),x&&(r=(0,T.t)(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:_}}));return e(b,y)}{const e=(0,fr._X)(((e,t,n,r)=>{let a=u.T2.runKernel(l.aAr,$,C);return r([t,e,a,n]),x&&(a=(0,T.t)(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:_}}));return e(b,y,k)}}});var wr=n(1890),vr=n(3134);const kr=(0,p.op)({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:p,activation:h="linear",preluActivationWeights:f,leakyreluAlpha:m}){if(!1===(0,br.zE)(u.T2.state.gradientDepth,h)){let u=(0,de.G)(e,t,n,r,a,s,i);return null!=p&&(u=(0,o.W)(u,p)),(0,br.f2)(u,h,f,m)}const g=(0,c.YT)(e,"x","depthwiseConv2d","float32"),y=(0,c.YT)(t,"filter","depthwiseConv2d","float32");let b=g,x=!1;3===g.rank&&(x=!0,b=(0,T.t)(g,[1,g.shape[0],g.shape[1],g.shape[2]])),d.vA(4===b.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${b.rank}.`)),d.vA(4===y.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${y.rank}.`)),d.vA(b.shape[3]===y.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${b.shape[3]}) must match the inChannels dimension in filter ${y.shape[2]}.`)),null==s&&(s=[1,1]),d.vA(I.G0(n,s),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),I.s_("fused depthwiseConv2d",r,i);const w=I.uf(b.shape,y.shape,n,s,r,i,!0);let v,k;null!=p&&(v=(0,c.YT)(p,"bias","fused conv2d"),[v]=(0,sr.makeTypesMatch)(v,g),mr.assertAndGetBroadcastShape(w.outShape,v.shape)),null!=f&&(k=(0,c.YT)(f,"prelu weights","fused depthwiseConv2d"));const S=(e,t)=>{d.vA(I.Dh(s),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`));const[a,o,u,l]=t,c=(0,br.XB)(e,u,h),p=(0,vr.l)(o.shape,c,a,n,r,s,i),f=(0,wr.x)(o,c,a.shape,n,r,s,i);if(null!=l){return[p,f,(0,br.Do)(v,c)]}return[p,f]},_={x:b,filter:y,bias:v,preluActivationWeights:k},$={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:i,activation:h,leakyreluAlpha:m};if(null==p){const e=(0,fr._X)(((e,t,n)=>{let r=u.T2.runKernel(l.T7M,_,$);return n([t,e,r]),x&&(r=(0,T.t)(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:S}}));return e(b,y)}{const e=(0,fr._X)(((e,t,n,r)=>{let a=u.T2.runKernel(l.T7M,_,$);return r([t,e,a,n]),x&&(a=(0,T.t)(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:S}}));return e(b,y,v)}}});const Sr=(0,p.op)({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:a,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:p=.2}){if(!1===(0,br.zE)(u.T2.state.gradientDepth,s)){let u=(0,N.N)(e,t,n,r);return null!=a&&(u=(0,o.W)(u,a)),(0,br.f2)(u,s,i,p)}let h=(0,c.YT)(e,"a","fused matMul"),f=(0,c.YT)(t,"b","fused matMul");[h,f]=(0,sr.makeTypesMatch)(h,f);const m=n?h.shape[h.rank-2]:h.shape[h.rank-1],g=r?f.shape[f.rank-1]:f.shape[f.rank-2],y=n?h.shape[h.rank-1]:h.shape[h.rank-2],b=r?f.shape[f.rank-2]:f.shape[f.rank-1],x=h.shape.slice(0,-2),w=f.shape.slice(0,-2),v=d.Ze(x),k=d.Ze(w);d.vA(m===g,(()=>`Error in fused matMul: inner shapes (${m}) and (${g}) of Tensors with shapes ${h.shape} and ${f.shape} and transposeA=${n} and transposeB=${r} must match.`));const S=mr.assertAndGetBroadcastShape(h.shape.slice(0,-2),f.shape.slice(0,-2)).concat([y,b]),_=n?(0,T.t)(h,[v,m,y]):(0,T.t)(h,[v,y,m]),I=r?(0,T.t)(f,[k,b,g]):(0,T.t)(f,[k,g,b]);let $,C;null!=a&&($=(0,c.YT)(a,"bias","fused matMul"),[$]=(0,sr.makeTypesMatch)($,h),mr.assertAndGetBroadcastShape(S,$.shape)),null!=i&&(C=(0,c.YT)(i,"prelu weights","fused matMul"));const E=(e,t)=>{const[i,o,u,l]=t,c=(0,br.XB)((0,T.t)(e,u.shape),u,s);let d,p;if(n||r?!n&&r?(d=(0,N.N)(c,o,!1,!1),p=(0,N.N)(c,i,!0,!1)):n&&!r?(d=(0,N.N)(o,c,!1,!0),p=(0,N.N)(i,c,!1,!1)):(d=(0,N.N)(o,c,!0,!0),p=(0,N.N)(c,i,!0,!0)):(d=(0,N.N)(c,o,!1,!0),p=(0,N.N)(i,c,!0,!1)),null!=a){return[d,p,(0,br.Do)(l,c)]}return[d,p]},A={a:_,b:I,bias:$,preluActivationWeights:C},R={transposeA:n,transposeB:r,activation:s,leakyreluAlpha:p};if(null==a){const e=(0,fr._X)(((e,t,n)=>{const r=u.T2.runKernel(l.Dr,A,R);return n([e,t,r]),{value:(0,T.t)(r,S),gradFunc:E}}));return e(_,I)}{const e=(0,fr._X)(((e,t,n,r)=>{const a=u.T2.runKernel(l.Dr,A,R);return r([e,t,a,n]),{value:(0,T.t)(a,S),gradFunc:E}}));return e(_,I,$)}}});const _r=(0,p.op)({hammingWindow_:function(e){return pr(e,.54,.46)}});const Ir=(0,p.op)({hannWindow_:function(e){return pr(e,.5,.5)}});const Tr=(0,p.op)({frame_:function(e,t,n,r=!1,a=0){let s=0;const i=[];for(;s+t<=e.size;)i.push((0,R.d)(e,s,t)),s+=n;if(r)for(;s<e.size;){const r=s+t-e.size,o=(0,C.x)([(0,R.d)(e,s,t-r),(0,Ce.G)([r],a)]);i.push(o),s+=n}return 0===i.length?zn([],[0,t]):(0,T.t)((0,C.x)(i),[i.length,t])}});const $r=(0,p.op)({stft_:function(e,t,n,r,a=Ir){null==r&&(r=dr(t));const s=Tr(e,t,n),i=(0,E.l)(s,a(t));return(0,_n.z)(i,r)}});const Cr=(0,p.op)({cropAndResize_:function(e,t,n,r,a="bilinear",s=0){const i=(0,c.YT)(e,"image","cropAndResize"),o=(0,c.YT)(t,"boxes","cropAndResize","float32"),p=(0,c.YT)(n,"boxInd","cropAndResize","int32"),h=o.shape[0];d.vA(4===i.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),d.vA(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${h},4] but had shape ${o.shape}.`)),d.vA(1===p.rank&&p.shape[0]===h,(()=>`Error in cropAndResize: boxInd must be have size [${h}] but had shape ${o.shape}.`)),d.vA(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),d.vA(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),d.vA("bilinear"===a||"nearest"===a,(()=>`method must be bilinear or nearest, but was ${a}`));const f={image:i,boxes:o,boxInd:p},m={method:a,extrapolationValue:s,cropSize:r};return u.T2.runKernel(l.MRQ,f,m)}});const Nr=(0,p.op)({flipLeftRight_:function(e){const t=(0,c.YT)(e,"image","flipLeftRight","float32");d.vA(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return u.T2.runKernel(l.BxF,n,{})}});const Er=(0,p.op)({grayscaleToRGB_:function(e){const t=(0,c.YT)(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];d.vA(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),d.vA(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,(0,Te.V)(t,a)}});const Ar=(0,p.op)({rgbToGrayscale_:function(e){const t=(0,c.YT)(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];d.vA(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),d.vA(3===r,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`));const a=t.dtype,s=(0,_.w)(t,"float32"),i=On([.2989,.587,.114]);let o;switch(t.rank){case 2:o=ye("ij,j->i",s,i);break;case 3:o=ye("ijk,k->ij",s,i);break;case 4:o=ye("ijkl,l->ijk",s,i);break;case 5:o=ye("ijklm,m->ijkl",s,i);break;case 6:o=ye("ijklmn,n->ijklm",s,i);break;default:throw new Error("Not a valid tensor rank.")}return o=(0,_e.U)(o,-1),(0,_.w)(o,a)}});const Rr=(0,p.op)({rotateWithOffset_:function(e,t,n=0,r=.5){const a=(0,c.YT)(e,"image","rotateWithOffset","float32");d.vA(4===a.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`));const s={image:a},i={radians:t,fillValue:n,center:r};return u.T2.runKernel(l.BK4,s,i)}});function Dr(e,t,n,r,a,s){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==s&&(s=0);const i=e.shape[0];return n=Math.min(n,i),d.vA(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),d.vA(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),d.vA(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),d.vA(1===t.rank,(()=>"scores must be a 1D tensor")),d.vA(t.shape[0]===i,(()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`)),d.vA(0<=s&&s<=1,(()=>`softNmsSigma must be in [0, 1], but was '${s}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:s}}const Fr=(0,p.op)({nonMaxSuppression_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=(0,c.YT)(e,"boxes","nonMaxSuppression","float32"),i=(0,c.YT)(t,"scores","nonMaxSuppression","float32"),o=Dr(s,i,n,r,a),d={maxOutputSize:n=o.maxOutputSize,iouThreshold:r=o.iouThreshold,scoreThreshold:a=o.scoreThreshold};return u.T2.runKernel(l.SDM,{boxes:s,scores:i},d)}});var Mr=n(8360);const Or=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=(0,c.YT)(e,"boxes","nonMaxSuppressionAsync"),i=(0,c.YT)(t,"scores","nonMaxSuppressionAsync"),o=Dr(s,i,n,r,a);n=o.maxOutputSize,r=o.iouThreshold,a=o.scoreThreshold;const u=await Promise.all([s.data(),i.data()]),l=u[0],d=u[1],{selectedIndices:p}=(0,Mr.c7)(l,d,n,r,a);return s!==e&&s.dispose(),i!==t&&i.dispose(),On(p,"int32")};const zr=(0,p.op)({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const i=(0,c.YT)(e,"boxes","nonMaxSuppression"),o=(0,c.YT)(t,"scores","nonMaxSuppression"),d=Dr(i,o,n,r,a,s),p={boxes:i,scores:o},h={maxOutputSize:n=d.maxOutputSize,iouThreshold:r=d.iouThreshold,scoreThreshold:a=d.scoreThreshold,softNmsSigma:s=d.softNmsSigma},f=u.T2.runKernel(l.e0f,p,h);return{selectedIndices:f[0],selectedScores:f[1]}}});const Lr=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const i=(0,c.YT)(e,"boxes","nonMaxSuppressionAsync"),o=(0,c.YT)(t,"scores","nonMaxSuppressionAsync"),u=Dr(i,o,n,r,a,s);n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,s=u.softNmsSigma;const l=await Promise.all([i.data(),o.data()]),d=l[0],p=l[1],{selectedIndices:h,selectedScores:f}=(0,Mr.ut)(d,p,n,r,a,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:On(h,"int32"),selectedScores:On(f)}};const Pr=(0,p.op)({nonMaxSuppressionPadded_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const i=(0,c.YT)(e,"boxes","nonMaxSuppression"),o=(0,c.YT)(t,"scores","nonMaxSuppression"),d=Dr(i,o,n,r,a,null),p={boxes:i,scores:o},h={maxOutputSize:d.maxOutputSize,iouThreshold:d.iouThreshold,scoreThreshold:d.scoreThreshold,padToMaxOutputSize:s},f=u.T2.runKernel(l.Zl4,p,h);return{selectedIndices:f[0],validOutputs:f[1]}}});const Br=async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const i=(0,c.YT)(e,"boxes","nonMaxSuppressionAsync"),o=(0,c.YT)(t,"scores","nonMaxSuppressionAsync"),u=Dr(i,o,n,r,a,null),l=u.maxOutputSize,d=u.iouThreshold,p=u.scoreThreshold,[h,f]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:g}=(0,Mr.ZS)(h,f,l,d,p,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:On(m,"int32"),validOutputs:(0,on.d)(g,"int32")}};var Wr=n(4711),Vr=n(2954);const Ur=(0,p.op)({threshold_:function(e,t="binary",n=!1,r=.5){const a=(0,c.YT)(e,"image","threshold"),s=a.shape[0]*a.shape[1];let i,u,l,p,h=(0,E.l)(On([r]),255);if(d.vA(3===a.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`)),d.vA(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]}.`)),d.vA("int32"===a.dtype||"float32"===a.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`)),d.vA("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===a.shape[2]){[i,u,l]=(0,In.l)(a,[1,1,1],-1);const e=(0,E.l)(i,.2989),t=(0,E.l)(u,.587),n=(0,E.l)(l,.114);p=(0,o.W)((0,o.W)(e,t),n)}else p=e;if("otsu"===t){h=function(e,t){let n,r,a,s,i,u,l=On([-1]),c=On([0]),d=On([0]);for(let p=0;p<e.size-1;p++){n=(0,R.d)(e,0,p+1),r=(0,R.d)(e,p+1),i=(0,fe.y)((0,Rn.c)(n),t),u=(0,fe.y)((0,Rn.c)(r),t);const h=(0,Rn.c)((0,E.l)(n,Zt(0,n.size)));a=(0,fe.y)(h,(0,Rn.c)(n));const f=(0,Ce.G)(r.shape,n.size),m=(0,o.W)(Zt(0,r.size),f),g=(0,E.l)(r,m);s=(0,fe.y)((0,Rn.c)(g),(0,Rn.c)(r));const y=(0,gt.j)(a,s),b=(0,gt.j)(a,s),x=(0,E.l)(i,u);d=(0,E.l)((0,E.l)(x,y),b);const w=(0,Re.r)(d,c);c=(0,Qn._)(w,d,c),l=(0,Qn._)(w,On([p]),l)}return l}(B((0,_.w)((0,an.L)(p),"int32"),(0,Fn.O)([]),256),s)}const f=n?(0,Be.I)(p,h):(0,Re.r)(p,h);return(0,_.w)((0,E.l)(f,255),"int32")}});const Gr=(0,p.op)({transform_:function(e,t,n="nearest",r="constant",a=0,s){const i=(0,c.YT)(e,"image","transform","float32"),o=(0,c.YT)(t,"transforms","transform","float32");d.vA(4===i.rank,(()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`)),d.vA(2===o.rank&&(o.shape[0]===i.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),d.vA(null==s||2===s.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`));const p={image:i,transforms:o},h={interpolation:n,fillMode:r,fillValue:a,outputShape:s};return u.T2.runKernel(l.dLy,p,h)}});const Hr=(0,p.op)({bandPart_:function(e,t,n){const r=(0,c.YT)(e,"a","bandPart");(0,d.vA)(r.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`));const a=r.shape,[s,i]=r.shape.slice(-2);let o,u;"number"===typeof t?((0,d.vA)(t%1===0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),(0,d.vA)(t<=s,(()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`)),o=(0,c.YT)(t<0?s:t,"numLower","bandPart")):((0,d.vA)("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),o=(0,Qn._)((0,Pe.M)(t,0),s,(0,dt.B)(t,s))),"number"===typeof n?((0,d.vA)(n%1===0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`)),(0,d.vA)(n<=i,(()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`)),u=(0,c.YT)(n<0?i:n,"numUpper","bandPart")):((0,d.vA)("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),u=(0,Qn._)((0,Pe.M)(n,0),i,(0,dt.B)(n,i)));const l=(0,T.t)(Zt(0,s,1,"int32"),[-1,1]),p=Zt(0,i,1,"int32"),h=(0,gt.j)(l,p),f=(0,Ze.n)((0,Be.I)(h,o),(0,De.D)(h,(0,wt.H)(u))),m=(0,er.U)([s,i],r.dtype);return(0,T.t)((0,Nn.t)((0,Zn.K)((0,T.t)(r,[-1,s,i])).map((e=>(0,Qn._)(f,e,m)))),a)}});const jr=(0,p.op)({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,(0,d.vA)(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)(0,d.vA)(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=(0,In.l)(e,e.shape[0],0).map((e=>(0,Cn.r)(e,[0])));(0,d.vA)(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(u.T2.tidy((()=>{let e=r[a];if(a>0)for(let t=0;t<a;++t){const r=(0,E.l)((0,Rn.c)((0,E.l)(n[t],e)),n[t]);e=(0,gt.j)(e,r)}return(0,fe.y)(e,(0,ar.x)(e,"euclidean"))})));return t?(0,Nn.t)(n,0):n}});var qr=n(5287);function Zr(e,t=!1){return u.T2.tidy((()=>{(0,d.vA)(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=$e(n),s=(0,q.o)(e);const i=zn([[1]],[1,1]);let o=(0,q.o)(i);const l=n>=r?r:n;for(let e=0;e<l;++e){const t=s,l=o,c=a;[o,s,a]=u.T2.tidy((()=>{const t=(0,R.d)(s,[e,e],[n-e,1]),u=(0,ar.x)(t),l=(0,R.d)(s,[e,e],[1,1]),c=(0,Qn._)((0,Re.r)(l,0),zn([[-1]]),zn([[1]])),d=(0,gt.j)(l,(0,E.l)(c,u)),p=(0,fe.y)(t,d);o=1===p.shape[0]?(0,q.o)(i):(0,C.x)([i,(0,R.d)(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const h=(0,wt.H)((0,fe.y)((0,N.N)(c,d),u)),f=(0,R.d)(s,[e,0],[n-e,r]),m=(0,E.l)(h,o),g=(0,rr.m)(o);if(0===e)s=(0,gt.j)(f,(0,N.N)(m,(0,N.N)(g,f)));else{const t=(0,gt.j)(f,(0,N.N)(m,(0,N.N)(g,f)));s=(0,C.x)([(0,R.d)(s,[0,0],[e,r]),t],0)}const y=(0,rr.m)(m),b=(0,R.d)(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=(0,gt.j)(b,(0,N.N)((0,N.N)(b,o),y));else{const t=(0,gt.j)(b,(0,N.N)((0,N.N)(b,o),y));a=(0,C.x)([(0,R.d)(a,[0,0],[n,e]),t],1)}return[o,s,a]})),(0,qr.AS)([t,l,c])}return!t&&n>r&&(a=(0,R.d)(a,[0,0],[n,r]),s=(0,R.d)(s,[0,0],[r,r])),[a,s]}))}const Kr=(0,p.op)({qr_:function(e,t=!1){if((0,d.vA)(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return Zr(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=(0,Zn.K)((0,T.t)(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];r.forEach((e=>{const[n,r]=Zr(e,t);a.push(n),s.push(r)}));return[(0,T.t)((0,Nn.t)(a,0),e.shape),(0,T.t)((0,Nn.t)(s,0),e.shape)]}}});var Yr=n(4703);const Qr=(0,p.op)({computeWeightedLoss_:function(e,t,n=Yr.i.SUM_BY_NONZERO_WEIGHTS){const r=(0,c.YT)(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=(0,c.YT)(t,"weights","computeWeightedLoss"));const s=null==a?r:(0,E.l)(r,a);if(n===Yr.i.NONE)return s;if(n===Yr.i.SUM)return(0,Rn.c)(s);if(n===Yr.i.MEAN){if(null==a)return(0,it.i)(s);{const e=r.size/a.size,t=(0,fe.y)((0,Rn.c)(s),(0,Rn.c)(a));return e>1?(0,fe.y)(t,(0,on.d)(e)):t}}if(n===Yr.i.SUM_BY_NONZERO_WEIGHTS){if(null==a)return(0,fe.y)((0,Rn.c)(s),(0,on.d)(r.size));{const e=(0,E.l)(a,(0,ot.S)(r.shape)),t=(0,_.w)((0,Rn.c)((0,vt.E)(e,(0,on.d)(0))),"float32");return(0,fe.y)((0,Rn.c)(s),t)}}throw Error(`Unknown reduction: ${n}`)}});const Xr=(0,p.op)({absoluteDifference_:function(e,t,n,r=Yr.i.SUM_BY_NONZERO_WEIGHTS){const s=(0,c.YT)(e,"labels","absoluteDifference"),i=(0,c.YT)(t,"predictions","absoluteDifference");let o=null;null!=n&&(o=(0,c.YT)(n,"weights","absoluteDifference")),(0,d.O3)(s.shape,i.shape,"Error in absoluteDifference: ");const u=(0,a.t)((0,gt.j)(s,i));return Qr(u,o,r)}});const Jr=(0,p.op)({cosineDistance_:function(e,t,n,r,a=Yr.i.SUM_BY_NONZERO_WEIGHTS){const s=(0,c.YT)(e,"labels","cosineDistance"),i=(0,c.YT)(t,"predictions","cosineDistance");let o=null;null!=r&&(o=(0,c.YT)(r,"weights","cosineDistance")),(0,d.O3)(s.shape,i.shape,"Error in cosineDistance: ");const u=(0,on.d)(1),l=(0,gt.j)(u,(0,Rn.c)((0,E.l)(s,i),n,!0));return Qr(l,o,a)}});const ea=(0,p.op)({hingeLoss_:function(e,t,n,r=Yr.i.SUM_BY_NONZERO_WEIGHTS){let a=(0,c.YT)(e,"labels","hingeLoss");const s=(0,c.YT)(t,"predictions","hingeLoss");let i=null;null!=n&&(i=(0,c.YT)(n,"weights","hingeLoss")),(0,d.O3)(a.shape,s.shape,"Error in hingeLoss: ");const o=(0,on.d)(1);a=(0,gt.j)((0,E.l)((0,on.d)(2),a),o);const u=(0,Qt.V)((0,gt.j)(o,(0,E.l)(a,s)));return Qr(u,i,r)}});const ta=(0,p.op)({huberLoss_:function(e,t,n,r=1,s=Yr.i.SUM_BY_NONZERO_WEIGHTS){const i=(0,c.YT)(e,"labels","huberLoss"),u=(0,c.YT)(t,"predictions","huberLoss");let l=null;null!=n&&(l=(0,c.YT)(n,"weights","huberLoss")),(0,d.O3)(i.shape,u.shape,"Error in huberLoss: ");const p=(0,on.d)(r),h=(0,a.t)((0,gt.j)(u,i)),f=(0,dt.B)(h,p),m=(0,gt.j)(h,f),g=(0,o.W)((0,E.l)((0,on.d)(.5),(0,mt.E)(f)),(0,E.l)(p,m));return Qr(g,l,s)}});const na=(0,p.op)({logLoss_:function(e,t,n,r=1e-7,a=Yr.i.SUM_BY_NONZERO_WEIGHTS){const s=(0,c.YT)(e,"labels","logLoss"),i=(0,c.YT)(t,"predictions","logLoss");let u=null;null!=n&&(u=(0,c.YT)(n,"weights","logLoss")),(0,d.O3)(s.shape,i.shape,"Error in logLoss: ");const l=(0,on.d)(1),p=(0,on.d)(r),h=(0,wt.H)((0,E.l)(s,(0,Ue.R)((0,o.W)(i,p)))),f=(0,E.l)((0,gt.j)(l,s),(0,Ue.R)((0,o.W)((0,gt.j)(l,i),p))),m=(0,gt.j)(h,f);return Qr(m,u,a)}});const ra=(0,p.op)({meanSquaredError_:function(e,t,n,r=Yr.i.SUM_BY_NONZERO_WEIGHTS){const a=(0,c.YT)(e,"labels","meanSquaredError"),s=(0,c.YT)(t,"predictions","meanSquaredError");let i=null;null!=n&&(i=(0,c.YT)(n,"weights","meanSquaredError")),(0,d.O3)(a.shape,s.shape,"Error in meanSquaredError: ");const o=(0,$n.P)(a,s);return Qr(o,i,r)}});const aa=(0,p.op)({sigmoidCrossEntropy_:function(e,t,n,r=0,s=Yr.i.SUM_BY_NONZERO_WEIGHTS){let i=(0,c.YT)(e,"multiClassLabels","sigmoidCrossEntropy");const u=(0,c.YT)(t,"logits","sigmoidCrossEntropy");let l=null;if(null!=n&&(l=(0,c.YT)(n,"weights","sigmoidCrossEntropy")),(0,d.O3)(i.shape,u.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=(0,on.d)(r),t=(0,on.d)(1),n=(0,on.d)(.5);i=(0,o.W)((0,E.l)(i,(0,gt.j)(t,e)),(0,E.l)(n,e))}const p=function(e,t){const n=(0,c.YT)(e,"labels","sigmoidCrossEntropyWithLogits"),r=(0,c.YT)(t,"logits","sigmoidCrossEntropyWithLogits");(0,d.O3)(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=(0,Qt.V)(r),i=(0,E.l)(r,n),u=(0,Ge.K)((0,Se.o)((0,wt.H)((0,a.t)(r))));return(0,o.W)((0,gt.j)(s,i),u)}(i,u);return Qr(p,l,s)}});const sa=(0,p.op)({softmaxCrossEntropy_:function(e,t,n,r=0,a=Yr.i.SUM_BY_NONZERO_WEIGHTS){let s=(0,c.YT)(e,"onehotLabels","softmaxCrossEntropy");const i=(0,c.YT)(t,"logits","softmaxCrossEntropy");let u=null;if(null!=n&&(u=(0,c.YT)(n,"weights","softmaxCrossEntropy")),(0,d.O3)(s.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){const e=(0,on.d)(r),t=(0,on.d)(1),n=(0,on.d)(s.shape[1]);s=(0,o.W)((0,E.l)(s,(0,gt.j)(t,e)),(0,fe.y)(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}`);const r=(0,fr._X)(((e,t,r)=>{const a=(0,qe.V)(t,[n],!0),s=(0,gt.j)((0,_.w)(t,"float32"),a);r([e,s]);const i=(0,wt.H)((0,E.l)(s,e));return{value:(0,Rn.c)(i,[n]),gradFunc:(e,t)=>{const[r,a]=t,s=(0,ft.SM)(e.shape,[n]);return[(0,E.l)((0,T.t)(e,s),(0,gt.j)((0,_.w)(r,"float32"),(0,Se.o)(a))),(0,E.l)((0,T.t)(e,s),(0,gt.j)((0,Se.o)(a),(0,_.w)(r,"float32")))]}}}));return r(e,t)}(s,i);return Qr(l,u,a)}});const ia=(0,p.op)({sparseFillEmptyRows_:function(e,t,n,r){const a=(0,c.YT)(e,"indices","sparseFillEmptyRows","int32"),s=(0,c.YT)(t,"values","sparseFillEmptyRows"),i=(0,c.YT)(n,"denseShape","sparseFillEmptyRows","int32"),o=(0,c.YT)(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!==i.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(0!==o.rank)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);const d={indices:a,values:s,denseShape:i,defaultValue:o},p=u.T2.runKernel(l.C8s,d);return{outputIndices:p[0],outputValues:p[1],emptyRowIndicator:p[2],reverseIndexMap:p[3]}}});const oa=(0,p.op)({sparseReshape_:function(e,t,n){const r=(0,c.YT)(e,"inputIndices","sparseReshape","int32"),a=(0,c.YT)(t,"inputShape","sparseReshape","int32"),s=(0,c.YT)(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 i={inputIndices:r,inputShape:a,newShape:s},o=u.T2.runKernel(l.BoJ,i);return{outputIndices:o[0],outputShape:o[1]}}});const ua=(0,p.op)({sparseSegmentMean_:function(e,t,n){const r=(0,c.YT)(e,"data","sparseSegmentMean"),a=(0,c.YT)(t,"indices","sparseSegmentMean","int32"),s=(0,c.YT)(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 i={data:r,indices:a,segmentIds:s};return u.T2.runKernel(l.L6G,i)}});const la=(0,p.op)({sparseSegmentSum_:function(e,t,n){const r=(0,c.YT)(e,"data","sparseSegmentSum"),a=(0,c.YT)(t,"indices","sparseSegmentSum","int32"),s=(0,c.YT)(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 i={data:r,indices:a,segmentIds:s};return u.T2.runKernel(l.DvZ,i)}});const ca=(0,p.op)({stringNGrams_:function(e,t,n,r,a,s,i,o){const d=(0,c.YT)(e,"data","stringNGrams","string");if("string"!==d.dtype)throw new Error("Data must be of datatype string");if(1!==d.shape.length)throw new Error(`Data must be a vector, saw: ${d.shape}`);const p=(0,c.YT)(t,"dataSplits","stringNGrams");if("int32"!==p.dtype)throw new Error("Data splits must be of datatype int32");const h={separator:n,nGramWidths:r,leftPad:a,rightPad:s,padWidth:i,preserveShortSequences:o},f={data:d,dataSplits:p},m=u.T2.runKernel(l.YAb,f,h);return{nGrams:m[0],nGramsSplits:m[1]}}});const da=(0,p.op)({stringSplit_:function(e,t,n=!0){const r=(0,c.YT)(e,"input","stringSplit","string"),a=(0,c.YT)(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},i={input:r,delimiter:a},o=u.T2.runKernel(l.iW0,i,s);return{indices:o[0],values:o[1],shape:o[2]}}});const pa=(0,p.op)({stringToHashBucketFast_:function(e,t){const n=(0,c.YT)(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 u.T2.runKernel(l.$jE,a,r)}});const ha=(0,p.op)({staticRegexReplace_:function(e,t,n,r=!0){const a=(0,c.YT)(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:n,replaceGlobal:r};return u.T2.runKernel(l.GZp,{x:a},s)}}),fa={fft:vn.h,ifft:kn.K,rfft:_n.z,irfft:Sn.g},ma={hammingWindow:_r,hannWindow:Ir,frame:Tr,stft:$r},ga={flipLeftRight:Nr,grayscaleToRGB:Er,resizeNearestNeighbor:Vr.b,resizeBilinear:Wr.v,rgbToGrayscale:Ar,rotateWithOffset:Rr,cropAndResize:Cr,nonMaxSuppression:Fr,nonMaxSuppressionAsync:Or,nonMaxSuppressionWithScore:zr,nonMaxSuppressionWithScoreAsync:Lr,nonMaxSuppressionPadded:Pr,nonMaxSuppressionPaddedAsync:Br,threshold:Ur,transform:Gr},ya={bandPart:Hr,gramSchmidt:jr,qr:Kr},ba={absoluteDifference:Xr,computeWeightedLoss:Qr,cosineDistance:Jr,hingeLoss:ea,huberLoss:ta,logLoss:na,meanSquaredError:ra,sigmoidCrossEntropy:aa,softmaxCrossEntropy:sa},xa={sparseFillEmptyRows:ia,sparseReshape:oa,sparseSegmentMean:ua,sparseSegmentSum:la},wa={stringNGrams:ca,stringSplit:da,stringToHashBucketFast:pa,staticRegexReplace:ha}},7311:(e,t,n)=>{"use strict";n.d(t,{y:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({tanh_:function(e){const t={x:(0,s.YT)(e,"x","tanh","float32")};return r.T2.runKernel(a.iuW,t)}})},7391:(e,t,n)=>{var r=n(7180),a=n(3181),s=n(3031),i=n(9067),o=n(6833),u=n(3717),l=n(4801);l.alea=r,l.xor128=a,l.xorwow=s,l.xorshift7=i,l.xor4096=o,l.tychei=u,e.exports=l},7436:(e,t,n)=>{"use strict";n.d(t,{j:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({min_:function(e,t=null,n=!1){const i={x:(0,s.YT)(e,"x","min")},o={axis:t,keepDims:n};return r.T2.runKernel(a.lNG,i,o)}})},7451:(e,t,n)=>{"use strict";n.d(t,{y:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({cosh_:function(e){const t={x:(0,s.YT)(e,"x","cosh","float32")};return r.T2.runKernel(a.MnK,t)}})},7523:(e,t,n)=>{"use strict";n.d(t,{W:()=>o});var r=n(1585),a=n(5441),s=n(565),i=n(8189);const o=(0,n(929).op)({add_:function(e,t){let n=(0,i.YT)(e,"a","add"),o=(0,i.YT)(t,"b","add");[n,o]=(0,s.makeTypesMatch)(n,o);const u={a:n,b:o};return r.T2.runKernel(a.OMN,u)}})},7558:(e,t,n)=>{"use strict";n.d(t,{F:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({acosh_:function(e){const t={x:(0,s.YT)(e,"x","acosh")};return r.T2.runKernel(a.PH8,t)}})},7703:(e,t,n)=>{"use strict";n.d(t,{m:()=>h});var r=n(1585),a=n(5287),s=n(5441),i=n(8189),o=n(5119),u=n(7148),l=n(5040),c=n(6522),d=n(929),p=n(1902);const h=(0,d.op)({transpose_:function(e,t,n){const d=(0,i.YT)(e,"x","transpose");if(null==t&&(t=d.shape.map(((e,t)=>t)).reverse()),o.vA(d.rank===t.length,(()=>`Error in transpose: rank of input ${d.rank} must match length of perm ${t}.`)),t.forEach((e=>{o.vA(e>=0&&e<d.rank,(()=>"All entries in 'perm' must be between 0 and "+(d.rank-1)+` but got ${t}`))})),d.rank<=1)return d.clone();const h={x:d},f={perm:t};return"complex64"===d.dtype?(0,a.DZ)((()=>{let e=(0,p.x)(d),t=(0,l.n)(d);return e=r.T2.runKernel(s.wx0,{x:e},f),t=r.T2.runKernel(s.wx0,{x:t},f),n&&(t=(0,c.H)(t)),(0,u.f)(e,t)})):r.T2.runKernel(s.wx0,h,f)}})},7706:(e,t,n)=>{"use strict";n.d(t,{z:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({unsortedSegmentSum_:function(e,t,n){const o=(0,s.YT)(e,"x","unsortedSegmentSum"),u=(0,s.YT)(t,"segmentIds","unsortedSegmentSum","int32");(0,i.vA)((0,i.E6)(n),(()=>"numSegments must be of dtype int"));const l={x:o,segmentIds:u},c={numSegments:n};return r.T2.runKernel(a.pPe,l,c)}})},7763:(e,t,n)=>{"use strict";n.d(t,{h:()=>a});var r=n(5838);function a(e,t,n,a){const s=r.ZSL.getArrayFromDType(n,r.ZSL.sizeFromShape(t));if(a&&"string"!==n){let t=0;e.forEach((e=>{const n=r.ZSL.sizeFromShape(e.shape);s.set(e.vals,t),t+=n}))}else{let a=0;e.forEach((e=>{const i="string"===n?r.C0T.fromUint8ToStringArray(e.vals):e.vals;let o=0;for(let n=0;n<e.shape[0];++n){const r=n*t[1]+a;for(let t=0;t<e.shape[1];++t)s[r+t]=i[o++]}a+=e.shape[1]}))}return s}},7771:(e,t,n)=>{"use strict";n.d(t,{_:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(9809);const o=(0,n(929).op)({prod_:function(e,t=null,n=!1){let o=(0,s.YT)(e,"x","prod");"bool"===o.dtype&&(o=(0,i.w)(o,"int32"));const u={x:o},l={axis:t,keepDims:n};return r.T2.runKernel(a.kdj,u,l)}})},7793:(e,t,n)=>{const r=n(126);t.parseFont=r,t.createCanvas=function(e,t){return Object.assign(document.createElement("canvas"),{width:e,height:t})},t.createImageData=function(e,t,n){switch(arguments.length){case 0:return new ImageData;case 1:return new ImageData(e);case 2:return new ImageData(e,t);default:return new ImageData(e,t,n)}},t.loadImage=function(e,t){return new Promise((function(n,r){const a=Object.assign(document.createElement("img"),t);function s(){a.onload=null,a.onerror=null}a.onload=function(){s(),n(a)},a.onerror=function(){s(),r(new Error('Failed to load the image "'+e+'"'))},a.src=e}))}},7820:(e,t,n)=>{"use strict";n.d(t,{Z:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({rsqrt_:function(e){const t={x:(0,s.YT)(e,"x","rsqrt","float32")};return r.T2.runKernel(a.TOR,t)}})},7823:(e,t,n)=>{"use strict";n.d(t,{M:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({tan_:function(e){const t={x:(0,s.YT)(e,"x","tan","float32")};return r.T2.runKernel(a.oFs,t)}})},7870:(e,t,n)=>{"use strict";n.d(t,{C:()=>a});var r=n(5838);function a(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&r.ZSL.assert("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}},7872:(e,t,n)=>{"use strict";n.d(t,{d:()=>p});var r=n(8189),a=n(5119),s=n(3909),i=n(9772),o=n(7195),u=n(6999),l=n(929),c=n(2302),d=n(776);const p=(0,l.op)({pool_:function(e,t,n,l,p,h,f){null==p&&(p=[1,1]),null==h&&(h=1),0===l&&(l="valid");const m=(0,r.YT)(e,"x","maxPool");let g=m,y=!1;3===m.rank&&(y=!0,g=(0,c.t)(m,[1,m.shape[0],m.shape[1],m.shape[2]])),a.vA(o.G0(h,p),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${h} and dilations '${p}'`));const b=o.E6(g.shape,t,h,p,l),x=[b.dilationHeight,b.dilationWidth];let w;w="same"===l?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]]))}([b.filterHeight,b.filterWidth],x):[[0,0],[0,0]];const v=1===x[0]&&1===x[1],[k,S]=function(e,t,n){const r=n.map((e=>e[0])),a=n.map((e=>e[1])),s=e.concat(r,a),i=t.map(((e,t)=>(e-s[t]%e)%e)),o=a.map(((e,t)=>e+i[t])),u=t.map(((e,t)=>[r[t],o[t]])),l=t.map(((e,t)=>[0,i[t]]));return[u,l]}([b.inHeight,b.inWidth],x,w),_=v?l:"valid",I=v?g:(0,d.e)(g,x,k),T=("avg"===n?()=>(0,s.$)(I,t,h,_,f):()=>(0,u.j)(I,t,h,_,f))(),$=v?T:(0,i.G)(T,x,S);return y?(0,c.t)($,[$.shape[1],$.shape[2],$.shape[3]]):$}})},7906:(e,t,n)=>{"use strict";n.d(t,{HS:()=>s,di:()=>i,lv:()=>o});var r=n(5838),a=n(7870);function s(e,t,n,a,s){const i=r.Kro.isSliceContinous(a,t,n),o=r.ZSL.sizeFromShape(n),u=r.ZSL.computeStrides(a);if(i){const n=r.Kro.computeFlatOffset(t,u);return"string"===s?e.slice(n,n+o):e.subarray(n,n+o)}const l="string"===s?r.C0T.fromUint8ToStringArray(e):e,c=(0,r.ra8)(a,s,l),d=(0,r.ra8)(n,s);for(let r=0;r<d.size;++r){const e=d.indexToLoc(r),n=e.map(((e,n)=>e+t[n]));d.set(c.get(...n),...e)}return"string"===s?r.C0T.fromStringArrayToUint8(d.values):d.values}function i(e){const{inputs:t,backend:n,attrs:i}=e,{x:o}=t,{begin:u,size:l}=i;(0,a.C)(o,"slice");const[c,d]=r.Kro.parseSliceParams(o,u,l);r.Kro.assertParamsValid(o,c,d);const p=s(n.data.get(o.dataId).values,c,d,o.shape,o.dtype);return n.makeTensorInfo(d,o.dtype,p)}const o={kernelName:r.JiE,backendName:"cpu",kernelFunc:i}},7986:(e,t,n)=>{"use strict";n.d(t,{d:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({slice_:function(e,t,n){const i=(0,s.YT)(e,"x","slice","string_or_numeric");if(0===i.rank)throw new Error("Slicing scalar is not possible");const o={x:i},u={begin:t,size:n};return r.T2.runKernel(a.JiE,o,u)}})},7991:(e,t,n)=>{"use strict";n.d(t,{H:()=>h});var r=n(1830),a=n(8189),s=n(9809),i=n(8631),o=n(4010),u=n(1938),l=n(9258),c=n(929),d=n(7126),p=n(3791);const h=(0,c.op)({logSoftmax_:function(e,t=-1){const n=(0,a.YT)(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(0,r._X)(((e,n)=>{const r=(0,u.T)(e,t,!0),a=(0,d.j)(e,r),c=(0,d.j)((0,s.w)(a,"float32"),(0,o.R)((0,p.c)((0,i.o)(a),t,!0)));n([c]);return{value:c,gradFunc:(e,n)=>{const[r]=n,a=(0,i.o)(r);return(0,d.j)(e,(0,l.l)((0,p.c)(e,t,!0),a))}}}))(n)}})},8074:()=>{},8108:()=>{},8189:(e,t,n)=>{"use strict";n.d(t,{MZ:()=>l,YT:()=>p,j1:()=>h});var r=n(1585),a=n(6574),s=n(259),i=n(2046),o=n(3879),u=n(5119);function l(e,t){let n=e;if((0,o.isTypedArray)(e))return"string"===t?[]:[e.length];if((0,i.Oj)(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if((0,i.Nw)(e))return[e.buffer.size/(null==t?4:(0,u.jv)(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||(0,o.isTypedArray)(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&(0,a._K)().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&c(e,r,[]),r}function c(e,t,n){if(n=n||[],!Array.isArray(e)&&!(0,o.isTypedArray)(e))return void(0,u.vA)(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));(0,u.vA)(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),(0,u.vA)(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)c(e[a],r,n.concat(a))}function d(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 p(e,t,n,a="numeric"){if(e instanceof(0,s.tp)())return d(a,e.dtype,t,n),e;let i=(0,u.X$)(e);if("string"!==i&&["bool","int32","float32"].indexOf(a)>=0&&(i=a),d(a,i,t,n),null==e||!(0,o.isTypedArray)(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 c=l(e,i);(0,o.isTypedArray)(e)||Array.isArray(e)||(e=[e]);const p="string"!==i?(0,o.toTypedArray)(e,i):(0,o.flatten)(e,[],!0);return r.T2.makeTensor(p,c,i)}function h(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)=>p(e,`${t}[${a}]`,n,r)))}},8229:(e,t,n)=>{"use strict";n.d(t,{k:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({gather_:function(e,t,n=0,i=0){const o={x:(0,s.YT)(e,"x","gather"),indices:(0,s.YT)(t,"indices","gather","int32")},u={axis:n,batchDims:i};return r.T2.runKernel(a.mxL,o,u)}})},8276:(e,t,n)=>{"use strict";n.d(t,{L:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({sinh_:function(e){const t={x:(0,s.YT)(e,"x","sinh")};return r.T2.runKernel(a.J3C,t)}})},8318:(e,t,n)=>{"use strict";n.d(t,{M:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({isFinite_:function(e){const t={x:(0,s.YT)(e,"x","isFinite")};return r.T2.runKernel(a.gIW,t)}})},8360:(e,t,n)=>{"use strict";function r(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,a=e.length,s=0,i=!1;for(;r<a;){s=r+(a-r>>>1);const o=n(t,e[s]);o>0?r=s+1:(a=s,i=!o)}return i?r:-r-1}(e,t,n||a)}(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function a(e,t){return e>t?1:e<t?-1:0}function s(e,t,n,r,a){return u(e,t,n,r,a,0)}function i(e,t,n,r,a,s){return u(e,t,n,r,a,0,!1,s,!0)}function o(e,t,n,r,a,s){return u(e,t,n,r,a,s,!0)}function u(e,t,n,a,s,i,o=!1,u=!1,p=!1){const h=[];for(let r=0;r<t.length;r++)t[r]>s&&h.push({score:t[r],boxIndex:r,suppressBeginIndex:0});h.sort(d);const f=i>0?-.5/i:0,m=[],g=[];for(;m.length<n&&h.length>0;){const t=h.pop(),{score:n,boxIndex:i,suppressBeginIndex:o}=t;if(n<s)break;let u=!1;for(let r=m.length-1;r>=o;--r){const n=l(e,i,m[r]);if(n>=a){u=!0;break}if(t.score=t.score*c(a,f,n),t.score<=s)break}t.suppressBeginIndex=m.length,u||(t.score===n?(m.push(i),g.push(t.score)):t.score>s&&r(h,t,d))}const y=m.length,b=n-y;u&&b>0&&(m.push(...new Array(b).fill(0)),g.push(...new Array(b).fill(0)));const x={selectedIndices:m};return o&&(x.selectedScores=g),p&&(x.validOutputs=y),x}function l(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]),i=Math.min(r[1],r[3]),o=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=(o-s)*(u-i),f=(d-l)*(p-c);if(h<=0||f<=0)return 0;const m=Math.max(s,l),g=Math.max(i,c),y=Math.min(o,d),b=Math.min(u,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(h+f-x)}function c(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function d(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}n.d(t,{c7:()=>s,ZS:()=>i,ut:()=>o})},8417:(e,t,n)=>{var r=(()=>{var e="undefined"!==typeof document&&document.currentScript?document.currentScript.src:void 0;return e=e||"/index.js",function(t){function r(){return A.buffer!=O&&H(A.buffer),z}function a(){return A.buffer!=O&&H(A.buffer),L}function s(){return A.buffer!=O&&H(A.buffer),P}function i(){return A.buffer!=O&&H(A.buffer),B}function o(){return A.buffer!=O&&H(A.buffer),W}var u,l,c,d="undefined"!=typeof(t=t||{})?t:{};d.ready=new Promise((function(e,t){u=e,l=t})),"undefined"!==typeof process&&process.listeners&&(c={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var p,h,f,m=Object.assign({},d),g=[],y=(e,t)=>{throw t},b="object"==typeof window,x="function"==typeof importScripts,w="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,v=d.ENVIRONMENT_IS_PTHREAD||!1,k="";function S(e){return d.locateFile?d.locateFile(e,k):k+e}if(w){var _=n(9893),I=n(5281);let e;k=x?I.dirname(k)+"/":"//",p=(e,t)=>(e=se(e)?new URL(e):I.normalize(e),_.readFileSync(e,t?void 0:"utf8")),f=e=>{var t=p(e,!0);return t.buffer||(t=new Uint8Array(t)),t},h=(e,t,n)=>{e=se(e)?new URL(e):I.normalize(e),_.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),g=process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof ue))throw e})),process.on("unhandledRejection",(function(e){throw e})),y=(e,t)=>{if(Q())throw process.exitCode=e,t;!function(e){if(e instanceof ue)return;N("exiting due to exception: "+e)}(t),process.exit(e)},d.inspect=function(){return"[Emscripten Module object]"};try{e=n(3556)}catch(Ke){throw Ke}n.g.Worker=e.Worker}else(b||x)&&(x?k=self.location.href:"undefined"!=typeof document&&document.currentScript&&(k=document.currentScript.src),"undefined"!==typeof e&&e&&(k=e),k=0!==k.indexOf("blob:")?k.substr(0,k.replace(/[?#].*/,"").lastIndexOf("/")+1):"",w||(p=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},x&&(f=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),h=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}),e=>document.title=e);w&&"undefined"==typeof performance&&(n.g.performance=n(7244).performance);var T=function(){}.bind(),$=function(){}.bind();w&&(T=e=>_.writeSync(1,e+"\n"),$=e=>_.writeSync(2,e+"\n"));var C=d.print||T,N=d.printErr||$;Object.assign(d,m),m=null,d.arguments&&(g=d.arguments),d.thisProgram&&d.thisProgram,d.quit&&(y=d.quit);var E;Atomics.load,Atomics.store,Atomics.compareExchange;d.wasmBinary&&(E=d.wasmBinary);var A,R,D=d.noExitRuntime||!0;"object"!=typeof WebAssembly&&ne("no native wasm support detected");var F,M=!1;var O,z,L,P,B,W,V="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function U(e,t,n){for(var r=(t>>>=0)+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.buffer&&V)return V.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,a):e.subarray(t,a));for(var s="";t<a;){var i=e[t++];if(128&i){var o=63&e[t++];if(192!=(224&i)){var u=63&e[t++];if((i=224==(240&i)?(15&i)<<12|o<<6|u:(7&i)<<18|o<<12|u<<6|63&e[t++])<65536)s+=String.fromCharCode(i);else{var l=i-65536;s+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else s+=String.fromCharCode((31&i)<<6|o)}else s+=String.fromCharCode(i)}return s}function G(e,t){return(e>>>=0)?U(a(),e,t):""}function H(e){O=e,d.HEAP8=z=new Int8Array(e),d.HEAP16=new Int16Array(e),d.HEAP32=P=new Int32Array(e),d.HEAPU8=L=new Uint8Array(e),d.HEAPU16=new Uint16Array(e),d.HEAPU32=B=new Uint32Array(e),d.HEAPF32=new Float32Array(e),d.HEAPF64=W=new Float64Array(e)}v&&(O=d.buffer);var j,q=d.INITIAL_MEMORY||16777216;if(v)A=d.wasmMemory,O=d.buffer;else if(d.wasmMemory)A=d.wasmMemory;else if(!((A=new WebAssembly.Memory({initial:q/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw N("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),w&&N("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");A&&(O=A.buffer),q=O.byteLength,H(O);var Z=[],K=[],Y=[];function Q(){return D}function X(){v||fe(K)}var J=0,ee=null,te=null;function ne(e){d.onAbort&&d.onAbort(e),N(e="Aborted("+e+")"),M=!0,F=1,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw l(t),t}var re;function ae(e){return e.startsWith("data:application/octet-stream;base64,")}function se(e){return e.startsWith("file://")}function ie(e){try{if(e==re&&E)return new Uint8Array(E);if(f)return f(e);throw"both async and sync fetching of the wasm failed"}catch(N){ne(N)}}ae(re="tfjs-backend-wasm-threaded-simd.wasm")||(re=S(re));var oe={};function ue(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function le(e){var t,n=he.pthreads[e];n||ne(t),he.returnWorkerToPool(n)}function ce(e){var t=he.getNewWorker();if(!t)return 6;he.runningWorkers.push(t),he.pthreads[e.pthread_ptr]=t,t.pthread_ptr=e.pthread_ptr;var n={cmd:"run",start_routine:e.startRoutine,arg:e.arg,pthread_ptr:e.pthread_ptr};return t.runPthread=()=>{w&&t.ref(),t.postMessage(n,e.transferList),delete t.runPthread},t.loaded&&t.runPthread(),0}function de(e){if(v)return ke(1,1,e);F=e,Q()||(he.terminateAllThreads(),d.onExit&&d.onExit(e),M=!0),y(e,new ue(e))}var pe=function(e,t){if(F=e,!t&&v)throw me(e),"unwind";de(e)};var he={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){v?he.initWorker():he.initMainThread()},initMainThread:function(){for(var e=8;e--;)he.allocateUnusedWorker()},initWorker:function(){D=!1},setExitStatus:function(e){F=e},terminateAllThreads:function(){for(var e of Object.values(he.pthreads))he.returnWorkerToPool(e);for(var e of he.unusedWorkers)e.terminate();he.unusedWorkers=[]},returnWorkerToPool:function(e){var t=e.pthread_ptr;delete he.pthreads[t],he.unusedWorkers.push(e),he.runningWorkers.splice(he.runningWorkers.indexOf(e),1),e.pthread_ptr=0,w&&e.unref(),We(t)},receiveObjectTransfer:function(e){},threadInitTLS:function(){he.tlsInitFunctions.forEach((e=>e()))},loadWasmModuleToWorker:function(t,n){t.onmessage=e=>{var r,a=e.data,s=a.cmd;if(t.pthread_ptr&&(he.currentProxiedOperationCallerThread=t.pthread_ptr),a.targetThread&&a.targetThread!=ze()){var i=he.pthreads[a.targetThread];return i?i.postMessage(a,a.transferList):N('Internal error! Worker sent a message "'+s+'" to target pthread '+a.targetThread+", but that thread no longer exists!"),void(he.currentProxiedOperationCallerThread=void 0)}"processProxyingQueue"===s?we(a.queue):"spawnThread"===s?ce(a):"cleanupThread"===s?le(a.thread):"killThread"===s?function(e){var t=he.pthreads[e];delete he.pthreads[e],t.terminate(),We(e),he.runningWorkers.splice(he.runningWorkers.indexOf(t),1),t.pthread_ptr=0}(a.thread):"cancelThread"===s?(r=a.thread,he.pthreads[r].postMessage({cmd:"cancel"})):"loaded"===s?(t.loaded=!0,w&&t.unref(),n&&n(t),t.runPthread&&t.runPthread()):"print"===s?C("Thread "+a.threadId+": "+a.text):"printErr"===s?N("Thread "+a.threadId+": "+a.text):"alert"===s?alert("Thread "+a.threadId+": "+a.text):"setimmediate"===a.target?t.postMessage(a):"callHandler"===s?d[a.handler](...a.args):s&&N("worker sent an unknown command "+s),he.currentProxiedOperationCallerThread=void 0},t.onerror=e=>{throw N("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},w&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){})));var r=[];for(var a of["onExit","onAbort","print","printErr"])d.hasOwnProperty(a)&&r.push(a);t.postMessage({cmd:"load",handlers:r,urlOrBlob:d.mainScriptUrlOrBlob||e,wasmMemory:A,wasmModule:R})},allocateUnusedWorker:function(){var e,t=S("tfjs-backend-wasm-threaded-simd.worker.js");e=new Worker(t),he.unusedWorkers.push(e)},getNewWorker:function(){return 0==he.unusedWorkers.length&&(he.allocateUnusedWorker(),he.loadWasmModuleToWorker(he.unusedWorkers[0])),he.unusedWorkers.pop()}};function fe(e){for(;e.length>0;)e.shift()(d)}function me(e){if(v)return ke(2,0,e);try{pe(e)}catch(Ke){!function(e){if(e instanceof ue||"unwind"==e)return F;y(1,e)}(Ke)}}d.PThread=he,d.establishStackSpace=function(){var e=ze(),t=s()[e+52>>>2],n=s()[e+56>>>2];Ue(t,t-n),He(t)};var ge=[];function ye(e,t,n,r){return v?ke(3,1,e,t,n,r):be(e,t,n,r)}function be(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return N("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];if(v&&0===a.length)return ye(e,t,n,r);var s={startRoutine:n,pthread_ptr:e,arg:r,transferList:a};return v?(s.cmd="spawnThread",postMessage(s,a),0):ce(s)}d.invokeEntryPoint=function(e,t){var n=function(e){var t=ge[e];return t||(e>=ge.length&&(ge.length=e+1),ge[e]=t=j.get(e)),t}(e)(t);Q()?he.setExitStatus(n):Ve(n)};var xe;function we(e){Atomics.store(s(),e>>2,1),ze()&&Be(e),Atomics.compareExchange(s(),e>>2,1,0)}function ve(e){ve.shown||(ve.shown={}),ve.shown[e]||(ve.shown[e]=1,w&&(e="warning: "+e),N(e))}function ke(e,t){var n=arguments.length-2,r=arguments;return function(e){var t=Ge(),n=e();return He(t),n}((()=>{for(var a=n,s=je(8*a),i=s>>3,u=0;u<n;u++){var l=r[2+u];o()[i+u>>>0]=l}return Pe(e,a,s,t)}))}d.executeNotifiedProxyingQueue=we,xe=w?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.timeOrigin+performance.now();var Se=[];function _e(e){try{return A.grow(e-O.byteLength+65535>>>16),H(A.buffer),1}catch(Ke){}}function Ie(e){return v?ke(4,1,e):52}function Te(e,t,n,r,a){return v?ke(5,1,e,t,n,r,a):70}var $e=[null,[],[]];function Ce(e,t){var n=$e[e];0===t||10===t?((1===e?C:N)(U(n,0)),n.length=0):n.push(t)}function Ne(e,t,n,r){if(v)return ke(6,1,e,t,n,r);for(var s=0,o=0;o<n;o++){var u=i()[t>>>2],l=i()[t+4>>>2];t+=8;for(var c=0;c<l;c++)Ce(e,a()[u+c>>>0]);s+=l}return i()[r>>>2]=s,0}function Ee(e){return d["_"+e]}function Ae(e,t,n,s,i){var o={string:e=>{var t=0;if(null!==e&&void 0!==e&&0!==e){var n=1+(e.length<<2);(function(e,t,n){(function(e,t,n,r){if(!(r>0))return 0;for(var a=n>>>=0,s=n+r-1,i=0;i<e.length;++i){var o=e.charCodeAt(i);if(o>=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++i)),o<=127){if(n>=s)break;t[n++>>>0]=o}else if(o<=2047){if(n+1>=s)break;t[n++>>>0]=192|o>>6,t[n++>>>0]=128|63&o}else if(o<=65535){if(n+2>=s)break;t[n++>>>0]=224|o>>12,t[n++>>>0]=128|o>>6&63,t[n++>>>0]=128|63&o}else{if(n+3>=s)break;t[n++>>>0]=240|o>>18,t[n++>>>0]=128|o>>12&63,t[n++>>>0]=128|o>>6&63,t[n++>>>0]=128|63&o}}t[n>>>0]=0})(e,a(),t,n)})(e,t=je(n),n)}return t},array:e=>{var t=je(e.length);return function(e,t){r().set(e,t>>>0)}(e,t),t}};var u=Ee(e),l=[],c=0;if(s)for(var d=0;d<s.length;d++){var p=o[n[d]];p?(0===c&&(c=Ge()),l[d]=p(s[d])):l[d]=s[d]}var h=u.apply(null,l);return h=function(e){return 0!==c&&He(c),function(e){return"string"===t?G(e):"boolean"===t?Boolean(e):e}(e)}(h)}he.init();var Re,De,Fe,Me=[null,de,me,ye,Ie,Te,Ne],Oe={__emscripten_init_main_thread_js:function(e){Le(e,!x,1,!b),he.threadInitTLS()},__emscripten_thread_cleanup:function(e){v?postMessage({cmd:"cleanupThread",thread:e}):le(e)},__pthread_create_js:be,_emscripten_default_pthread_stack_size:function(){return 65536},_emscripten_get_now_is_monotonic:function(){return true},_emscripten_notify_task_queue:function(e,t,n,r){if(e==t)setTimeout((()=>we(r)));else if(v)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{var a=he.pthreads[e];if(!a)return;a.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},_emscripten_set_offscreencanvas_size:function(e,t,n){return-1},abort:function(){ne("")},emscripten_check_blocking_allowed:function(){w||x||ve("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")},emscripten_date_now:function(){return Date.now()},emscripten_get_heap_max:function(){return 4294901760},emscripten_get_now:xe,emscripten_memcpy_big:function(e,t,n){a().copyWithin(e>>>0,t>>>0,t+n>>>0)},emscripten_num_logical_cores:function(){return w?n(8074).cpus().length:navigator.hardwareConcurrency},emscripten_receive_on_main_thread_js:function(e,t,n){Se.length=t;for(var r=n>>3,a=0;a<t;a++)Se[a]=o()[r+a>>>0];return(e<0?oe[-e-1]:Me[e]).apply(null,Se)},emscripten_resize_heap:function(e){var t=a().length;if((e>>>=0)<=t)return!1;var n,r,s=4294901760;if(e>s)return!1;for(var i=1;i<=4;i*=2){var o=t*(1+.2/i);if(o=Math.min(o,e+100663296),_e(Math.min(s,(n=Math.max(e,o))+((r=65536)-n%r)%r)))return!0}return!1},emscripten_unwind_to_js_event_loop:function(){throw"unwind"},exit:pe,fd_close:Ie,fd_seek:Te,fd_write:Ne,memory:A||d.wasmMemory},ze=(function(){var e={env:Oe,wasi_snapshot_preview1:Oe};function t(e,t){var n,r,a=e.exports;if(d.asm=a,n=d.asm._emscripten_tls_init,he.tlsInitFunctions.push(n),j=d.asm.__indirect_function_table,r=d.asm.__wasm_call_ctors,K.unshift(r),R=t,!v){var s=he.unusedWorkers.length;he.unusedWorkers.forEach((function(e){he.loadWasmModuleToWorker(e,(function(){--s||function(){if(J--,d.monitorRunDependencies&&d.monitorRunDependencies(J),0==J&&(null!==ee&&(clearInterval(ee),ee=null),te)){var e=te;te=null,e()}}()}))}))}}function n(e){t(e.instance,e.module)}function r(t){return function(){if(!E&&(b||x)){if("function"==typeof fetch&&!se(re))return fetch(re,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+re+"'";return e.arrayBuffer()})).catch((function(){return ie(re)}));if(h)return new Promise((function(e,t){h(re,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return ie(re)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){N("failed to asynchronously prepare wasm: "+e),ne(e)}))}if(v||(J++,d.monitorRunDependencies&&d.monitorRunDependencies(J)),d.instantiateWasm)try{return d.instantiateWasm(e,t)}catch(Ke){N("Module.instantiateWasm callback failed with error: "+Ke),l(Ke)}(E||"function"!=typeof WebAssembly.instantiateStreaming||ae(re)||se(re)||w||"function"!=typeof fetch?r(n):fetch(re,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return N("wasm streaming compile failed: "+e),N("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(l)}(),d.___wasm_call_ctors=function(){return(d.___wasm_call_ctors=d.asm.__wasm_call_ctors).apply(null,arguments)},d._init=function(){return(d._init=d.asm.init).apply(null,arguments)},d._init_with_threads_count=function(){return(d._init_with_threads_count=d.asm.init_with_threads_count).apply(null,arguments)},d._get_threads_count=function(){return(d._get_threads_count=d.asm.get_threads_count).apply(null,arguments)},d._register_tensor=function(){return(d._register_tensor=d.asm.register_tensor).apply(null,arguments)},d._dispose_data=function(){return(d._dispose_data=d.asm.dispose_data).apply(null,arguments)},d._dispose=function(){return(d._dispose=d.asm.dispose).apply(null,arguments)},d._Abs=function(){return(d._Abs=d.asm.Abs).apply(null,arguments)},d._Acos=function(){return(d._Acos=d.asm.Acos).apply(null,arguments)},d._Acosh=function(){return(d._Acosh=d.asm.Acosh).apply(null,arguments)},d._Add=function(){return(d._Add=d.asm.Add).apply(null,arguments)},d._AddN=function(){return(d._AddN=d.asm.AddN).apply(null,arguments)},d._All=function(){return(d._All=d.asm.All).apply(null,arguments)},d._Any=function(){return(d._Any=d.asm.Any).apply(null,arguments)},d._ArgMax=function(){return(d._ArgMax=d.asm.ArgMax).apply(null,arguments)},d._ArgMin=function(){return(d._ArgMin=d.asm.ArgMin).apply(null,arguments)},d._Asin=function(){return(d._Asin=d.asm.Asin).apply(null,arguments)},d._Asinh=function(){return(d._Asinh=d.asm.Asinh).apply(null,arguments)},d._Atan=function(){return(d._Atan=d.asm.Atan).apply(null,arguments)},d._Atan2=function(){return(d._Atan2=d.asm.Atan2).apply(null,arguments)},d._Atanh=function(){return(d._Atanh=d.asm.Atanh).apply(null,arguments)},d._AvgPool=function(){return(d._AvgPool=d.asm.AvgPool).apply(null,arguments)},d._AvgPool3D=function(){return(d._AvgPool3D=d.asm.AvgPool3D).apply(null,arguments)},d._AvgPool3DGrad=function(){return(d._AvgPool3DGrad=d.asm.AvgPool3DGrad).apply(null,arguments)},d._AvgPoolGrad=function(){return(d._AvgPoolGrad=d.asm.AvgPoolGrad).apply(null,arguments)},d._BatchMatMul=function(){return(d._BatchMatMul=d.asm.BatchMatMul).apply(null,arguments)},d._Bincount=function(){return(d._Bincount=d.asm.Bincount).apply(null,arguments)},d._BitwiseAnd=function(){return(d._BitwiseAnd=d.asm.BitwiseAnd).apply(null,arguments)},d._Ceil=function(){return(d._Ceil=d.asm.Ceil).apply(null,arguments)},d._ClipByValue=function(){return(d._ClipByValue=d.asm.ClipByValue).apply(null,arguments)},d._Conv2D=function(){return(d._Conv2D=d.asm.Conv2D).apply(null,arguments)},d._Conv2DBackpropInput=function(){return(d._Conv2DBackpropInput=d.asm.Conv2DBackpropInput).apply(null,arguments)},d._Conv3D=function(){return(d._Conv3D=d.asm.Conv3D).apply(null,arguments)},d._Conv3DBackpropFilterV2=function(){return(d._Conv3DBackpropFilterV2=d.asm.Conv3DBackpropFilterV2).apply(null,arguments)},d._Conv3DBackpropInputV2=function(){return(d._Conv3DBackpropInputV2=d.asm.Conv3DBackpropInputV2).apply(null,arguments)},d._Cos=function(){return(d._Cos=d.asm.Cos).apply(null,arguments)},d._Cosh=function(){return(d._Cosh=d.asm.Cosh).apply(null,arguments)},d._CropAndResize=function(){return(d._CropAndResize=d.asm.CropAndResize).apply(null,arguments)},d._Cumprod=function(){return(d._Cumprod=d.asm.Cumprod).apply(null,arguments)},d._Cumsum=function(){return(d._Cumsum=d.asm.Cumsum).apply(null,arguments)},d._DenseBincount=function(){return(d._DenseBincount=d.asm.DenseBincount).apply(null,arguments)},d._DepthToSpace=function(){return(d._DepthToSpace=d.asm.DepthToSpace).apply(null,arguments)},d._DepthwiseConv2dNative=function(){return(d._DepthwiseConv2dNative=d.asm.DepthwiseConv2dNative).apply(null,arguments)},d._Diag=function(){return(d._Diag=d.asm.Diag).apply(null,arguments)},d._Dilation2D=function(){return(d._Dilation2D=d.asm.Dilation2D).apply(null,arguments)},d._Dilation2DBackpropFilter=function(){return(d._Dilation2DBackpropFilter=d.asm.Dilation2DBackpropFilter).apply(null,arguments)},d._Dilation2DBackpropInput=function(){return(d._Dilation2DBackpropInput=d.asm.Dilation2DBackpropInput).apply(null,arguments)},d._Elu=function(){return(d._Elu=d.asm.Elu).apply(null,arguments)},d._EluGrad=function(){return(d._EluGrad=d.asm.EluGrad).apply(null,arguments)},d._Equal=function(){return(d._Equal=d.asm.Equal).apply(null,arguments)},d._Erf=function(){return(d._Erf=d.asm.Erf).apply(null,arguments)},d._Exp=function(){return(d._Exp=d.asm.Exp).apply(null,arguments)},d._Expm1=function(){return(d._Expm1=d.asm.Expm1).apply(null,arguments)},d._FlipLeftRight=function(){return(d._FlipLeftRight=d.asm.FlipLeftRight).apply(null,arguments)},d._Floor=function(){return(d._Floor=d.asm.Floor).apply(null,arguments)},d._FloorDiv=function(){return(d._FloorDiv=d.asm.FloorDiv).apply(null,arguments)},d._FusedBatchNorm=function(){return(d._FusedBatchNorm=d.asm.FusedBatchNorm).apply(null,arguments)},d._FusedConv2D=function(){return(d._FusedConv2D=d.asm.FusedConv2D).apply(null,arguments)},d._FusedDepthwiseConv2D=function(){return(d._FusedDepthwiseConv2D=d.asm.FusedDepthwiseConv2D).apply(null,arguments)},d._Gather=function(){return(d._Gather=d.asm.Gather).apply(null,arguments)},d._GatherNd=function(){return(d._GatherNd=d.asm.GatherNd).apply(null,arguments)},d._Greater=function(){return(d._Greater=d.asm.Greater).apply(null,arguments)},d._GreaterEqual=function(){return(d._GreaterEqual=d.asm.GreaterEqual).apply(null,arguments)},d._IsFinite=function(){return(d._IsFinite=d.asm.IsFinite).apply(null,arguments)},d._IsInf=function(){return(d._IsInf=d.asm.IsInf).apply(null,arguments)},d._IsNan=function(){return(d._IsNan=d.asm.IsNan).apply(null,arguments)},d._LRN=function(){return(d._LRN=d.asm.LRN).apply(null,arguments)},d._LRNGrad=function(){return(d._LRNGrad=d.asm.LRNGrad).apply(null,arguments)},d._LeakyRelu=function(){return(d._LeakyRelu=d.asm.LeakyRelu).apply(null,arguments)},d._Less=function(){return(d._Less=d.asm.Less).apply(null,arguments)},d._LessEqual=function(){return(d._LessEqual=d.asm.LessEqual).apply(null,arguments)},d._LinSpace=function(){return(d._LinSpace=d.asm.LinSpace).apply(null,arguments)},d._Log=function(){return(d._Log=d.asm.Log).apply(null,arguments)},d._Log1p=function(){return(d._Log1p=d.asm.Log1p).apply(null,arguments)},d._LogicalAnd=function(){return(d._LogicalAnd=d.asm.LogicalAnd).apply(null,arguments)},d._LogicalNot=function(){return(d._LogicalNot=d.asm.LogicalNot).apply(null,arguments)},d._LogicalOr=function(){return(d._LogicalOr=d.asm.LogicalOr).apply(null,arguments)},d._LogicalXor=function(){return(d._LogicalXor=d.asm.LogicalXor).apply(null,arguments)},d._Max=function(){return(d._Max=d.asm.Max).apply(null,arguments)},d._MaxPool=function(){return(d._MaxPool=d.asm.MaxPool).apply(null,arguments)},d._MaxPool3D=function(){return(d._MaxPool3D=d.asm.MaxPool3D).apply(null,arguments)},d._MaxPool3DGrad=function(){return(d._MaxPool3DGrad=d.asm.MaxPool3DGrad).apply(null,arguments)},d._MaxPoolGrad=function(){return(d._MaxPoolGrad=d.asm.MaxPoolGrad).apply(null,arguments)},d._MaxPoolWithArgmax=function(){return(d._MaxPoolWithArgmax=d.asm.MaxPoolWithArgmax).apply(null,arguments)},d._Maximum=function(){return(d._Maximum=d.asm.Maximum).apply(null,arguments)},d._Mean=function(){return(d._Mean=d.asm.Mean).apply(null,arguments)},d._Min=function(){return(d._Min=d.asm.Min).apply(null,arguments)},d._Minimum=function(){return(d._Minimum=d.asm.Minimum).apply(null,arguments)},d._MirrorPad=function(){return(d._MirrorPad=d.asm.MirrorPad).apply(null,arguments)},d._Mod=function(){return(d._Mod=d.asm.Mod).apply(null,arguments)},d._Multinomial=function(){return(d._Multinomial=d.asm.Multinomial).apply(null,arguments)},d._Multiply=function(){return(d._Multiply=d.asm.Multiply).apply(null,arguments)},d._Neg=function(){return(d._Neg=d.asm.Neg).apply(null,arguments)},d._NonMaxSuppressionV3=function(){return(d._NonMaxSuppressionV3=d.asm.NonMaxSuppressionV3).apply(null,arguments)},d._NonMaxSuppressionV4=function(){return(d._NonMaxSuppressionV4=d.asm.NonMaxSuppressionV4).apply(null,arguments)},d._NonMaxSuppressionV5=function(){return(d._NonMaxSuppressionV5=d.asm.NonMaxSuppressionV5).apply(null,arguments)},d._NotEqual=function(){return(d._NotEqual=d.asm.NotEqual).apply(null,arguments)},d._OneHot=function(){return(d._OneHot=d.asm.OneHot).apply(null,arguments)},d._PadV2=function(){return(d._PadV2=d.asm.PadV2).apply(null,arguments)},d._Pow=function(){return(d._Pow=d.asm.Pow).apply(null,arguments)},d._Prelu=function(){return(d._Prelu=d.asm.Prelu).apply(null,arguments)},d._Prod=function(){return(d._Prod=d.asm.Prod).apply(null,arguments)},d._RealDiv=function(){return(d._RealDiv=d.asm.RealDiv).apply(null,arguments)},d._Reciprocal=function(){return(d._Reciprocal=d.asm.Reciprocal).apply(null,arguments)},d._Relu=function(){return(d._Relu=d.asm.Relu).apply(null,arguments)},d._Relu6=function(){return(d._Relu6=d.asm.Relu6).apply(null,arguments)},d._ResizeBilinear=function(){return(d._ResizeBilinear=d.asm.ResizeBilinear).apply(null,arguments)},d._ResizeBilinearGrad=function(){return(d._ResizeBilinearGrad=d.asm.ResizeBilinearGrad).apply(null,arguments)},d._ResizeNearestNeighbor=function(){return(d._ResizeNearestNeighbor=d.asm.ResizeNearestNeighbor).apply(null,arguments)},d._ResizeNearestNeighborGrad=function(){return(d._ResizeNearestNeighborGrad=d.asm.ResizeNearestNeighborGrad).apply(null,arguments)},d._Reverse=function(){return(d._Reverse=d.asm.Reverse).apply(null,arguments)},d._RotateWithOffset=function(){return(d._RotateWithOffset=d.asm.RotateWithOffset).apply(null,arguments)},d._Round=function(){return(d._Round=d.asm.Round).apply(null,arguments)},d._Rsqrt=function(){return(d._Rsqrt=d.asm.Rsqrt).apply(null,arguments)},d._ScatterNd=function(){return(d._ScatterNd=d.asm.ScatterNd).apply(null,arguments)},d._SearchSorted=function(){return(d._SearchSorted=d.asm.SearchSorted).apply(null,arguments)},d._SelectV2=function(){return(d._SelectV2=d.asm.SelectV2).apply(null,arguments)},d._Selu=function(){return(d._Selu=d.asm.Selu).apply(null,arguments)},d._Sigmoid=function(){return(d._Sigmoid=d.asm.Sigmoid).apply(null,arguments)},d._Sign=function(){return(d._Sign=d.asm.Sign).apply(null,arguments)},d._Sin=function(){return(d._Sin=d.asm.Sin).apply(null,arguments)},d._Sinh=function(){return(d._Sinh=d.asm.Sinh).apply(null,arguments)},d._Softmax=function(){return(d._Softmax=d.asm.Softmax).apply(null,arguments)},d._Softplus=function(){return(d._Softplus=d.asm.Softplus).apply(null,arguments)},d._SparseFillEmptyRows=function(){return(d._SparseFillEmptyRows=d.asm.SparseFillEmptyRows).apply(null,arguments)},d._SparseReshape=function(){return(d._SparseReshape=d.asm.SparseReshape).apply(null,arguments)},d._SparseSegmentReduction=function(){return(d._SparseSegmentReduction=d.asm.SparseSegmentReduction).apply(null,arguments)},d._SparseToDense=function(){return(d._SparseToDense=d.asm.SparseToDense).apply(null,arguments)},d._Sqrt=function(){return(d._Sqrt=d.asm.Sqrt).apply(null,arguments)},d._Square=function(){return(d._Square=d.asm.Square).apply(null,arguments)},d._SquaredDifference=function(){return(d._SquaredDifference=d.asm.SquaredDifference).apply(null,arguments)},d._Step=function(){return(d._Step=d.asm.Step).apply(null,arguments)},d._StridedSlice=function(){return(d._StridedSlice=d.asm.StridedSlice).apply(null,arguments)},d._Sub=function(){return(d._Sub=d.asm.Sub).apply(null,arguments)},d._Sum=function(){return(d._Sum=d.asm.Sum).apply(null,arguments)},d._Tan=function(){return(d._Tan=d.asm.Tan).apply(null,arguments)},d._Tanh=function(){return(d._Tanh=d.asm.Tanh).apply(null,arguments)},d._TensorScatterUpdate=function(){return(d._TensorScatterUpdate=d.asm.TensorScatterUpdate).apply(null,arguments)},d._Tile=function(){return(d._Tile=d.asm.Tile).apply(null,arguments)},d._TopK=function(){return(d._TopK=d.asm.TopK).apply(null,arguments)},d._Transform=function(){return(d._Transform=d.asm.Transform).apply(null,arguments)},d._Transpose=function(){return(d._Transpose=d.asm.Transpose).apply(null,arguments)},d.__FusedMatMul=function(){return(d.__FusedMatMul=d.asm._FusedMatMul).apply(null,arguments)},d._malloc=function(){return(d._malloc=d.asm.malloc).apply(null,arguments)},d._free=function(){return(d._free=d.asm.free).apply(null,arguments)},d.__emscripten_tls_init=function(){return(d.__emscripten_tls_init=d.asm._emscripten_tls_init).apply(null,arguments)},d._pthread_self=function(){return(ze=d._pthread_self=d.asm.pthread_self).apply(null,arguments)}),Le=(d.___errno_location=function(){return(d.___errno_location=d.asm.__errno_location).apply(null,arguments)},d.__emscripten_thread_init=function(){return(Le=d.__emscripten_thread_init=d.asm._emscripten_thread_init).apply(null,arguments)}),Pe=(d.__emscripten_thread_crashed=function(){return(d.__emscripten_thread_crashed=d.asm._emscripten_thread_crashed).apply(null,arguments)},d._emscripten_main_thread_process_queued_calls=function(){return(d._emscripten_main_thread_process_queued_calls=d.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},d._emscripten_main_browser_thread_id=function(){return(d._emscripten_main_browser_thread_id=d.asm.emscripten_main_browser_thread_id).apply(null,arguments)},d._emscripten_run_in_main_runtime_thread_js=function(){return(Pe=d._emscripten_run_in_main_runtime_thread_js=d.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)}),Be=(d._emscripten_dispatch_to_thread_=function(){return(d._emscripten_dispatch_to_thread_=d.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},d.__emscripten_proxy_execute_task_queue=function(){return(Be=d.__emscripten_proxy_execute_task_queue=d.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)}),We=d.__emscripten_thread_free_data=function(){return(We=d.__emscripten_thread_free_data=d.asm._emscripten_thread_free_data).apply(null,arguments)},Ve=d.__emscripten_thread_exit=function(){return(Ve=d.__emscripten_thread_exit=d.asm._emscripten_thread_exit).apply(null,arguments)},Ue=d._emscripten_stack_set_limits=function(){return(Ue=d._emscripten_stack_set_limits=d.asm.emscripten_stack_set_limits).apply(null,arguments)},Ge=d.stackSave=function(){return(Ge=d.stackSave=d.asm.stackSave).apply(null,arguments)},He=d.stackRestore=function(){return(He=d.stackRestore=d.asm.stackRestore).apply(null,arguments)},je=d.stackAlloc=function(){return(je=d.stackAlloc=d.asm.stackAlloc).apply(null,arguments)};d.dynCall_iijjiiii=function(){return(d.dynCall_iijjiiii=d.asm.dynCall_iijjiiii).apply(null,arguments)},d.dynCall_jiji=function(){return(d.dynCall_jiji=d.asm.dynCall_jiji).apply(null,arguments)};function qe(e){if(e=e||g,!(J>0)){if(v)return u(d),X(),void startWorker(d);!function(){if(d.preRun)for("function"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)e=d.preRun.shift(),Z.unshift(e);var e;fe(Z)}(),J>0||(d.setStatus?(d.setStatus("Running..."),setTimeout((function(){setTimeout((function(){d.setStatus("")}),1),t()}),1)):t())}function t(){Re||(Re=!0,d.calledRun=!0,M||(X(),u(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),function(){if(!v){if(d.postRun)for("function"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;)e=d.postRun.shift(),Y.unshift(e);var e;fe(Y)}}()))}}if(d.keepRuntimeAlive=Q,d.wasmMemory=A,d.cwrap=function(e,t,n,r){var a=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&a&&!r?Ee(e):function(){return Ae(e,t,n,arguments)}},d.ExitStatus=ue,d.PThread=he,te=function e(){Re||qe(),Re||(te=e)},d.preInit)for("function"==typeof d.preInit&&(d.preInit=[d.preInit]);d.preInit.length>0;)d.preInit.pop()();if(qe(),c&&(De={uncaughtException:process.listeners("uncaughtException").filter((function(e){return!c.uncaughtException.indexOf(e)>-1})),unhandledRejection:process.listeners("unhandledRejection").filter((function(e){return!c.unhandledRejection.indexOf(e)>-1}))}),"undefined"!==typeof WasmBackendModule)Fe=WasmBackendModule;else{if("undefined"===typeof t)throw new Error("Could not find wasm module in post.js");Fe=t}if(De){var Ze=Fe._dispose;Fe._dispose=function(){Ze(),De.uncaughtException.forEach((function(e){process.removeListener("uncaughtException",e)})),De.unhandledRejection.forEach((function(e){process.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=r},8570:e=>{e.exports=n;var t=null;try{t=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(I){}function n(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function r(e){return!0===(e&&e.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var a={},s={};function i(e,t){var n,r,i;return t?(i=0<=(e>>>=0)&&e<256)&&(r=s[e])?r:(n=u(e,(0|e)<0?-1:0,!0),i&&(s[e]=n),n):(i=-128<=(e|=0)&&e<128)&&(r=a[e])?r:(n=u(e,e<0?-1:0,!1),i&&(a[e]=n),n)}function o(e,t){if(isNaN(e))return t?y:g;if(t){if(e<0)return y;if(e>=h)return k}else{if(e<=-f)return S;if(e+1>=f)return v}return e<0?o(-e,t).neg():u(e%p|0,e/p|0,t)}function u(e,t,r){return new n(e,t,r)}n.fromInt=i,n.fromNumber=o,n.fromBits=u;var l=Math.pow;function c(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return g;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 c(e.substring(1),t,n).neg();for(var a=o(l(n,8)),s=g,i=0;i<e.length;i+=8){var u=Math.min(8,e.length-i),d=parseInt(e.substring(i,i+u),n);if(u<8){var p=o(l(n,u));s=s.mul(p).add(o(d))}else s=(s=s.mul(a)).add(o(d))}return s.unsigned=t,s}function d(e,t){return"number"===typeof e?o(e,t):"string"===typeof e?c(e,t):u(e.low,e.high,"boolean"===typeof t?t:e.unsigned)}n.fromString=c,n.fromValue=d;var p=4294967296,h=p*p,f=h/2,m=i(1<<24),g=i(0);n.ZERO=g;var y=i(0,!0);n.UZERO=y;var b=i(1);n.ONE=b;var x=i(1,!0);n.UONE=x;var w=i(-1);n.NEG_ONE=w;var v=u(-1,2147483647,!1);n.MAX_VALUE=v;var k=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=k;var S=u(0,-2147483648,!1);n.MIN_VALUE=S;var _=n.prototype;_.toInt=function(){return this.unsigned?this.low>>>0:this.low},_.toNumber=function(){return this.unsigned?(this.high>>>0)*p+(this.low>>>0):this.high*p+(this.low>>>0)},_.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(S)){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(l(e,6),this.unsigned),s=this,i="";;){var u=s.div(a),c=(s.sub(u.mul(a)).toInt()>>>0).toString(e);if((s=u).isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}},_.getHighBits=function(){return this.high},_.getHighBitsUnsigned=function(){return this.high>>>0},_.getLowBits=function(){return this.low},_.getLowBitsUnsigned=function(){return this.low>>>0},_.getNumBitsAbs=function(){if(this.isNegative())return this.eq(S)?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},_.isZero=function(){return 0===this.high&&0===this.low},_.eqz=_.isZero,_.isNegative=function(){return!this.unsigned&&this.high<0},_.isPositive=function(){return this.unsigned||this.high>=0},_.isOdd=function(){return 1===(1&this.low)},_.isEven=function(){return 0===(1&this.low)},_.equals=function(e){return r(e)||(e=d(e)),(this.unsigned===e.unsigned||this.high>>>31!==1||e.high>>>31!==1)&&(this.high===e.high&&this.low===e.low)},_.eq=_.equals,_.notEquals=function(e){return!this.eq(e)},_.neq=_.notEquals,_.ne=_.notEquals,_.lessThan=function(e){return this.comp(e)<0},_.lt=_.lessThan,_.lessThanOrEqual=function(e){return this.comp(e)<=0},_.lte=_.lessThanOrEqual,_.le=_.lessThanOrEqual,_.greaterThan=function(e){return this.comp(e)>0},_.gt=_.greaterThan,_.greaterThanOrEqual=function(e){return this.comp(e)>=0},_.gte=_.greaterThanOrEqual,_.ge=_.greaterThanOrEqual,_.compare=function(e){if(r(e)||(e=d(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?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},_.comp=_.compare,_.negate=function(){return!this.unsigned&&this.eq(S)?S:this.not().add(b)},_.neg=_.negate,_.add=function(e){r(e)||(e=d(e));var t=this.high>>>16,n=65535&this.high,a=this.low>>>16,s=65535&this.low,i=e.high>>>16,o=65535&e.high,l=e.low>>>16,c=0,p=0,h=0,f=0;return h+=(f+=s+(65535&e.low))>>>16,p+=(h+=a+l)>>>16,c+=(p+=n+o)>>>16,c+=t+i,u((h&=65535)<<16|(f&=65535),(c&=65535)<<16|(p&=65535),this.unsigned)},_.subtract=function(e){return r(e)||(e=d(e)),this.add(e.neg())},_.sub=_.subtract,_.multiply=function(e){if(this.isZero())return g;if(r(e)||(e=d(e)),t)return u(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return g;if(this.eq(S))return e.isOdd()?S:g;if(e.eq(S))return this.isOdd()?S:g;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(m)&&e.lt(m))return o(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,a=65535&this.high,s=this.low>>>16,i=65535&this.low,l=e.high>>>16,c=65535&e.high,p=e.low>>>16,h=65535&e.low,f=0,y=0,b=0,x=0;return b+=(x+=i*h)>>>16,y+=(b+=s*h)>>>16,b&=65535,y+=(b+=i*p)>>>16,f+=(y+=a*h)>>>16,y&=65535,f+=(y+=s*p)>>>16,y&=65535,f+=(y+=i*c)>>>16,f+=n*h+a*p+s*c+i*l,u((b&=65535)<<16|(x&=65535),(f&=65535)<<16|(y&=65535),this.unsigned)},_.mul=_.multiply,_.divide=function(e){if(r(e)||(e=d(e)),e.isZero())throw Error("division by zero");var n,a,s;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?u((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?y:g;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return y;if(e.gt(this.shru(1)))return x;s=y}else{if(this.eq(S))return e.eq(b)||e.eq(w)?S:e.eq(S)?b:(n=this.shr(1).div(e).shl(1)).eq(g)?e.isNegative()?b:w:(a=this.sub(e.mul(n)),s=n.add(a.div(e)));if(e.eq(S))return this.unsigned?y:g;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=g}for(a=this;a.gte(e);){n=Math.max(1,Math.floor(a.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(n)/Math.LN2),c=i<=48?1:l(2,i-48),p=o(n),h=p.mul(e);h.isNegative()||h.gt(a);)h=(p=o(n-=c,this.unsigned)).mul(e);p.isZero()&&(p=b),s=s.add(p),a=a.sub(h)}return s},_.div=_.divide,_.modulo=function(e){return r(e)||(e=d(e)),t?u((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},_.mod=_.modulo,_.rem=_.modulo,_.not=function(){return u(~this.low,~this.high,this.unsigned)},_.and=function(e){return r(e)||(e=d(e)),u(this.low&e.low,this.high&e.high,this.unsigned)},_.or=function(e){return r(e)||(e=d(e)),u(this.low|e.low,this.high|e.high,this.unsigned)},_.xor=function(e){return r(e)||(e=d(e)),u(this.low^e.low,this.high^e.high,this.unsigned)},_.shiftLeft=function(e){return r(e)&&(e=e.toInt()),0===(e&=63)?this:e<32?u(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):u(0,this.low<<e-32,this.unsigned)},_.shl=_.shiftLeft,_.shiftRight=function(e){return r(e)&&(e=e.toInt()),0===(e&=63)?this:e<32?u(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):u(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},_.shr=_.shiftRight,_.shiftRightUnsigned=function(e){if(r(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?u(this.low>>>e|t<<32-e,t>>>e,this.unsigned):u(32===e?t:t>>>e-32,0,this.unsigned)},_.shru=_.shiftRightUnsigned,_.shr_u=_.shiftRightUnsigned,_.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},_.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},_.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},_.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]},_.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]},n.fromBytes=function(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},8576:(e,t,n)=>{"use strict";n.d(t,{X:()=>a,j:()=>r});const r=1.7580993408473768,a=1.0507009873554805},8590:()=>{},8631:(e,t,n)=>{"use strict";n.d(t,{o:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({exp_:function(e){const t={x:(0,s.YT)(e,"x","exp")};return r.T2.runKernel(a.ox3,t)}})},8646:(e,t,n)=>{"use strict";n.d(t,{Do:()=>m,XB:()=>f,f2:()=>g,zE:()=>y});var r=n(2198),a=n(3416),s=n(6919),i=n(9258),o=n(4394),u=n(112),l=n(3732),c=n(2302),d=n(8968),p=n(700),h=n(3791);function f(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return(0,i.l)(e,(0,p.P)(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function m(e,t){let n=t;const a=r.getReductionAxes(e.shape,t.shape);return a.length>0&&(n=(0,h.c)(n,a)),(0,c.t)(n,e.shape)}function g(e,t,n,r){if("linear"===t)return e;if("relu"===t)return(0,u.V)(e);if("elu"===t)return(0,a.P)(e);if("relu6"===t)return(0,l.j)(e);if("prelu"===t)return(0,o.N)(e,n);if("leakyrelu"===t)return(0,s.H)(e,r);if("sigmoid"===t)return(0,d.r)(e);throw new Error(`Unknown fused activation ${t}.`)}const y=(e,t)=>!(e>0)||"linear"===t},8710:(e,t,n)=>{"use strict";n.d(t,{U:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({expandDims_:function(e,t=0){const n=(0,s.YT)(e,"x","expandDims","string_or_numeric");i.vA(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const o={input:n},u={dim:t};return r.T2.runKernel(a.ybN,o,u)}})},8775:(e,t,n)=>{"use strict";n.d(t,{z:()=>m});var r=n(5119),a=n(7148),s=n(5030),i=n(5040),o=n(929),u=n(1902),l=n(2302),c=n(7986),d=n(6512),p=n(2855),h=n(5537),f=n(1361);const m=(0,o.op)({rfft_:function(e,t){(0,r.vA)("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const o=e.size/n;let m;if(null!=t&&t<n){const r=e.shape.map((e=>0)),a=e.shape.map((e=>e));a[e.shape.length-1]=t,m=(0,c.d)(e,r,a),n=t}else if(null!=t&&t>n){const r=e.shape.map((e=>e));r[e.shape.length-1]=t-n,m=(0,s.x)([e,(0,p.U)(r)],e.shape.length-1),n=t}else m=e;const g=(0,h.P)(m),y=(0,l.t)((0,a.f)(m,g),[o,n]),b=(0,f.h)(y),x=Math.floor(n/2)+1,w=(0,u.x)(b),v=(0,i.n)(b),k=(0,d.l)(w,[x,n-x],w.shape.length-1),S=(0,d.l)(v,[x,n-x],v.shape.length-1),_=m.shape.slice();return _[m.shape.length-1]=x,(0,l.t)((0,a.f)(k[0],S[0]),_)}})},8794:(e,t,n)=>{"use strict";n.d(t,{X:()=>c});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(7195),u=n(929),l=n(2302);const c=(0,u.op)({conv2d_:function(e,t,n,u,c="NHWC",d=[1,1],p){const h=(0,s.YT)(e,"x","conv2d","float32"),f=(0,s.YT)(t,"filter","conv2d","float32");let m=h,g=!1;3===h.rank&&(g=!0,m=(0,l.t)(h,[1,h.shape[0],h.shape[1],h.shape[2]])),i.vA(4===m.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${m.rank}.`)),i.vA(4===f.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${f.rank}.`)),o.s_("conv2d",u,p);const y="NHWC"===c?m.shape[3]:m.shape[1];i.vA(y===f.shape[2],(()=>`Error in conv2d: depth of input (${y}) must match input depth for filter ${f.shape[2]}.`)),i.vA(o.G0(n,d),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${d}'`)),i.vA(o.qk(d),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),i.vA(o.qk(n),(()=>"Error in conv2D: Strides should be larger than 0."));const b={x:m,filter:f},x={strides:n,pad:u,dataFormat:c,dilations:d,dimRoundingMode:p},w=r.T2.runKernel(a.p2J,b,x);return g?(0,l.t)(w,[w.shape[1],w.shape[2],w.shape[3]]):w}})},8962:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Abs:()=>D.ljI,Acos:()=>D.Vvy,Acosh:()=>D.PH8,AdadeltaOptimizer:()=>D.K$F,AdagradOptimizer:()=>D.ah4,AdamOptimizer:()=>D.FYc,AdamaxOptimizer:()=>D.oC7,Add:()=>D.OMN,AddN:()=>D.EkD,All:()=>D.u8Z,Any:()=>D.FSt,ArgMax:()=>D.Jp_,ArgMin:()=>D.p_m,Asin:()=>D.QKF,Asinh:()=>D.epO,Atan:()=>D.TyE,Atan2:()=>D.lxb,Atanh:()=>D.zP9,AvgPool:()=>D.ho8,AvgPool3D:()=>D.cS,AvgPool3DGrad:()=>D.wwC,AvgPoolGrad:()=>D.VCH,BatchMatMul:()=>D.jAQ,BatchToSpaceND:()=>D.Ik2,Bincount:()=>D.N4F,BitwiseAnd:()=>D.HNs,BroadcastArgs:()=>D.vj7,BroadcastTo:()=>D.LB5,Callback:()=>Np,CallbackList:()=>io,Cast:()=>D.KXH,Ceil:()=>D.QDP,ClipByValue:()=>D.vaV,Complex:()=>D.pr3,ComplexAbs:()=>D.$zE,Concat:()=>D.$dB,Conv2D:()=>D.p2J,Conv2DBackpropFilter:()=>D.rFm,Conv2DBackpropInput:()=>D.jfg,Conv3D:()=>D.A1h,Conv3DBackpropFilterV2:()=>D.iGz,Conv3DBackpropInputV2:()=>D.gC7,Cos:()=>D.Mn0,Cosh:()=>D.MnK,CropAndResize:()=>D.MRQ,Cumprod:()=>D.jj_,Cumsum:()=>D.nY8,CustomCallback:()=>lo,DataStorage:()=>D.GJx,DenseBincount:()=>D.wNW,DepthToSpace:()=>D.TMz,DepthwiseConv2dNative:()=>D.tGH,DepthwiseConv2dNativeBackpropFilter:()=>D.X$8,DepthwiseConv2dNativeBackpropInput:()=>D.nVu,Diag:()=>D.ORI,Dilation2D:()=>D.jxD,Dilation2DBackpropFilter:()=>D.pk0,Dilation2DBackpropInput:()=>D.bP9,Draw:()=>D.XmO,ENV:()=>D.Kmu,EarlyStopping:()=>Rp,Einsum:()=>D.Qgm,Elu:()=>D.Pah,EluGrad:()=>D.rsH,Environment:()=>D.OH$,Equal:()=>D.BRl,Erf:()=>D._s9,Exp:()=>D.ox3,ExpandDims:()=>D.ybN,Expm1:()=>D.ybj,FFT:()=>D.rGP,Fill:()=>D.SQl,FlipLeftRight:()=>D.BxF,Floor:()=>D.ZgB,FloorDiv:()=>D.ElG,FromPixels:()=>D.awo,FusedBatchNorm:()=>D.i5R,FusedConv2D:()=>D.aAr,FusedDepthwiseConv2D:()=>D.T7M,GPGPUContext:()=>s_,GatherNd:()=>D.O4G,GatherV2:()=>D.mxL,GraphModel:()=>nf,Greater:()=>D.XhZ,GreaterEqual:()=>D.lLS,History:()=>uo,IFFT:()=>D.OAQ,Identity:()=>D.lzr,Imag:()=>D.dv8,InputSpec:()=>di,IsFinite:()=>D.gIW,IsInf:()=>D.E3$,IsNan:()=>D.iPs,KernelBackend:()=>D.uI_,LRN:()=>D.jM4,LRNGrad:()=>D.ToN,LayerVariable:()=>ui,LayersModel:()=>fu,LeakyRelu:()=>D.X0$,Less:()=>D.mIA,LessEqual:()=>D.CwD,LinSpace:()=>D.mnI,Log:()=>D.tG8,Log1p:()=>D.Cg$,LogSoftmax:()=>D.zfU,LogicalAnd:()=>D.RUm,LogicalNot:()=>D.nZd,LogicalOr:()=>D.LXA,LogicalXor:()=>D.RW8,LowerBound:()=>D.yPW,MathBackendCPU:()=>wm,MathBackendWebGL:()=>wI,MatrixBandPart:()=>D.WRv,Max:()=>D.VAI,MaxPool:()=>D.t3d,MaxPool3D:()=>D.ySp,MaxPool3DGrad:()=>D.cHb,MaxPoolGrad:()=>D.RXX,MaxPoolWithArgmax:()=>D.TL8,Maximum:()=>D.LDN,Mean:()=>D.g5A,Min:()=>D.lNG,Minimum:()=>D.LG0,MirrorPad:()=>D.x7F,Mod:()=>D.BLA,MomentumOptimizer:()=>D.Qu_,Multinomial:()=>D.WT3,Multiply:()=>D.xu7,Neg:()=>D.l0G,NonMaxSuppressionV3:()=>D.SDM,NonMaxSuppressionV4:()=>D.Zl4,NonMaxSuppressionV5:()=>D.e0f,NotEqual:()=>D.ylV,OP_SCOPE_SUFFIX:()=>D.BTT,OneHot:()=>D.urI,OnesLike:()=>D.LWX,Optimizer:()=>D.ELo,OptimizerConstructors:()=>D.L5p,Pack:()=>D.mM$,PadV2:()=>D.ODT,Pool:()=>D.bCz,Pow:()=>D.pyJ,Prelu:()=>D.Ncv,Prod:()=>D.kdj,RMSPropOptimizer:()=>D.PS5,RNN:()=>_l,RaggedGather:()=>D.oJ2,RaggedRange:()=>D.CQC,RaggedTensorToTensor:()=>D.mH5,Range:()=>D.Q6t,Rank:()=>D.rgM,Real:()=>D.LRy,RealDiv:()=>D.sDr,Reciprocal:()=>D.huO,Reduction:()=>D.iDl,Relu:()=>D.fUj,Relu6:()=>D.P_L,Reshape:()=>D.R23,ResizeBilinear:()=>D.hgw,ResizeBilinearGrad:()=>D.FCQ,ResizeNearestNeighbor:()=>D.jOE,ResizeNearestNeighborGrad:()=>D.XQy,Reverse:()=>D.D7i,RotateWithOffset:()=>D.BK4,Round:()=>D.hVg,Rsqrt:()=>D.TOR,SGDOptimizer:()=>D.SYI,ScatterNd:()=>D.pJc,SearchSorted:()=>D.uWl,Select:()=>D.l6P,Selu:()=>D.u$b,Sequential:()=>bu,Sigmoid:()=>D.vI1,Sign:()=>D.YVe,Sin:()=>D.hql,Sinh:()=>D.J3C,Slice:()=>D.JiE,Softmax:()=>D.rFG,Softplus:()=>D.Fin,SpaceToBatchND:()=>D.A8B,SparseFillEmptyRows:()=>D.C8s,SparseReshape:()=>D.BoJ,SparseSegmentMean:()=>D.L6G,SparseSegmentSum:()=>D.DvZ,SparseToDense:()=>D.jgd,SplitV:()=>D.Blb,Sqrt:()=>D.dFH,Square:()=>D.M6A,SquaredDifference:()=>D.Ddj,StaticRegexReplace:()=>D.GZp,Step:()=>D.pnw,StridedSlice:()=>D.UcO,StringNGrams:()=>D.YAb,StringSplit:()=>D.iW0,StringToHashBucketFast:()=>D.$jE,Sub:()=>D.PbM,Sum:()=>D.WuN,SymbolicTensor:()=>pi,Tan:()=>D.oFs,Tanh:()=>D.iuW,Tensor:()=>D.qYS,TensorBuffer:()=>D.ylz,TensorScatterUpdate:()=>D.X4r,Tile:()=>D.FAs,TopK:()=>D.TBb,Transform:()=>D.dLy,Transpose:()=>D.wx0,Unique:()=>D.EwU,Unpack:()=>D.dXR,UnsortedSegmentSum:()=>D.pPe,UpperBound:()=>D.RMm,Variable:()=>D.rTt,ZerosLike:()=>D.xJ3,_FusedMatMul:()=>D.Dr,abs:()=>D.tnl,acos:()=>D.HQu,acosh:()=>D.FqL,add:()=>D.WQq,addN:()=>D.QiD,all:()=>D.Q7R,any:()=>D.bzn,argMax:()=>D.FLi,argMin:()=>D.XRg,asin:()=>D.qRo,asinh:()=>D.yHs,atan:()=>D.rYl,atan2:()=>D.FPz,atanh:()=>D.rfv,avgPool:()=>D.$jT,avgPool3d:()=>D.sub,backend:()=>D.Hs,backend_util:()=>D.C0T,basicLSTMCell:()=>D.lZX,batchNorm:()=>D.$v7,batchNorm2d:()=>D.BFc,batchNorm3d:()=>D.kSi,batchNorm4d:()=>D.T5N,batchToSpaceND:()=>D.GTe,bincount:()=>D.HbZ,bitwiseAnd:()=>D.vjT,booleanMaskAsync:()=>D.ftb,broadcastArgs:()=>D.ROE,broadcastTo:()=>D.hOW,broadcast_util:()=>D.ZEY,browser:()=>D.TaL,buffer:()=>D.ra8,callbacks:()=>Dp,cast:()=>D.wgE,ceil:()=>D.mkO,clipByValue:()=>D.zQh,clone:()=>D.o8B,complex:()=>D.faB,concat:()=>D.xWs,concat1d:()=>D.I1m,concat2d:()=>D.RPU,concat3d:()=>D.O5O,concat4d:()=>D.P1l,constraints:()=>r,conv1d:()=>D.kA9,conv2d:()=>D.Xtf,conv2dTranspose:()=>D.wX9,conv3d:()=>D.IPL,conv3dTranspose:()=>D.jIJ,copyRegisteredKernels:()=>D.Cfv,cos:()=>D.gnS,cosh:()=>D.yIG,cosineWindow:()=>D._jP,cumprod:()=>D.Lp0,cumsum:()=>D.rCv,customGrad:()=>D._Xg,data:()=>N,denseBincount:()=>D.aOp,deprecationWarn:()=>D.fLc,depthToSpace:()=>D.Rj8,depthwiseConv2d:()=>D.Gl3,deregisterOp:()=>Pp,device_util:()=>D.eMq,diag:()=>D.smy,dilation2d:()=>D.X7t,disableDeprecationWarnings:()=>D.ISJ,dispose:()=>D.ASo,disposeVariables:()=>D.rm6,div:()=>D.y4m,divNoNan:()=>D.ek5,dot:()=>D.Omf,dropout:()=>D.EZY,einsum:()=>D._3C,elu:()=>D.Pqc,enableDebugMode:()=>D.gYU,enableProdMode:()=>D.SmG,enclosingPowerOfTwo:()=>D.FJY,engine:()=>D.Hi9,ensureShape:()=>D.QP2,env:()=>D._K2,equal:()=>D.LCg,erf:()=>D.Y12,euclideanNorm:()=>D.p4S,exp:()=>D.oNF,expandDims:()=>D.UG6,expm1:()=>D.IYd,eye:()=>D.y5U,fft:()=>D.hVP,fill:()=>D.GSj,findBackend:()=>D.goy,findBackendFactory:()=>D.W4C,floor:()=>D.RIf,floorDiv:()=>D.wh_,forceHalfFloat:()=>kI,fused:()=>D.cZk,gather:()=>D.kgh,gatherND:()=>D.SY9,gather_util:()=>D.FJy,getBackend:()=>D.jz4,getGradient:()=>D.vQR,getKernel:()=>D._5H,getKernelsForBackend:()=>D.OpK,gpgpu_util:()=>R,grad:()=>D.Dvk,grads:()=>D.ok9,greater:()=>D.rhj,greaterEqual:()=>D.DQN,ifft:()=>D.KGM,imag:()=>D.ngS,image:()=>D.Slp,inTopKAsync:()=>D.U4u,initializers:()=>a,input:()=>vu,io:()=>D.io,irfft:()=>D.ggX,isFinite:()=>D.MIs,isInf:()=>D.EN4,isNaN:()=>D.yrW,keep:()=>D.aCs,kernel_impls:()=>D.kpo,layers:()=>s,leakyRelu:()=>D.H8d,less:()=>D.M7h,lessEqual:()=>D.InN,linalg:()=>D.mPL,linspace:()=>D.mT8,loadGraphModel:()=>rf,loadGraphModelSync:()=>af,loadLayersModel:()=>yu,localResponseNormalization:()=>D.Kgs,log:()=>D.Rm2,log1p:()=>D.Kko,logSigmoid:()=>D.nqI,logSoftmax:()=>D.HPB,logSumExp:()=>D.VZ,logicalAnd:()=>D.n76,logicalNot:()=>D.NSZ,logicalOr:()=>D.ztW,logicalXor:()=>D.rxB,losses:()=>D.YYh,lowerBound:()=>D.yzS,matMul:()=>D.NoW,math:()=>D.DyF,max:()=>D.T9B,maxPool:()=>D.jgi,maxPool3d:()=>D.NYV,maxPoolWithArgmax:()=>D.RO,maximum:()=>D.PhQ,mean:()=>D.i2o,memory:()=>D.m1Z,meshgrid:()=>D.OYQ,metrics:()=>i,min:()=>D.jkA,minimum:()=>D.BpO,mirrorPad:()=>D.FFZ,mod:()=>D.ziu,model:()=>xu,models:()=>o,moments:()=>D.Clk,movingAverage:()=>D.CRk,mul:()=>D.lKK,multiRNNCell:()=>D.YDF,multinomial:()=>D.OjQ,neg:()=>D.HZy,nextFrame:()=>D.dA1,norm:()=>D.xbf,notEqual:()=>D.Ec,oneHot:()=>D.Mw0,ones:()=>D.SaS,onesLike:()=>D.P61,op:()=>D.op,outerProduct:()=>D.X4o,pad:()=>D.eVF,pad1d:()=>D.BZs,pad2d:()=>D.grY,pad3d:()=>D.XHu,pad4d:()=>D.WLX,pool:()=>D.dzn,pow:()=>D.n7C,prelu:()=>D.NsG,print:()=>D.yyV,prod:()=>D._eU,profile:()=>D.MEE,raggedGather:()=>D.whe,raggedRange:()=>D.iyU,raggedTensorToTensor:()=>D.Q0_,rand:()=>D._9M,randomGamma:()=>D.pR9,randomNormal:()=>D.FE$,randomStandardNormal:()=>D.m0H,randomUniform:()=>D.YeY,randomUniformInt:()=>D.HYA,range:()=>D.y17,ready:()=>D.Gc4,real:()=>D.xav,reciprocal:()=>D.VOZ,registerBackend:()=>D.gJX,registerCallbackConstructor:()=>ku,registerGradient:()=>D.krJ,registerKernel:()=>D.tAK,registerOp:()=>zp,regularizers:()=>u,relu:()=>D.VVh,relu6:()=>D.j__,removeBackend:()=>D.rEj,reshape:()=>D.tQQ,reverse:()=>D.BEg,reverse1d:()=>D.QD2,reverse2d:()=>D.LMr,reverse3d:()=>D.I2l,reverse4d:()=>D.JYU,rfft:()=>D.z8$,round:()=>D.LIG,rsqrt:()=>D.Z$r,scalar:()=>D.d_2,scatterND:()=>D.NFr,scatter_util:()=>D.g23,searchSorted:()=>D.sZg,selu:()=>D.WfX,separableConv2d:()=>D.wdz,sequential:()=>wu,serialization:()=>D.JFn,setBackend:()=>D.jh6,setPlatform:()=>D.OkC,setWebGLContext:()=>Xv,setdiff1dAsync:()=>D.F12,shared:()=>E,sigmoid:()=>D.ry7,sign:()=>D._SZ,signal:()=>D.vPA,sin:()=>D.F8e,sinh:()=>D.L0l,slice:()=>D.dik,slice1d:()=>D.Q$M,slice2d:()=>D.zAd,slice3d:()=>D.wck,slice4d:()=>D.R0O,slice_util:()=>D.Kro,softmax:()=>D.Vs9,softplus:()=>D.lw0,spaceToBatchND:()=>D.eDJ,sparse:()=>D.lMo,sparseToDense:()=>D.Zhr,spectral:()=>D.lOn,split:()=>D.lDo,sqrt:()=>D.RZD,square:()=>D.EwI,squaredDifference:()=>D.Pbu,squeeze:()=>D.r2V,stack:()=>D.t$z,step:()=>D.PMw,stridedSlice:()=>D.Ym9,string:()=>D.YjP,sub:()=>D.jbE,sum:()=>D.czq,sumOutType:()=>D.chL,tan:()=>D.Mlm,tanh:()=>D.ymU,tensor:()=>D.OEK,tensor1d:()=>D.tGX,tensor2d:()=>D.KtR,tensor3d:()=>D.$_$,tensor4d:()=>D.g9W,tensor5d:()=>D.Lpo,tensor6d:()=>D.yxw,tensorScatterUpdate:()=>D.NNh,tensor_util:()=>D.d_S,test_util:()=>D.Obs,tidy:()=>D.DZQ,tile:()=>D.Vsq,time:()=>D.kBw,topk:()=>D.rfw,train:()=>D.BaG,transpose:()=>D.mgz,truncatedNormal:()=>D.efE,unique:()=>D.AmM,unregisterGradient:()=>D.rYx,unregisterKernel:()=>D.iPt,unsortedSegmentSum:()=>D.zAU,unstack:()=>D.K$i,upcastType:()=>D.TuY,upperBound:()=>D.rni,util:()=>D.ZSL,valueAndGrad:()=>D.jYt,valueAndGrads:()=>D.muS,variable:()=>D.bvq,variableGrads:()=>D.y7e,version:()=>gR,version_converter:()=>sf,version_core:()=>D.bgA,version_cpu:()=>Uy,version_layers:()=>Zo,version_webgl:()=>vI,webgl:()=>SI,webgl_util:()=>A,where:()=>D._M9,whereAsync:()=>D.YJN,zeros:()=>D.Ul9,zerosLike:()=>D.POl});var r={};n.r(r),n.d(r,{maxNorm:()=>zi,minMaxNorm:()=>Bi,nonNeg:()=>Pi,unitNorm:()=>Li});var a={};n.r(a),n.d(a,{constant:()=>Ui,glorotNormal:()=>Yi,glorotUniform:()=>Ki,heNormal:()=>Qi,heUniform:()=>Xi,identity:()=>qi,leCunNormal:()=>Ji,leCunUniform:()=>eo,ones:()=>Vi,orthogonal:()=>to,randomNormal:()=>Hi,randomUniform:()=>Gi,truncatedNormal:()=>ji,varianceScaling:()=>Zi,zeros:()=>Wi});var s={};n.r(s),n.d(s,{Layer:()=>gi,RNN:()=>_l,RNNCell:()=>Il,activation:()=>ad,add:()=>hd,alphaDropout:()=>rp,average:()=>fd,averagePooling1d:()=>Sd,averagePooling2d:()=>Td,averagePooling3d:()=>Nd,avgPool1d:()=>_d,avgPool2d:()=>$d,avgPool3d:()=>Ed,avgPooling1d:()=>Id,avgPooling2d:()=>Cd,avgPooling3d:()=>Ad,batchNormalization:()=>wd,bidirectional:()=>Kd,categoryEncoding:()=>up,centerCrop:()=>ip,concatenate:()=>md,conv1d:()=>Kc,conv2d:()=>Yc,conv2dTranspose:()=>Qc,conv3d:()=>Xc,conv3dTranspose:()=>Jc,convLstm2d:()=>Hd,convLstm2dCell:()=>jd,cropping2D:()=>td,dense:()=>sd,depthwiseConv2d:()=>rd,dot:()=>xd,dropout:()=>id,elu:()=>Uc,embedding:()=>pd,flatten:()=>ud,gaussianDropout:()=>np,gaussianNoise:()=>tp,globalAveragePooling1d:()=>Rd,globalAveragePooling2d:()=>Dd,globalMaxPool1d:()=>Qd,globalMaxPool2d:()=>Xd,globalMaxPooling1d:()=>Fd,globalMaxPooling2d:()=>Md,gru:()=>Pd,gruCell:()=>Bd,input:()=>vu,inputLayer:()=>Vc,layerNormalization:()=>vd,leakyReLU:()=>Hc,lstm:()=>Wd,lstmCell:()=>Vd,masking:()=>ap,maxPool1d:()=>Jd,maxPool2d:()=>ep,maxPooling1d:()=>Od,maxPooling2d:()=>zd,maxPooling3d:()=>Ld,maximum:()=>gd,minimum:()=>yd,multiply:()=>bd,permute:()=>dd,prelu:()=>jc,randomWidth:()=>lp,reLU:()=>Gc,repeatVector:()=>ld,rescaling:()=>sp,reshape:()=>cd,resizing:()=>op,rnn:()=>qd,separableConv2d:()=>ed,simpleRNN:()=>Ud,simpleRNNCell:()=>Gd,softmax:()=>qc,spatialDropout1d:()=>od,stackedRNNCells:()=>Zd,thresholdedReLU:()=>Zc,timeDistributed:()=>Yd,upSampling2d:()=>nd,zeroPadding2d:()=>kd});var i={};n.r(i),n.d(i,{MAPE:()=>wp,MSE:()=>Sp,binaryAccuracy:()=>cp,binaryCrossentropy:()=>dp,categoricalAccuracy:()=>hp,categoricalCrossentropy:()=>fp,cosineProximity:()=>yp,mape:()=>vp,meanAbsoluteError:()=>bp,meanAbsolutePercentageError:()=>xp,meanSquaredError:()=>kp,mse:()=>_p,precision:()=>mp,r2Score:()=>Ip,recall:()=>gp,sparseCategoricalAccuracy:()=>pp});var o={};n.r(o),n.d(o,{modelFromJSON:()=>gu});var u={};n.r(u),n.d(u,{l1:()=>$p,l1l2:()=>Tp,l2:()=>Cp});var l={};n.r(l),n.d(l,{json:()=>Zp});var c={};n.r(c),n.d(c,{json:()=>Kp});var d={};n.r(d),n.d(d,{json:()=>Yp});var p={};n.r(p),n.d(p,{json:()=>Qp});var h={};n.r(h),n.d(h,{json:()=>Xp});var f={};n.r(f),n.d(f,{json:()=>Jp});var m={};n.r(m),n.d(m,{json:()=>eh});var g={};n.r(g),n.d(g,{json:()=>th});var y={};n.r(y),n.d(y,{json:()=>nh});var b={};n.r(b),n.d(b,{json:()=>rh});var x={};n.r(x),n.d(x,{json:()=>ah});var w={};n.r(w),n.d(w,{json:()=>sh});var v={};n.r(v),n.d(v,{json:()=>ih});var k={};n.r(k),n.d(k,{json:()=>oh});var S={};n.r(S),n.d(S,{json:()=>uh});var _={};n.r(_),n.d(_,{json:()=>lh});var I={};n.r(I),n.d(I,{json:()=>ch});var T={};n.r(T),n.d(T,{json:()=>dh});var $={};n.r($),n.d($,{json:()=>ph});var C={};n.r(C),n.d(C,{OP_SCOPE_SUFFIX:()=>Nh.BTT,abs:()=>Nh.tnl,acos:()=>Nh.HQu,acosh:()=>Nh.FqL,add:()=>Nh.WQq,addN:()=>Nh.QiD,all:()=>Nh.Q7R,any:()=>Nh.bzn,argMax:()=>Nh.FLi,argMin:()=>Nh.XRg,asin:()=>Nh.qRo,asinh:()=>Nh.yHs,atan:()=>Nh.rYl,atan2:()=>Nh.FPz,atanh:()=>Nh.rfv,avgPool:()=>Nh.$jT,avgPool3d:()=>Nh.sub,basicLSTMCell:()=>Nh.lZX,batchNorm:()=>Nh.$v7,batchNorm2d:()=>Nh.BFc,batchNorm3d:()=>Nh.kSi,batchNorm4d:()=>Nh.T5N,batchToSpaceND:()=>Nh.GTe,bincount:()=>Nh.HbZ,bitwiseAnd:()=>Nh.vjT,booleanMaskAsync:()=>Nh.ftb,broadcastArgs:()=>Nh.ROE,broadcastTo:()=>Nh.hOW,buffer:()=>Nh.ra8,cast:()=>Nh.wgE,ceil:()=>Nh.mkO,clipByValue:()=>Nh.zQh,clone:()=>Nh.o8B,complex:()=>Nh.faB,concat:()=>Nh.xWs,concat1d:()=>Nh.I1m,concat2d:()=>Nh.RPU,concat3d:()=>Nh.O5O,concat4d:()=>Nh.P1l,conv1d:()=>Nh.kA9,conv2d:()=>Nh.Xtf,conv2dTranspose:()=>Nh.wX9,conv3d:()=>Nh.IPL,conv3dTranspose:()=>Nh.jIJ,cos:()=>Nh.gnS,cosh:()=>Nh.yIG,cosineWindow:()=>Nh._jP,cumprod:()=>Nh.Lp0,cumsum:()=>Nh.rCv,denseBincount:()=>Nh.aOp,depthToSpace:()=>Nh.Rj8,depthwiseConv2d:()=>Nh.Gl3,diag:()=>Nh.smy,dilation2d:()=>Nh.X7t,div:()=>Nh.y4m,divNoNan:()=>Nh.ek5,dot:()=>Nh.Omf,dropout:()=>Nh.EZY,einsum:()=>Nh._3C,elu:()=>Nh.Pqc,enclosingPowerOfTwo:()=>Nh.FJY,ensureShape:()=>Nh.QP2,equal:()=>Nh.LCg,erf:()=>Nh.Y12,euclideanNorm:()=>Nh.p4S,exp:()=>Nh.oNF,expandDims:()=>Nh.UG6,expm1:()=>Nh.IYd,eye:()=>Nh.y5U,fft:()=>Nh.hVP,fill:()=>Nh.GSj,floor:()=>Nh.RIf,floorDiv:()=>Nh.wh_,fused:()=>Nh.cZk,gather:()=>Nh.kgh,gatherND:()=>Nh.SY9,greater:()=>Nh.rhj,greaterEqual:()=>Nh.DQN,ifft:()=>Nh.KGM,imag:()=>Nh.ngS,image:()=>Nh.Slp,inTopKAsync:()=>Nh.U4u,irfft:()=>Nh.ggX,isFinite:()=>Nh.MIs,isInf:()=>Nh.EN4,isNaN:()=>Nh.yrW,leakyRelu:()=>Nh.H8d,less:()=>Nh.M7h,lessEqual:()=>Nh.InN,linalg:()=>Nh.mPL,linspace:()=>Nh.mT8,localResponseNormalization:()=>Nh.Kgs,log:()=>Nh.Rm2,log1p:()=>Nh.Kko,logSigmoid:()=>Nh.nqI,logSoftmax:()=>Nh.HPB,logSumExp:()=>Nh.VZ,logicalAnd:()=>Nh.n76,logicalNot:()=>Nh.NSZ,logicalOr:()=>Nh.ztW,logicalXor:()=>Nh.rxB,losses:()=>Nh.YYh,lowerBound:()=>Nh.yzS,matMul:()=>Nh.NoW,max:()=>Nh.T9B,maxPool:()=>Nh.jgi,maxPool3d:()=>Nh.NYV,maxPoolWithArgmax:()=>Nh.RO,maximum:()=>Nh.PhQ,mean:()=>Nh.i2o,meshgrid:()=>Nh.OYQ,min:()=>Nh.jkA,minimum:()=>Nh.BpO,mirrorPad:()=>Nh.FFZ,mod:()=>Nh.ziu,moments:()=>Nh.Clk,movingAverage:()=>Nh.CRk,mul:()=>Nh.lKK,multiRNNCell:()=>Nh.YDF,multinomial:()=>Nh.OjQ,neg:()=>Nh.HZy,norm:()=>Nh.xbf,notEqual:()=>Nh.Ec,oneHot:()=>Nh.Mw0,ones:()=>Nh.SaS,onesLike:()=>Nh.P61,op:()=>Nh.op,outerProduct:()=>Nh.X4o,pad:()=>Nh.eVF,pad1d:()=>Nh.BZs,pad2d:()=>Nh.grY,pad3d:()=>Nh.XHu,pad4d:()=>Nh.WLX,pool:()=>Nh.dzn,pow:()=>Nh.n7C,prelu:()=>Nh.NsG,print:()=>Nh.yyV,prod:()=>Nh._eU,raggedGather:()=>Nh.whe,raggedRange:()=>Nh.iyU,raggedTensorToTensor:()=>Nh.Q0_,rand:()=>Nh._9M,randomGamma:()=>Nh.pR9,randomNormal:()=>Nh.FE$,randomStandardNormal:()=>Nh.m0H,randomUniform:()=>Nh.YeY,randomUniformInt:()=>Nh.HYA,range:()=>Nh.y17,real:()=>Nh.xav,reciprocal:()=>Nh.VOZ,relu:()=>Nh.VVh,relu6:()=>Nh.j__,reshape:()=>Nh.tQQ,reverse:()=>Nh.BEg,reverse1d:()=>Nh.QD2,reverse2d:()=>Nh.LMr,reverse3d:()=>Nh.I2l,reverse4d:()=>Nh.JYU,rfft:()=>Nh.z8$,round:()=>Nh.LIG,rsqrt:()=>Nh.Z$r,scalar:()=>Nh.d_2,scatterND:()=>Nh.NFr,searchSorted:()=>Nh.sZg,selu:()=>Nh.WfX,separableConv2d:()=>Nh.wdz,setdiff1dAsync:()=>Nh.F12,sigmoid:()=>Nh.ry7,sign:()=>Nh._SZ,signal:()=>Nh.vPA,sin:()=>Nh.F8e,sinh:()=>Nh.L0l,slice:()=>Nh.dik,slice1d:()=>Nh.Q$M,slice2d:()=>Nh.zAd,slice3d:()=>Nh.wck,slice4d:()=>Nh.R0O,softmax:()=>Nh.Vs9,softplus:()=>Nh.lw0,spaceToBatchND:()=>Nh.eDJ,sparse:()=>Nh.lMo,sparseToDense:()=>Nh.Zhr,spectral:()=>Nh.lOn,split:()=>Nh.lDo,sqrt:()=>Nh.RZD,square:()=>Nh.EwI,squaredDifference:()=>Nh.Pbu,squeeze:()=>Nh.r2V,stack:()=>Nh.t$z,step:()=>Nh.PMw,stridedSlice:()=>Nh.Ym9,string:()=>Nh.YjP,sub:()=>Nh.jbE,sum:()=>Nh.czq,tan:()=>Nh.Mlm,tanh:()=>Nh.ymU,tensor:()=>Nh.OEK,tensor1d:()=>Nh.tGX,tensor2d:()=>Nh.KtR,tensor3d:()=>Nh.$_$,tensor4d:()=>Nh.g9W,tensor5d:()=>Nh.Lpo,tensor6d:()=>Nh.yxw,tensorScatterUpdate:()=>Nh.NNh,tile:()=>Nh.Vsq,topk:()=>Nh.rfw,transpose:()=>Nh.mgz,truncatedNormal:()=>Nh.efE,unique:()=>Nh.AmM,unsortedSegmentSum:()=>Nh.zAU,unstack:()=>Nh.K$i,upperBound:()=>Nh.rni,variable:()=>Nh.bvq,where:()=>Nh._M9,whereAsync:()=>Nh.YJN,zeros:()=>Nh.Ul9,zerosLike:()=>Nh.POl});var N={};n.r(N),n.d(N,{CSVDataset:()=>Qf,Dataset:()=>Pf,FileDataSource:()=>cm,TextLineDataset:()=>Gf,URLDataSource:()=>dm,array:()=>Wf,csv:()=>pm,func:()=>hm,generator:()=>fm,microphone:()=>gm,version_data:()=>ym,webcam:()=>mm,zip:()=>Vf});var E={};n.r(E),n.d(E,{addImpl:()=>Om,bincountImpl:()=>Bm,bincountReduceImpl:()=>Wm,bitwiseAndImpl:()=>Vm,castImpl:()=>Am,ceilImpl:()=>Zm,concatImpl:()=>Qm.h,equalImpl:()=>Xm,expImpl:()=>tg,expm1Impl:()=>ag,floorDivImpl:()=>cg,floorImpl:()=>og,gatherNdImpl:()=>hg,gatherV2Impl:()=>fg,greaterEqualImpl:()=>bg,greaterImpl:()=>mg,lessEqualImpl:()=>_g,lessImpl:()=>vg,linSpaceImpl:()=>$g,logImpl:()=>Cg,maxImpl:()=>Ag,maximumImpl:()=>Rg,minimumImpl:()=>Mg,multiplyImpl:()=>Lg,negImpl:()=>Vg,notEqualImpl:()=>Gg,prodImpl:()=>Yg,raggedGatherImpl:()=>ty,raggedRangeImpl:()=>ry,raggedTensorToTensorImpl:()=>uy,rangeImpl:()=>ly.q,rsqrtImpl:()=>cy,scatterImpl:()=>hy,sigmoidImpl:()=>fy,simpleAbsImpl:()=>vm,sliceImpl:()=>yy.HS,sparseFillEmptyRowsImpl:()=>by,sparseReshapeImpl:()=>xy,sparseSegmentReductionImpl:()=>wy,sqrtImpl:()=>vy,squaredDifferenceImpl:()=>_y,staticRegexReplaceImpl:()=>$y,stridedSliceImpl:()=>Ey,stringNGramsImpl:()=>Ay.G,stringSplitImpl:()=>Ry.S,stringToHashBucketFastImpl:()=>Dy.f,subImpl:()=>Fy,tileImpl:()=>Ly,topKImpl:()=>Wy,transposeImpl:()=>qg,uniqueImpl:()=>Vy.w});var A={};n.r(A),n.d(A,{assertNotComplex:()=>aS,bindCanvasToFramebuffer:()=>Rk,bindColorTextureToFramebuffer:()=>Dk,bindTextureToProgramUniformSampler:()=>Ak,bindTextureUnit:()=>$k,bindVertexBufferToProgramAttribute:()=>Tk,callAndCheck:()=>ok,canBeRepresented:()=>ck,createFragmentShader:()=>fk,createFramebuffer:()=>Ik,createProgram:()=>yk,createStaticIndexBuffer:()=>vk,createStaticVertexBuffer:()=>wk,createTexture:()=>Sk,createVertexShader:()=>hk,getBatchDim:()=>Pk,getExtensionOrThrow:()=>pk,getFramebufferErrorMessage:()=>Ok,getMaxTexturesInShader:()=>Yk,getNumChannels:()=>kk,getProgramUniformLocation:()=>Ek,getProgramUniformLocationOrThrow:()=>Nk,getRowsCols:()=>Bk,getShapeAs3D:()=>Wk,getTextureShapeFromLogicalShape:()=>Vk,getWebGLDisjointQueryTimerVersion:()=>Qk,getWebGLErrorMessage:()=>dk,getWebGLMaxTextureSize:()=>qk,hasExtension:()=>Xk,isCapableOfRenderingToFloatTexture:()=>eS,isDownloadFloatTextureEnabled:()=>tS,isReshapeFree:()=>Gk,isWebGLFenceEnabled:()=>rS,isWebGLVersionEnabled:()=>Jk,linkProgram:()=>bk,logShaderSourceAndInfoLog:()=>gk,resetMaxTextureSize:()=>Zk,resetMaxTexturesInShader:()=>Kk,unbindColorTextureFromFramebuffer:()=>Fk,unbindTextureUnit:()=>Ck,validateFramebuffer:()=>Mk,validateProgram:()=>xk,validateTextureSize:()=>_k});var R={};n.r(R),n.d(R,{bindVertexProgramAttributeStreams:()=>QS,createBufferFromOutputTexture:()=>e_,createFloat16MatrixTexture:()=>GS,createFloat16PackedMatrixTexture:()=>YS,createFloat32MatrixTexture:()=>VS,createIndexBuffer:()=>PS,createPackedMatrixTexture:()=>ZS,createUnsignedBytesMatrixTexture:()=>jS,createVertexBuffer:()=>LS,createVertexShader:()=>zS,downloadByteEncodedFloatMatrixFromOutputTexture:()=>n_,downloadFloat32MatrixFromBuffer:()=>t_,downloadMatrixFromPackedOutputTexture:()=>a_,downloadPackedMatrixFromBuffer:()=>r_,getInternalFormatForFloat16MatrixTexture:()=>US,getInternalFormatForFloat16PackedMatrixTexture:()=>KS,getInternalFormatForFloat32MatrixTexture:()=>WS,getInternalFormatForPackedMatrixTexture:()=>qS,getInternalFormatForUnsignedBytesMatrixTexture:()=>HS,uploadDenseMatrixToTexture:()=>XS,uploadPixelDataToTexture:()=>JS});var D=n(5838),F=n(5441),M=n(9809),O=n(9258),z=n(700);const L={kernelName:F.ljI,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)(e,(0,z.P)((0,M.w)(n,"float32"),-1))}}};var P=n(9359),B=n(6522),W=n(5702),V=n(9348),U=n(5793),G=n(7126);const H={kernelName:F.Vvy,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=(0,U.E)((0,M.w)(n,"float32")),r=(0,V.R)((0,G.j)((0,W.d)(1),t));return(0,B.H)((0,P.y)(e,r))}}}},j={kernelName:F.PH8,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=(0,V.R)((0,G.j)((0,U.E)((0,M.w)(n,"float32")),1));return(0,P.y)(e,t)}}}};var q=n(2198),Z=n(2302),K=n(3791);const Y={kernelName:F.OMN,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,a=q.assertAndGetBroadcastShape(n.shape,r.shape);return{a:()=>{let t=e;const r=q.getReductionAxes(n.shape,a);return r.length>0&&(t=(0,K.c)(t,r)),(0,Z.t)(t,n.shape)},b:()=>{let t=e;const n=q.getReductionAxes(r.shape,a);return n.length>0&&(t=(0,K.c)(t,n)),(0,Z.t)(t,r.shape)}}}},Q={kernelName:F.EkD,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,r)=>{n[r]=()=>e.clone()})),n}};var X=n(5537);const J={kernelName:F.Jp_,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,X.P)(n)}}},ee={kernelName:F.p_m,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,X.P)(n)}}},te={kernelName:F.QKF,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,P.y)(e,(0,V.R)((0,G.j)((0,W.d)(1),(0,U.E)((0,M.w)(n,"float32")))))}}};var ne=n(7523);const re={kernelName:F.epO,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=(0,V.R)((0,ne.W)((0,W.d)(1),(0,U.E)((0,M.w)(n,"float32"))));return(0,P.y)(e,t)}}}},ae={kernelName:F.lxb,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,a=(0,q.assertAndGetBroadcastShape)(n.shape,r.shape);return{a:()=>{const t=(0,ne.W)((0,U.E)(n),(0,U.E)(r));let s=(0,O.l)(e,(0,P.y)(r,t));const i=(0,q.getReductionAxes)(n.shape,a);return i.length>0&&(s=(0,K.c)(s,i)),(0,Z.t)(s,n.shape)},b:()=>{const t=(0,ne.W)((0,U.E)(n),(0,U.E)(r));let s=(0,B.H)((0,O.l)(e,(0,P.y)(n,t)));const i=(0,q.getReductionAxes)(r.shape,a);return i.length>0&&(s=(0,K.c)(s,i)),(0,Z.t)(s,r.shape)}}}},se={kernelName:F.TyE,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,P.y)(e,(0,ne.W)((0,U.E)((0,M.w)(n,"float32")),1))}}},ie={kernelName:F.zP9,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,P.y)(e,(0,G.j)((0,W.d)(1),(0,U.E)((0,M.w)(n,"float32"))))}}};var oe=n(1585),ue=n(8189),le=n(5119),ce=n(7195),de=n(929);const pe=(0,de.op)({avgPool3dGrad_:function(e,t,n,r,a,s){const i=(0,ue.YT)(e,"dy","avgPool3dGrad"),o=(0,ue.YT)(t,"input","avgPool3dGrad");let u=i,l=o,c=!1;4===o.rank&&(c=!0,u=(0,Z.t)(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),l=(0,Z.t)(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),le.vA(5===u.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`)),le.vA(5===l.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`)),(0,ce.s_)("avgPool3dGrad",a,s);const d={dy:u,input:l},p={filterSize:n,strides:r,pad:a,dimRoundingMode:s},h=oe.T2.runKernel(F.wwC,d,p);return c?(0,Z.t)(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),he={kernelName:F.cS,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:a,strides:s,pad:i,dimRoundingMode:o}=n;return{x:()=>pe(e,r,a,s,i,o)}}};const fe=(0,de.op)({avgPoolGrad_:function(e,t,n,r,a){const s=(0,ue.YT)(e,"dy","avgPoolGrad"),i=(0,ue.YT)(t,"input","avgPoolGrad");le.vA(i.rank===s.rank,(()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`));let o=i,u=s,l=!1;3===i.rank&&(l=!0,o=(0,Z.t)(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=(0,Z.t)(s,[1,s.shape[0],s.shape[1],s.shape[2]])),le.vA(4===u.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${u.rank}.`)),le.vA(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const c={dy:u,input:o},d={filterSize:n,strides:r,pad:a},p=oe.T2.runKernel(F.VCH,c,d);return l?(0,Z.t)(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),me={kernelName:F.ho8,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{filterSize:a,strides:s,pad:i}=n;return{x:()=>fe(e,r,a,s,i)}}};var ge=n(5703);const ye={kernelName:F.jAQ,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[r,a]=t,{transposeA:s,transposeB:i}=n;return s||i?!s&&i?{a:()=>(0,ge.N)(e,a,!1,!1),b:()=>(0,ge.N)(e,r,!0,!1)}:s&&!i?{a:()=>(0,ge.N)(a,e,!1,!0),b:()=>(0,ge.N)(r,e,!1,!1)}:{a:()=>(0,ge.N)(a,e,!0,!0),b:()=>(0,ge.N)(e,r,!0,!0)}:{a:()=>(0,ge.N)(e,a,!1,!0),b:()=>(0,ge.N)(r,e,!0,!1)}}};var be=n(776);const xe={kernelName:F.Ik2,gradFunc:(e,t,n)=>{const{blockShape:r,crops:a}=n;return{x:()=>(0,be.e)(e,r,a)}}},we={kernelName:F.LB5,gradFunc:(e,t,n)=>{const r=n,a=r.inputShape,s=r.shape,i=Array.from(s);for(let u=a.length-1;u>=0;u--)if(a[u]===s[u])i[u]=1;else if(1!==a[u])throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${s}].`);const o=[];for(let u=0;u<i.length;u++)i[u]>1&&o.push(u);return{x:()=>(0,K.c)(e,o,!0)}}},ve={kernelName:F.KXH,gradFunc:e=>({x:()=>e.clone()})},ke={kernelName:F.QDP,gradFunc:e=>({x:()=>(0,X.P)(e)})};var Se=n(3337),_e=n(6508),Ie=n(3789),Te=n(2151);const $e={kernelName:F.vaV,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{clipValueMin:a,clipValueMax:s}=n;return{x:()=>(0,Te._)((0,Ie.n)((0,Se.D)(r,a),(0,_e.I)(r,s)),e,(0,X.P)(e))}}},Ce={kernelName:F.$zE,inputsToSave:["x"],gradFunc:L.gradFunc};var Ne=n(6512);const Ee={kernelName:F.$dB,saveAllInputs:!0,gradFunc:(e,t,n)=>{const r=t.map((e=>e.shape)),{axis:a}=n,s=(0,le.Y6)(a,t[0].shape)[0],i=r.map((e=>e[s]));return(0,Ne.l)(e,i,s).map((e=>()=>e))}};var Ae=n(5248),Re=n(252);const De={kernelName:F.p2J,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,a]=t,{dilations:s,strides:i,pad:o,dataFormat:u}=n;return le.vA(ce.Dh(s),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`)),{x:()=>(0,Re.v)(r.shape,e,a,i,o,u),filter:()=>(0,Ae.H)(r,e,a.shape,i,o,u)}}};var Fe=n(8794);const Me={kernelName:F.jfg,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[r,a]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:u}=n;return{dy:()=>(0,Fe.X)(e,a,s,i,o,1,u),filter:()=>(0,Ae.H)(e,r,a.shape,s,i,o,u)}}};const Oe=(0,de.op)({conv3DBackpropFilter_:function(e,t,n,r,a){let s=e;4===e.rank&&(s=(0,Z.t)(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=(0,Z.t)(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),le.vA(5===s.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`)),le.vA(5===i.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`)),le.vA(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),le.vA(s.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`)),le.vA(i.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:s,dy:i},u={strides:r,pad:a,filterShape:n};return oe.T2.runKernel(F.iGz,o,u)}});var ze=n(1895);const Le={kernelName:F.A1h,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:a,pad:s}=n;le.vA((0,ce.Dh)(r),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`));const[i,o]=t;return{x:()=>(0,ze.c)(i.shape,e,o,a,s),filter:()=>Oe(i,e,o.shape,a,s)}}};var Pe=n(3726);const Be={kernelName:F.Mn0,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)((0,B.H)((0,Pe.F)((0,M.w)(n,"float32"))),e)}}};var We=n(8276);const Ve={kernelName:F.MnK,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)((0,We.L)((0,M.w)(n,"float32")),e)}}};var Ue=n(1078),Ge=n(6808),He=n(7703);const je={kernelName:F.nY8,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:a,exclusive:s,reverse:i}=n;return{x:()=>{const t=(0,Ue.Em)([a],r.rank);let n=(0,Ge.r)(e,a,s,!i);return null!=t&&(n=(0,He.m)(n,t)),n}}}};var qe=n(1890),Ze=n(3134);const Ke={kernelName:F.tGH,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:r,strides:a,pad:s,dimRoundingMode:i}=n,o=null==r?[1,1]:r;le.vA(ce.Dh(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[u,l]=t;return le.vA(4===u.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${u.rank}.`)),le.vA(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${l.rank}.`)),le.vA(u.shape[3]===l.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`)),le.vA(ce.G0(a,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be  1. Got strides ${a} and dilations '${o}'.`)),ce.s_("depthwiseConv2d",s,i),{x:()=>(0,Ze.l)(u.shape,e,l,a,s,o,i),filter:()=>(0,qe.x)(u,e,l.shape,a,s,o,i)}}},Ye={kernelName:F.jxD,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[r,a]=t,s={x:r,filter:a,dy:e},i={x:r,filter:a,dy:e};return{x:()=>oe.T2.runKernel(F.bP9,s,n),filter:()=>oe.T2.runKernel(F.pk0,i,n)}}},Qe={kernelName:F.Pah,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,r={dy:e,y:n};return{x:()=>oe.T2.runKernel(F.rsH,r)}}};var Xe=n(8631);const Je={kernelName:F._s9,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=(0,O.l)((0,Xe.o)((0,B.H)((0,U.E)(n))),2/Math.sqrt(Math.PI));return{x:()=>(0,O.l)(e,r)}}},et={kernelName:F.ox3,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)(e,n)}}},tt={kernelName:F.ybN,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>(0,Z.t)(e,n.shape)}}},nt={kernelName:F.ybj,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)(e,(0,Xe.o)(n))}}},rt={kernelName:F.ZgB,gradFunc:e=>({x:()=>(0,X.P)(e)})},at={kernelName:F.ElG,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,a=(0,q.assertAndGetBroadcastShape)(n.shape,r.shape);return{a:()=>{const t=(0,P.y)(e,(0,M.w)(r,"float32")),s=(0,q.getReductionAxes)(n.shape,a);return s.length>0?(0,Z.t)((0,K.c)(t,s),n.shape):t},b:()=>{let t=(0,O.l)(e,(0,M.w)(n,"float32"));const s=(0,q.getReductionAxes)(r.shape,a);s.length>0&&(t=(0,Z.t)((0,K.c)(t,s),r.shape));const i=(0,U.E)(r);return(0,B.H)((0,P.y)(t,(0,M.w)(i,"float32")))}}}};var st=n(7820),it=n(4826);const ot={kernelName:F.i5R,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:r}=n,[a,s,i,o]=t,u=null==o?(0,W.d)(1):o,l=(0,q.getReductionAxes)(s.shape,a.shape),c=[];if(1===s.rank){for(let e=0;e<a.shape.length-1;++e)c.push(a.shape[e]);c.push(1)}const d=(0,G.j)(a,s),p=(0,O.l)(e,u),h=(0,st.Z)((0,ne.W)(i,(0,W.d)(r))),f=(0,O.l)((0,O.l)((0,O.l)(h,h),h),(0,W.d)(-.5));return{x:()=>1===s.rank?(0,Z.t)((0,O.l)((0,O.l)(e,(0,it.V)((0,Z.t)(h,[1,1,1,s.shape[0]]),c)),u),a.shape):(0,Z.t)((0,O.l)((0,O.l)(e,h),u),a.shape),mean:()=>{let e=(0,O.l)((0,O.l)(h,(0,W.d)(-1)),p);return 1===s.rank&&(e=(0,K.c)(e,l)),(0,Z.t)(e,s.shape)},variance:()=>{let e=(0,O.l)((0,O.l)(f,d),p);return 1===s.rank&&(e=(0,K.c)(e,l)),(0,Z.t)(e,s.shape)},scale:()=>{const t=(0,O.l)(d,h);let n=(0,O.l)(e,t);return 1===s.rank&&(n=(0,K.c)(n,l)),(0,Z.t)(n,s.shape)},offset:()=>{let t=e;return 1===s.rank&&(t=(0,K.c)(t,l)),(0,Z.t)(t,s.shape)}}}};var ut=n(4268),lt=n(7706);const ct={kernelName:F.mxL,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[r,a]=t,{axis:s,batchDims:i}=n,o=(0,le.Y6)(s,r.shape)[0],u=(e,t,n)=>()=>{const r=e.shape,a=t.size,i=r.slice(0,o),u=i.length,l=r.slice(s,r.length).slice(1),c=l.length,d=dt(0,u),p=dt(u+1,u+1+c),h=pt([i,[a],l]),f=(0,Z.t)(n,h),m=(0,Z.t)(t,[a]),g=pt([[u],d,p]),y=(0,He.m)(f,g);let b=(0,lt.z)(y,m,e.shape[o]);const x=(0,Ue.gx)(g);return b=(0,He.m)(b,x),b};if(1===i){const t=r.shape[0],n=r.split(t,0);return{x:()=>{const t=(0,ut.t)(n.map(((t,n)=>u(t,a.slice(n,1),e.slice(n,1))())));return t.reshape(r.shape)},indices:()=>a}}return{x:u(r,a,e),indices:()=>a}}};function dt(e,t){const n=[];for(let r=e;r<t;++r)n.push(r);return n}function pt(e){const t=[];for(let n=0;n<e.length;++n)for(let r=0;r<e[n].length;++r)t.push(e[n][r]);return t}const ht={kernelName:F.lLS,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>(0,X.P)(n),b:()=>(0,X.P)(r)}}},ft={kernelName:F.lzr,gradFunc:e=>({x:()=>(0,M.w)(e,"float32")})},mt={kernelName:F.gIW,gradFunc:e=>({x:()=>(0,X.P)(e)})},gt={kernelName:F.E3$,gradFunc:e=>({x:()=>(0,X.P)(e)})},yt={kernelName:F.iPs,gradFunc:e=>({x:()=>(0,X.P)(e)})};var bt=n(2058);const xt={kernelName:F.X0$,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{alpha:a}=n,s=(0,bt.r)(r,0);return{x:()=>(0,Te._)(s,e,(0,O.l)(e,a))}}},wt={kernelName:F.Cg$,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,P.y)(e,(0,ne.W)(n,1))}}},vt={kernelName:F.tG8,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,P.y)(e,(0,M.w)(n,"float32"))}}},kt={kernelName:F.zfU,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{axis:a}=n;return{logits:()=>{const t=(0,Xe.o)(r);return(0,G.j)(e,(0,O.l)((0,K.c)(e,a,!0),t))}}}};const St=(0,de.op)({localResponseNormalizationBackprop_:function(e,t,n,r=5,a=1,s=1,i=.5){const o={x:e,y:t,dy:n},u={depthRadius:r,bias:a,alpha:s,beta:i};return oe.T2.runKernel(F.ToN,o,u)}}),_t={kernelName:F.jM4,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,a]=t,{depthRadius:s,bias:i,alpha:o,beta:u}=n;return{x:()=>St(r,a,e,s,i,o,u)}}};var It=n(3020);function Tt(e,t,n,r){return t.rank<n.rank&&(t=(0,Z.t)(t,Ue.SM(t.shape,r))),e.rank<n.rank&&(e=(0,Z.t)(e,Ue.SM(e.shape,r))),{x:()=>(0,O.l)(e,(0,M.w)((0,It.L)(n,t),e.dtype))}}const $t={kernelName:F.VAI,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{reductionIndices:a}=r,s=t[0],i=Tt(e,t[1],s,le.Y6(a,s.shape));return{x:()=>i.x()}}};var Ct=n(1303);const Nt={kernelName:F.LDN,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>(0,O.l)(e,(0,M.w)((0,Se.D)(n,r),"float32")),b:()=>(0,O.l)(e,(0,M.w)((0,Ct.M)(n,r),"float32"))}}};const Et=(0,de.op)({maxPool3dGrad_:function(e,t,n,r,a,s,i){const o=(0,ue.YT)(e,"dy","maxPool3dGrad"),u=(0,ue.YT)(t,"input","maxPool3dGrad"),l=(0,ue.YT)(n,"output","maxPool3dGrad");let c=o,d=u,p=l,h=!1;4===u.rank&&(h=!0,c=(0,Z.t)(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),d=(0,Z.t)(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]]),p=(0,Z.t)(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),le.vA(5===c.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`)),le.vA(5===d.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`)),le.vA(5===p.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`)),(0,ce.s_)("maxPool3dGrad",s,i);const f={dy:c,input:d,output:p},m={filterSize:r,strides:a,pad:s,dimRoundingMode:i},g=oe.T2.runKernel(F.cHb,f,m);return h?(0,Z.t)(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),At={kernelName:F.ySp,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,a]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:u}=n;return{x:()=>Et(e,r,a,s,i,o,u)}}};const Rt=(0,de.op)({maxPoolGrad_:function(e,t,n,r,a,s,i){const o=(0,ue.YT)(e,"dy","maxPoolGrad"),u=(0,ue.YT)(t,"input","maxPoolGrad"),l=(0,ue.YT)(n,"output","maxPoolGrad");le.vA(u.rank===o.rank,(()=>`Rank of input (${u.rank}) does not match rank of dy (${o.rank})`)),le.vA(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),le.vA(4===u.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${u.rank}.`)),ce.s_("maxPoolGrad",s,i);const c={dy:o,input:u,output:l},d={filterSize:r,strides:a,pad:s,dimRoundingMode:i};return oe.T2.runKernel(F.RXX,c,d)}}),Dt={kernelName:F.t3d,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r,a]=t,{filterSize:s,strides:i,pad:o}=n;return{x:()=>Rt(e,r,a,s,i,o)}}};var Ft=n(1411);const Mt={kernelName:F.g5A,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:a}=n,s=le.Y6(a,r.shape),i=(0,Ue.lb)(r.shape,s)[1],o=le.Ze(i);return{x:()=>{const t=r.shape.slice();s.forEach((e=>{t[e]=1}));const n=(0,Z.t)(e,t);return(0,P.y)((0,O.l)(n,(0,Ft.S)(r.shape,"float32")),o)}}}},Ot={kernelName:F.lNG,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const r=n,{axis:a}=r,[s,i]=t,o=Tt(e,i,s,le.Y6(a,s.shape));return{x:()=>o.x()}}},zt={kernelName:F.LG0,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t;return{a:()=>(0,O.l)(e,(0,M.w)((0,_e.I)(n,r),"float32")),b:()=>(0,O.l)(e,(0,M.w)((0,bt.r)(n,r),"float32"))}}};var Lt=n(7986);const Pt={kernelName:F.x7F,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>(0,Lt.d)(e,s,r.shape)}}};var Bt=n(5606);const Wt={kernelName:F.BLA,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,a=(0,q.assertAndGetBroadcastShape)(n.shape,r.shape);return{a:()=>{const t=(0,q.getReductionAxes)(n.shape,a);return t.length>0?(0,Z.t)((0,K.c)(e,t),n.shape):e},b:()=>{const t=(0,O.l)(e,(0,B.H)((0,Bt.R)((0,P.y)(n,r)))),s=(0,q.getReductionAxes)(r.shape,a);return s.length>0?(0,Z.t)((0,K.c)(t,s),r.shape):t}}}},Vt={kernelName:F.xu7,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,a=(0,q.assertAndGetBroadcastShape)(n.shape,r.shape);return{a:()=>{const t=(0,O.l)(e,(0,M.w)(r,"float32")),s=(0,q.getReductionAxes)(n.shape,a);return s.length>0?(0,Z.t)((0,K.c)(t,s),n.shape):t},b:()=>{const t=(0,O.l)(e,(0,M.w)(n,"float32")),s=(0,q.getReductionAxes)(r.shape,a);return s.length>0?(0,Z.t)((0,K.c)(t,s),r.shape):t}}}},Ut={kernelName:F.l0G,gradFunc:e=>({x:()=>(0,B.H)(e)})};var Gt=n(2855);const Ht={kernelName:F.urI,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>(0,Gt.U)(n.shape,"float32")}}},jt={kernelName:F.LWX,gradFunc:e=>({x:()=>(0,X.P)(e)})};var qt=n(7261);const Zt={kernelName:F.mM$,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:r}=n;return(0,qt.K)(e,r).map((e=>()=>e))}},Kt={kernelName:F.ODT,inputsToSave:["x"],gradFunc:(e,t,n)=>{const r=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>(0,Lt.d)(e,s,r.shape)}}};var Yt=n(4010),Qt=n(8990);const Xt={kernelName:F.pyJ,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,r,a]=t,s=n,i=r,o=q.assertAndGetBroadcastShape(s.shape,i.shape);return{a:()=>{const t=(0,M.w)(i,"float32");let n=(0,O.l)(e,(0,O.l)(t,(0,Qt.n)(s,(0,G.j)(t,(0,W.d)(1)))));const r=q.getReductionAxes(s.shape,o);return r.length>0&&(n=(0,K.c)(n,r)),(0,Z.t)(n,s.shape)},b:()=>{const t=(0,bt.r)(s,0),n=(0,Te._)(t,(0,Yt.R)(s),(0,X.P)(s));let r=(0,O.l)(e,(0,O.l)(a,n));const u=q.getReductionAxes(i.shape,o);return u.length>0&&(r=(0,K.c)(r,u)),(0,Z.t)(r,i.shape)}}}},Jt={kernelName:F.Ncv,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,r]=t,a=(0,bt.r)(n,0);return{x:()=>(0,Te._)(a,e,(0,O.l)(e,r)),alpha:()=>{let t=(0,Te._)(a,(0,X.P)(e),(0,O.l)(e,n));const s=(0,q.getReductionAxes)(r.shape,e.shape);return s.length>0&&(t=(0,K.c)(t,s)),(0,Z.t)(t,r.shape)}}}};var en=n(302);function tn(e,t,n){const r=e.shape.length,a=r-n.length,s=Ue.Em(n,r);let i=e;null!=s&&(i=(0,He.m)(e,s));const o=i.shape.slice(),u=o.splice(r-n.length,n.length).reduce(((e,t)=>e*t),1);o.push(u);let l=function(e,t,n){const r=e.shape.slice();r[n]=1;const a=(0,Z.t)(t,r),s=(0,en.L)(e,n,!0,!1),i=(0,en.L)(e,n,!0,!0),o=(0,O.l)(s,i);return(0,O.l)(a,o)}(i.reshape(o),t,a);if(l=l.reshape(i.shape),null!=s){const e=Ue.gx(s);l=(0,He.m)(l,e)}return l}const nn={kernelName:F.kdj,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{axis:a}=n;let s=[];return s=void 0===a||null===a?r.shape.map(((e,t)=>t)):"number"===typeof a?[a]:a,{x:()=>tn(r,e,s)}}},rn={kernelName:F.sDr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,a=q.assertAndGetBroadcastShape(n.shape,r.shape);return{a:()=>{const t=(0,P.y)(e,(0,M.w)(r,"float32")),s=q.getReductionAxes(n.shape,a);return s.length>0?(0,Z.t)((0,K.c)(t,s),n.shape):t},b:()=>{let t=(0,O.l)(e,(0,M.w)(n,"float32"));const s=q.getReductionAxes(r.shape,a);s.length>0&&(t=(0,Z.t)((0,K.c)(t,s),r.shape));const i=(0,U.E)(r);return(0,B.H)((0,P.y)(t,(0,M.w)(i,"float32")))}}}},an={kernelName:F.huO,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,P.y)(e,(0,B.H)((0,U.E)(n)))}}},sn={kernelName:F.P_L,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,r=(0,O.l)((0,_e.I)(n,6),(0,z.P)(n));return{x:()=>(0,O.l)(e,(0,M.w)(r,"float32"))}}},on={kernelName:F.fUj,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)(e,(0,M.w)((0,z.P)(n),"float32"))}}},un={kernelName:F.R23,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,Z.t)(e,n.shape)}}},ln={kernelName:F.hgw,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,a={dy:e,images:r};return{images:()=>oe.T2.runKernel(F.FCQ,a,n)}}},cn={kernelName:F.jOE,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[r]=t,a={dy:e,images:r};return{images:()=>oe.T2.runKernel(F.XQy,a,n)}}};var dn=n(3262);const pn={kernelName:F.D7i,gradFunc:(e,t,n)=>{const{dims:r}=n,a=(0,le.Y6)(r,e.shape);return{x:()=>(0,dn.B)(e,a)}}},hn={kernelName:F.hVg,gradFunc:e=>({x:()=>(0,X.P)(e)})},fn={kernelName:F.TOR,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,B.H)((0,P.y)(e,(0,O.l)((0,Qt.n)(n,1.5),2)))}}};var mn=n(9881);const gn={kernelName:F.l6P,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>(0,M.w)((0,X.P)(n),"float32"),t:()=>(0,O.l)(e,(0,M.w)(n,e.dtype)),e:()=>(0,O.l)(e,(0,M.w)((0,mn.N)(n),e.dtype))}}};var yn=n(8576);const bn={kernelName:F.u$b,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=(0,bt.r)(n,(0,W.d)(0)),r=(0,W.d)(yn.j),a=(0,W.d)(yn.X),s=(0,O.l)(e,a),i=(0,O.l)((0,O.l)(e,r),(0,Xe.o)((0,M.w)(n,"float32")));return(0,Te._)(t,s,i)}}}},xn={kernelName:F.vI1,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)(e,(0,O.l)(n,(0,G.j)((0,W.d)(1),n)))}}},wn={kernelName:F.YVe,gradFunc:e=>({x:()=>(0,X.P)(e)})};var vn=n(9907);const kn={kernelName:F.hql,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)((0,vn.g)((0,M.w)(n,"float32")),e)}}};var Sn=n(7451);const _n={kernelName:F.J3C,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)((0,Sn.y)((0,M.w)(n,"float32")),e)}}};var In=n(5661),Tn=n(4969);const $n={kernelName:F.JiE,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{begin:a,size:s}=n,i=r.shape,[o,u]=(0,Tn.parseSliceParams)(r,a,s),l=[];for(let c=0;c<e.rank;c++)l.push([o[c],i[c]-o[c]-u[c]]);return{x:()=>(0,In.e)(e,l)}}},Cn={kernelName:F.rFG,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[r]=t,{dim:a}=n,s=(0,O.l)(e,r);return{logits:()=>(0,G.j)(s,(0,O.l)((0,K.c)(s,[a],true),r))}}};var Nn=n(8968);const En={kernelName:F.Fin,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)(e,(0,Nn.r)(n))}}};var An=n(9772);const Rn={kernelName:F.A8B,gradFunc:(e,t,n)=>{const{blockShape:r,paddings:a}=n;return{x:()=>(0,An.G)(e,r,a)}}};var Dn=n(5030);const Fn={kernelName:F.Blb,gradFunc:(e,t,n)=>{const{axis:r}=n;return{x:()=>(0,Dn.x)(e,r)}}},Mn={kernelName:F.dFH,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,P.y)(e,(0,O.l)((0,V.R)((0,M.w)(n,"float32")),2))}}},On={kernelName:F.M6A,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)(e,(0,O.l)((0,M.w)(n,"float32"),2))}}},zn={kernelName:F.Ddj,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,a=(0,W.d)(2);return{a:()=>(0,O.l)(e,(0,O.l)(a,(0,G.j)(n,r))),b:()=>(0,O.l)(e,(0,O.l)(a,(0,G.j)(r,n)))}}},Ln={kernelName:F.pnw,gradFunc:e=>({x:()=>(0,X.P)(e)})},Pn={kernelName:F.PbM,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,r]=t,a=q.assertAndGetBroadcastShape(n.shape,r.shape);return{a:()=>{let t=e;const r=q.getReductionAxes(n.shape,a);return r.length>0&&(t=(0,K.c)(t,r)),(0,Z.t)(t,n.shape)},b:()=>{let t=e;const n=q.getReductionAxes(r.shape,a);return n.length>0&&(t=(0,K.c)(t,n)),(0,Z.t)((0,B.H)(t),r.shape)}}}},Bn={kernelName:F.WuN,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,a=r.shape.slice(),{axis:s}=n;(0,le.Y6)(s,r.shape).forEach((e=>{a[e]=1}));const i=(0,Z.t)(e,a),o=(0,O.l)(i,(0,Ft.S)(r.shape,"float32"));return{x:()=>o}}},Wn={kernelName:F.oFs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,P.y)(e,(0,U.E)((0,vn.g)(n)))}}},Vn={kernelName:F.iuW,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>(0,O.l)((0,G.j)((0,W.d)(1),(0,U.E)(n)),e)}}},Un={kernelName:F.FAs,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[r]=t,{reps:a}=n;return{x:()=>{let t=(0,X.P)(r);if(1===r.rank)for(let n=0;n<a[0];++n)t=(0,ne.W)(t,(0,Lt.d)(e,[n*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)t=(0,ne.W)(t,(0,Lt.d)(e,[n*r.shape[0],s*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)for(let i=0;i<a[2];++i)t=(0,ne.W)(t,(0,Lt.d)(e,[n*r.shape[0],s*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error(`Gradient for tile operation is not implemented for rank-${r.rank} tensors yet.`);for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)for(let i=0;i<a[2];++i)for(let o=0;o<a[3];++o)t=(0,ne.W)(t,(0,Lt.d)(e,[n*r.shape[0],s*r.shape[1],i*r.shape[2],o*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return t}}}},Gn={kernelName:F.wx0,gradFunc:(e,t,n)=>{const r=n,{perm:a}=r,s=Ue.gx(a);return{x:()=>(0,He.m)(e,s)}}},Hn={kernelName:F.dXR,gradFunc:(e,t,n)=>{const r=n,{axis:a}=r;return{value:()=>(0,ut.t)(e,a)}}};var jn=n(8710),qn=n(8229),Zn=n(178);const Kn={kernelName:F.pPe,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=(0,Zn.P)(t,(0,X.P)(t)),r=(0,qn.k)(e,n);let a=(0,Se.D)(t,(0,W.d)(0,"int32"));const s=r.rank-a.rank;for(let o=0;o<s;++o)a=(0,jn.U)(a,o+1);a=(0,Ie.n)(a,(0,Ft.S)(r.shape,"bool"));const i=(0,X.P)(r);return(0,Te._)(a,r,i)}(e,n)}}};const Yn={kernelName:F.xJ3,gradFunc:e=>({x:()=>(0,X.P)(e)})};var Qn=n(7074);const Xn=[L,H,j,Y,Q,J,ee,te,re,ae,se,ie,he,me,ye,xe,we,ve,ke,$e,Ce,Ee,Me,De,Le,Be,Ve,je,Ke,Ye,rn,Qe,Je,et,tt,nt,at,rt,ot,ct,ht,ft,mt,gt,yt,xt,wt,vt,kt,_t,$t,$t,Nt,At,Dt,Mt,Ot,zt,Pt,Wt,Vt,Ut,Ht,jt,Zt,Kt,Kt,Xt,Jt,nn,an,sn,on,un,ln,cn,pn,hn,fn,gn,bn,xn,wn,kn,_n,$n,Cn,En,Rn,Rn,Fn,Fn,Mn,zn,On,Ln,Pn,Bn,Wn,Vn,Un,Gn,Hn,Kn,Yn];for(const yR of Xn)(0,Qn.kr)(yR);var Jn=n(4888),er=n(259);(0,er.tp)().prototype.abs=function(){return this.throwIfDisposed(),(0,Jn.t)(this)};var tr=n(2804);(0,er.tp)().prototype.acos=function(){return this.throwIfDisposed(),(0,tr.H)(this)};var nr=n(7558);(0,er.tp)().prototype.acosh=function(){return this.throwIfDisposed(),(0,nr.F)(this)},(0,er.tp)().prototype.add=function(e){return this.throwIfDisposed(),(0,ne.W)(this,e)};var rr=n(2307);(0,er.tp)().prototype.all=function(e,t){return this.throwIfDisposed(),(0,rr.Q)(this,e,t)};var ar=n(9326);(0,er.tp)().prototype.any=function(e,t){return this.throwIfDisposed(),(0,ar.b)(this,e,t)};var sr=n(897);(0,er.tp)().prototype.argMax=function(e){return this.throwIfDisposed(),(0,sr.F)(this,e)};var ir=n(4339);(0,er.tp)().prototype.argMin=function(e){return this.throwIfDisposed(),(0,ir.X)(this,e)},(0,er.tp)().prototype.asScalar=function(){return this.throwIfDisposed(),(0,le.vA)(1===this.size,(()=>"The array must have only 1 element.")),(0,Z.t)(this,[])},(0,er.tp)().prototype.asType=function(e){return this.throwIfDisposed(),(0,M.w)(this,e)},(0,er.tp)().prototype.as1D=function(){return this.throwIfDisposed(),(0,Z.t)(this,[this.size])},(0,er.tp)().prototype.as2D=function(e,t){return this.throwIfDisposed(),(0,Z.t)(this,[e,t])},(0,er.tp)().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),(0,Z.t)(this,[e,t,n])},(0,er.tp)().prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),(0,Z.t)(this,[e,t,n,r])},(0,er.tp)().prototype.as5D=function(e,t,n,r,a){return this.throwIfDisposed(),(0,Z.t)(this,[e,t,n,r,a])};var or=n(6841);(0,er.tp)().prototype.asin=function(){return this.throwIfDisposed(),(0,or.q)(this)};var ur=n(269);(0,er.tp)().prototype.asinh=function(){return this.throwIfDisposed(),(0,ur.y)(this)};var lr=n(9580);(0,er.tp)().prototype.atan=function(){return this.throwIfDisposed(),(0,lr.r)(this)};var cr=n(1404);(0,er.tp)().prototype.atan2=function(e){return this.throwIfDisposed(),(0,cr.F)(this,e)};var dr=n(3774);(0,er.tp)().prototype.atanh=function(){return this.throwIfDisposed(),(0,dr.r)(this)};var pr=n(3909);(0,er.tp)().prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),(0,pr.$)(this,e,t,n,r)},(0,er.tp)().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),(0,An.G)(this,e,t)};var hr=n(9160);(0,er.tp)().prototype.batchNorm=function(e,t,n,r,a){return this.throwIfDisposed(),(0,hr.$)(this,e,t,n,r,a)};var fr=n(3567);(0,er.tp)().prototype.broadcastTo=function(e){return this.throwIfDisposed(),(0,fr.h)(this,e)},(0,er.tp)().prototype.cast=function(e){return this.throwIfDisposed(),(0,M.w)(this,e)};var mr=n(855);(0,er.tp)().prototype.ceil=function(){return this.throwIfDisposed(),(0,mr.m)(this)};var gr=n(6928);(0,er.tp)().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),(0,gr.z)(this,e,t)},(0,er.tp)().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof er.qY&&(e=[e]),(0,Dn.x)([this,...e],t)};var yr=n(3701);(0,er.tp)().prototype.conv1d=function(e,t,n,r,a,s){return this.throwIfDisposed(),(0,yr.k)(this,e,t,n,r,a,s)};var br=n(1106);(0,er.tp)().prototype.conv2dTranspose=function(e,t,n,r,a){return this.throwIfDisposed(),(0,br.w)(this,e,t,n,r,a)},(0,er.tp)().prototype.conv2d=function(e,t,n,r,a,s){return this.throwIfDisposed(),(0,Fe.X)(this,e,t,n,r,a,s)},(0,er.tp)().prototype.cos=function(){return this.throwIfDisposed(),(0,vn.g)(this)},(0,er.tp)().prototype.cosh=function(){return this.throwIfDisposed(),(0,Sn.y)(this)},(0,er.tp)().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),(0,en.L)(this,e,t,n)},(0,er.tp)().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),(0,Ge.r)(this,e,t,n)};var xr=n(1216);(0,er.tp)().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),(0,xr.R)(this,e,t)};var wr=n(676);(0,er.tp)().prototype.depthwiseConv2d=function(e,t,n,r,a,s){return this.throwIfDisposed(),(0,wr.G)(this,e,t,n,r,a,s)};var vr=n(3002);(0,er.tp)().prototype.dilation2d=function(e,t,n,r,a){return this.throwIfDisposed(),(0,vr.X)(this,e,t,n,r,a)};var kr=n(919);(0,er.tp)().prototype.divNoNan=function(e){return this.throwIfDisposed(),(0,kr.e)(this,e)},(0,er.tp)().prototype.div=function(e){return this.throwIfDisposed(),(0,P.y)(this,e)};var Sr=n(9759);(0,er.tp)().prototype.dot=function(e){return this.throwIfDisposed(),(0,Sr.O)(this,e)};var _r=n(3416);(0,er.tp)().prototype.elu=function(){return this.throwIfDisposed(),(0,_r.P)(this)},(0,er.tp)().prototype.equal=function(e){return this.throwIfDisposed(),(0,It.L)(this,e)};var Ir=n(5207);(0,er.tp)().prototype.erf=function(){return this.throwIfDisposed(),(0,Ir.Y)(this)};var Tr=n(4881);(0,er.tp)().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),(0,Tr.p)(this,e,t)},(0,er.tp)().prototype.exp=function(){return this.throwIfDisposed(),(0,Xe.o)(this)},(0,er.tp)().prototype.expandDims=function(e){return this.throwIfDisposed(),(0,jn.U)(this,e)};var $r=n(517);(0,er.tp)().prototype.expm1=function(){return this.throwIfDisposed(),(0,$r.I)(this)};var Cr=n(1361);(0,er.tp)().prototype.fft=function(){return this.throwIfDisposed(),(0,Cr.h)(this)},(0,er.tp)().prototype.flatten=function(){return this.throwIfDisposed(),(0,Z.t)(this,[this.size])},(0,er.tp)().prototype.floor=function(){return this.throwIfDisposed(),(0,Bt.R)(this)};var Nr=n(8991);(0,er.tp)().prototype.floorDiv=function(e){return this.throwIfDisposed(),(0,Nr.w)(this,e)},(0,er.tp)().prototype.gather=function(e,t,n){return this.throwIfDisposed(),(0,qn.k)(this,e,t,n)},(0,er.tp)().prototype.greaterEqual=function(e){return this.throwIfDisposed(),(0,Se.D)(this,e)},(0,er.tp)().prototype.greater=function(e){return this.throwIfDisposed(),(0,bt.r)(this,e)};var Er=n(3108);(0,er.tp)().prototype.ifft=function(){return this.throwIfDisposed(),(0,Er.K)(this)};var Ar=n(2292);(0,er.tp)().prototype.irfft=function(){return this.throwIfDisposed(),(0,Ar.g)(this)};var Rr=n(8318);(0,er.tp)().prototype.isFinite=function(){return this.throwIfDisposed(),(0,Rr.M)(this)};var Dr=n(3454);(0,er.tp)().prototype.isInf=function(){return this.throwIfDisposed(),(0,Dr.E)(this)};var Fr=n(6300);(0,er.tp)().prototype.isNaN=function(){return this.throwIfDisposed(),(0,Fr.y)(this)};var Mr=n(6919);(0,er.tp)().prototype.leakyRelu=function(e){return this.throwIfDisposed(),(0,Mr.H)(this,e)},(0,er.tp)().prototype.lessEqual=function(e){return this.throwIfDisposed(),(0,_e.I)(this,e)},(0,er.tp)().prototype.less=function(e){return this.throwIfDisposed(),(0,Ct.M)(this,e)};var Or=n(3531);(0,er.tp)().prototype.localResponseNormalization=function(e,t,n,r){return this.throwIfDisposed(),(0,Or.K)(this,e,t,n,r)};var zr=n(5645);(0,er.tp)().prototype.logSigmoid=function(){return this.throwIfDisposed(),(0,zr.n)(this)};var Lr=n(7991);(0,er.tp)().prototype.logSoftmax=function(e){return this.throwIfDisposed(),(0,Lr.H)(this,e)};var Pr=n(3330);(0,er.tp)().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),(0,Pr.V)(this,e,t)},(0,er.tp)().prototype.log=function(){return this.throwIfDisposed(),(0,Yt.R)(this)};var Br=n(2015);(0,er.tp)().prototype.log1p=function(){return this.throwIfDisposed(),(0,Br.K)(this)},(0,er.tp)().prototype.logicalAnd=function(e){return this.throwIfDisposed(),(0,Ie.n)(this,e)},(0,er.tp)().prototype.logicalNot=function(){return this.throwIfDisposed(),(0,mn.N)(this)};var Wr=n(9879);(0,er.tp)().prototype.logicalOr=function(e){return this.throwIfDisposed(),(0,Wr.z)(this,e)};var Vr=n(9925);(0,er.tp)().prototype.logicalXor=function(e){return this.throwIfDisposed(),(0,Vr.r)(this,e)},(0,er.tp)().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),(0,ge.N)(this,e,t,n)};var Ur=n(6999);(0,er.tp)().prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),(0,Ur.j)(this,e,t,n,r)};var Gr=n(1938);(0,er.tp)().prototype.max=function(e,t){return this.throwIfDisposed(),(0,Gr.T)(this,e,t)},(0,er.tp)().prototype.maximum=function(e){return this.throwIfDisposed(),(0,Zn.P)(this,e)};var Hr=n(2611);(0,er.tp)().prototype.mean=function(e,t){return this.throwIfDisposed(),(0,Hr.i)(this,e,t)};var jr=n(7436);(0,er.tp)().prototype.min=function(e,t){return this.throwIfDisposed(),(0,jr.j)(this,e,t)};var qr=n(2644);(0,er.tp)().prototype.minimum=function(e){return this.throwIfDisposed(),(0,qr.B)(this,e)};var Zr=n(6567);(0,er.tp)().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),(0,Zr.F)(this,e,t)};var Kr=n(152);(0,er.tp)().prototype.mod=function(e){return this.throwIfDisposed(),(0,Kr.z)(this,e)},(0,er.tp)().prototype.mul=function(e){return this.throwIfDisposed(),(0,O.l)(this,e)},(0,er.tp)().prototype.neg=function(){return this.throwIfDisposed(),(0,B.H)(this)};var Yr=n(2596);(0,er.tp)().prototype.norm=function(e,t,n){return this.throwIfDisposed(),(0,Yr.x)(this,e,t,n)};var Qr=n(2118);(0,er.tp)().prototype.notEqual=function(e){return this.throwIfDisposed(),(0,Qr.E)(this,e)};var Xr=n(1760);(0,er.tp)().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),(0,Xr.M)(this,e,t,n)};var Jr=n(9885);(0,er.tp)().prototype.onesLike=function(){return this.throwIfDisposed(),(0,Jr.P)(this)},(0,er.tp)().prototype.pad=function(e,t){return this.throwIfDisposed(),(0,In.e)(this,e,t)};var ea=n(7872);(0,er.tp)().prototype.pool=function(e,t,n,r,a,s){return this.throwIfDisposed(),(0,ea.d)(this,e,t,n,r,a,s)},(0,er.tp)().prototype.pow=function(e){return this.throwIfDisposed(),(0,Qt.n)(this,e)};var ta=n(4394);(0,er.tp)().prototype.prelu=function(e){return this.throwIfDisposed(),(0,ta.N)(this,e)};var na=n(7771);(0,er.tp)().prototype.prod=function(e,t){return this.throwIfDisposed(),(0,na._)(this,e,t)};var ra=n(9870);(0,er.tp)().prototype.reciprocal=function(){return this.throwIfDisposed(),(0,ra.V)(this)};var aa=n(112);(0,er.tp)().prototype.relu=function(){return this.throwIfDisposed(),(0,aa.V)(this)};var sa=n(3732);(0,er.tp)().prototype.relu6=function(){return this.throwIfDisposed(),(0,sa.j)(this)},(0,er.tp)().prototype.reshapeAs=function(e){return this.throwIfDisposed(),(0,Z.t)(this,e.shape)},(0,er.tp)().prototype.reshape=function(e){return this.throwIfDisposed(),(0,Z.t)(this,e)};var ia=n(4711);(0,er.tp)().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),(0,ia.v)(this,e,t,n)};var oa=n(2954);(0,er.tp)().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),(0,oa.b)(this,e,t,n)},(0,er.tp)().prototype.reverse=function(e){return this.throwIfDisposed(),(0,dn.B)(this,e)};var ua=n(8775);(0,er.tp)().prototype.rfft=function(){return this.throwIfDisposed(),(0,ua.z)(this)};var la=n(5912);(0,er.tp)().prototype.round=function(){return this.throwIfDisposed(),(0,la.L)(this)},(0,er.tp)().prototype.rsqrt=function(){return this.throwIfDisposed(),(0,st.Z)(this)};var ca=n(6325);(0,er.tp)().prototype.selu=function(){return this.throwIfDisposed(),(0,ca.W)(this)};var da=n(9986);(0,er.tp)().prototype.separableConv2d=function(e,t,n,r,a,s){return this.throwIfDisposed(),(0,da.w)(this,e,t,n,r,a,s)},(0,er.tp)().prototype.sigmoid=function(){return this.throwIfDisposed(),(0,Nn.r)(this)};var pa=n(1115);(0,er.tp)().prototype.sign=function(){return this.throwIfDisposed(),(0,pa._)(this)},(0,er.tp)().prototype.sin=function(){return this.throwIfDisposed(),(0,Pe.F)(this)},(0,er.tp)().prototype.sinh=function(){return this.throwIfDisposed(),(0,We.L)(this)},(0,er.tp)().prototype.slice=function(e,t){return this.throwIfDisposed(),(0,Lt.d)(this,e,t)};var ha=n(6346);(0,er.tp)().prototype.softmax=function(e){return this.throwIfDisposed(),(0,ha.V)(this,e)};var fa=n(6030);(0,er.tp)().prototype.softplus=function(){return this.throwIfDisposed(),(0,fa.l)(this)},(0,er.tp)().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),(0,be.e)(this,e,t)},(0,er.tp)().prototype.split=function(e,t){return this.throwIfDisposed(),(0,Ne.l)(this,e,t)},(0,er.tp)().prototype.sqrt=function(){return this.throwIfDisposed(),(0,V.R)(this)},(0,er.tp)().prototype.square=function(){return this.throwIfDisposed(),(0,U.E)(this)};var ma=n(3427);(0,er.tp)().prototype.squaredDifference=function(e){return this.throwIfDisposed(),(0,ma.P)(this,e)};var ga=n(5932);(0,er.tp)().prototype.squeeze=function(e){return this.throwIfDisposed(),(0,ga.r)(this,e)},(0,er.tp)().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof er.qY?[this,e]:[this,...e];return(0,ut.t)(n,t)},(0,er.tp)().prototype.step=function(e){return this.throwIfDisposed(),(0,z.P)(this,e)};var ya=n(5894);(0,er.tp)().prototype.stridedSlice=function(e,t,n,r,a,s,i,o){return this.throwIfDisposed(),(0,ya.Y)(this,e,t,n,r,a,s,i,o)},(0,er.tp)().prototype.sub=function(e){return this.throwIfDisposed(),(0,G.j)(this,e)},(0,er.tp)().prototype.sum=function(e,t){return this.throwIfDisposed(),(0,K.c)(this,e,t)};var ba=n(7823);(0,er.tp)().prototype.tan=function(){return this.throwIfDisposed(),(0,ba.M)(this)};var xa=n(7311);(0,er.tp)().prototype.tanh=function(){return this.throwIfDisposed(),(0,xa.y)(this)},(0,er.tp)().prototype.tile=function(e){return this.throwIfDisposed(),(0,it.V)(this,e)},(0,er.tp)().prototype.toBool=function(){return this.throwIfDisposed(),(0,M.w)(this,"bool")},(0,er.tp)().prototype.toFloat=function(){return this.throwIfDisposed(),(0,M.w)(this,"float32")},(0,er.tp)().prototype.toInt=function(){return this.throwIfDisposed(),(0,M.w)(this,"int32")};var wa=n(1190);(0,er.tp)().prototype.topk=function(e,t){return this.throwIfDisposed(),(0,wa.r)(this,e,t)},(0,er.tp)().prototype.transpose=function(e){return this.throwIfDisposed(),(0,He.m)(this,e)};var va=n(3937);(0,er.tp)().prototype.unique=function(e){return this.throwIfDisposed(),(0,va.A)(this,e)},(0,er.tp)().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),(0,lt.z)(this,e,t)},(0,er.tp)().prototype.unstack=function(e){return this.throwIfDisposed(),(0,qt.K)(this,e)},(0,er.tp)().prototype.where=function(e,t){return this.throwIfDisposed(),(0,Te._)(e,this,t)},(0,er.tp)().prototype.zerosLike=function(){return this.throwIfDisposed(),(0,X.P)(this)};class ka extends Error{constructor(e){super(e),Object.setPrototypeOf(this,ka.prototype)}}class Sa extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Sa.prototype)}}class _a extends Error{constructor(e){super(e),Object.setPrototypeOf(this,_a.prototype)}}class Ia extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ia.prototype)}}class Ta extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ta.prototype)}}Error;class $a{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){const e=this.cache.keys().next().value;this.cache.delete(e)}this.maxEntries=e}}function Ca(e,t){if(Array.isArray(e)){let n=[];for(let r=0;r<t;r++)n=n.concat(e);return n}{const n=new Array(t);return n.fill(e),n}}function Na(e,t){if(!e)throw new Ta(t)}function Ea(e,t){let n=0;for(const r of e)r===t&&n++;return n}function Aa(e){return 1===e.length?e[0]:e}function Ra(e){return Array.isArray(e)?e:[e]}function Da(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==t[0]?t:"private"+t}function Fa(e){return e.length<=1||-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,((e,t)=>t.toUpperCase()))}let Ma={};function Oa(e){if(null===e||void 0===e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function za(e){if(null!=e&&"object"===typeof e)if(Array.isArray(e))e.forEach((e=>za(e)));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"===typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!==typeof t.value?za(t):e[n]=t.value)}}}function La(e,t={},n={},r="object",a=!1){if("string"===typeof e){const a=e;let s;if(a in n)s=n[a];else if(a in Ma)s=Ma[a];else if(s=t[a],null==s)throw new _a(`Unknown ${r}: ${e}. This may be due to one of the following reasons:\n1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return s}{const s=e;if(null==s.className||null==s.config)throw new _a(`${r}: Improper config format: ${JSON.stringify(s)}.\n'className' and 'config' must set.`);const i=s.className;let o,u;if(i in n?[o,u]=n[i]:i in Ma?[o,u]=Ma.className:i in t&&([o,u]=t[i]),null==o)throw new _a(`Unknown ${r}: ${i}. This may be due to one of the following reasons:\n1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=u){const e={};for(const n of Object.keys(Ma))e[n]=Ma[n];for(const a of Object.keys(n))e[a]=n[a];s.config.customObjects=e;const t=Object.assign({},Ma);for(const a of Object.keys(n))Ma[a]=n[a];za(s.config);const r=u(o,s.config,n,a);return Ma=Object.assign({},t),r}{const e=Object.assign({},Ma);for(const r of Object.keys(n))Ma[r]=n[r];const t=new o(s.config);return Ma=Object.assign({},e),t}}}function Pa(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0}(e,t)}function Ba(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function Wa(e){if(null==e)throw new _a(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Va(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new _a(`${n} is not a valid ${t}.  Valid values are ${e} or null/undefined.`)}function Ua(e,t,n=0,r=1/0){return Na(n>=0),Na(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every((e=>typeof e===t))}function Ga(e,t){Array.isArray(e)?(D.ZSL.assert(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>Ga(e,`element ${n+1} of ${t}`)))):D.ZSL.assert(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${Ha(e)}.`))}function Ha(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>Ha(e))).join(",")+"]":"string"===typeof e?`"${e}"`:`${e}`}function ja(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}let qa=0;function Za(){return qa++}const Ka={};function Ya(e=""){return e in Ka||(Ka[e]=0),Ka[e]+=1,e+Ka[e].toString()}const Qa=["channelsFirst","channelsLast"],Xa=["nearest","bilinear"],Ja=["valid","same","causal"],es=["max","avg"],ts=["sum","mul","concat","ave"],ns=new Map;function rs(e){Va(Qa,"DataFormat",e)}function as(e){Va(Ja,"PaddingMode",e)}function ss(e){Va(es,"PoolMode",e)}const is=[];function os(e,t){is.push(e);try{const e=t();return is.pop(),e}catch(n){throw is.pop(),n}}function us(e){if(!ds(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===is.length?"":is.join("/")+"/")+e}function ls(e){if(!ds(e))throw new Error("Not a valid tensor name: '"+e+"'");ns.has(e)||ns.set(e,0);const t=ns.get(e);if(ns.set(e,ns.get(e)+1),t>0){const n=`${e}_${t}`;return ns.set(n,1),n}return e}const cs=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function ds(e){return!!e.match(cs)}function ps(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let r=1;for(let a=t;a<n;++a)r*=e[a];return r}function hs(e){if(0===e.length)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){const r=e[n];r<t&&(t=r)}return t}function fs(e){if(0===e.length)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){const r=e[n];r>t&&(t=r)}return t}function ms(e,t){if(t<e)throw new _a(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let r=e;r<t;++r)n.push(r);return n}let gs;function ys(){return null==gs&&(gs=(0,D.Hs)().epsilon()),gs}function bs(e,t){return D.wgE(e,t)}function xs(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),D.tQQ(e,n)}function ws(e,t,n){return(0,D.DZQ)((()=>{switch(e.rank){case 1:return D.Q$M(e,t,n);case 2:return D.zAd(e,[t,0],[n,e.shape[1]]);case 3:return D.wck(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return D.R0O(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return D.dik(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return D.dik(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new _a(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function vs(e,t,n){return(0,D.DZQ)((()=>{switch(e.rank){case 1:return D.Q$M(e,t,n);case 2:return D.zAd(e,[0,t],[e.shape[0],n]);case 3:return D.wck(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return D.R0O(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new _a(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function ks(e,t,n,r){return(0,D.DZQ)((()=>{switch(e.rank){case 1:return D.Q$M(e,t,n);case 2:switch(r){case 1:return ws(e,t,n);case 2:return vs(e,t,n);default:throw new _a(`The axis is not within the rank of the tensor ${r}`)}case 3:switch(r){case 1:return ws(e,t,n);case 2:return D.wck(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return vs(e,t,n);default:throw new _a(`The axis is not within the rank of the tensor ${r}`)}case 4:switch(r){case 1:return ws(e,t,n);case 2:return D.R0O(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return D.R0O(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return vs(e,t,n);default:throw new _a(`The axis is not within the rank of the tensor ${r}`)}default:throw new _a(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ss(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),D.xWs(e,t)}function _s(e,t){switch(e.rank){case 1:return D.I1m([e,t]);case 2:return D.RPU([e,t],0);case 3:return D.O5O([e,t],0);case 4:return D.P1l([e,t],0);default:throw new _a(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Is(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new _a(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return D.Vsq(e,t)}function Ts(e,t=0,n=1,r,a){return D.FE$(e,t,n,r,a)}function $s(e,t,n,r){if(e.rank<2||t.rank<2)throw new Ia(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){if(e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new Ia(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and  y shape = ${t.shape}`)}if(2===e.rank&&2===t.rank){const a=!1,s=!1;return D.cZk.matMul({a:e,b:t,transposeA:a,transposeB:s,bias:r?Es(e.rank,r,"channelsLast"):null,activation:n})}{const a=e.shape.slice(),s=a.pop();e=D.tQQ(e,[-1,s]);const i=t.shape.slice(),o=i.pop(),u=i.pop(),l=[...i,o],c=Array.from({length:t.rank},((e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n));t=D.tQQ(D.mgz(t,c),[u,-1]);const d=[...a,...l],p=!1,h=!1;return D.tQQ(D.cZk.matMul({a:e,b:t,transposeA:p,transposeB:h,bias:r?Es(e.rank,r,"channelsLast"):null,activation:n}),d)}}function Cs(e,t,n){return(0,D.DZQ)((()=>(t=Array.isArray(t)?(0,D.tGX)(t,"int32"):D.wgE(t,"int32"),D.kgh(e,t,n))))}function Ns(e){return D.lKK(e,e)}function Es(e,t,n){const r=t.shape;if(1!==t.rank&&t.rank!==e)throw new _a(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===r.length?D.tQQ(t,[1,r[0],1,1,1]):D.tQQ(t,[1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?D.tQQ(t,[1,1,1,1,r[0]]):D.tQQ(t,[1].concat(r))}else if(4===e){if("channelsFirst"===n)return 1===r.length?D.tQQ(t,[1,r[0],1,1]):D.tQQ(t,[1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?D.tQQ(t,[1,1,1,r[0]]):D.tQQ(t,[1].concat(r))}else if(3===e){if("channelsFirst"===n)return 1===r.length?D.tQQ(t,[1,r[0],1]):D.tQQ(t,[1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?D.tQQ(t,[1,1,r[0]]):D.tQQ(t,[1].concat(r))}else if(e<3)return t;throw new _a(`Unsupported input rank by biasAdd: ${t.rank}`)}function As(e,t,n){return(0,D.DZQ)((()=>(null==n&&(n="channelsLast"),rs(n),D.WQq(e,Es(e.rank,t,n)))))}function Rs(e,t,n,r){return(0,D.DZQ)((()=>D.EZY(e,t,n,r)))}function Ds(e,t,n=!1){return n?e():t()}const Fs=["fanIn","fanOut","fanAvg"],Ms=["normal","uniform","truncatedNormal"];class Os extends D.JFn.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class zs extends Os{apply(e,t){return(0,D.Ul9)(e,t)}}zs.className="Zeros",D.JFn.registerClass(zs);class Ls extends Os{apply(e,t){return(0,D.SaS)(e,t)}}Ls.className="Ones",D.JFn.registerClass(Ls);class Ps extends Os{constructor(e){if(super(),"object"!==typeof e)throw new _a(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new _a(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return(0,D.DZQ)((()=>(0,D.lKK)((0,D.d_2)(this.value),(0,D.SaS)(e,t))))}getConfig(){return{value:this.value}}}Ps.className="Constant",D.JFn.registerClass(Ps);class Bs extends Os{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return(0,D.YeY)(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Bs.className="RandomUniform",D.JFn.registerClass(Bs);class Ws extends Os{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Ia(`randomNormal does not support dType ${t}.`);return Ts(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Ws.className="RandomNormal",D.JFn.registerClass(Ws);class Vs extends Os{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Ia(`truncatedNormal does not support dType ${t}.`);return(0,D.efE)(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Vs.className="TruncatedNormal",D.JFn.registerClass(Vs);class Us extends Os{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return(0,D.DZQ)((()=>{if(2!==e.length||e[0]!==e[1])throw new _a("Identity matrix initializer can only be used for 2D square matrices.");return(0,D.lKK)(this.gain,(0,D.y5U)(e[0]))}))}getConfig(){return{gain:this.gain}}}Us.className="Identity",D.JFn.registerClass(Us);class Gs extends Os{constructor(e){if(super(),e.scale<0)throw new _a(`scale must be a positive float. Got: ${e.scale}`);var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,Va(Fs,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){Va(Ms,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,r;if(rs(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=ps(e,2);n=e[1]*t,r=e[0]*t}else if("channelsLast"===t){const t=ps(e,0,e.length-2);n=e[e.length-2]*t,r=e[e.length-1]*t}}else{const t=ps(e);n=Math.sqrt(t),r=Math.sqrt(t)}return[n,r]}(e),r=n[0],a=n[1];let s=this.scale;if("fanIn"===this.mode?s/=Math.max(1,r):"fanOut"===this.mode?s/=Math.max(1,a):s/=Math.max(1,(r+a)/2),"normal"===this.distribution){const n=Math.sqrt(s);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Ia(`${this.getClassName()} does not support dType ${t}.`);return(0,D.efE)(e,0,n,t,this.seed)}{const n=Math.sqrt(3*s);return(0,D.YeY)(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Gs.className="VarianceScaling",D.JFn.registerClass(Gs);class Hs extends Gs{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Gs.className}}Hs.className="GlorotUniform",D.JFn.registerClass(Hs);class js extends Gs{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Gs.className}}js.className="GlorotNormal",D.JFn.registerClass(js);class qs extends Gs{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Gs.className}}qs.className="HeNormal",D.JFn.registerClass(qs);class Zs extends Gs{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Gs.className}}Zs.className="HeUniform",D.JFn.registerClass(Zs);class Ks extends Gs{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Gs.className}}Ks.className="LeCunNormal",D.JFn.registerClass(Ks);class Ys extends Gs{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Gs.className}}Ys.className="LeCunUniform",D.JFn.registerClass(Ys);class Qs extends Os{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return(0,D.DZQ)((()=>{if(e.length<2)throw new Ia("Shape must be at least 2D.");if("int32"!==t&&"float32"!==t&&void 0!==t)throw new TypeError(`Unsupported data type ${t}.`);const n=D.ZSL.sizeFromShape(e.slice(0,-1)),r=e[e.length-1];this.ELEMENTS_WARN_SLOW;const a=Ts([Math.max(r,n),Math.min(r,n)],0,1,t,this.seed),s=D.mPL.qr(a,!1);let i=s[0];const o=s[1].flatten().stridedSlice([0],[Math.min(r,n)*Math.min(r,n)],[Math.min(r,n)+1]);return i=(0,D.lKK)(i,o.sign()),n<r&&(i=i.transpose()),(0,D.lKK)((0,D.d_2)(this.gain),i.reshape(e))}))}getConfig(){return{gain:this.gain,seed:this.seed}}}Qs.className="Orthogonal",D.JFn.registerClass(Qs);const Xs={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Js(e,t={}){return La(e,D.JFn.SerializationMap.getMap().classNameMap,t,"initializer")}function ei(e){return Oa(e)}function ti(e){if("string"===typeof e){const t=e in Xs?Xs[e]:e;if("GlorotNormal"===t)return new js;if("GlorotUniform"===t)return new Hs;if("HeNormal"===t)return new qs;if("HeUniform"===t)return new Zs;if("LeCunNormal"===t)return new Ks;if("LeCunUniform"===t)return new Ys;{const e={};return e.className=t,e.config={},Js(e)}}return e instanceof Os?e:Js(e)}function ni(e){return Array.isArray(e)&&Array.isArray(e[0])}function ri(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function ai(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new _a(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function si(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return e[0];throw new _a(`Expected exactly 1 Shape; got ${e.length}`)}return e}function ii(e){let t=0;for(const n of e)0===n.shape.length?t+=1:t+=n.shape.reduce(((e,t)=>e*t));return t}const oi="Variable";class ui{constructor(e,t="float32",n=oi,r=!0,a=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=Za(),n=null==n?oi:n,this.originalName=us(n),this.name=ls(this.originalName),this.trainable_=r,this.constraint=a,this.val=D.bvq(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function li(e){return e.map((e=>e.read()))}function ci(e){e.forEach((e=>{e[0].write(e[1])}))}class di{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class pi{constructor(e,t,n,r,a,s,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=r,this.callArgs=a,this.outputTensorIndex=i,this.id=Za(),null!=s&&(this.originalName=us(s),this.name=ls(this.originalName)),this.rank=t.length}}let hi=0;class fi{constructor(e,t){this.callArgs=t,this.id=hi++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const n of e.inboundLayers)null!=n&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let mi=0;class gi extends D.JFn.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=mi++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=Da(e)+"_"+Ya(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new Sa(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new _a(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Aa(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Aa(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ka(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new ka(`Layer ${this.name} is not connected, no input to return.`);return Aa(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new ka(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ka(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Aa(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((e=>e()))}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach((t=>t.trainable=e)),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((e=>e.trainable)):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((e=>!e.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){const t=Ra(e);if(null==this.inputSpec||0===this.inputSpec.length)return;const n=Ra(this.inputSpec);if(t.length!==n.length)throw new _a(`Layer ${this.name} expects ${n.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let r=0;r<t.length;r++){const e=t[r],a=n[r];if(null==a)continue;const s=e.rank;if(null!=a.ndim&&s!==a.ndim)throw new _a(`Input ${r} is incompatible with layer ${this.name}: expected ndim=${a.ndim}, found ndim=${s}`);if(null!=a.maxNDim&&s>a.maxNDim)throw new _a(`Input ${r} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${s}`);if(null!=a.minNDim&&s<a.minNDim)throw new _a(`Input ${r} is incompatible with layer ${this.name}: expected min_ndim=${a.minNDim}, found ndim=${s}.`);if(null!=a.dtype&&e.dtype!==a.dtype)throw new _a(`Input ${r} is incompatible with layer ${this.name} : expected dtype=${a.dtype}, found dtype=${e.dtype}.`);if(a.axes){const t=e.shape;for(const e in a.axes){const n=Number(e),s=a.axes[e],i=n>=0?t[n]:t[t.length+n];if(null!=s&&-1===[s,null].indexOf(i))throw new _a(`Input ${r} is incompatible with layer ${this.name}: expected axis ${n} of input shape to have value ${s} but got shape ${t}.`)}}if(null!=a.shape)for(let t=0;t<a.shape.length;++t){const n=a.shape[t],s=e.shape[t];if(null!=n&&null!=s&&n!==s)throw new _a(`Input ${r} is incompatible with layer ${this.name}: expected shape=${a.shape}, found shape=${e.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Ra(e),r=function(e){let t=!0;for(const n of Ra(e))if(!(n instanceof pi)){t=!1;break}return t}(e),a=function(e){let t=!0;for(const n of Ra(e))if(n instanceof pi){t=!1;break}return t}(e);if(r===a)throw new _a("Arguments to apply() must be all SymbolicTensors or all Tensors");return os(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Ra(e))t.push(n.shape);this.build(Aa(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let r=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,r);const a=Ra(r),s=[];for(let e of a)-1!==n.indexOf(e)&&(e=e.clone()),s.push(e);if(r=Aa(s),null!=this.activityRegularizer)throw new Ia("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}{const n=function(e){e=Ra(e);const t=[];for(const n of e)t.push(n.shape);return Aa(t)}(e),r=this.computeOutputShape(n);let a;const s="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),a=null!=r&&r.length>0&&Array.isArray(r[0])?r.map(((n,r)=>new pi(s,n,this,Ra(e),t,this.name,r))):new pi(s,r,this,Ra(e),t,this.name),this.addInboundNode(e,a,null,null,n,r,t),this._refCount++,null!=this.activityRegularizer)throw new Ia("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length);else{let t=!1;this.batchInputShape.forEach(((n,r)=>{null!=n&&null!=e[r]&&e[r]!==n&&(t=!0)}))}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new ka(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new ka(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Sa(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return ii(this.weights)}build(e){this.built=!0}getWeights(e=!1){return li(e?this.trainableWeights:this.weights)}setWeights(e){(0,D.DZQ)((()=>{const t=this.weights;if(t.length!==e.length)throw new _a(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],r=li(t);for(let a=0;a<r.length;++a){const s=r[a],i=t[a],o=e[a];if(!D.ZSL.arraysEqual(s.shape,o.shape))throw new _a(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}ci(n)}))}addWeight(e,t,n,r,a,s,i,o){if(-1!==this._addedWeightNames.indexOf(e))throw new _a(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(r=null!=o?o():ti("zeros"));const u=r.apply(t,n),l=new ui(u,n,e,s,i);return u.dispose(),null!=a&&this.addLoss((()=>a.apply(l.read()))),null==s&&(s=!0),s?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=Ra(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}setMaskMetadata(e,t,n){if(!this.supportsMasking)return;const r=this.computeMask(e,n),a=Ra(t),s=Ra(r);if(a.length!==s.length)throw new Error(`${this.name} outputs ${a.length} tensors but ${a.length} masks for those tensors`);for(let i=0;i<a.length;i++)a[i].kerasMask=s[i]}addInboundNode(e,t,n,r,a,s,i=null){const o=Ra(e);t=Ra(t),n=Ra(n),r=Ra(r),a=ri(a),s=ri(s);const u=[],l=[],c=[];for(const d of o)u.push(d.sourceLayer),l.push(d.nodeIndex),c.push(d.tensorIndex);new fi({outboundLayer:this,inboundLayers:u,nodeIndices:l,tensorIndices:c,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:r,inputShapes:a,outputShapes:s},i);for(let d=0;d<t.length;d++)t[d].sourceLayer=this,t[d].nodeIndex=this.inboundNodes.length-1,t[d].tensorIndex=d}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach((e=>e.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0===--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function yi(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const r=yi(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of r)-1===t.indexOf(e)&&t.push(e)}return t}}}class bi extends gi{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:Ya("input").toString()}),null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new _a("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(null==t){if(null==e.inputShape)throw new _a("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new _a("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const r=new pi(this.dtype,this.batchInputShape,this,[],{},this.name);r.nodeIndex=0,r.tensorIndex=0,new fi({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[r],outputTensors:[r],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new _a(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}function xi(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new _a("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;null==n&&(n="float32");return new bi({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}bi.className="InputLayer",D.JFn.registerClass(bi);class wi{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof wi)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(null==e)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(null!=this.id2Value[e.id])throw new _a(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return(0,D.wgE)(t,e.dtype)}catch(n){throw new _a(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}(e,t),this.name2Id[e.name]=e.id,null!=n&&(this.id2Mask[e.id]=n),this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return null!=this.id2Value[e.id]}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof pi){if(null==this.id2Value[e.id])throw new _a(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(null==t)throw new _a(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof pi){if(null==this.id2Value[e.id])throw new _a(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(null==t)throw new _a(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){null!=this.id2Mask&&(0,D.ASo)(this.id2Mask)}}const vi=new $a,ki=new $a;function Si(e,t,n,r){const a=null!=n&&n.training,s=Array.isArray(e),i=s?e:[e],o=i.map((e=>e.name)),u=[],l=t.names();for(const f of o)-1!==l.indexOf(f)?u.push(t.getValue(f)):u.push(null);null!=r&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);const c=o.join(",")+"|"+t.names().sort().join(",");let d,p=vi.get(c);if(null==p){const e=function(e,t){D.ZSL.assert(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],r={};if(1===e.length){const a=Ii(e[0],t);n=a.sorted,r=a.recipientMap}else{const a=new Set;for(const s of e){const{sorted:e,recipientMap:i}=Ii(s,t);for(const t of e)a.has(t.name)||(n.push(t),a.add(t.name));for(const t in i)null==r[t]&&(r[t]=new Set),i[t].forEach((e=>r[t].add(e)))}}return{sorted:n,recipientCounts:_i(r)}}(i,t);p=e.sorted,d=e.recipientCounts,vi.put(c,p),ki.put(c,d)}d={},a||Object.assign(d,ki.get(c));const h=new wi(t);for(let f=0;f<p.length;++f){if(null!=r){const e=(0,D.m1Z)().numTensors;e>r.maxNumTensors&&(r.maxNumTensors=e),e<r.minNumTensors&&(r.minNumTensors=e)}const e=p[f],s=e.sourceLayer;if(s instanceof bi)continue;const i=[],l=[],c=[];let m=!1;for(const n of e.inputs){const e=h.getValue(n),r=h.getMask(n);i.push(e),l.push(r),null!=r&&(m=!0),a||(d[n.name]--,0!==d[n.name]||t.hasKey(n)||-1!==o.indexOf(n.name)||e.isDisposed||!0===n.sourceLayer.stateful||c.push(e))}m&&((n=n||{}).mask=l[0]);const g=Ra(s.apply(i,n));let y=null;s.supportsMasking&&(y=s.computeMask(i,l));const b=Ti(e),x=Array.isArray(b)?b:[b];for(let t=0;t<x.length;++t){h.hasKey(x[t])||h.add(x[t],g[t],Array.isArray(y)?y[0]:y);const e=o.indexOf(x[t].name);-1!==e&&(u[e]=g[t])}a||(0,D.ASo)(c)}return h.disposeMasks(),s?u:u[0]}function _i(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Ii(e,t){const n=new Set,r=[],a={};for(const o of t.names())n.add(o);const s=[],i=[];for(s.push(e);s.length>0;){const e=s[s.length-1];if(n.has(e.name)){s.pop();continue}const t=i[i.length-1]===s.length-1;if(0===e.inputs.length||t)s.pop(),r.push(e),n.add(e.name),t&&i.pop();else{i.push(s.length-1);for(const t of e.inputs)null==a[t.name]&&(a[t.name]=new Set),a[t.name].add(e.name),n.has(t.name)||s.push(t)}}return{sorted:r,recipientMap:a}}function Ti(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;t<e.sourceLayer.inboundNodes.length;++t)for(const r of e.sourceLayer.inboundNodes[t].outputTensors)if(r.id===e.id){n=t;break}t=e.sourceLayer.getOutputAt(n)}return t}function $i(e,t){return(0,D.DZQ)((()=>D.RZD(D.czq(D.lKK(e,e),t,!0))))}(0,D._K2)().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",(()=>100),(function(e){null!=vi&&vi.setMaxEntries(e),null!=ki&&ki.setMaxEntries(e)}));class Ci extends D.JFn.Serializable{getConfig(){return{}}}class Ni extends Ci{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return(0,D.DZQ)((()=>{const t=$i(e,this.axis),n=D.zQh(t,0,this.maxValue);return D.lKK(e,D.y4m(n,D.WQq(ys(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Ni.className="MaxNorm",D.JFn.registerClass(Ni);class Ei extends Ci{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return(0,D.DZQ)((()=>D.y4m(e,D.WQq(ys(),$i(e,this.axis)))))}getConfig(){return{axis:this.axis}}}Ei.className="UnitNorm",D.JFn.registerClass(Ei);class Ai extends Ci{apply(e){return D.VVh(e)}}Ai.className="NonNeg",D.JFn.registerClass(Ai);class Ri extends Ci{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return(0,D.DZQ)((()=>{const t=$i(e,this.axis),n=D.WQq(D.lKK(this.rate,D.zQh(t,this.minValue,this.maxValue)),D.lKK(1-this.rate,t));return D.lKK(e,D.y4m(n,D.WQq(ys(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Ri.className="MinMaxNorm",D.JFn.registerClass(Ri);const Di={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Fi(e){return Oa(e)}function Mi(e,t={}){return La(e,D.JFn.SerializationMap.getMap().classNameMap,t,"constraint")}function Oi(e){if(null==e)return null;if("string"===typeof e){return Mi({className:e in Di?Di[e]:e,config:{}})}return e instanceof Ci?e:Mi(e)}function zi(e){return new Ni(e)}function Li(e){return new Ei(e)}function Pi(){return new Ai}function Bi(e){return new Ri(e)}function Wi(){return new zs}function Vi(){return new Ls}function Ui(e){return new Ps(e)}function Gi(e){return new Bs(e)}function Hi(e){return new Ws(e)}function ji(e){return new Vs(e)}function qi(e){return new Us(e)}function Zi(e){return new Gs(e)}function Ki(e){return new Hs(e)}function Yi(e){return new js(e)}function Qi(e){return new qs(e)}function Xi(e){return new Zs(e)}function Ji(e){return new Ks(e)}function eo(e){return new Ys(e)}function to(e){return new Qs(e)}async function no(e){if(null==e)return;const t=[],n=[],r=[];for(const a in e){const s=e[a];if("number"!==typeof s){const e=s;t.push(e.data()),n.push(a),r.push(e)}}if(t.length>0){const a=await Promise.all(t);for(let t=0;t<a.length;++t)e[n[t]]=a[t][0];(0,D.ASo)(r)}}function ro(e){if(null!=e)for(const t in e){const n=e[t];"number"!==typeof n&&n.dispose()}}var ao;!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(ao||(ao={}));class so{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class io{constructor(e,t=10){null==e&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class oo extends so{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){null==t&&(t={});const n=null==t.size?0:t.size;this.seen+=n;for(const r in t){const e=t[r];if("number"===typeof e)this.totals.hasOwnProperty(r)||(this.totals[r]=0),this.totals[r]=this.totals[r]+e*n;else{let t;r in this.totals?t=this.totals[r]:this.totals[r]=0;const a=(0,D.DZQ)((()=>(0,D.WQq)(this.totals[r],(0,D.lKK)(e,n))));this.totals[r]=a,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const n of this.params.metrics)null!=this.totals[n]&&("number"===typeof this.totals[n]?t[n]=this.totals[n]/this.seen:(0,D.DZQ)((()=>{const e=(0,D.lKK)((0,D.y4m)(1,this.seen),this.totals[n]);t[n]=e,this.totals[n].dispose(),(0,D.aCs)(t[n])})))}}class uo extends so{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const n in t)null==this.history[n]&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){const e=[],t=[],n=[];for(const a in this.history){const r=this.history[a];for(let s=0;s<r.length;++s)if("number"!==typeof r[s]){const i=r[s];e.push(i.data()),t.push(a),n.push(s)}}const r=await Promise.all(e);for(let a=0;a<r.length;++a){this.history[t[a]][n[a]].dispose(),this.history[t[a]][n[a]]=r[a][0]}}}class lo extends so{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||D.dA1,this.yieldEvery=t||"auto","auto"===this.yieldEvery&&(this.yieldEvery=125),"never"===this.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");D.ZSL.isNumber(this.yieldEvery)&&(this.maybeWait=function(e,t,n){let r,a=null!=n?n():D.ZSL.now();return(...s)=>{const i=null!=n?n():D.ZSL.now();return i-a<t||(a=i,r=e(...s)),r}}(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){const r=[];null!=this.yield&&(await no(n),r.push(this.yield(e,t,n))),r.push(this.nextFrameFunc()),await Promise.all(r)}async onEpochBegin(e,t){this.currentEpoch=e,null!=this.epochBegin&&(await no(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await no(t),n.push(this.epochEnd(e,t))),"epoch"===this.yieldEvery&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){null!=this.batchBegin&&(await no(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await no(t),n.push(this.batchEnd(e,t))),"batch"===this.yieldEvery?n.push(this.nextFrameFunc()):D.ZSL.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){null!=this.trainBegin&&(await no(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await no(e),await this.trainEnd(e))}}function co(e,t){if(null==e&&(e={}),e instanceof so)return[e];if(Array.isArray(e)&&e[0]instanceof so)return e;return Ra(e).map((e=>new lo(e,t)))}class po{constructor(){}static registerCallbackConstructor(e,t){D.ZSL.assert(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),po.checkForDuplicate(t),null==po.constructors[e]&&(po.constructors[e]=[]),po.constructors[e].push(t)}static checkForDuplicate(e){for(const t in po.constructors){po.constructors[+t].forEach((t=>{if(t===e)throw new _a("Duplicate callback constructor.")}))}}static clear(){po.constructors={}}static createCallbacks(e){const t=[];for(const n in po.constructors){const r=+n;e>=r&&t.push(...po.constructors[r])}return t.map((e=>new e))}}function ho(e,t,n,r,a,s,i,o,u){const l=new uo,c=[new oo,...po.createCallbacks(t)];null!=e&&c.push(...e),c.push(l);const d=new io(c);return d.setParams({epochs:n,initialEpoch:r,samples:a,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:u}),{callbackList:d,history:l}}function fo(e,t={},n=!1){return La(e,D.JFn.SerializationMap.getMap().classNameMap,t,"layer",n)}function mo(e,t){return(0,D.DZQ)((()=>{"float32"!==e.dtype&&(e=D.wgE(e,"float32"));const n=D.czq(Ns(e),t,!0),r=D.GSj(n.shape,ys()),a=D.RZD(D.PhQ(n,r));return D.y4m(e,a)}))}function go(e,t){return(0,D.DZQ)((()=>D.i2o(Ns(D.jbE(t,e)),-1)))}function yo(e,t){return(0,D.DZQ)((()=>D.i2o(D.tnl(D.jbE(t,e)),-1)))}function bo(e,t){return(0,D.DZQ)((()=>{const n=D.jbE(e,t),r=D.zQh(D.tnl(e),ys(),Number.MAX_VALUE),a=D.tnl(D.y4m(n,r));return D.lKK(100,D.i2o(a,-1))}))}function xo(e,t){return(0,D.DZQ)((()=>{const n=D.zQh(t,ys(),Number.MAX_VALUE),r=D.Rm2(D.WQq(1,n)),a=D.zQh(e,ys(),Number.MAX_VALUE),s=D.Rm2(D.WQq(1,a));return D.i2o(Ns(D.jbE(r,s)),-1)}))}function wo(e,t,n=!1){return(0,D.DZQ)((()=>{if(n)t=D.Vs9(t);else{const e=D.czq(t,t.shape.length-1,!0);t=D.y4m(t,e)}return t=D.zQh(t,ys(),1-ys()),D.HZy(D.czq(D.lKK(D.wgE(e,"float32"),D.Rm2(t)),t.shape.length-1))}))}function vo(e,t,n=!1){return(0,D.DZQ)((()=>{const r=D.wgE(D.RIf(function(e){const t=[ps(e.shape)];return D.tQQ(e,t)}(e)),"int32"),a=(t=D.zQh(t,ys(),1-ys())).shape;return wo(D.tQQ(D.Mw0(r,a[a.length-1]),a),t,n)}))}function ko(e,t){return(0,D.DZQ)((()=>{let n;return n=D.zQh(t,ys(),1-ys()),n=D.Rm2(D.y4m(n,D.jbE(1,n))),D.i2o(function(e,t){if(!D.ZSL.arraysEqual(e.shape,t.shape))throw new _a(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return(0,D.DZQ)((()=>{const n=D.VVh(t),r=D.HZy(D.tnl(t));return D.WQq(D.jbE(n,D.lKK(t,e)),D.Kko(D.oNF(r)))}))}(e,n),-1)}))}function So(e,t){return(0,D.DZQ)((()=>{const n=D.zQh(e,ys(),1),r=D.zQh(t,ys(),1);return D.czq(D.lKK(e,D.Rm2(D.y4m(n,r))),-1)}))}function _o(e,t){return(0,D.DZQ)((()=>{const n=mo(e,-1),r=mo(t,-1),a=D.lKK(n,r);return D.HZy(D.czq(a,-1))}))}po.constructors={};const Io={meanSquaredError:go,meanAbsoluteError:yo,meanAbsolutePercentageError:bo,meanSquaredLogarithmicError:xo,squaredHinge:function(e,t){return(0,D.DZQ)((()=>{const n=D.PhQ(0,D.jbE(1,D.lKK(e,t)));return D.i2o(Ns(n),-1)}))},hinge:function(e,t){return(0,D.DZQ)((()=>{const n=D.PhQ(0,D.jbE(1,D.lKK(e,t)));return D.i2o(n,-1)}))},categoricalHinge:function(e,t){return(0,D.DZQ)((()=>{const n=D.czq(D.lKK(e,t),-1),r=D.T9B(D.lKK(D.jbE(1,e),t),-1);return D.PhQ(0,D.WQq(1,D.jbE(r,n)))}))},logcosh:function(e,t){return(0,D.DZQ)((()=>{const n=Math.log(2),r=D.jbE(t,e),a=D.jbE(D.WQq(r,D.lw0(D.lKK(-2,r))),n);return D.i2o(a,-1)}))},categoricalCrossentropy:wo,sparseCategoricalCrossentropy:vo,binaryCrossentropy:ko,kullbackLeiblerDivergence:So,poisson:function(e,t){return(0,D.DZQ)((()=>{const n=D.Rm2(D.WQq(ys(),t));return D.i2o(D.jbE(t,D.lKK(e,n)),-1)}))},cosineProximity:_o};function To(e){if("string"===typeof e){if(e in Io)return Io[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new _a(t)}return e}function $o(e,t){return(0,D.DZQ)((()=>{const n=D.lKK(.5,D.P61(t)),r=bs(D.rhj(t,n),e.dtype);return D.i2o(D.LCg(e,r),-1)}))}function Co(e,t){return(0,D.DZQ)((()=>bs(D.LCg(D.FLi(e,-1),D.FLi(t,-1)),"float32")))}function No(e,t){return(0,D.DZQ)((()=>D.wgE(D.czq(D.n76(D.LCg(e,1),D.LCg(t,1))),"float32")))}function Eo(e,t){return(0,D.DZQ)((()=>{const n=No(e,t),r=function(e,t){return(0,D.DZQ)((()=>D.wgE(D.czq(D.n76(D.LCg(e,0),D.LCg(t,1))),"float32")))}(e,t),a=D.WQq(n,r);return D.wgE(D._M9(D.rhj(a,0),D.y4m(n,a),0),"float32")}))}function Ao(e,t){return(0,D.DZQ)((()=>{const n=No(e,t),r=function(e,t){return(0,D.DZQ)((()=>D.wgE(D.czq(D.n76(D.LCg(e,1),D.LCg(t,0))),"float32")))}(e,t),a=D.WQq(n,r);return D.wgE(D._M9(D.rhj(a,0),D.y4m(n,a),0),"float32")}))}function Ro(e,t){return ko(e,t)}function Do(e,t){return e.rank===t.rank&&(e=D.r2V(e,[e.rank-1])),(t=D.FLi(t,-1)).dtype!==e.dtype&&(t=D.wgE(t,e.dtype)),D.wgE(D.LCg(e,t),"float32")}const Fo=wo,Mo=vo,Oo={binaryAccuracy:$o,categoricalAccuracy:Co,precision:Eo,categoricalCrossentropy:Fo,sparseCategoricalCrossentropy:Mo,mse:go,MSE:go,mae:yo,MAE:yo,mape:bo,MAPE:bo,cosine:_o};function zo(e){if("string"===typeof e&&e in Oo)return Oo[e];if("string"!==typeof e&&null!=e)return e;throw new _a(`Unknown metric ${e}`)}function Lo(e){if(Na(null!==e,`Unknown LossOrMetricFn ${e}`),"string"===typeof e)return e;{let t;for(const n of Object.keys(Io))if(Io[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(Oo))if(Oo[n]===e){t=n;break}return void 0!==t?t:e.name}}function Po(e,t,n=!1){if(null==e||"object"!==typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Bo(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){JSON.stringify(e).length}}function Bo(e){if(null===e)return!0;if("object"===typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!==typeof n)return!1;if(!Bo(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Bo(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}function Wo(e,t,n,r=console.log){const a=function(e){let t=!0;const n=[],r=[];for(const a in e.nodesByDepth)n.push(e.nodesByDepth[a]);for(const a of n){if(a.length>1||1===a.length&&a[0].inboundLayers.length>1){t=!1;break}r.push(...a)}if(t)for(const a of e.layers){let e=!1;for(const n of a.inboundNodes)if(-1!==r.indexOf(n)){if(e){t=!1;break}e=!0}if(!t)break}return t}(e),s=["Layer (type)","Input Shape","Output shape","Param #"];let i;if(a?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map((e=>Math.floor(t*e)))),!a){s.push("Receives inputs"),i=[];for(const t in e.nodesByDepth)i.push(...e.nodesByDepth[t])}r("_".repeat(t)),Vo(s,n,r),r("=".repeat(t));const o=e.layers;for(let c=0;c<o.length;++c)a?Uo(o[c],n,r):Go(o[c],n,i,r),r((c===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const u=function(e){let t;t=null!=e.collectedTrainableWeights?ii(e.collectedTrainableWeights):ii(e.trainableWeights);return t}(e),l=ii(e.nonTrainableWeights);r(`Total params: ${u+l}`),r(`Trainable params: ${u}`),r(`Non-trainable params: ${l}`),r("_".repeat(t))}function Vo(e,t,n=console.log){let r="";for(let a=0;a<e.length;++a)a>0&&(r=r.slice(0,r.length-1)+" "),r+=e[a],r=r.slice(0,t[a]),r+=" ".repeat(t[a]-r.length);n(r)}function Uo(e,t,n){let r,a;try{a=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(s){a="multiple"}try{r=JSON.stringify(e.outputShape)}catch(s){r="multiple"}Vo([`${e.name} (${e.getClassName()})`,a,r,e.countParams().toString()],t,n)}function Go(e,t,n,r){let a,s;try{s=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(c){s="multiple"}try{a=JSON.stringify(e.outputShape)}catch(c){a="multiple"}const i=[];for(const d of e.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(d)))for(let e=0;e<d.inboundLayers.length;++e){const t=d.inboundLayers[e].name,n=d.nodeIndices[e],r=d.tensorIndices[e];i.push(`${t}[${n}][${r}]`)}const o=e.name,u=e.getClassName(),l=0===i.length?"":i[0];Vo([`${o} (${u})`,s,a,e.countParams().toString(),l],t,r);for(let d=1;d<i.length;++d)Vo(["","","","",i[d]],t,r)}function Ho(e,t,n){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"===typeof n}function jo(e,t){if(null===e)return null;if("string"===typeof e)return Fa(e);if("number"===typeof e||"boolean"===typeof e)return e;if(e instanceof Array){const n=[],r=e.length;for(let a=0;a<r;++a){const r=e[a];Ho(t,a,r)?n.push(r):n.push(jo(r,t))}return n}{const t={};for(const n of Object.keys(e)){const r=e[n];if("name"===n&&"string"===typeof r)t[n]=r;else{const e=Fa(n);t[e]=jo(r,e)}}return t}}function qo(e,t){if(null===e||void 0===e)return null;if("string"===typeof e)return Da(e);if("number"===typeof e||"boolean"===typeof e)return e;if(e instanceof Array){const n=[],r=e.length;for(let a=0;a<r;++a){const r=e[a];Ho(t,a,r)?n.push(r):n.push(qo(r,t))}return n}{const t={};for(const n of Object.keys(e)){const r=e[n],a=Da(n);t[a]="name"!==n&&"className"!==n||"string"!==typeof r?qo(r,n):r}return t}}const Zo="4.22.0";class Ko extends gi{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=Ya(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Ba(this.inputs).length!==this.inputs.length)throw new _a(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);Ba(this.outputs).length,this.outputs.length,this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const y of this.outputs){const e=y.sourceLayer,t=y.nodeIndex,n=y.tensorIndex;this.outputLayers.push(e),this.outputLayersNodeIndices.push(t),this.outputLayersTensorIndices.push(n)}for(const y of this.inputs){const e=y.sourceLayer,t=y.nodeIndex,n=y.tensorIndex;Na(0===t,"input layer has >1 nodes"),Na(0===n,"input layer has >1 tensors"),this.inputLayers.push(e),this.inputLayersNodeIndices.push(t),this.inputLayersTensorIndices.push(n)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){const t=this.inputLayers[y];if(!(t instanceof bi))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${t.getClassName()}.`);this.inputNames.push(t.name),this.feedInputShapes.push(t.batchInputShape),this.feedInputNames.push(t.name)}for(const y of this.outputLayers)this.outputNames.push(y.name);this.internalInputShapes=this.inputs.map((e=>e.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},r={},a={},s={},i=[],o=(e,t,n,r,a,u)=>{null!=r&&null!=a&&null!=u||(r=e.sourceLayer,a=e.nodeIndex,u=e.tensorIndex);const l=r.inboundNodes[a];if(-1!==n.indexOf(l))throw new Sa(`The tensor ${e.name} at layer "${r.name}" is part of a cycle.`);if(-1!==t.indexOf(l))return;this.containerNodes.add(Ko.nodeKey(r,a)),r.id in s||(s[r.id]=Object.keys(s).length),-1===n.indexOf(l)&&n.push(l);const c=l.inboundLayers.length;for(let s=0;s<c;s++){const e=l.inputTensors[s],r=l.inboundLayers[s],a=l.nodeIndices[s],i=l.tensorIndices[s];o(e,t,n,r,a,i)}for(t.push(l);n.indexOf(l)>=0;)n.splice(n.indexOf(l),1);i.push(l)},u=[],l=[];for(const y of this.outputs)o(y,u,l);const c=i.slice().reverse();for(const y of c){n[y.id]=y,y.id in t||(t[y.id]=0);let e=t[y.id];const s=null==r[y.outboundLayer.id]?0:r[y.outboundLayer.id];e=Math.max(e,s),r[y.outboundLayer.id]=e,a[y.outboundLayer.id]=y.outboundLayer,t[y.id]=e;for(let r=0;r<y.inboundLayers.length;r++){const a=y.inboundLayers[r],s=y.nodeIndices[r],i=a.inboundNodes[s],o=null==t[i.id]?0:t[i.id];t[i.id]=Math.max(e+1,o),n[i.id]=i}}const d={};for(const y in t){const e=t[y];e in d||(d[e]=[]),d[e].push(n[y])}const p={};for(const y in r){const e=r[y];e in p||(p[e]=[]),p[e].push(a[y])}let h=Object.keys(p).map((e=>parseInt(e,10))).sort(Pa);this.layers=[];for(const y of h){const e=p[y];e.sort(((e,t)=>{const n=s[e.id],r=s[t.id];return n<r?-1:n>r?1:0}));for(const t of e)t instanceof Ko&&this.internalContainerRefs.push(t),this.layers.push(t)}this.layersByDepth=p,h=Object.keys(d).map((e=>parseInt(e,10))).sort(Pa);const f=this.inputs.slice(),m=[];for(const y of h)for(const e of d[y]){const t=e.outboundLayer;if(null!=t){for(const n of e.inputTensors)if(-1===f.indexOf(n))throw new Sa(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${t.name}". The following previous layers were accessed without issue: ${m}`);for(const t of e.outputTensors)f.push(t);m.push(t.name)}}this.nodesByDepth=d;const g=this.layers.map((e=>e.name));for(const y of g){const e=g.filter((e=>e===y)).length;if(1!==e)throw new Sa(`The name "${y}" is used ${e} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new fi({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0===--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new _a("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let r=0;const a=(e=>{const t=Object.keys(e);if(0===t.length)return!1;const n=t[0].split("/");return!isNaN(parseInt(n[n.length-1],10))})(e);a&&this.parseWeights(e);for(const i of this.layers)for(const[e,t]of i.weights.entries()){const s=a?`${t.name.split("/").slice(0,-1).join("/")+"/"}${e}`:t.originalName;if(null!=n[s])throw new _a(`Duplicate weight name: ${s}`);n[s]=t,r++}const s=[];for(const i in e){let r=i;if(null==n[i]){const e=i.split("/");r=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[r])s.push([n[r],e[i]]);else if(t)throw new _a(`Provided weight data has no target variable: ${i}`);delete n[r]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new _a(`${e.length} of ${r} weights are not set: ${e}`)}ci(s)}parseWeights(e){for(const t in Object.keys(e)){const n=t.split("/"),r=["vars","layer_checkpoint_dependencies"],a=n.map((e=>e.startsWith("_")?e.slice(1):e)).filter((e=>!r.includes(e))).join("/");a!==t&&(e[a]=e[t],delete e[t])}}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Zo}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=qo(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return(0,D.DZQ)((()=>{e=Ra(e);const n=new wi;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return Si(this.outputs,n,t)}))}computeMask(e,t){return(0,D.DZQ)((()=>{let n;return e=Ra(e),n=null==t?Ca(null,e.length):Ra(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=ri(e);if(t.length!==this.inputLayers.length)throw new _a(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let i=0;i<t.length;i++){const e=this.inputLayers[i],r=t[i];n[e.name+"_0_0"]=r}const r=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(Pa);if(r.length>1)for(const i of r){const e=this.nodesByDepth[i];for(const t of e){const e=t.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(e.id))continue;const r=[];for(let i=0;i<t.inboundLayers.length;i++){const e=t.inboundLayers[i],a=t.nodeIndices[i],s=t.tensorIndices[i],o=n[`${e.name}_${a}_${s}`];r.push(o)}const a=ri(e.computeOutputShape(Aa(r))),s=e.inboundNodes.indexOf(t);for(let t=0;t<a.length;t++){n[`${e.name}_${s}_${t}`]=a[t]}}}const a=[],s=[];for(let i=0;i<this.outputLayers.length;i++){const e=this.outputLayers[i],t=this.outputLayersNodeIndices[i],n=this.outputLayersTensorIndices[i],r=`${e.name}_${t}_${n}`;s.push(r)}for(let i=0;i<s.length;i++){const e=s[i];Na(e in n),a.push(n[e])}return Aa(a)}runInternalGraph(e,t){null==t&&(t=Ca(null,e.length));const n={};for(let o=0;o<this.inputs.length;++o){const r=this.inputs[o],a=e[o],s=t[o];n[r.id]=[a,s]}const r=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(Pa);for(const o of r){const e=this.nodesByDepth[o];for(const t of e){const e=t.outboundLayer,r=t.inputTensors,a=t.outputTensors,s=new Array;for(const t of r)t.id in n&&s.push(n[t.id]);if(s.length===r.length){let r,i,o,u,l={};if(null!=t.callArgs&&(l=t.callArgs),1===s.length){const[t,n]=s[0];null==l.mask&&(l.mask=n),o=Ra(e.call(t,l)),u=Ra(e.computeMask(t,n)),r=[t],i=[n]}else r=s.map((e=>e[0])),i=s.map((e=>e[1])),null==l.mask&&(l.mask=i),o=Ra(e.call(r,l)),u=Ra(e.computeMask(r,i));if(e.activityRegularizer)throw new Ia("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<a.length;++e){const t=a[e],r=o[e],s=u[e];n[t.id]=[r,s]}}}}const a=[],s=[],i=[];for(const o of this.outputs){Na(o.id in n,`Could not compute output ${o.name} : ${o.id}`);const[e,t]=n[o.id];i.push(e.shape),a.push(e),s.push(t)}return[a,s,i]}buildNodeConversionMap(e){const t={};let n;for(const r of this.layers){n=r instanceof Ko?1:0;for(let e=0;e<r.inboundNodes.length;e++){const a=Ko.nodeKey(r,e);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(null!=t)return this.findLayer(t);if(null==e)throw new _a("Provide either a layer name or layer index");if("number"===typeof e)return this.findLayer(e);for(const n of this.layers)if(n.name===e)return n;throw new _a(`No such layer: ${e}`)}findLayer(e){if(this.layers.length<=e)throw new _a(`Was asked to retrieve layer at index ${e}, but model only has ${this.layers.length} layer(s).`);return this.layers[e]}calculateLosses(){return(0,D.DZQ)((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const r=Ko.nodeKey(t,n);this.containerNodes.has(r)&&e.push(...t.calculateLosses())}return e}))}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const i of this.layers){const e=i.getClassName(),r=i.getConfig(),a=[];for(let n=0;n<i.inboundNodes.length;n++){const e=i.inboundNodes[n],r=Ko.nodeKey(i,n);let o={};if(this.containerNodes.has(r)){if(e.callArgs)try{JSON.stringify(e.callArgs),o=e.callArgs}catch(s){o={}}if(e.inboundLayers.length>0){const n=[];for(let r=0;r<e.inboundLayers.length;r++){const a=e.inboundLayers[r],s=e.nodeIndices[r],i=e.tensorIndices[r];let u=t[Ko.nodeKey(a,s)];null==u&&(u=0),n.push([a.name,u,i,o])}a.push(n)}}}const o={};o.name=i.name,o.className=e,o.config=r,o.inboundNodes=a,n.push(o)}e.layers=n;const r=[];for(let i=0;i<this.inputLayers.length;i++){const e=this.inputLayers[i],n=this.inputLayersNodeIndices[i],a=Ko.nodeKey(e,n);if(!this.containerNodes.has(a))continue;let s=t[a];null!==s&&void 0!==s||(s=0);const o=this.inputLayersTensorIndices[i];r.push([e.name,s,o])}e.inputLayers=r;const a=[];for(let i=0;i<this.outputLayers.length;i++){const e=this.outputLayers[i],n=this.outputLayersNodeIndices[i],r=Ko.nodeKey(e,n);if(!this.containerNodes.has(r))continue;let s=t[r];null!==s&&void 0!==s||(s=0);const o=this.outputLayersTensorIndices[i];a.push([e.name,s,o])}return e.outputLayers=a,e}static fromConfig(e,t,n={},r=!1){const a={},s={};function i(e,t){e.name in s?s[e.name].push(t):s[e.name]=[t]}function o(e,t){const n=[];let r;for(const s of t){const o=s[0],u=s[1],l=s[2];if(r=null==s[3]?{}:s[3],!(o in a))return void i(e,t);const c=a[o];if(c.inboundNodes.length<=u)return void i(e,t);const d=c.inboundNodes[u];n.push(d.outputTensors[l])}n.length>0&&e.apply(Aa(n),r)}function u(e){const n=e.name,s=fo(e,null!=t.customObjects?t.customObjects:{});s.setFastWeightInitDuringBuild(r),a[n]=s;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new _a(`Corrupted configuration, expected array for nodeData: ${e}`);i(s,e)}))}const l=t.name,c=t.layers;for(const m of c)u(m);for(;!Wa(s);)for(const e of c){const t=a[e.name];if(t.name in s){const e=s[t.name];delete s[t.name];for(const n of e)o(t,n)}}const d=[],p=[],h=t.inputLayers;for(const m of h){const e=m[0],t=m[1],n=m[2];Na(e in a);const r=a[e].inboundNodes[t].outputTensors;d.push(r[n])}const f=t.outputLayers;for(const m of f){const e=m[0],t=m[1],n=m[2];Na(e in a);const r=a[e].inboundNodes[t].outputTensors;p.push(r[n])}return new e({inputs:d,outputs:p,name:l})}get stateful(){if(this._stateful)throw new _a("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){(0,D.DZQ)((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}function Yo(e,t,n){const r=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===r)return Array.isArray(e)&&1===e.length?e:"object"===typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==r)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${r} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"===typeof e&&Object.keys(e).length>0&&"object"===typeof e[Object.keys(e)[0]]){const n=[];return t.forEach((t=>{t in e?n.push(e[t]):n.push(null)})),n}throw new Error(`The model has multiple (${r}) outputs, so ${n} must be either an array with ${r} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function Qo(e,t){return Yo(e,t,"classWeight")}async function Xo(e,t,n,r){if(null!=t||null!=r)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=(0,D.DZQ)((()=>{if(1===e.shape.length)return(0,D.o8B)(e);if(2===e.shape.length){if(e.shape[1]>1){const t=1;return(0,D.FLi)(e,t)}if(1===e.shape[1])return(0,D.tQQ)(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)})),r=Array.from(await t.data());(0,D.ASo)(t);const a=[];return r.forEach((e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);a.push(n[e])})),(0,D.tGX)(a,"float32")}return null}function Jo(e,t){return(0,D.lKK)(e,t)}function eu(e,t){let n,r;const a=t;n=a.xs,r=a.ys,D.ZSL.assert(null!=n&&null!=r,(()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor.  The provided Dataset instead generates ${t}`));const s=tu("input",e.inputNames,n),i=tu("output",e.outputNames,r),o=s[0].shape[0];D.ZSL.assert(s.length===e.inputs.length,(()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs.  (Expected input keys: ${JSON.stringify(e.inputNames)})`)),D.ZSL.assert(i.length===e.outputs.length,(()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs.  (Expected output keys: ${JSON.stringify(e.outputNames)})`));for(let u=0;u<s.length;u++)D.ZSL.assert(s[u].shape[0]===o,(()=>`Batch size mismatch: input ${e.inputNames[u]} has ${s[u].shape[0]}; expected  ${o} based on input ${e.inputNames[0]}.`));for(let u=0;u<i.length;u++)D.ZSL.assert(i[u].shape[0]===o,(()=>`Batch size mismatch: output ${e.outputNames[u]} has ${i[u].shape[0]}; expected  ${o} based on input ${e.inputNames[0]}.`));return{xs:s,ys:i}}function tu(e,t,n){if(n instanceof D.qYS)return[n];if(Array.isArray(n))return D.ZSL.assert(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const r=[];for(const a of t){if(null==n[a])throw new _a(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);r.push(n[a])}return r}}async function nu(e,t,n){const r=null!=n.batchesPerEpoch;if(D.ZSL.assert(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),D.ZSL.assert(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),D.ZSL.assert(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`)),D.ZSL.assert(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),D.ZSL.assert(null==n.validationSplit,(()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead.")),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const a=null!=n.validationData;let s,i;if(a)if(ru(n.validationData))D.ZSL.assert(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),(()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`));else{const e=function(e){if(3===e.length)throw new Ia("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);s=e.xs,i=e.ys}const o=e.makeTrainFunction(),u=e.getDedupedMetricsNames();let l;l=a?u.slice().concat(u.map((e=>"val_"+e))):u.slice();const c=co(n.callbacks,n.yieldEvery),d=null==n.verbose?1:n.verbose,{callbackList:p,history:h}=ho(c,d,n.epochs,null,null,function(e,t){let n=null;null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size);return n}(t,n),null,a,l);p.setModel(e),e.history=h,await p.onTrainBegin(),e.stopTraining_=!1;let f=null==n.initialEpoch?0:n.initialEpoch,m=await t.iterator();for(;f<n.epochs;){const l={};await p.onEpochBegin(f);let c=0,d=0;for(r||(m=await t.iterator());!r||c<n.batchesPerEpoch;){const t=await m.next();if(r&&t.done)break;if(null!=t.value){const{xs:r,ys:a}=eu(e,t.value),s={};s.batch=d,s.size=r[0].shape[0],await p.onBatchBegin(d,s);const i=[];if(null!=n.classWeight){const t=Qo(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)i.push(await Xo(a[e],null,t[e]))}const l=r.concat(a).concat(i),h=o(l);D.ASo(l);for(let e=0;e<u.length;++e){const t=u[e],n=h[e];s[t]=n,D.aCs(n)}await p.onBatchEnd(d,s),ro(s),d++,c++}if(r?c>=n.batchesPerEpoch:t.done){if(a){let t;t=ru(n.validationData)?Ra(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):Ra(e.evaluate(s,i,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n<e.metricsNames.length;++n)l[`val_${e.metricsNames[n]}`]=t[n]}break}if(e.stopTraining_)break}if(await p.onEpochEnd(f,l),f++,e.stopTraining_)break}return await p.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function ru(e){return"function"===typeof e.iterator}function au(e){D.ZSL.assert(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function su(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>ws(e,t,n-t))):ws(e,t,n-t)}function iu(e,t){return D.DZQ((()=>null==e?null:Array.isArray(e)?e.map((e=>iu(e,t))):Cs(e,"int32"===t.dtype?t:D.wgE(t,"int32"))))}function ou(e,t){const n=[];let r=0,a=null;for(;r<e;)a=r+t,a>=e&&(a=e),n.push([r,a]),r=a;return n}function uu(e){const t=[];e instanceof D.qYS&&(e=[e]);for(let n=0;n<e.length;++n){const r=e[n];if(1===r.rank)t.push(xs(r,1));else{if(0===r.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(r)}}return t}function lu(e,t){if(null==e)return;const n=[];if(t instanceof D.qYS)n.push(t.id);else if(Array.isArray(t))t.forEach((e=>n.push(e.id)));else if(null!=t)for(const a in t){const e=t[a];n.push(e.id)}const r=[];if(e instanceof D.qYS)-1===n.indexOf(e.id)&&r.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&r.push(e)}));else if(null!=e)for(const a in e){const t=e[a];-1===n.indexOf(t.id)&&r.push(t)}r.forEach((e=>{e.isDisposed||e.dispose()}))}function cu(e){return Array.isArray(e)}function du(e){return!function(e){return e instanceof D.qYS}(e)&&!cu(e)}function pu(e,t,n,r=!0,a=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(cu(e)&&e.length>0)t=!0;else if(du(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new _a(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let s;if(du(e)){s=[];for(const n of t){if(null==e[n])throw new _a(`No data provided for "${n}". Need data for each key in: ${t}`);s.push(e[n])}}else if(cu(e)){if(e.length!==t.length)throw new _a(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(t.length>1)throw new _a(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=uu(s),null!=n)for(let i=0;i<t.length;++i){if(null==n[i])continue;const e=s[i];if(e.shape.length!==n[i].length)throw new _a(`Error when checking ${a}: expected ${t[i]} to have ${n[i].length} dimension(s). but got array with shape ${e.shape}`);for(let t=0;t<n[i].length;++t){if(0===t&&!r)continue;const s=e.shape[t],o=n[i][t];if(null!=o&&o>=0&&s!==o)throw new _a(`${a} expected a batch of elements where each example has shape [${n[i].slice(1,n[i].length)}] (i.e.,tensor shape [*,${n[i].slice(1,n[i].length)}]) but the ${a} received an input with ${e.shape[0]} examples, each with shape [${e.shape.slice(1,e.shape.length)}] (tensor shape [${e.shape}])`)}}return s}function hu(e,t,n,r=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new _a(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new _a(`The model expects ${t.length} ${a} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(null!=n)for(let i=0;i<t.length;++i){if(null==n[i])continue;const e=s[i];if(e.shape.length!==n[i].length)throw new _a(`Error when checking ${a}: expected ${t[i]} to have ${n[i].length} dimension(s), but got array with shape ${JSON.stringify(e.shape)}`);for(let s=0;s<n[i].length;++s){if(0===s&&!r)continue;const o=e.shape[s],u=n[i][s];if(null!=u&&u!==o)throw new _a(`Error when checking ${a}: expected ${t[i]} to have shape ${JSON.stringify(n[i])} but got array with shape ${JSON.stringify(e.shape)}.`)}}}class fu extends Ko{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new _a("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");Wo(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"===typeof e.optimizer)this.optimizer_=function(e){const t={Adagrad:()=>D.BaG.adagrad(.01),Adadelta:()=>D.BaG.adadelta(1,.95,ys()),Adam:()=>D.BaG.adam(.001,.9,.999,ys()),Adamax:()=>D.BaG.adamax(.002,.9,.999,ys(),0),RMSProp:()=>D.BaG.rmsprop(.001,.9,0,ys()),SGD:()=>D.BaG.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new _a(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof D.ELo))throw new _a("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"===typeof e.loss||"function"===typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new _a(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>To(e)))}else{const n=To(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new _a(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)e.loss[n],t.push(To(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s<this.outputs.length;++s){const e=this.internalOutputShapes[s],t=this.outputNames[s];this.feedOutputNames.push(t),this.feedOutputShapes.push(e),this.feedLossFns.push(this.lossFunctions[s])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],os("loss",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const r=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"===typeof e||"function"===typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!==typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const r of t){let t=n.hasOwnProperty(r)?n[r]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),a=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};os("metric",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;(t=>{let n,r,s;for(const i of t){if("string"===typeof i&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(i)){const t=this.internalOutputShapes[e];let a;1===t[t.length-1]||this.lossFunctions[e]===ko?-1!==["accuracy","acc"].indexOf(i)?r=$o:-1!==["crossentropy","ce"].indexOf(i)&&(r=Ro):this.lossFunctions[e]===vo?-1!==["accuracy","acc"].indexOf(i)?r=Do:-1!==["crossentropy","ce"].indexOf(i)&&(r=Mo):-1!==["accuracy","acc"].indexOf(i)?r=Co:-1!==["crossentropy","ce"].indexOf(i)&&(r=Fo),-1!==["accuracy","acc"].indexOf(i)?a="acc":-1!==["crossentropy","ce"].indexOf(i)&&(a="ce"),s=r,n=""+a}else{const e=zo(i);s=e,n=""+Lo(i)}let t;os(n,(()=>{t=s})),a(e,n,t)}})(r[e])}})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&(this.trainableWeights.length,this.collectedTrainableWeights.length)}evaluate(e,t,n={}){const r=null==n.batchSize?32:n.batchSize;au(r);const a=this.standardizeUserDataXY(e,t,!0,r);try{const e=a[0].concat(a[1]);this.makeTestFunction();const t=this.testFunction;return Aa(this.testLoop(t,e,r,n.verbose,n.steps))}finally{lu(a[0],e),lu(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const r=null!=(n=n||{}).batches,a=e.testFunction;let s=[];if(n.verbose>0)throw new Ia("Verbose mode is not implemented yet.");D.ZSL.assert(!r||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const i="function"===typeof t.next?t:await t.iterator();let o=0,u=0;for(;!r||u<n.batches;){const t=await i.next();if(s=D.DZQ((()=>{if(t.value){const{xs:n,ys:r}=eu(e,t.value),i=n.concat(r),l=D.DZQ((()=>a(i)));if(D.ASo(i),0===u)for(let e=0;e<l.length;++e)s.push((0,D.d_2)(0));const c=i[0].shape[0];for(let e=0;e<l.length;++e){const t=l[e],n=s[e];s[e]=D.DZQ((()=>D.WQq(s[e],D.lKK(c,t)))),u>0&&D.ASo(n)}D.ASo(l),o+=c,++u}return s})),t.done)break}for(let l=0;l<s.length;++l){const e=s[l];s[l]=D.y4m(s[l],o),D.ASo(e)}return Aa(s)}(this,e,t)}checkNumSamples(e,t,n,r="steps"){let a;if(null!=n){if(a=null,null!=t)throw new _a(`If ${r} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new _a(`Either the input data should have a defined shape, or ${r} shoud be specified.`);a=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return a}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new _a("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),r=n?t:[t],a=this.retrieveSymbolicTensors(r),s=new wi;if(e instanceof D.qYS&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new _a(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)s.add(this.inputs[t],e[t])}else for(const o of this.inputs){const t=e[o.name];if(null==t)throw new _a(`No value is provided for the model's input ${o.name}`);s.add(o,t)}const i=Si(a,s);return n?i:i[0]}retrieveSymbolicTensors(e){const t=Ca(null,e.length);let n=e.length;for(const r of this.layers){const a=Array.isArray(r.output)?r.output:[r.output],s=a.map((e=>e.name));for(let r=0;r<e.length;++r){const i=s.indexOf(e[r]);if(-1!==i&&(t[r]=a[i],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach(((t,r)=>{null==t&&n.push(e[r])})),new _a(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return D.DZQ((()=>{const r=this.checkNumSamples(e);if(n)throw new Ia("Verbose predictLoop() is not implemented yet.");const a=ou(r,t),s=this.outputs.map((e=>[]));for(let t=0;t<a.length;++t){D.DZQ((()=>{const n=a[t][0],r=a[t][1],s=su(e,n,r),i=[];if(Array.isArray(s))for(let e=0;e<s.length;++e)i.push({key:this.inputs[e],value:s[e]});else i.push({key:this.inputs[0],value:s});const o=new wi(i);return Si(this.outputs,o)})).forEach(((e,t)=>s[t].push(e)))}return Aa(s.map((e=>D.xWs(e,0))))}))}predict(e,t={}){const n=uu(e);hu(n,this.inputNames,this.feedInputShapes,!1);try{const e=null==t.batchSize?32:t.batchSize;return au(e),this.predictLoop(n,e)}finally{lu(n,e)}}predictOnBatch(e){hu(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,r){if(null==this.optimizer_)throw new Sa("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const a=[];for(let s=0;s<this.feedOutputShapes.length;++s){const e=this.feedOutputShapes[s];this.feedLossFns[s]===vo?a.push(e.slice(0,e.length-1).concat([1])):a.push(e)}if(function(e,t){const n=Ba(e.map((e=>e.shape[0])));n.sort();const r=Ba(t.map((e=>e.shape[0])));if(r.sort(),n.length>1)throw new _a(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(r.length>1)throw new _a(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(n.length>0&&r.length>0&&!D.ZSL.arraysEqual(n,r))throw new _a(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${r[0]} target sample(s).`)}(e=pu(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=pu(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){const r=[go,ko,wo];for(let a=0;a<e.length;++a){const s=e[a],i=t[a],o=n[a];if(null!=i){if(i===wo&&1===s.shape[s.shape.length-1])throw new _a(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==r.indexOf(i)){const e=s.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const r=e[n],a=t[n];if(null!=a&&r!==a)throw new _a(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>0&&e[0].shape[0]%r!==0)throw new _a(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${r}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,r,a=!0,s){const[i,o]=this.standardizeUserDataXY(e,t,a,s);if(null!=n)throw new Error("sample weight is not supported yet.");let u=null;if(null!=r){const e=Qo(r,this.outputNames);u=[];for(let t=0;t<e.length;++t)u.push(await Xo(o[t],null,e[t]))}return[i,o,u]}testLoop(e,t,n,r=0,a){return D.DZQ((()=>{const s=this.checkNumSamples(t,n,a,"steps"),i=[];if(r>0)throw new Ia("Verbose mode is not implemented yet.");if(null!=a)throw new Ia("steps mode in testLoop() is not implemented yet");{const r=ou(s,n),a=(0,D.tGX)(ms(0,s));for(let n=0;n<r.length;++n){const s=r[n][0],o=r[n][1],u=ws(a,s,o-s),l=iu(t,u),c=e(l);if(0===n)for(let e=0;e<c.length;++e)i.push((0,D.d_2)(0));for(let e=0;e<c.length;++e){const t=c[e];i[e]=D.WQq(i[e],D.lKK(o-s,t))}}for(let e=0;e<i.length;++e)i[e]=D.y4m(i[e],s)}return i}))}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const r=e[n];let a=r;if(Ea(e,r)>1){a+=`_${Ea(e.slice(0,n),r)}`}t.push(a)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),s=[],i=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const i=new wi(e),o=Si(this.outputs,i,{training:!0});let u;for(let n=0;n<this.lossFunctions.length;++n){let e=(0,this.lossFunctions[n])(r[n],o[n]);null!=a[n]&&(e=Jo(e,a[n]));const s=D.i2o(e);t.push(s),u=0===n?e:D.WQq(u,e)}for(let n=0;n<this.metricsTensors.length;++n){let e;if(this.outputs.length>1&&n<this.outputs.length)e=t[n];else{const t=this.metricsTensors[n][0],a=this.metricsTensors[n][1];e=D.i2o(t(r[a],o[a]))}D.aCs(e),s.push(e)}return u=D.i2o(u),this.calculateLosses().forEach((e=>{u=D.WQq(u,e)})),u}),!0,i)].concat(s)}}makeTestFunction(){this.testFunction=e=>D.DZQ((()=>{const t=[];let n;const r=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let e=0;e<this.inputs.length;++e)s.push({key:this.inputs[e],value:r[e]});const i=new wi(s),o=Si(this.outputs,i);for(let e=0;e<this.lossFunctions.length;++e){const r=this.lossFunctions[e],s=D.i2o(r(a[e],o[e]));n=0===e?s:D.WQq(n,s),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],r=this.metricsTensors[e][1],s=D.i2o(n(a[r],o[r]));t.push(s)}return t}))}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let r,a,s,i,o,u,l,c,d;this.isTraining=!0;try{const p=null==n.batchSize?32:n.batchSize;au(p);const h=!1,f=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,h,p);r=f[0],a=f[1],d=f[2];let m,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Ia("validationData including sample weights is not supported yet."):new _a(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],u=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,u,null,null,e,p);l=t[0],c=t[1],m=l.concat(c)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(r[0].shape[0]*(1-n.validationSplit)),t=r[0].shape[0];l=su(r,e,t),s=r,r=su(r,0,e),c=su(a,e,t),i=a,a=su(a,0,e),m=l.concat(c)}else null!=n.validationSteps&&(g=!0);const y=r.concat(a).concat(d);this.checkTrainableWeightsConsistency();const b=this.makeTrainFunction(),x=this.getDedupedMetricsNames();let w,v;g?(this.makeTestFunction(),w=this.testFunction,v=x.slice().concat(x.map((e=>"val_"+e)))):(w=null,m=[],v=x.slice());const k=co(n.callbacks,n.yieldEvery);return await this.fitLoop(b,y,x,p,n.epochs,n.verbose,k,w,m,n.shuffle,v,n.initialEpoch,null,null)}finally{this.isTraining=!1,lu(r,e),lu(a,t),lu(s,e),lu(i,t),lu(l,o),lu(c,u),null!=d&&D.ASo(d)}}async fitLoop(e,t,n,r,a,s,i,o,u,l,c,d,p,h){null==r&&(r=32),null==a&&(a=1),null==l&&(l=!0),null==d&&(d=0);let f=!1;if(null!=o&&null!=u&&(f=!0),null!=h&&(f=!0,null==p))throw new _a("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const m=this.checkNumSamples(t,r,p,"steps_per_epoch");let g;null!=m&&(g=ms(0,m)),null==s&&(s=1);const{callbackList:y,history:b}=ho(i,s,a,d,m,p,r,f,c);y.setModel(this),this.history=b,await y.onTrainBegin(),this.stopTraining_=!1;for(let x=d;x<a;++x){await y.onEpochBegin(x);const a={};if(null!=p)throw new Ia("stepsPerEpoch mode is not implemented yet.");{if("batch"===l)throw new Ia("batch shuffling is not implemneted yet");l&&D.ZSL.shuffle(g);const s=(0,D.tGX)(g),i=ou(m,r);for(let l=0;l<i.length;++l){const c={};if(await y.onBatchBegin(l,c),D.DZQ((()=>{const d=i[l][0],p=i[l][1],h=ws(s,d,p-d);c.batch=l,c.size=p-d;const m=iu(t,h),g=e(m);for(let e=0;e<n.length;++e){const t=n[e],r=g[e];c[t]=r,D.aCs(r)}if(l===i.length-1&&f){const e=this.testLoop(o,u,r);for(let t=0;t<n.length;++t){const r=n[t],s=e[t];D.aCs(s),a["val_"+r]=s}}})),await y.onBatchEnd(l,c),ro(c),this.stopTraining_)break}s.dispose()}if(await y.onEpochEnd(x,a),this.stopTraining_)break}return await y.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return nu(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),r=n[0],a=n[1],s=this.makeTrainFunction()(r.concat(a)),i=[];for(const o of s){const e=await o.data();i.push(e[0])}return D.ASo(s),lu(n[0],e),lu(n[1],t),Aa(i)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,r=n?this.trainableWeights:this.weights,a=this.getWeights(n);for(let s=0;s<r.length;++s)n&&!r[s].trainable||t.push({name:r[s].originalName,tensor:a[s]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=D.m1Z().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-D.m1Z().numTensors}return e}getLossIdentifiers(){let e;if("string"===typeof this.loss)e=Da(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!==typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map((e=>Da(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const r of t){if("string"!==typeof n[r])throw new Error("Serialization of non-string loss is not supported.");e[r]=Da(n[r])}}return e}getMetricIdentifiers(){if("string"===typeof this.metrics||"function"===typeof this.metrics)return[Da(Lo(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Da(Lo(e))));{const e={};for(const t in this.metrics)e[t]=Da(Lo(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=fo(jo(e.optimizer_config));let n,r;if("string"===typeof e.loss)n=Fa(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Fa(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Fa(e.loss[t])}if(Array.isArray(e.metrics))r=e.metrics.map((e=>Fa(e)));else if(null!=e.metrics){r={};for(const t in e.metrics)r[t]=Fa(e.metrics[t])}this.compile({loss:n,metrics:r,optimizer:t})}async save(e,t){if("string"===typeof e){const t=D.io.getSaveHandlers(e);if(0===t.length)throw new _a(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new _a(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new _a("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await D.io.encodeWeights(this.getNamedWeights(t)),r={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${Zo}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){r.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:a}=await D.io.encodeWeights(await this.optimizer.getWeights(),e);n.specs.push(...a),n.data=D.io.concatenateArrayBuffers([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Po(this.userDefinedMetadata,this.name,e),r.userDefinedMetadata=this.userDefinedMetadata}return r.weightData=n.data,r.weightSpecs=n.specs,e.save(r)}setUserDefinedMetadata(e){Po(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}fu.className="Model",D.JFn.registerClass(fu);class mu extends fu{}async function gu(e,t){"modelTopology"in e||(e={modelTopology:e});let n=e.modelTopology;null!=n.model_config&&(n=n.model_config);const r=fo(jo(n),t);if(null!=e.weightsManifest){const t=await D.io.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map((e=>e.originalName))),n={};for(const e of r.weights)n[e.originalName]=t[e.originalName];r.loadWeights(n),(0,D.ASo)(t)}return r}async function yu(e,t){if(null==t&&(t={}),"string"===typeof e){const n=D.io.getLoadHandlers(e,t);if(0===n.length)n.push(D.io.browserHTTPRequest(e,t));else if(n.length>1)throw new _a(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new _a("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const r=await e.load();let a=r.modelTopology;null!=a.model_config&&(a=a.model_config);const s=null==n.strict||n.strict,i=null!=r.weightData&&null!=r.weightSpecs&&s,o=fo(jo(a),t,i),u=r.trainingConfig;null!=u&&o.loadTrainingConfig(u);null!=r.userDefinedMetadata&&o.setUserDefinedMetadata(r.userDefinedMetadata);if(null!=r.weightData){if(null==r.weightSpecs)throw new _a("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=D.io.decodeWeights(e,t),r={},a=[];return t.forEach((e=>{"optimizer"===e.group?a.push({name:e.name,tensor:n[e.name]}):r[e.name]=n[e.name]})),{modelWeights:r,optimizerWeights:a}}(r.weightData,r.weightSpecs);o.loadWeights(e,s),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),(0,D.ASo)(e),(0,D.ASo)(t.map((e=>e.tensor)))}return o}(e,void 0,t)}mu.className="Functional",D.JFn.registerClass(mu);class bu extends fu{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:Ya("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new _a(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof bu||e instanceof fu;let n;if(t){if(n=e,1!==n.outputs.length)throw new _a("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new _a("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new _a("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=xi({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new _a(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new _a("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=yi(this.outputs[0])}this.inboundNodes=[],new fi({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Ca(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(si(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new fu({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new Sa("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new Sa("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new Sa("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new Sa("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},r=!1){let a,s={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new _a("Legacy serialization format not supported yet.");a=t}else D.ZSL.assert(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),a=t.layers,delete t.layers,s=t;const i=new e(s);if(!(i instanceof bu))throw new Ia(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const o of a){const e=fo(o,void 0,r);r&&e.setFastWeightInitDuringBuild(!0),i.add(e)}return i}set stopTraining(e){if(null==this.model)throw new _a("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new _a("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}function xu(e){return new fu(e)}function wu(e){return new bu(e)}function vu(e){return xi(e)}function ku(e,t){po.registerCallbackConstructor(e,t)}bu.className="Sequential",D.JFn.registerClass(bu);class Su extends D.JFn.Serializable{getConfig(){return{}}}class _u extends Su{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Ia(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return D.Pqc(e)}(e,t)}}_u.className="elu",D.JFn.registerClass(_u);class Iu extends Su{apply(e){return D.WfX(e)}}Iu.className="selu",D.JFn.registerClass(Iu);class Tu extends Su{apply(e){return D.VVh(e)}}Tu.className="relu",D.JFn.registerClass(Tu);class $u extends Su{apply(e){return(0,D.DZQ)((()=>D.BpO(6,D.VVh(e))))}}$u.className="relu6",D.JFn.registerClass($u);class Cu extends Su{apply(e){return e}}Cu.className="linear",D.JFn.registerClass(Cu);class Nu extends Su{apply(e){return D.ry7(e)}}Nu.className="sigmoid",D.JFn.registerClass(Nu);class Eu extends Su{apply(e){return function(e){return(0,D.DZQ)((()=>{const t=D.WQq(.5,D.lKK(.2,e));return D.zQh(t,0,1)}))}(e)}}Eu.className="hardSigmoid",D.JFn.registerClass(Eu);class Au extends Su{apply(e){return D.lw0(e)}}Au.className="softplus",D.JFn.registerClass(Au);class Ru extends Su{apply(e){return function(e){return(0,D.DZQ)((()=>D.y4m(e,D.WQq(D.tnl(e),1))))}(e)}}Ru.className="softsign",D.JFn.registerClass(Ru);class Du extends Su{apply(e){return D.ymU(e)}}Du.className="tanh",D.JFn.registerClass(Du);class Fu extends Su{apply(e,t=-1){return D.Vs9(e,t)}}Fu.className="softmax",D.JFn.registerClass(Fu);class Mu extends Su{apply(e,t=-1){return D.HPB(e,t)}}Mu.className="logSoftmax",D.JFn.registerClass(Mu);class Ou extends Su{apply(e){return(0,D.DZQ)((()=>D.DZQ((()=>{const t=Math.sqrt(2),n=D.lKK(.5,D.WQq(1,D.Y12(D.y4m(e,t))));return D.lKK(e,n)}))))}}Ou.className="gelu",D.JFn.registerClass(Ou);class zu extends Su{apply(e){return(0,D.DZQ)((()=>D.lKK(.5,D.lKK(e,D.WQq(1,D.ymU(D.lKK(D.RZD(D.y4m(2,Math.PI)),D.WQq(e,D.lKK(.044715,D.n7C(e,3))))))))))}}zu.className="gelu_new",D.JFn.registerClass(zu);class Lu extends Su{apply(e){return(0,D.DZQ)((()=>D.lKK(e,D.ymU(D.lw0(e)))))}}Lu.className="mish",D.JFn.registerClass(Lu);class Pu extends Su{apply(e,t=1){return(0,D.DZQ)((()=>D.lKK(D.ry7(D.lKK(e,t)),e)))}}function Bu(e){return e.getClassName()}function Wu(e,t={}){return La(e,D.JFn.SerializationMap.getMap().classNameMap,t,"activation")}function Vu(e){if(null==e){const e={className:"linear",config:{}};return Wu(e)}if("string"===typeof e){const t={};return t.className=e,t.config={},Wu(t)}return e instanceof Su?e:Wu(e)}function Uu(e){if(null!=e&&"object"!==typeof e)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}Pu.className="swish",D.JFn.registerClass(Pu);class Gu extends D.JFn.Serializable{}class Hu extends Gu{constructor(e){super(),Uu(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return(0,D.DZQ)((()=>{let t=(0,D.Ul9)([1]);return this.hasL1&&(t=(0,D.WQq)(t,(0,D.czq)(D.lKK(this.l1,(0,D.tnl)(e))))),this.hasL2&&(t=(0,D.WQq)(t,(0,D.czq)(D.lKK(this.l2,Ns(e))))),D.tQQ(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Hu.className="L1L2",D.JFn.registerClass(Hu);const ju={l1l2:"L1L2"};function qu(e){return Oa(e)}function Zu(e,t={}){return La(e,D.JFn.SerializationMap.getMap().classNameMap,t,"regularizer")}function Ku(e){if(null==e)return null;if("string"===typeof e){return Zu({className:e in ju?ju[e]:e,config:{}})}return e instanceof Gu?e:Zu(e)}class Yu extends gi{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=ai(e);let n=(0,D.VVh)(e);return null!=this.maxValue&&(n=(0,D.zQh)(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Yu.className="ReLU",D.JFn.registerClass(Yu);class Qu extends gi{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=ai(e);return(0,D.H8d)(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Qu.className="LeakyReLU",D.JFn.registerClass(Qu);class Xu extends gi{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=ti(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Ku(e.alphaRegularizer),this.alphaConstraint=Oi(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!==typeof e.sharedAxes)throw new _a(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=si(e)).slice(1);if(null!=this.sharedAxes)for(const r of this.sharedAxes)t[r-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let r=1;r<e.length;++r)n[r]=e[r];this.inputSpec=[new di({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=ai(e),(0,D.NsG)(e,this.alpha.read())}getConfig(){const e={alphaInitializer:ei(this.alphaInitializer),alphaRegularizer:qu(this.alphaRegularizer),alphaConstraint:Fi(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Xu.className="PReLU",D.JFn.registerClass(Xu);class Ju extends gi{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new Ia(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=ai(e);return(0,D.Pqc)(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Ju.className="ELU",D.JFn.registerClass(Ju);class el extends gi{constructor(e){super(null==e?{}:e),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,t){const n=ai(e);return(0,D.lKK)(n,(0,D.wgE)((0,D.rhj)(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}el.className="ThresholdedReLU",D.JFn.registerClass(el);class tl extends gi{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new Fu).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){return(0,D.DZQ)((()=>{let n=ai(e);const r=t.mask;if(null!=r){const e=(0,D.lKK)((0,D.jbE)((0,D.SaS)(n.shape),(0,D.wgE)(r,n.dtype)),(0,D.d_2)(-1e9));n=(0,D.WQq)(n,e)}return this.axis instanceof Array?this.axis.length>1?(0,D.oNF)((0,D.jbE)(n,(0,D.VZ)(n,this.axis,!0))):this.softmax(n,this.axis[0]):this.softmax(n,this.axis)}))}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function nl(e,t,n){if("number"===typeof e)return Ca(e,t);if(e.length!==t)throw new _a(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let a=0;a<t;++a){const s=e[a];if((r=s)!==parseInt(r.toString(),10))throw new _a(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${s}`)}return e;var r}function rl(e,t,n,r,a=1){if(null==e)return e;let s;return s="same"===n?e:e-(t+(t-1)*(a-1))+1,Math.floor((s+r-1)/r)}function al(e,t,n,r){if(null==e)return null;if("valid"===r)e=e*t+fs([n-t,0]);else{if("same"!==r)throw new _a(`Unsupport padding mode: ${r}.`);e*=t}return e}function sl(e,t){return(0,D.DZQ)((()=>(rs(t),"channelsFirst"===t?D.mgz(e,[0,2,3,1]):e)))}function il(e,t){return(0,D.DZQ)((()=>(rs(t),"channelsFirst"===t?D.mgz(e,[0,2,3,4,1]):e)))}function ol(e,t,n,r=1,a="valid",s,i=1){return(0,D.DZQ)((()=>{if(null==s&&(s="channelsLast"),rs(s),3!==e.shape.length)throw new _a(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new _a(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new _a(`The bias for a conv1dWithBias operation should be 1, but is ${n.shape.length} instead`);if("channelsFirst"===s&&(e=D.mgz(e,[0,2,1])),"causal"===a)throw new Ia("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=D.kA9(e,t,r,"same"===a?"same":"valid","NWC",i);return null!=n&&(o=As(o,n)),o}))}function ul(e,t,n,r=[1,1],a="valid",s,i,o=null){return(0,D.DZQ)((()=>{if(null==s&&(s="channelsLast"),rs(s),3!==e.rank&&4!==e.rank)throw new _a(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new _a(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let u=sl(e,s);if("causal"===a)throw new Ia("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return u=D.cZk.conv2d({x:u,filter:t,strides:r,pad:"same"===a?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===s&&(u=D.mgz(u,[0,3,1,2])),u}))}function ll(e,t,n,r=[1,1,1],a="valid",s,i){return(0,D.DZQ)((()=>{if(null==s&&(s="channelsLast"),rs(s),4!==e.rank&&5!==e.rank)throw new _a(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new _a(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=il(e,s);if("causal"===a)throw new Ia("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=D.IPL(o,t,r,"same"===a?"same":"valid","NDHWC",i),null!=n&&(o=As(o,n)),"channelsFirst"===s&&(o=D.mgz(o,[0,4,1,2,3])),o}))}tl.className="Softmax",D.JFn.registerClass(tl);class cl extends gi{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",cl.verifyArgs(t),this.rank=e,Ga(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Ia(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=nl(t.kernelSize,e,"kernelSize"),this.strides=nl(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,as(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,rs(this.dataFormat),this.activation=Vu(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=ti(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Oi(t.biasConstraint),this.biasRegularizer=Ku(t.biasRegularizer),this.activityRegularizer=Ku(t.activityRegularizer),this.dilationRate=nl(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new _a(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"===typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new _a(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"===typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new _a(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Na("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!==typeof e.kernelSize&&!Ua(e.kernelSize,"number",1,3))throw new _a(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Bu(this.activation),useBias:this.useBias,biasInitializer:ei(this.biasInitializer),biasRegularizer:qu(this.biasRegularizer),activityRegularizer:qu(this.activityRegularizer),biasConstraint:Fi(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class dl extends cl{constructor(e,t){super(e,t),this.kernel=null,dl.verifyArgs(t),this.filters=t.filters,Ga(this.filters,"filters"),this.kernelInitializer=ti(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Oi(t.kernelConstraint),this.kernelRegularizer=Ku(t.kernelRegularizer)}build(e){e=si(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new _a(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],r=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return(0,D.DZQ)((()=>{let t;e=ai(e);const n=null==this.bias?null:this.bias.read(),r=ja(this.activation.getClassName());if(null!=r&&2===this.rank)t=ul(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(1===this.rank)t=ol(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=ul(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Ia("convolutions greater than 3D are not implemented yet.");t=ll(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=si(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let a=0;a<n.length;++a){const e=rl(n[a],this.kernelSize[a],this.padding,this.strides[a],"number"===typeof this.dilationRate?this.dilationRate:this.dilationRate[a]);t.push(e)}let r=[e[0]];return"channelsLast"===this.dataFormat?(r=r.concat(t),r.push(this.filters)):(r.push(this.filters),r=r.concat(t)),r}getConfig(){const e={filters:this.filters,kernelInitializer:ei(this.kernelInitializer),kernelRegularizer:qu(this.kernelRegularizer),kernelConstraint:Fi(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!==typeof e.filters||e.filters<1)throw new _a(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class pl extends dl{constructor(e){super(2,e),pl.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!==typeof e.kernelSize&&!Ua(e.kernelSize,"number",1,2))throw new _a(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}pl.className="Conv2D",D.JFn.registerClass(pl);class hl extends dl{constructor(e){super(3,e),hl.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!==typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new _a(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}hl.className="Conv3D",D.JFn.registerClass(hl);class fl extends pl{constructor(e){if(super(e),this.inputSpec=[new di({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new _a(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=si(e)).length)throw new _a("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new _a("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new di({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return D.DZQ((()=>{let t=ai(e);if(4!==t.shape.length)throw new _a(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,r=n[0];let a,s;"channelsFirst"===this.dataFormat?(a=2,s=3):(a=1,s=2);const i=n[a],o=n[s],u=this.kernelSize[0],l=this.kernelSize[1],c=this.strides[0],d=this.strides[1],p=[r,al(i,c,u,this.padding),al(o,d,l,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=D.mgz(t,[0,2,3,1]));let h=D.wX9(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(h=D.mgz(h,[0,3,1,2])),null!=this.bias&&(h=As(h,this.bias.read(),this.dataFormat)),null!=this.activation&&(h=this.activation.apply(h)),h}))}computeOutputShape(e){const t=(e=si(e)).slice();let n,r,a;"channelsFirst"===this.dataFormat?(n=1,r=2,a=3):(n=3,r=1,a=2);const s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],u=this.strides[1];return t[n]=this.filters,t[r]=al(t[r],o,s,this.padding),t[a]=al(t[a],u,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}fl.className="Conv2DTranspose",D.JFn.registerClass(fl);class ml extends hl{constructor(e){if(super(e),this.inputSpec=[new di({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new _a(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=si(e)).length)throw new _a("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new _a("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new di({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return D.DZQ((()=>{let t=ai(e);if(5!==t.shape.length)throw new _a(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,r=n[0];let a,s,i;"channelsFirst"===this.dataFormat?(i=2,a=3,s=4):(i=1,a=2,s=3);const o=n[i],u=n[a],l=n[s],c=this.kernelSize[0],d=this.kernelSize[1],p=this.kernelSize[2],h=this.strides[0],f=this.strides[1],m=this.strides[2],g=[r,al(o,h,c,this.padding),al(u,f,d,this.padding),al(l,m,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=D.mgz(t,[0,2,3,4,1]));let y=D.jIJ(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=D.mgz(y,[0,4,1,2,3])),null!==this.bias&&(y=As(y,this.bias.read(),this.dataFormat)),null!==this.activation&&(y=this.activation.apply(y)),y}))}computeOutputShape(e){const t=(e=si(e)).slice();let n,r,a,s;"channelsFirst"===this.dataFormat?(n=1,r=2,a=3,s=4):(n=4,r=1,a=2,s=3);const i=this.kernelSize[0],o=this.kernelSize[1],u=this.kernelSize[2],l=this.strides[0],c=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[r]=al(t[r],l,i,this.padding),t[a]=al(t[a],c,o,this.padding),t[s]=al(t[s],d,u,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}ml.className="Conv3DTranspose",D.JFn.registerClass(ml);class gl extends dl{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new _a("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new _a("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new _a(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=ti(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Ku(t.depthwiseRegularizer),this.depthwiseConstraint=Oi(t.depthwiseConstraint),this.pointwiseInitializer=ti(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Ku(t.pointwiseRegularizer),this.pointwiseConstraint=Oi(t.pointwiseConstraint)}build(e){if((e=si(e)).length<this.rank+2)throw new _a(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new _a(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],r=this.kernelSize.concat([n,this.depthMultiplier]),a=[];for(let i=0;i<this.rank;++i)a.push(1);a.push(n*this.depthMultiplier,this.filters);const s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",r,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new di({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return(0,D.DZQ)((()=>{let t;if(e=ai(e),1===this.rank)throw new Ia("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=D.mgz(e,[0,2,3,1])),t=D.wdz(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=As(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=D.mgz(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=ei(this.depthwiseInitializer),e.pointwiseInitializer=ei(this.pointwiseInitializer),e.depthwiseRegularizer=qu(this.depthwiseRegularizer),e.pointwiseRegularizer=qu(this.pointwiseRegularizer),e.depthwiseConstraint=Fi(this.depthwiseConstraint),e.pointwiseConstraint=Fi(this.pointwiseConstraint),e}}gl.className="SeparableConv";class yl extends gl{constructor(e){super(2,e)}}yl.className="SeparableConv2D",D.JFn.registerClass(yl);class bl extends dl{constructor(e){super(1,e),bl.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!==typeof e.kernelSize&&!Ua(e.kernelSize,"number",1,1))throw new _a(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}bl.className="Conv1D",D.JFn.registerClass(bl);class xl extends gi{constructor(e){super(e),"number"===typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"===typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return(0,D.DZQ)((()=>{if(e=ai(e),"channelsLast"===this.dataFormat){const t=ks(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return ks(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=ks(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return ks(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}xl.className="Cropping2D",D.JFn.registerClass(xl);class wl extends gi{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,rs(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,Va(Xa,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return D.DZQ((()=>{let t=ai(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=D.mgz(t,[0,2,3,1]);const e=this.size[0]*n[2],r=this.size[1]*n[3],a="nearest"===this.interpolation?D.Slp.resizeNearestNeighbor(t,[e,r]):D.Slp.resizeBilinear(t,[e,r]);return D.mgz(a,[0,3,1,2])}{const e=this.size[0]*n[1],r=this.size[1]*n[2];return"nearest"===this.interpolation?D.Slp.resizeNearestNeighbor(t,[e,r]):D.Slp.resizeBilinear(t,[e,r])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}wl.className="UpSampling2D",D.JFn.registerClass(wl);class vl extends cl{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=ti(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Oi(e.depthwiseConstraint),this.depthwiseRegularizer=Ku(e.depthwiseRegularizer)}build(e){if((e=si(e)).length<4)throw new _a(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new _a(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return(0,D.DZQ)((()=>{let t=function(e,t,n=[1,1],r="valid",a,s){return(0,D.DZQ)((()=>{null==a&&(a="channelsLast"),rs(a);let i=sl(e,a);if(4!==e.rank)throw new _a(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new _a(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=D.Gl3(i,t,n,"same"===r?"same":"valid","NHWC",s),"channelsFirst"===a&&(i=D.mgz(i,[0,3,1,2])),i}))}(e=ai(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=As(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=si(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=rl(t,this.kernelSize[0],this.padding,this.strides[0]),s=rl(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],r,a,s]:[e[0],a,s,r]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=ei(this.depthwiseInitializer),e.depthwiseRegularizer=qu(this.depthwiseRegularizer),e.depthwiseConstraint=Fi(this.depthwiseRegularizer),e}}function kl(e,t,n,r){if(Array.isArray(e)){if(null!=t||null!=n)throw new _a("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:n=a(n)}}function Sl(e,t,n,r=!1,a,s,i=!1,o=!1){return D.DZQ((()=>{const i=t.shape.length;if(i<3)throw new _a(`Input should be at least 3D, but is ${i}D.`);const u=[1,0].concat(ms(2,i));if(t=D.mgz(t,u),null!=s)throw new Ia("The rnn() functoin of the deeplearn.js backend does not support constants yet.");null!=a&&((a=D.wgE(D.wgE(a,"bool"),"float32")).rank===i-1&&(a=D.UG6(a,-1)),a=D.mgz(a,u)),r&&(t=D.BEg(t,0),null!=a&&(a=D.BEg(a,0)));const l=[];let c,d=n;const p=t.shape[0],h=D.K$i(t);let f,m;null!=a&&(f=D.K$i(a));for(let t=0;t<p;++t){const n=h[t],r=D.DZQ((()=>e(n,d)));if(null==a)c=r[0],d=r[1];else{const e=D.DZQ((()=>{const e=f[t],n=D.jbE(D.P61(e),e);return{output:D.WQq(D.lKK(r[0],e),D.lKK(d[0],n)),newStates:d.map(((t,a)=>D.WQq(D.lKK(r[1][a],e),D.lKK(t,n))))}}));c=e.output,d=e.newStates}o&&l.push(c)}if(o){const e=1;m=D.t$z(l,e)}return[c,m,d]}))}vl.className="DepthwiseConv2D",D.JFn.registerClass(vl);class _l extends gi{constructor(e){let t;if(super(e),null==e.cell)throw new _a("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Rl({cells:e.cell}):e.cell,null==t.stateSize)throw new _a("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new di({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return ms(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){ni(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let r;if(r=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const r of t)n.push([e[0],r]);return[r].concat(n)}return r}computeMask(e,t){return D.DZQ((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new Ia("Constants support is not implemented in RNN yet.");ni(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new di({shape:[t,null,...n]});const r=[e[0]].concat(e.slice(2));let a;if(this.cell.build(r),a=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!D.ZSL.arraysEqual(this.stateSpec.map((e=>e.shape[e.shape.length-1])),a))throw new _a(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map((e=>new di({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){(0,D.DZQ)((()=>{if(!this.stateful)throw new ka("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new _a("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>D.Ul9([n,e]))):this.states_=[D.Ul9([n,this.cell.stateSize])];else if(null==e)D.ASo(this.states_),null!=this.keptStates&&(D.ASo(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>D.Ul9([n,e]))):this.states_[0]=D.Ul9([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new _a(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):D.ASo(this.states_);for(let t=0;t<this.states_.length;++t){const r=e[t],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,s=[n,a];if(!D.ZSL.arraysEqual(r.shape,s))throw new _a(`State ${t} is incompatible with layer ${this.name}: expected shape=${s}, received shape=${r.shape}`);this.states_[t]=r}}this.states_=this.states_.map((e=>D.aCs(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,r=null==t?null:t.constants;null==t&&(t={});const a=kl(e,n,r,this.numConstants);e=a.inputs,n=a.initialState,r=a.constants;let s=[],i=[];if(null!=n){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new di({shape:e.shape}));i=i.concat(this.stateSpec)}null!=r&&(t.constants=r,s=s.concat(r),this.numConstants=r.length);if(s[0]instanceof pi){const n=[e].concat(s),r=this.inputSpec.concat(i),a=this.inputSpec;this.inputSpec=r;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return(0,D.DZQ)((()=>{const n=null==t?null:t.mask,r=null==t?null:t.training;let a=null==t?null:t.initialState;e=ai(e),null==a&&(a=this.stateful?this.states_:this.getInitialState(e));const s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==s)throw new _a(`RNN Layer has ${s} state(s) but was passed ${a.length} initial state(s).`);this.unroll;const i={training:r},o=Sl(((e,t)=>{const n=this.cell.call([e].concat(t),i);return[n[0],n.slice(1)]}),e,a,this.goBackwards,n,null,this.unroll,this.returnSequences),u=o[0],l=o[1],c=o[2];this.stateful&&this.resetStates(c,r);const d=this.returnSequences?l:u;return this.returnState?[d].concat(c):d}))}getInitialState(e){return(0,D.DZQ)((()=>{let t=D.Ul9(e.shape);return t=D.czq(t,[1,2]),t=xs(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Is(t,[1,e]):t)):this.cell.stateSize>1?[Is(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===_l.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const r=fo(t.cell,n);return new e(Object.assign(t,{cell:r}))}}_l.className="RNN",D.JFn.registerClass(_l);class Il extends gi{}class Tl extends Il{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Ga(this.units,"units"),this.activation=Vu(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=ti(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ti(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ti(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ku(e.kernelRegularizer),this.recurrentRegularizer=Ku(e.recurrentRegularizer),this.biasRegularizer=Ku(e.biasRegularizer),this.kernelConstraint=Oi(e.kernelConstraint),this.recurrentConstraint=Oi(e.recurrentConstraint),this.biasConstraint=Oi(e.biasConstraint),this.dropout=hs([1,fs([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=hs([1,fs([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=si(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return(0,D.DZQ)((()=>{if(2!==e.length)throw new _a(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const r=null!=t.training&&t.training;let a;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Dl({ones:()=>D.P61(e),rate:this.dropout,training:r,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Dl({ones:()=>D.P61(n),rate:this.recurrentDropout,training:r,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,i=this.recurrentDropoutMask;a=$s(null!=s?D.lKK(e,s):e,this.kernel.read()),null!=this.bias&&(a=As(a,this.bias.read())),null!=i&&(n=D.lKK(n,i));let o=D.WQq(a,$s(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Bu(this.activation),useBias:this.useBias,kernelInitializer:ei(this.kernelInitializer),recurrentInitializer:ei(this.recurrentInitializer),biasInitializer:ei(this.biasInitializer),kernelRegularizer:qu(this.kernelRegularizer),recurrentRegularizer:qu(this.recurrentRegularizer),biasRegularizer:qu(this.biasRegularizer),activityRegularizer:qu(this.activityRegularizer),kernelConstraint:Fi(this.kernelConstraint),recurrentConstraint:Fi(this.recurrentConstraint),biasConstraint:Fi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}Tl.className="SimpleRNNCell",D.JFn.registerClass(Tl);class $l extends _l{constructor(e){e.cell=new Tl(e),super(e)}call(e,t){return(0,D.DZQ)((()=>{null!=this.cell.dropoutMask&&(D.ASo(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(D.ASo(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:a})}))}static fromConfig(e,t){return new e(t)}}$l.className="SimpleRNN",D.JFn.registerClass($l);class Cl extends Il{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new _a("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Ga(this.units,"units"),this.activation=Vu(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vu(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=ti(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ti(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ti(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ku(e.kernelRegularizer),this.recurrentRegularizer=Ku(e.recurrentRegularizer),this.biasRegularizer=Ku(e.biasRegularizer),this.kernelConstraint=Oi(e.kernelConstraint),this.recurrentConstraint=Oi(e.recurrentConstraint),this.biasConstraint=Oi(e.biasConstraint),this.dropout=hs([1,fs([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=hs([1,fs([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=si(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return(0,D.DZQ)((()=>{if(2!==e.length)throw new _a(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let r=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Dl({ones:()=>D.P61(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Dl({ones:()=>D.P61(r),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,s=this.recurrentDropoutMask;let i,o,u;0<this.dropout&&this.dropout<1&&(e=D.lKK(e,a[0]));let l=$s(e,this.kernel.read());this.useBias&&(l=As(l,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(r=D.lKK(r,s[0]));const c=this.recurrentKernel.read(),[d,p]=D.lDo(c,[2*this.units,this.units],c.rank-1),h=$s(r,d),[f,m,g]=D.lDo(l,3,l.rank-1),[y,b]=D.lDo(h,2,h.rank-1);i=this.recurrentActivation.apply(D.WQq(f,y)),o=this.recurrentActivation.apply(D.WQq(m,b));const x=$s(D.lKK(o,r),p);u=this.activation.apply(D.WQq(g,x));const w=D.WQq(D.lKK(i,r),D.lKK(D.WQq(1,D.HZy(i)),u));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Bu(this.activation),recurrentActivation:Bu(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ei(this.kernelInitializer),recurrentInitializer:ei(this.recurrentInitializer),biasInitializer:ei(this.biasInitializer),kernelRegularizer:qu(this.kernelRegularizer),recurrentRegularizer:qu(this.recurrentRegularizer),biasRegularizer:qu(this.biasRegularizer),activityRegularizer:qu(this.activityRegularizer),kernelConstraint:Fi(this.kernelConstraint),recurrentConstraint:Fi(this.recurrentConstraint),biasConstraint:Fi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Cl.className="GRUCell",D.JFn.registerClass(Cl);class Nl extends _l{constructor(e){e.implementation,e.cell=new Cl(e),super(e)}call(e,t){return(0,D.DZQ)((()=>{null!=this.cell.dropoutMask&&(D.ASo(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(D.ASo(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Nl.className="GRU",D.JFn.registerClass(Nl);class El extends Il{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Ga(this.units,"units"),this.activation=Vu(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vu(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=ti(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ti(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ti(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Ku(e.kernelRegularizer),this.recurrentRegularizer=Ku(e.recurrentRegularizer),this.biasRegularizer=Ku(e.biasRegularizer),this.kernelConstraint=Oi(e.kernelConstraint),this.recurrentConstraint=Oi(e.recurrentConstraint),this.biasConstraint=Oi(e.biasConstraint),this.dropout=hs([1,fs([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=hs([1,fs([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=si(e))[e.length-1];let r;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;r=new((t=class extends Os{apply(t,r){const a=e.apply([n]),s=(new Ls).apply([n]),i=e.apply([2*n]);return _s(_s(a,s),i)}}).className="CustomInit",t)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return(0,D.DZQ)((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new _a(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=e[1];const a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Dl({ones:()=>D.P61(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Dl({ones:()=>D.P61(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,i=this.recurrentDropoutMask;let o,u,l,c;0<this.dropout&&this.dropout<1&&(e=D.lKK(e,s[0]));let d=$s(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(r=D.lKK(r,i[0])),d=D.WQq(d,$s(r,this.recurrentKernel.read())),this.useBias&&(d=As(d,this.bias.read()));const[p,h,f,m]=D.lDo(d,4,d.rank-1);o=this.recurrentActivation.apply(p),u=this.recurrentActivation.apply(h),l=D.WQq(D.lKK(u,a),D.lKK(o,this.activation.apply(f))),c=this.recurrentActivation.apply(m);const g=D.lKK(c,this.activation.apply(l));return[g,g,l]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Bu(this.activation),recurrentActivation:Bu(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ei(this.kernelInitializer),recurrentInitializer:ei(this.recurrentInitializer),biasInitializer:ei(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:qu(this.kernelRegularizer),recurrentRegularizer:qu(this.recurrentRegularizer),biasRegularizer:qu(this.biasRegularizer),activityRegularizer:qu(this.activityRegularizer),kernelConstraint:Fi(this.kernelConstraint),recurrentConstraint:Fi(this.recurrentConstraint),biasConstraint:Fi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}El.className="LSTMCell",D.JFn.registerClass(El);class Al extends _l{constructor(e){e.implementation,e.cell=new El(e),super(e)}call(e,t){return(0,D.DZQ)((()=>{null!=this.cell.dropoutMask&&(D.ASo(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(D.ASo(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,r=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Al.className="LSTM",D.JFn.registerClass(Al);class Rl extends Il{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return(0,D.DZQ)((()=>{let n=e.slice(1);const r=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?r.push(n.splice(0,e.stateSize.length)):r.push(n.splice(0,1));r.reverse();const a=[];let s;for(let i=0;i<this.cells.length;++i){const o=this.cells[i];n=r[i],s=0===i?[e[0]].concat(n):[s[0]].concat(n),s=o.call(s,t),a.push(s.slice(1))}n=[];for(const e of a.slice().reverse())n.push(...e);return[s[0]].concat(n)}))}build(e){let t;ni(e)&&(e=e[0]),this.cells.forEach(((n,r)=>{os(`RNNCell_${r}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const r=[];for(const a of t.cells)r.push(fo(a,n));return new e({cells:r})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return li(e)}setWeights(e){const t=[];for(const n of this.cells){const r=n.weights.length,a=e.splice(r);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],a[e]])}ci(t)}}function Dl(e){const{ones:t,rate:n,training:r=!1,count:a=1,dropoutFunc:s}=e,i=()=>null!=s?s(t(),n):Rs(t(),n),o=()=>Ds(i,t,r);if(!a||a<=1)return D.aCs(o().clone());return Array(a).fill(void 0).map(o).map((e=>D.aCs(e.clone())))}Rl.className="StackedRNNCells",D.JFn.registerClass(Rl);var Fl=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n};class Ml extends _l{constructor(e){if(e.unroll)throw new Ia("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Ia("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new di({ndim:5})]}call(e,t){return D.DZQ((()=>{if(null!=this.cell.dropoutMask&&(D.ASo(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(D.ASo(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new _a("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,r=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:a})}))}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return D.DZQ((()=>{const{stateSize:t}=this.cell,n=e.shape,r=this.computeSingleOutputShape(n),a=[r[0],...r.slice(2)],s=D.Ul9(a);return Array.isArray(t)?Array(t.length).fill(s):[s]}))}resetStates(e,t=!1){D.DZQ((()=>{if(!this.stateful)throw new ka("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,r=this.computeSingleOutputShape(n),a=[r[0],...r.slice(2)];if(null==n[0])throw new _a("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>D.Ul9(a))):this.states_=[D.Ul9(a)];else if(null==e)D.ASo(this.states_),null!=this.keptStates&&(D.ASo(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>D.Ul9(a))):this.states_[0]=D.Ul9(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new _a(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):D.ASo(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],r=a;if(!D.ZSL.arraysEqual(n.shape,r))throw new _a(`State ${t} is incompatible with layer ${this.name}: expected shape=${r}, received shape=${n.shape}`);this.states_[t]=n}}this.states_=this.states_.map((e=>D.aCs(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:r,padding:a,strides:s,dilationRate:i}=this.cell,o="channelsFirst"===t,u=e[o?3:2],l=e[o?4:3],c=rl(u,r[0],a,s[0],i[0]),d=rl(l,r[1],a,s[1],i[1]);return[...e.slice(0,2),...o?[n,c,d]:[c,d,n]]}}Ml.className="ConvRNN2D";class Ol extends El{constructor(e){const{filters:t,kernelSize:n,strides:r,padding:a,dataFormat:s,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,Ga(this.filters,"filters"),this.kernelSize=nl(n,2,"kernelSize"),this.kernelSize.forEach((e=>Ga(e,"kernelSize"))),this.strides=nl(r||1,2,"strides"),this.strides.forEach((e=>Ga(e,"strides"))),this.padding=a||"valid",as(this.padding),this.dataFormat=s||"channelsLast",rs(this.dataFormat),this.dilationRate=nl(i||1,2,"dilationRate"),this.dilationRate.forEach((e=>Ga(e,"dilationRate")))}build(e){var t;e=si(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new _a(`The channel dimension of the input should be defined. Found ${e[n]}`);const r=e[n],a=this.kernelSize.concat([r,4*this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const s=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",s,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,r=this.filters;e=new((t=class extends Os{apply(e,t){return Ss([n.apply([r]),D.SaS([r]),n.apply([2*r])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return D.DZQ((()=>{if(3!==e.length)throw new _a(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,r=e[0],a=e[1],s=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Dl({ones:()=>D.P61(r),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?D.lKK(t[n],e):e;let u=o(r,i,0),l=o(r,i,1),c=o(r,i,2),d=o(r,i,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Dl({ones:()=>D.P61(a),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const p=this.recurrentDropoutMask;let h=o(a,p,0),f=o(a,p,1),m=o(a,p,2),g=o(a,p,3);const[y,b,x,w]=D.lDo(this.kernel.read(),4,3),[v,k,S,_]=this.useBias?D.lDo(this.bias.read(),4):[null,null,null,null];u=this.inputConv(u,y,v,this.padding),l=this.inputConv(l,b,k,this.padding),c=this.inputConv(c,x,S,this.padding),d=this.inputConv(d,w,_,this.padding);const[I,T,$,C]=D.lDo(this.recurrentKernel.read(),4,3);h=this.recurrentConv(h,I),f=this.recurrentConv(f,T),m=this.recurrentConv(m,$),g=this.recurrentConv(g,C);const N=this.recurrentActivation.apply(D.WQq(u,h)),E=this.recurrentActivation.apply(D.WQq(l,f)),A=D.WQq(D.lKK(E,s),D.lKK(N,this.activation.apply(D.WQq(c,m)))),R=D.lKK(this.recurrentActivation.apply(D.WQq(d,g)),this.activation.apply(A));return[R,R,A]}))}getConfig(){const e=super.getConfig(),{units:t}=e,n=Fl(e,["units"]),r={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),r)}inputConv(e,t,n,r){const a=D.Xtf(e,t,this.strides,r||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?As(a,n,this.dataFormat):a}recurrentConv(e,t){return D.Xtf(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}Ol.className="ConvLSTM2DCell",D.JFn.registerClass(Ol);class zl extends Ml{constructor(e){const t=new Ol(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}zl.className="ConvLSTM2D",D.JFn.registerClass(zl);class Ll extends gi{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let r=0;r<this.noiseShape.length;++r)n.push(null==this.noiseShape[r]?t[r]:this.noiseShape[r]);return n}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);const n=ai(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,r=this.getNoiseShape(n);return Ds((()=>Rs(n,this.rate,r,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Ll.className="Dropout",D.JFn.registerClass(Ll);class Pl extends Ll{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Pl.className="SpatialDropout1D",D.JFn.registerClass(Pl);class Bl extends gi{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Ga(this.units,"units"),this.activation=Vu(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=ti(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=ti(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Oi(e.kernelConstraint),this.biasConstraint=Oi(e.biasConstraint),this.kernelRegularizer=Ku(e.kernelRegularizer),this.biasRegularizer=Ku(e.biasRegularizer),this.activityRegularizer=Ku(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=si(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=si(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);const n=ai(e),r=ja(this.activation.getClassName());let a;return null!=r?a=$s(n,this.kernel.read(),r,this.bias?this.bias.read():null):(a=$s(n,this.kernel.read()),null!=this.bias&&(a=As(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a}))}getConfig(){const e={units:this.units,activation:Bu(this.activation),useBias:this.useBias,kernelInitializer:ei(this.kernelInitializer),biasInitializer:ei(this.biasInitializer),kernelRegularizer:qu(this.kernelRegularizer),biasRegularizer:qu(this.biasRegularizer),activityRegularizer:qu(this.activityRegularizer),kernelConstraint:Fi(this.kernelConstraint),biasConstraint:Fi(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Bl.className="Dense",D.JFn.registerClass(Bl);class Wl extends gi{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=si(e);for(const t of e.slice(1))if(null==t)throw new _a(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],ps(e,1)]}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);let n=ai(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=(0,D.mgz)(n,e)}return function(e){if(e.rank<=1)throw new _a(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],ps(e.shape,1)];return D.tQQ(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Wl.className="Flatten",D.JFn.registerClass(Wl);class Vl extends gi{constructor(e){super(e),this.supportsMasking=!0,this.activation=Vu(e.activation)}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);const n=ai(e);return this.activation.apply(n)}))}getConfig(){const e={activation:Bu(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Vl.className="Activation",D.JFn.registerClass(Vl);class Ul extends gi{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return(0,D.DZQ)((()=>{return e=ai(e),t=e,n=this.n,(0,D.DZQ)((()=>{if(2!==t.shape.length)throw new _a(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Is(xs(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Ul.className="RepeatVector",D.JFn.registerClass(Ul);class Gl extends gi{constructor(e){super(e),this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",r=t.slice();let a=1,s=null;for(let o=0;o<r.length;++o){const e=r[o];if(this.isUnknown(e)){if(null!==s)throw new _a("Can only specifiy one unknown dimension.");s=o}else a*=e}const i=ps(e);if(null!==s){if(0===a||i%a!==0)throw new _a(n);r[s]=i/a}else if(i!==a)throw new _a(n);return r}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);const n=ai(e),r=n.shape,a=r.slice(0,1).concat(this.fixUnknownDimension(r.slice(1),this.targetShape));return(0,D.tQQ)(n,a)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Gl.className="Reshape",D.JFn.registerClass(Gl);class Hl extends gi{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=ms(1,e.dims.length+1);if(!D.ZSL.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new di({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=si(e)).slice();return this.dims.forEach(((n,r)=>{t[r+1]=e[n]})),t}call(e,t){return(0,D.mgz)(ai(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Hl.className="Permute",D.JFn.registerClass(Hl);class jl extends gi{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=ai(e);return(0,D.bzn)((0,D.Ec)(n,this.maskValue),-1)}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);const n=ai(e),r=(0,D.bzn)((0,D.Ec)(n,this.maskValue),-1,!0);return(0,D.lKK)(n,(0,D.wgE)(r,n.dtype))}))}}jl.className="Masking",D.JFn.registerClass(jl);class ql extends gi{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Ra(e.inputLength))}this.inputDim=e.inputDim,Ga(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Ga(this.outputDim,"outputDim"),this.embeddingsInitializer=ti(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Ku(e.embeddingsRegularizer),this.activityRegularizer=Ku(e.activityRegularizer),this.embeddingsConstraint=Oi(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return(0,D.DZQ)((()=>this.maskZero?(e=ai(e),(0,D.Ec)(e,(0,D.POl)(e))):null))}computeOutputShape(e){if(e=si(e),null==this.inputLength)return[...e,this.outputDim];const t=Ra(this.inputLength);if(t.length!==e.length-1)throw new _a(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let r=0;r<t.length;++r){const a=t[r],s=e[r+1];if(null!=a&&null!=s&&a!==s)throw new _a(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);null==a&&(t[n]=s),n++}}return[e[0],...t,this.outputDim]}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);let n=ai(e);"int32"!==n.dtype&&(n=bs(n,"int32"));const r=Cs(this.embeddings.read(),(0,D.tQQ)(n,[n.size]));return(0,D.tQQ)(r,si(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:ei(this.embeddingsInitializer),embeddingsRegularizer:qu(this.embeddingsRegularizer),activityRegularizer:qu(this.activityRegularizer),embeddingsConstraint:Fi(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}ql.className="Embedding",D.JFn.registerClass(ql);class Zl extends gi{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Ia}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;const n=e.slice(0,e.length-t.length);for(let r=0;r<t.length;++r){const a=e[e.length-t.length+r],s=t[r];if(null==a||null==s||a<0||s<0)n.push(null);else if(1===a)n.push(s);else if(1===s)n.push(a);else{if(a!==s)throw new _a("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(a)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[si(e)]),e.length<2)throw new _a(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const a of e)null!=a&&null!==a[0]&&t.push(a[0]);if(t=Ba(t),t.length>1)throw new _a(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let a=1;a<e.length;++a){const t=null==e[a]?null:e[a].slice(1);n=this.computeElementwiseOpOutputShape(n,t)}const r=e.map((e=>e.length));-1===e.indexOf(null)&&1===Ba(r).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return(0,D.DZQ)((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const r=fs(n);for(let n of e){const e=n.rank;for(let t=0;t<r-e;++t)n=xs(n,1);t.push(n)}return this.mergeFunction(t)}{let n=!1;for(const s of e){const e=s.rank;if(null==e){const e=s.shape,r=e[0],a=e.slice(1).concat([r]);let i=D.tQQ(s,[r].concat(ps(e.slice(1))));i=D.mgz(i,[1,0]),i=D.tQQ(i,a),t.push(i),n=!0}else if(e>1){const r=ms(1,e).concat([0]);t.push(D.mgz(s,r)),n=!0}else t.push(s)}let r=this.mergeFunction(t);const a=r.rank;if(n)if(null==a){const e=r.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));r=D.tQQ(D.mgz(D.tQQ(r,[-1,t]),[1,0]),n)}else if(a>1){const e=[a-1].concat(ms(0,a-1));r=D.mgz(r,e)}return r}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==e[0]?null:e[0].slice(1);for(let r=1;r<e.length;++r){const n=null==e[r]?null:e[r].slice(1);t=this.computeElementwiseOpOutputShape(t,n)}let n=[];for(const r of e)null!=r&&null!==r[0]&&n.push(r[0]);return n=Ba(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return D.DZQ((()=>{if(null==t)return null;if(!Array.isArray(t))throw new _a("`mask` should be an Array");if(!Array.isArray(e))throw new _a("`inputs` should be an Array");if(t.length!==e.length)throw new _a(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every((e=>null==e)))return null;let n=(t=t.map((e=>null==e?e:D.UG6(e,0))))[0];for(let e=1;e<t.length-1;++e)n=D.n76(n,t[e]);return n}))}}class Kl extends Zl{constructor(e){super(e)}mergeFunction(e){return(0,D.DZQ)((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=D.WQq(t,e[n]);return t}))}}Kl.className="Add",D.JFn.registerClass(Kl);class Yl extends Zl{constructor(e){super(e)}mergeFunction(e){return(0,D.DZQ)((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=D.lKK(t,e[n]);return t}))}}Yl.className="Multiply",D.JFn.registerClass(Yl);class Ql extends Zl{constructor(e){super(e)}mergeFunction(e){return(0,D.DZQ)((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=D.WQq(t,e[n]);return D.lKK(1/e.length,t)}))}}Ql.className="Average",D.JFn.registerClass(Ql);class Xl extends Zl{constructor(e){super(e)}mergeFunction(e){return(0,D.DZQ)((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=D.PhQ(t,e[n]);return t}))}}Xl.className="Maximum",D.JFn.registerClass(Xl);class Jl extends Zl{constructor(e){super(e)}mergeFunction(e){return(0,D.DZQ)((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=D.BpO(t,e[n]);return t}))}}Jl.className="Minimum",D.JFn.registerClass(Jl);class ec extends Zl{constructor(e){super(e),this.DEFAULT_AXIS=-1,null==e&&(e={}),this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new _a("A `Concatenate` layer should be called on a list of at least 2 inputs");let t=!0;for(const r of e)if(null!=r){t=!1;break}if(t)return;const n=[];for(let r=0;r<e.length;++r){const t=e[r].slice();t.splice(this.axis,1);let a=!1;for(const e of n)if(D.ZSL.arraysEqual(e,t)){a=!0;break}a||n.push(t)}if(n.length>1)throw new _a("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return(0,D.DZQ)((()=>Ss(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new _a("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis;for(const a of t.slice(1)){if(null==n[r]||null==a[r]){n[r]=null;break}n[r]+=a[r]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new _a("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new _a("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new _a(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return D.DZQ((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const r=[];for(let s=0;s<e.length;++s)null==t[s]?r.push(D.wgE(D.P61(e[s]),"bool")):t[s].rank<e[s].rank?r.push(D.UG6(t[s],-1)):r.push(t[s]);const a=D.xWs(r,this.axis);return D.Q7R(a,-1,!1)}))}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function tc(e,t){for(;e<0;)e+=t;return e}ec.className="Concatenate",D.JFn.registerClass(ec);class nc extends Zl{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){D.ZSL.assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Ia("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,n);if(t[r[0]]!==n[r[1]])throw new _a(`Dimension incompatibility: ${t[r[0]]} !== ${n[r[1]]}`)}mergeFunction(e){if(2!==e.length)throw new _a(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],r=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>tc(t,e[n].shape.length))):[tc(this.axes,n.shape.length),tc(this.axes,r.shape.length)],this.normalize&&(n=mo(n,t[0]),r=mo(r,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Ia("batchDot is not implemented for tensors of 4D or higher rank yet");if(D.ZSL.assert(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),D.ZSL.assert(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`)),"number"===typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new Ia("batchDot is not implemented for complex64-type Tensors yet.");const r=e.shape.length,a=t.shape.length;null==n&&(n=[r-1,a-2]);const s=n;return D.DZQ((()=>{let n,i;if(r>a){n=r-a;const e=[];for(let t=0;t<n;++t)e.push(1);t=D.tQQ(t,t.shape.concat(e))}else if(a>r){n=a-r;const t=[];for(let e=0;e<n;++e)t.push(1);e=D.tQQ(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)i=s[0]===s[1]?D.czq(D.lKK(e,t),s[0]):D.czq(D.lKK(D.mgz(e,[1,0]),t),s[1]);else{const n=s[0]!==e.shape.length-1,r=s[1]===t.shape.length-1;i=D.NoW(e,t,n,r)}if(n>0){let e;e=r>a?r+a-3:r-1;const t=[];for(let r=e;r<e+n;++r)t.push(r);i=D.r2V(i,t)}return 1===i.shape.length&&(i=D.UG6(i,1)),i}))}(n,r,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[tc(this.axes,e.length),tc(this.axes,t.length)],n}computeOutputShape(e){D.ZSL.assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Ia("Dot layer does not support tensors of 4D or higher rank yet.");const r=this.interpretAxes(t,n);t.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);const a=t.concat(n);return 1===a.length&&a.push(1),a}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}nc.className="Dot",D.JFn.registerClass(nc);class rc extends gi{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);const n=ai(e);return Ds((()=>(0,D.WQq)(Ts(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}rc.className="GaussianNoise",D.JFn.registerClass(rc);class ac extends gi{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t);const n=ai(e);if(this.rate>0&&this.rate<1){return Ds((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return(0,D.lKK)(n,Ts(n.shape,1,e))}),(()=>n),t.training||!1)}return n}))}}ac.className="GaussianDropout",D.JFn.registerClass(ac);class sc extends gi{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||ai(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return(0,D.DZQ)((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),r=()=>{const t=ai(e),r=-1.7580993408473766;let a=(0,D.DQN)((0,D.YeY)(n),this.rate);a=bs(a,"float32");const s=((1-this.rate)*(1+this.rate*r**2))**-.5,i=-s*r*this.rate,o=(0,D.WQq)((0,D.lKK)(t,a),(0,D.lKK)((0,D.WQq)(a,-1),r));return(0,D.WQq)((0,D.lKK)(o,s),i)};return Ds(r,(()=>ai(e)),t.training||!1)}return e}))}}function ic(e,t,n,r,a,s=.001){let i;if(2===e.rank)i=D.BFc(e,t,n,r,a,s);else if(3===e.rank)i=D.kSi(e,t,n,r,a,s);else{if(4!==e.rank)throw new Ia(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=D.T5N(e,t,n,r,a,s)}return i}function oc(e,t,n,r,a=.001){return D.ZSL.arraysEqual(r.slice().sort(),ms(0,e.rank-1))?function(e,t,n,r,a=.001){return(0,D.DZQ)((()=>{const s=D.Clk(e,r),i=s.mean,o=s.variance;return[ic(e,i,o,n,t,a),i,o]}))}(e,t,n,r,a):function(e,t,n,r,a=.001){return(0,D.DZQ)((()=>{const s=D.Clk(e,r),i=s.mean,o=s.variance,u=[];for(const t of ms(0,e.rank))-1!==r.indexOf(t)?u.push(1):u.push(e.shape[t]);const l=(0,D.tQQ)(i,u),c=(0,D.tQQ)(o,u),d=null==t?null:(0,D.tQQ)(t,u),p=null==n?null:(0,D.tQQ)(n,u);return[ic(e,l,c,p,d,a),i,o]}))}(e,t,n,r,a)}sc.className="AlphaDropout",D.JFn.registerClass(sc);class uc extends gi{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=ti(e.betaInitializer||"zeros"),this.gammaInitializer=ti(e.gammaInitializer||"ones"),this.movingMeanInitializer=ti(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=ti(e.movingVarianceInitializer||"ones"),this.betaConstraint=Oi(e.betaConstraint),this.gammaConstraint=Oi(e.gammaConstraint),this.betaRegularizer=Ku(e.betaRegularizer),this.gammaRegularizer=Ku(e.gammaRegularizer)}build(e){e=si(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new _a(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new di({ndim:e.length,axes:{[t]:n}})];const r=[n];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return(0,D.DZQ)((()=>{const n=null!=t.training&&t.training,r=ai(e),a=r.shape,s=a.length,i=ms(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);const u=Ca(1,s);u[o]=a[o];const l=i.slice();l.sort();const c=!D.ZSL.arraysEqual(l,ms(0,s).slice(0,s-1));if(!n)return(()=>{if(c){const e=(0,D.tQQ)(this.movingMean.read(),u),t=(0,D.tQQ)(this.movingVariance.read(),u),n=this.center?(0,D.tQQ)(this.beta.read(),u):null,a=this.scale?(0,D.tQQ)(this.gamma.read(),u):null;return ic(r,e,t,n,a,this.epsilon)}return ic(r,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[d,p,h]=oc(r,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(e,t,n)=>{D.DZQ((()=>{const r=1-n,a=e.read(),s=D.lKK(D.jbE(a,t),r);e.write(D.jbE(a,s))}))};return(()=>{f(this.movingMean,p,this.momentum),f(this.movingVariance,h,this.momentum)})(),d}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ei(this.betaInitializer),gammaInitializer:ei(this.gammaInitializer),movingMeanInitializer:ei(this.movingMeanInitializer),movingVarianceInitializer:ei(this.movingVarianceInitializer),betaRegularizer:qu(this.betaRegularizer),gammaRegularizer:qu(this.gammaRegularizer),betaConstraint:Fi(this.betaConstraint),gammaConstraint:Fi(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}uc.className="BatchNormalization",D.JFn.registerClass(uc);class lc extends gi{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"===typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=ti(e.betaInitializer||"zeros"),this.gammaInitializer=ti(e.gammaInitializer||"ones"),this.betaRegularizer=Ku(e.betaRegularizer),this.gammaRegularizer=Ku(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=si(e)).length;"number"===typeof this.axis&&(this.axis=[this.axis]);for(let a=0;a<this.axis.length;++a)this.axis[a]<0&&(this.axis[a]+=t);for(const a of this.axis)if(a<0||a>=t)throw new Error(`Invalid axis: ${a}`);if(this.axis.length!==Ba(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t])),r=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,r):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,r):this.beta=null,this.built=!0}call(e,t){const n=ai(e),r=n.shape,a=r.length;return(0,D.DZQ)((()=>{let{mean:e,variance:t}=(0,D.Clk)(n,this.axis,!0);const s=Ca(1,a);for(const n of this.axis)s[n]=r[n];const i=e=>null!=e&&e.shape.length!==a?D.tQQ(e,s):e;let o=this.scale?i(this.gamma.read()):null,u=this.center?i(this.beta.read()):null;const l=[],c=[];for(let n=0;n<a;++n)-1!==this.axis.indexOf(n)?(l.push(r[n]),c.push(1)):(l.push(1),c.push(r[n]));return e=D.Vsq(e,l),t=D.Vsq(t,l),null!=o&&(o=D.Vsq(o,c)),null!=u&&(u=D.Vsq(u,c)),ic(n,e,t,u,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ei(this.betaInitializer),gammaInitializer:ei(this.gammaInitializer),betaRegularizer:qu(this.betaRegularizer),gammaRegularizer:qu(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}lc.className="LayerNormalization",D.JFn.registerClass(lc);class cc extends gi{constructor(e){if(null==e&&(e={}),super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)this.padding=[[1,1],[1,1]];else if("number"===typeof e.padding)this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new _a(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if("number"===typeof e.padding[0])t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new _a(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],2!==e.padding[1].length)throw new _a(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new di({ndim:4})]}computeOutputShape(e){let t,n;return e=si(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return(0,D.DZQ)((()=>{return t=ai(e),n=this.padding,r=this.dataFormat,(0,D.DZQ)((()=>{if(4!==t.rank)throw new _a(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new _a("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==r&&(r="channelsLast"),"channelsLast"!==r&&"channelsFirst"!==r)throw new _a(`Unknown data format: ${r}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===r?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],D.eVF(t,e)}));var t,n,r}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}function dc(e,t,n,r,a,s){return(0,D.DZQ)((()=>{let i;rs(a),ss(s),as(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=sl(e,a);const o="same"===r?"same":"valid";return i="max"===s?D.jgi(e,t,n,o):D.$jT(e,t,n,o),"channelsFirst"===a&&(i=D.mgz(i,[0,3,1,2])),i}))}function pc(e,t,n,r,a,s){return(0,D.DZQ)((()=>{let i;rs(a),ss(s),as(r),null==n&&(n=[1,1,1]),null==r&&(r="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=il(e,a);const o="same"===r?"same":"valid";return i="max"===s?D.NYV(e,t,n,o):D.sub(e,t,n,o),"channelsFirst"===a&&(i=D.mgz(i,[0,4,1,2,3])),i}))}cc.className="ZeroPadding2D",D.JFn.registerClass(cc);class hc extends gi{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"===typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!==typeof e.poolSize[0])throw new _a(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(Ga(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"===typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!==typeof e.strides[0])throw new _a(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}Ga(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,as(this.padding),this.inputSpec=[new di({ndim:3})]}computeOutputShape(e){const t=rl((e=si(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return(0,D.DZQ)((()=>{this.invokeCallHook(e,t),e=xs(ai(e),2);const n=this.poolingFunction(ai(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return D.r2V(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class fc extends hc{constructor(e){super(e)}poolingFunction(e,t,n,r,a){return rs(a),as(r),dc(e,t,n,r,a,"max")}}fc.className="MaxPooling1D",D.JFn.registerClass(fc);class mc extends hc{constructor(e){super(e)}poolingFunction(e,t,n,r,a){return rs(a),as(r),dc(e,t,n,r,a,"avg")}}mc.className="AveragePooling1D",D.JFn.registerClass(mc);class gc extends gi{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new _a(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Ga(this.poolSize,"poolSize"),Ga(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,rs(this.dataFormat),as(this.padding),this.inputSpec=[new di({ndim:4})]}computeOutputShape(e){e=si(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=rl(t,this.poolSize[0],this.padding,this.strides[0]),n=rl(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return(0,D.DZQ)((()=>(this.invokeCallHook(e,t),this.poolingFunction(ai(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class yc extends gc{constructor(e){super(e)}poolingFunction(e,t,n,r,a){return rs(a),as(r),dc(e,t,n,r,a,"max")}}yc.className="MaxPooling2D",D.JFn.registerClass(yc);class bc extends gc{constructor(e){super(e)}poolingFunction(e,t,n,r,a){return rs(a),as(r),dc(e,t,n,r,a,"avg")}}bc.className="AveragePooling2D",D.JFn.registerClass(bc);class xc extends gi{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new _a(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Ga(this.poolSize,"poolSize"),Ga(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,rs(this.dataFormat),as(this.padding),this.inputSpec=[new di({ndim:5})]}computeOutputShape(e){e=si(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[4]:e[3];return t=rl(t,this.poolSize[0],this.padding,this.strides[0]),n=rl(n,this.poolSize[1],this.padding,this.strides[1]),r=rl(r,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,r]:[e[0],t,n,r,e[4]]}call(e,t){return(0,D.DZQ)((()=>(this.invokeCallHook(e,t),this.poolingFunction(ai(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class wc extends xc{constructor(e){super(e)}poolingFunction(e,t,n,r,a){return rs(a),as(r),pc(e,t,n,r,a,"max")}}wc.className="MaxPooling3D",D.JFn.registerClass(wc);class vc extends xc{constructor(e){super(e)}poolingFunction(e,t,n,r,a){return rs(a),as(r),pc(e,t,n,r,a,"avg")}}vc.className="AveragePooling3D",D.JFn.registerClass(vc);class kc extends gi{constructor(e){super(e),this.inputSpec=[new di({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ia}}class Sc extends kc{constructor(e){super(e||{})}call(e,t){return(0,D.DZQ)((()=>{const t=ai(e);return D.i2o(t,1)}))}}Sc.className="GlobalAveragePooling1D",D.JFn.registerClass(Sc);class _c extends kc{constructor(e){super(e||{})}call(e,t){return(0,D.DZQ)((()=>{const t=ai(e);return D.T9B(t,1)}))}}_c.className="GlobalMaxPooling1D",D.JFn.registerClass(_c);class Ic extends gi{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,rs(this.dataFormat),this.inputSpec=[new di({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Ia}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Tc extends Ic{call(e,t){return(0,D.DZQ)((()=>{const t=ai(e);return"channelsLast"===this.dataFormat?D.i2o(t,[1,2]):D.i2o(t,[2,3])}))}}Tc.className="GlobalAveragePooling2D",D.JFn.registerClass(Tc);class $c extends Ic{call(e,t){return(0,D.DZQ)((()=>{const t=ai(e);return"channelsLast"===this.dataFormat?D.T9B(t,[1,2]):D.T9B(t,[2,3])}))}}$c.className="GlobalMaxPooling2D",D.JFn.registerClass($c);class Cc extends gi{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const r=fo(t.layer,n);delete t.layer;const a={layer:r};return Object.assign(a,t),new e(a)}}class Nc extends Cc{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=si(e)).length<3)throw new _a(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=si(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))}call(e,t){return(0,D.DZQ)((()=>Sl(((e,n)=>[ai(this.layer.call(e,t)),[]]),e=ai(e),[],!1,null,null,!1,!0)[1]))}}Nc.className="TimeDistributed",D.JFn.registerClass(Nc);class Ec extends Cc{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=fo(n),t.goBackwards=!0!==t.goBackwards;const r={};var a;if(r.className=e.layer.getClassName(),r.config=t,this.backwardLayer=fo(r),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,a=this.mergeMode,Va(ts,"BidirectionalMergeMode",a),e.weights)throw new Ia("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,r,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),this.returnState?(r=a.slice(1),t=a[0]):t=a[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):Aa(n)}apply(e,t){let n=null==t?null:t.initialState,r=null==t?null:t.constants;null==t&&(t={});const a=kl(e,n,r,this.numConstants);if(e=a.inputs,n=a.initialState,r=a.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==r)return super.apply(e,t);const s=[],i=[];if(null!=n){const e=n.length;if(e%2>0)throw new _a("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);const r=n.map((e=>new di({shape:e.shape})));this.forwardLayer.stateSpec=r.slice(0,e/2),this.backwardLayer.stateSpec=r.slice(e/2),i.push(...r)}if(null!=r)throw new Ia("Support for constants in Bidirectional layers is not implemented yet.");const o=s[0]instanceof pi;for(const u of s)if(u instanceof pi!==o)throw new _a("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(s),r=this.inputSpec.concat(i),a=this.inputSpec;this.inputSpec=r;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return(0,D.DZQ)((()=>{const n=t.initialState;let r,a,s,i;if(null==n)r=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{const s=n.slice(0,n.length/2),i=n.slice(n.length/2);r=this.forwardLayer.call(e,Object.assign(t,{initialState:s})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:i}))}return this.returnState&&(Array.isArray(r)&&(s=r.slice(1).concat(a.slice(1))),r=r[0],a=a[0]),this.returnSequences&&(a=D.BEg(a,1)),"concat"===this.mergeMode?i=Ss([r,a]):"sum"===this.mergeMode?i=D.WQq(r,a):"ave"===this.mergeMode?i=D.lKK(.5,D.WQq(r,a)):"mul"===this.mergeMode?i=D.lKK(r,a):null==this.mergeMode&&(i=[r,a]),this.returnState?null==this.mergeMode?i.concat(s):[i].concat(s):i}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){os(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),os(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=fo(t.layer);if(delete t.layer,null!=t.numConstants)throw new Ia("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const r=t;return r.layer=n,new e(r)}}Ec.className="Bidirectional",D.JFn.registerClass(Ec);class Ac extends gi{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return(0,D.DZQ)((()=>("float32"!==(e=ai(e)).dtype&&(e=bs(e,"float32")),(0,D.WQq)((0,D.lKK)(e,this.scale),this.offset))))}}Ac.className="Rescaling",D.JFn.registerClass(Ac);const{resizeBilinear:Rc,cropAndResize:Dc}=D.Slp;class Fc extends gi{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,r,a,s,i,o){return(0,D.DZQ)((()=>{let u,l=!1;const c=[t/s,n/i,(r+t)/s,(a+n)/i],d=[];3===e.rank?(l=!0,u=(0,D.t$z)([e])):u=e;for(let e=0;e<u.shape[0];e++)d.push(c);const p=(0,D.OEK)(d,[d.length,4]),h=(0,D.y17)(0,d.length,1,"int32"),f=Dc(u,p,h,[r,a],"nearest");return bs(l?ai((0,D.K$i)(f)):f,o)}))}upsize(e,t,n,r){return(0,D.DZQ)((()=>bs(Rc(e,[t,n]),r)))}call(e,t){return(0,D.DZQ)((()=>{const t=ai(e),n=t.dtype,r=t.shape,a=r[r.length-3],s=r[r.length-2];let i=0;a!==this.height&&(i=Math.floor((a-this.height)/2));let o=0;return s!==this.width&&(o=Math.floor((s-this.width)/2),0===o&&(o=1)),i>=0&&o>=0?this.centerCrop(t,i,o,this.height,this.width,a,s,n):this.upsize(e,this.height,this.width,n)}))}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=si(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}Fc.className="CenterCrop",D.JFn.registerClass(Fc);class Mc extends gi{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return null==(e=si(e))?[this.numTokens]:"oneHot"===this.outputMode&&1!==e[e.length-1]?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return(0,D.DZQ)((()=>{let n;if("int32"!==(e=ai(e)).dtype&&(e=bs(e,"int32")),"undefined"!==typeof t.countWeights){if("count"!==this.outputMode)throw new _a(`countWeights is not used when outputMode !== count.\n              Received countWeights=${t.countWeights}`);n=ai(t.countWeights)}const r=(0,D.T9B)(e),a=(0,D.jkA)(e),s=(0,D.rhj)(this.numTokens,r).bufferSync().get(0),i=(0,D.DQN)(a,0).bufferSync().get(0);if(!s||!i)throw new _a(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return function(e,t,n,r){let a=ai(e);if("int32"!==a.dtype&&(a=bs(a,"int32")),"int"===t)return a;const s=a.shape;if(0===a.rank&&(a=(0,D.UG6)(a,-1)),"oneHot"===t&&1!==a.shape[a.shape.length-1]&&(a=(0,D.UG6)(a,-1)),a.rank>2)throw new _a(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${s} which would result in output rank ${a.rank}.`);const i=["multiHot","oneHot"].includes(t),o=a;let u;if(u="undefined"!==typeof r&&"count"===t?(0,D.aOp)(o,r,n,i):(0,D.aOp)(o,[],n,i),"tfIdf"!==t)return u;if(r)return(0,D.lKK)(u,r);throw new _a("When outputMode is 'tfIdf', weights must be provided.")}(e,this.outputMode,this.numTokens,n)}))}}Mc.className="CategoryEncoding",D.JFn.registerClass(Mc);const Oc=new Set(["bilinear","nearest"]);class zc extends gi{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation){if(!Oc.has(e.interpolation))throw new _a(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);this.interpolation=e.interpolation}else this.interpolation="bilinear";this.cropToAspectRatio=Boolean(e.cropToAspectRatio)}computeOutputShape(e){const t=(e=si(e))[2];return[this.height,this.width,t]}getConfig(){const e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return(0,D.DZQ)((()=>{const t=[this.height,this.width];if("bilinear"===this.interpolation)return D.Slp.resizeBilinear(e,t,!this.cropToAspectRatio);if("nearest"===this.interpolation)return D.Slp.resizeNearestNeighbor(e,t,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...Oc]} are supported`)}))}}zc.className="Resizing",D.JFn.registerClass(zc);class Lc{constructor(e){this.seed=e}next(){if(void 0!==this.seed)return this.seed++}}Lc.className="RandomSeed";class Pc extends gi{constructor(e){super(e),this.randomGenerator=new Lc(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}}Pc.className="BaseRandomLayer";const Bc=new Set(["bilinear","nearest"]);class Wc extends Pc{constructor(e){super(e);const{factor:t,interpolation:n="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&2===this.factor.length)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else{if(Array.isArray(this.factor)||!(this.factor>0))throw new _a(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);this.widthLower=-this.factor,this.widthUpper=this.factor}if(this.widthLower<-1||this.widthUpper<-1)throw new _a(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new _a(`factor cannot have upper bound less than lower bound.\n        Got upper bound: ${this.widthUpper}.\n        Got lower bound: ${this.widthLower}\n      `);if(n){if(!Bc.has(n))throw new _a(`Invalid interpolation parameter: ${n} is not implemented`);this.interpolation=n}}getConfig(){const e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=si(e))[2];return[this.imgHeight,-1,t]}call(e,t){return(0,D.DZQ)((()=>{const t=ai(e);this.imgHeight=t.shape[t.shape.length-3];const n=t.shape[t.shape.length-2];this.widthFactor=(0,D.YeY)([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let r=this.widthFactor.dataSync()[0]*n;r=Math.round(r);const a=[this.imgHeight,r];switch(this.interpolation){case"bilinear":return D.Slp.resizeBilinear(e,a);case"nearest":return D.Slp.resizeNearestNeighbor(e,a);default:throw new Error(`Interpolation is ${this.interpolation}\n          but only ${[...Bc]} are supported`)}}))}}function Vc(e){return new bi(e)}function Uc(e){return new Ju(e)}function Gc(e){return new Yu(e)}function Hc(e){return new Qu(e)}function jc(e){return new Xu(e)}function qc(e){return new tl(e)}function Zc(e){return new el(e)}function Kc(e){return new bl(e)}function Yc(e){return new pl(e)}function Qc(e){return new fl(e)}function Xc(e){return new hl(e)}function Jc(e){return new ml(e)}function ed(e){return new yl(e)}function td(e){return new xl(e)}function nd(e){return new wl(e)}function rd(e){return new vl(e)}function ad(e){return new Vl(e)}function sd(e){return new Bl(e)}function id(e){return new Ll(e)}function od(e){return new Pl(e)}function ud(e){return new Wl(e)}function ld(e){return new Ul(e)}function cd(e){return new Gl(e)}function dd(e){return new Hl(e)}function pd(e){return new ql(e)}function hd(e){return new Kl(e)}function fd(e){return new Ql(e)}function md(e){return new ec(e)}function gd(e){return new Xl(e)}function yd(e){return new Jl(e)}function bd(e){return new Yl(e)}function xd(e){return new nc(e)}function wd(e){return new uc(e)}function vd(e){return new lc(e)}function kd(e){return new cc(e)}function Sd(e){return new mc(e)}function _d(e){return Sd(e)}function Id(e){return Sd(e)}function Td(e){return new bc(e)}function $d(e){return Td(e)}function Cd(e){return Td(e)}function Nd(e){return new vc(e)}function Ed(e){return Nd(e)}function Ad(e){return Nd(e)}function Rd(e){return new Sc(e)}function Dd(e){return new Tc(e)}function Fd(e){return new _c(e)}function Md(e){return new $c(e)}function Od(e){return new fc(e)}function zd(e){return new yc(e)}function Ld(e){return new wc(e)}function Pd(e){return new Nl(e)}function Bd(e){return new Cl(e)}function Wd(e){return new Al(e)}function Vd(e){return new El(e)}function Ud(e){return new $l(e)}function Gd(e){return new Tl(e)}function Hd(e){return new zl(e)}function jd(e){return new Ol(e)}function qd(e){return new _l(e)}function Zd(e){return new Rl(e)}function Kd(e){return new Ec(e)}function Yd(e){return new Nc(e)}Wc.className="RandomWidth",D.JFn.registerClass(Wc);const Qd=Fd,Xd=Md,Jd=Od,ep=zd;function tp(e){return new rc(e)}function np(e){return new ac(e)}function rp(e){return new sc(e)}function ap(e){return new jl(e)}function sp(e){return new Ac(e)}function ip(e){return new Fc(e)}function op(e){return new zc(e)}function up(e){return new Mc(e)}function lp(e){return new Wc(e)}function cp(e,t){return $o(e,t)}function dp(e,t){return Ro(e,t)}function pp(e,t){return Do(e,t)}function hp(e,t){return Co(e,t)}function fp(e,t){return Fo(e,t)}function mp(e,t){return Eo(e,t)}function gp(e,t){return Ao(e,t)}function yp(e,t){return _o(e,t)}function bp(e,t){return yo(e,t)}function xp(e,t){return bo(e,t)}function wp(e,t){return bo(e,t)}function vp(e,t){return bo(e,t)}function kp(e,t){return go(e,t)}function Sp(e,t){return go(e,t)}function _p(e,t){return go(e,t)}function Ip(e,t){return function(e,t){return(0,D.DZQ)((()=>{const n=e.sub(t).square().sum(),r=e.sub(e.mean()).square().sum();return D.d_2(1).sub(n.div(r))}))}(e,t)}function Tp(e){return new Hu(e)}function $p(e){return Uu(t=e),new Hu({l1:null!=t?t.l1:null,l2:0});var t}function Cp(e){return Uu(t=e),new Hu({l2:null!=t?t.l2:null,l1:0});var t}class Np extends so{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof fu))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function Ep(e,t){return e<t}function Ap(e,t){return e>t}class Rp extends Np{constructor(e){if(super(),null==e&&(e={}),e.restoreBestWeights)throw new Ia("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,-1===["auto","min","max"].indexOf(this.mode)&&(this.mode="auto"),"min"===this.mode?this.monitorFunc=Ep:"max"===this.mode||-1!==this.monitor.indexOf("acc")?this.monitorFunc=Ap:this.monitorFunc=Ep,this.monitorFunc===Ep&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===Ep?1/0:-1/0}async onEpochEnd(e,t){await no(t);const n=this.getMonitorValue(t);null!=n&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose}getMonitorValue(e){null==e&&(e={});const t=e[this.monitor];return t}}const Dp={earlyStopping:function(e){return new Rp(e)}};var Fp,Mp;(0,D._K2)().registerFlag("KEEP_INTERMEDIATE_TENSORS",(()=>!1),(e=>{})),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"}(Fp||(Fp={})),function(e){let t;!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}(Mp||(Mp={}));const Op={};function zp(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Op[e]=n}function Lp(e){return Op[e]}function Pp(e){delete Op[e]}function Bp(e,t,n,r,a){const s=t.inputParams[e];if(s&&void 0!==s.inputIndexStart){const e=s.inputIndexStart,i=0===s.inputIndexEnd?void 0:void 0===s.inputIndexEnd?e+1:s.inputIndexEnd,o=e<0?t.inputNames.length+e:e;if("tensor"===s.type)return Wp(t.inputNames[o],n,r,a);if("tensors"===s.type){const s=t.inputs.slice(e,i);return t.inputNames.slice(e,i).filter(((e,t)=>{var n;return"NoOp"!==(null===(n=s[t])||void 0===n?void 0:n.op)})).map((e=>Wp(e,n,r,a)))}const u=Wp(t.inputNames[o],n,r,a),l=u.dataSync();return"number"===s.type?l[0]:D.ZSL.toNestedArray(u.shape,l)}const i=t.attrParams[e];return i&&i.value}function Wp(e,t,n,r){const[a,s]=Hp(e,n);if(null!=r){const e=r.getHashTableHandleByName(a);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[Gp(a,e)]));return void 0!==i?t[Gp(a,i)][s]:void 0}function Vp(e,t,n){return t[Gp(e,n.currentContextId)]}function Up(e,t){const[n,r,a]=Hp(e,t);return[Gp(n,t&&t.currentContextId),r,a]}function Gp(e,t){return t?`${e}-${t}`:e}function Hp(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 jp(e,t,n){let r=Bp("pad",e,t,n);if("explicit"===r){r=Bp("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 qp(e){return e.kept?e:(0,D.o8B)(e)}const Zp=[{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}]}],Kp=[{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}]}],Yp=[{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"}]}],Qp=[{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"}]}],Xp=[{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"}]}],Jp=[{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}]}],eh=[{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"}]}],th=[{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"}]}],nh=[{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"}]}],rh=[{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"}]}],ah=[{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"}]}],sh=[{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"}]}],ih=[{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"}]}],oh=[{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"}]}],uh=[{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"}]}],lh=[{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"}]}],ch=[{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}]}],dh=[{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"}]}],ph=[{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:[]}];class hh{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[l,c,d,p,h,f,m,g,y,b,x,w,v,k,S,_,I,T,$].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=[],i=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 o=[];const u=[];let l={},c={};null!=t&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const d=Object.keys(i);d.forEach((e=>{const t=i[e];t.inputNames.forEach(((e,n)=>{const[r,,a]=Up(e),s=i[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=i[e];0===t.children.length&&u.push(t)})):Object.keys(c).forEach((e=>{const[t]=Up(e),n=i[t];null!=n&&(n.signatureKey=c[e],u.push(n))})),Object.keys(l).length>0?Object.keys(l).forEach((e=>{const[t]=Up(e),n=i[t];n&&(n.signatureKey=l[e],o.push(n))})):o=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:i,inputs:o,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=Lp(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=mh(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=mh(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=Ih(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Ih(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=yh(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=yh(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=_h(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=_h(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=gh(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=gh(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=$h(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=$h(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=Sh(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Sh(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Th(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Th(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":a=wh(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=wh(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":a=vh(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=vh(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=xh(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=xh(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]=Up(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:bh(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]=Up(e),i=r[a];if(null!=i.outputs){const e=i.outputs.indexOf(s);if(-1!==e){const r=`${a}:${e}`;t.inputNames[n]=r}}t.inputs.push(i),i.children.push(t)}))}));const i=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=Up(i[e.name]),a=r[t];null!=a&&(a.defaultOutput=n,s.push(a))}));const o=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:s,weights:n,placeholders:[],signature:o}}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 fh(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=(0,D._K2)().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 mh(e,t,n,r=!1){const a=e[t];return null!=a?fh(a.s,r):n}function gh(e,t,n){const r=e[t];return r?r.b:n}function yh(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 bh(e){switch("string"===typeof e&&(e=Fp[e]),e){case Fp.DT_FLOAT:case Fp.DT_HALF:return"float32";case Fp.DT_INT32:case Fp.DT_INT64:case Fp.DT_INT8:case Fp.DT_UINT8:return"int32";case Fp.DT_BOOL:return"bool";case Fp.DT_DOUBLE:return"float32";case Fp.DT_STRING:return"string";case Fp.DT_COMPLEX64:case Fp.DT_COMPLEX128:return"complex64";default:return null}}function xh(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function wh(e,t,n){const r=e[t];return r&&r.type?bh(r.type):n}function vh(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>bh(e))):n}function kh(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"===typeof e.size?e.size:parseInt(e.size,10))):[]}function Sh(e,t,n){const r=e[t];return r&&r.shape?kh(r.shape):n}function _h(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 Ih(e,t,n,r=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map((e=>fh(e,r))):n}function Th(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>kh(e))):n}function $h(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Ch{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 Wp(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return Wp(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return yh(this.node.rawAttrs,e,t);if(null!=n.s)return mh(this.node.rawAttrs,e,t);if(null!=n.b)return gh(this.node.rawAttrs,e,t);if(null!=n.shape)return Sh(this.node.rawAttrs,e,t);if(null!=n.type)return wh(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return _h(this.node.rawAttrs,e,t);if(null!=n.list.s)return Ih(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Th(this.node.rawAttrs,e,t);if(null!=n.list.b)return $h(this.node.rawAttrs,e,t);if(null!=n.list.type)return vh(this.node.rawAttrs,e,t)}return t}}var Nh=n(7270);function Eh(e,t,n=""){if("number"!==typeof e&&"number"!==typeof t){D.ZSL.assert(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];D.ZSL.assert(a<0||s<0||a===s,(()=>n+` Shapes ${e} and ${t} must match`))}}}function Ah(e){return"number"!==typeof e&&!e.some((e=>e<0))}function Rh(e,t,n){let r=Dh(e,n);const a=!Ah(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=Dh(e.shape,r)})),!Ah(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Dh(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 Fh{constructor(e,t,n,r,a,s,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=(0,D.d_2)(0),(0,D.aCs)(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),Eh(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,(0,D.aCs)(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(0,D.OEK)([],[0].concat(this.elementShape));const n=this.readMany(e);return Eh(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),(0,D.t$z)(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(0,D.OEK)([],[0].concat(this.elementShape));const t=[];for(let r=0;r<this.size();r++)t.push(r);const n=this.readMany(t);return Eh(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),(0,D.xWs)(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,(0,D.K$i)(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=[];(0,D.DZQ)((()=>{t=(0,D.tQQ)(t,[1,n,a]);for(let n=0;n<e.length;++n){const i=[0,0===n?0:r[n-1],0],o=[1,e[n],a];s[n]=(0,D.tQQ)((0,D.dik)(t,i,o),this.elementShape)}return s}));const i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}}class Mh{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}`);Eh(t,e.shape,"TensorList shape mismatch: "),(0,D.aCs)(e)})),this.idTensor=(0,D.d_2)(0),this.maxNumElements=r,(0,D.aCs)(this.idTensor)}copy(){return new Mh([...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.`);Eh(e,this.elementShape,"TensorList shape mismatch: ");const r=Rh(this.elementShape,this.tensors,e);return(0,D.DZQ)((()=>{const e=this.tensors.map((e=>(0,D.tQQ)(e,r)));return(0,D.t$z)(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=Rh(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Eh(r.shape,e,"TensorList shape mismatch: "),(0,D.tQQ)(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(Eh(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");(0,D.aCs)(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 Mh([],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.`);Eh(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=Rh(this.elementShape,this.tensors,t);return(0,D.tQQ)(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.`);Eh(this.elementShape,t.shape,"TensorList shape mismatch: "),(0,D.aCs)(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}`);Eh(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=Rh(this.elementShape,this.tensors,n);return 0===e.length?(0,D.OEK)([],[0].concat(r)):(0,D.DZQ)((()=>{const t=e.map((e=>(0,D.tQQ)(this.tensors[e],r)));return(0,D.t$z)(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Eh(this.elementShape,t,"TensorList shape mismatch: ");const n=Rh(this.elementShape,this.tensors,t);return 0===this.size()?(0,D.OEK)([],[0].concat(n)):(0,D.DZQ)((()=>{const e=this.tensors.map((e=>(0,D.tQQ)(e,n)));return(0,D.xWs)(e,0)}))}}const Oh=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=Bp("thenBranch",e,t,n),a=Bp("elseBranch",e,t,n),s=Bp("cond",e,t,n),i=Bp("args",e,t,n);return(await s.data())[0]?n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[a].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=Bp("body",e,t,n),a=Bp("cond",e,t,n),s=Bp("args",e,t,n),i=await n.functionMap[a].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),o=s.map((e=>e.id));let u=await i[0].data();i.forEach((e=>{e.kept||-1!==o.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!==o.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!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return l}case"LoopCond":return[qp(Bp("pred",e,t,n))];case"Switch":{const r=Bp("pred",e,t,n);let a=Bp("data",e,t,n);return a.kept||(a=qp(a)),(await r.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const r=e.inputNames.find((e=>void 0!==Wp(e,t,n)));if(r){return[qp(Wp(r,t,n))]}return}case"Enter":{const r=Bp("frameName",e,t,n),a=Bp("tensor",e,t,n);return n.enterFrame(r),[qp(a)]}case"Exit":{const r=Bp("tensor",e,t,n);return n.exitFrame(),[qp(r)]}case"NextIteration":{const r=Bp("tensor",e,t,n);return n.nextIteration(),[qp(r)]}case"TensorArrayV3":{const r=Bp("size",e,t,n),a=Bp("dtype",e,t,n),s=Bp("elementShape",e,t,n),i=Bp("dynamicSize",e,t,n),o=Bp("clearAfterRead",e,t,n),u=Bp("identicalElementShapes",e,t,n),l=Bp("name",e,t,n),c=new Fh(l,a,r,s,u,i,o);return n.addTensorArray(c),[c.idTensor,(0,D.d_2)(1)]}case"TensorArrayWriteV3":{const r=Bp("tensorArrayId",e,t,n),a=Bp("index",e,t,n),s=Bp("tensor",e,t,n),i=n.getTensorArray(r.id);return i.write(a,s),[i.idTensor]}case"TensorArrayReadV3":{const r=Bp("tensorArrayId",e,t,n),a=Bp("index",e,t,n);return[n.getTensorArray(r.id).read(a)]}case"TensorArrayGatherV3":{const r=Bp("tensorArrayId",e,t,n),a=Bp("indices",e,t,n),s=Bp("dtype",e,t,n);return[n.getTensorArray(r.id).gather(a,s)]}case"TensorArrayScatterV3":{const r=Bp("tensorArrayId",e,t,n),a=Bp("indices",e,t,n),s=Bp("tensor",e,t,n),i=n.getTensorArray(r.id);return i.scatter(a,s),[i.idTensor]}case"TensorArrayConcatV3":{const r=Bp("tensorArrayId",e,t,n),a=n.getTensorArray(r.id),s=Bp("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=Bp("tensorArrayId",e,t,n),a=Bp("tensor",e,t,n),s=Bp("lengths",e,t,n),i=n.getTensorArray(r.id);return i.split(s,a),[i.idTensor]}case"TensorArraySizeV3":{const r=Bp("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return[(0,D.d_2)(a.size(),"int32")]}case"TensorArrayCloseV3":{const r=Bp("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const r=Bp("tensorListId",e,t,n),a=Bp("index",e,t,n),s=Bp("tensor",e,t,n),i=n.getTensorList(r.id);return i.setItem(a,s),[i.idTensor]}case"TensorListGetItem":{const r=Bp("tensorListId",e,t,n),a=Bp("index",e,t,n),s=Bp("elementShape",e,t,n),i=Bp("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(a,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{const r=Bp("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 Mh([],n,e.dtype,r),i=(0,D.K$i)(e,0);return t.forEach(((e,t)=>{s.setItem(e,i[t])})),s}(Bp("tensor",e,t,n),r,Bp("elementShape",e,t,n),Bp("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=Bp("elementShape",e,t,n),a=Bp("elementDType",e,t,n);let s;s="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=Bp(s,e,t,n),o=function(e,t,n,r){return new Mh([],e,t,r)}(r,a,0,"TensorListReserve"===e.op?-1:i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{const r=Bp("tensorListId",e,t,n),a=Bp("indices",e,t,n),s=Bp("elementShape",e,t,n),i=Bp("elementDType",e,t,n);return[n.getTensorList(r.id).gather(a,i,s)]}case"TensorListStack":{const r=Bp("tensorListId",e,t,n),a=Bp("elementShape",e,t,n),s=Bp("elementDType",e,t,n),i=Bp("numElements",e,t,n);return[n.getTensorList(r.id).stack(a,s,i)]}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}`);Eh(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=(0,D.K$i)(e);return new Mh(a,t,r)}(Bp("tensor",e,t,n),Bp("elementShape",e,t,n),Bp("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=Bp("tensorListId",e,t,n),a=n.getTensorList(r.id),s=Bp("dtype",e,t,n),i=Bp("elementShape",e,t,n);return[a.concat(s,i)]}case"TensorListPushBack":{const r=Bp("tensorListId",e,t,n),a=Bp("tensor",e,t,n),s=n.getTensorList(r.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{const r=Bp("tensorListId",e,t,n),a=Bp("elementShape",e,t,n),s=Bp("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(a,s)]}case"TensorListSplit":{const r=Bp("tensor",e,t,n),a=Bp("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=Dh(e.shape.slice(1),n),i=0===r?0:e.size/r,o=(0,D.DZQ)((()=>{const n=[];e=(0,D.tQQ)(e,[1,r,i]);for(let r=0;r<t.length;++r){const o=[0,0===r?0:a[r-1],0],u=[1,t[r],i];n[r]=(0,D.tQQ)((0,D.dik)(e,o,u),s)}return e.dispose(),n})),u=new Mh([],n,e.dtype,t.length);for(let l=0;l<o.length;l++)u.setItem(l,o[l]);return u}(r,Bp("lengths",e,t,n),a);return n.addTensorList(s),[s.idTensor]}case"TensorListLength":{const r=Bp("tensorListId",e,t,n),a=n.getTensorList(r.id);return[(0,D.d_2)(a.size(),"int32")]}case"TensorListResize":{const r=Bp("tensorListId",e,t,n),a=Bp("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 zh(e,t,n){const[r,a]=Bp("fusedOps",e,t,n),s="biasadd"===r,i=!s,o="prelu"===a,u="fusedbatchnorm"===r,l=Bp("numArgs",e,t,n);if(s){if(o&&2!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&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=Bp("strides",e,t,n),d=jp(e,t,n),p=Bp("dataFormat",e,t,n).toUpperCase(),h=Bp("dilations",e,t,n);let[f,m]=Bp("args",e,t,n);i&&(m=f,f=void 0);return{stride:c,pad:d,dataFormat:p,dilations:h,biasArg:f,preluArg:m,activationFunc:a,leakyreluAlpha:Bp("leakyreluAlpha",e,t,n)}}function Lh(e,t,n){return{boxes:Bp("boxes",e,t,n),scores:Bp("scores",e,t,n),maxOutputSize:Bp("maxOutputSize",e,t,n),iouThreshold:Bp("iouThreshold",e,t,n),scoreThreshold:Bp("scoreThreshold",e,t,n),softNmsSigma:Bp("softNmsSigma",e,t,n)}}class Ph{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=(0,D.d_2)(0),this.tensorMap=new Map,(0,D.aCs)(this.handle)}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return W.d(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(),(0,D.DZQ)((()=>{const e=(0,D.K$i)(t),r=n.length,a=e.length;D.ZSL.assert(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];(0,D.aCs)(a),this.tensorMap.set(r,a)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return(0,D.DZQ)((()=>{const e=[];for(let r=0;r<n.length;r++){const a=n[r],s=this.findWithDefault(a,t);e.push(s)}return(0,D.t$z)(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 Bh(e,t,n,r,a=D.DZQ){const s=((e,t,n)=>{switch(e.category){case"arithmetic":return a((()=>((e,t,n,r=C)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(Bp("a",e,t,n),Bp("b",e,t,n))];case"AddN":return[r.addN(Bp("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(Bp("a",e,t,n),Bp("b",e,t,n))];case"Mul":return[r.mul(Bp("a",e,t,n),Bp("b",e,t,n))];case"RealDiv":case"Div":return[r.div(Bp("a",e,t,n),Bp("b",e,t,n))];case"DivNoNan":return[r.divNoNan(Bp("a",e,t,n),Bp("b",e,t,n))];case"FloorDiv":return[r.floorDiv(Bp("a",e,t,n),Bp("b",e,t,n))];case"Sub":return[r.sub(Bp("a",e,t,n),Bp("b",e,t,n))];case"Minimum":return[r.minimum(Bp("a",e,t,n),Bp("b",e,t,n))];case"Maximum":return[r.maximum(Bp("a",e,t,n),Bp("b",e,t,n))];case"Pow":return[r.pow(Bp("a",e,t,n),Bp("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(Bp("a",e,t,n),Bp("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=C)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(Bp("x",e,t,n))];case"Acos":return[r.acos(Bp("x",e,t,n))];case"Acosh":return[r.acosh(Bp("x",e,t,n))];case"Asin":return[r.asin(Bp("x",e,t,n))];case"Asinh":return[r.asinh(Bp("x",e,t,n))];case"Atan":return[r.atan(Bp("x",e,t,n))];case"Atan2":return[r.atan2(Bp("x",e,t,n),Bp("y",e,t,n))];case"Atanh":return[r.atanh(Bp("x",e,t,n))];case"Ceil":return[r.ceil(Bp("x",e,t,n))];case"Complex":return[r.complex(Bp("real",e,t,n),Bp("imag",e,t,n))];case"Cos":return[r.cos(Bp("x",e,t,n))];case"Cosh":return[r.cosh(Bp("x",e,t,n))];case"Elu":return[r.elu(Bp("x",e,t,n))];case"Erf":return[r.erf(Bp("x",e,t,n))];case"Exp":return[r.exp(Bp("x",e,t,n))];case"Expm1":return[r.expm1(Bp("x",e,t,n))];case"Floor":return[r.floor(Bp("x",e,t,n))];case"Log":return[r.log(Bp("x",e,t,n))];case"Log1p":return[r.log1p(Bp("x",e,t,n))];case"Imag":return[r.imag(Bp("x",e,t,n))];case"Neg":return[r.neg(Bp("x",e,t,n))];case"Reciprocal":return[r.reciprocal(Bp("x",e,t,n))];case"Real":return[r.real(Bp("x",e,t,n))];case"Relu":return[r.relu(Bp("x",e,t,n))];case"Round":return[r.round(Bp("x",e,t,n))];case"Selu":return[r.selu(Bp("x",e,t,n))];case"Sigmoid":return[r.sigmoid(Bp("x",e,t,n))];case"Sin":return[r.sin(Bp("x",e,t,n))];case"Sign":return[r.sign(Bp("x",e,t,n))];case"Sinh":return[r.sinh(Bp("x",e,t,n))];case"Softplus":return[r.softplus(Bp("x",e,t,n))];case"Sqrt":return[r.sqrt(Bp("x",e,t,n))];case"Square":return[r.square(Bp("x",e,t,n))];case"Tanh":return[r.tanh(Bp("x",e,t,n))];case"Tan":return[r.tan(Bp("x",e,t,n))];case"ClipByValue":return[r.clipByValue(Bp("x",e,t,n),Bp("clipValueMin",e,t,n),Bp("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(Bp("x",e,t,n))];case"Rsqrt":return[r.rsqrt(Wp(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(Bp("x",e,t,n),Bp("alpha",e,t,n))];case"Prelu":return[r.prelu(Bp("x",e,t,n),Bp("alpha",e,t,n))];case"IsNan":return[r.isNaN(Wp(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(Wp(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(Wp(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return Oh(e,t,n);case"convolution":return a((()=>((e,t,n,r=C)=>{switch(e.op){case"Conv1D":{const a=Bp("stride",e,t,n),s=Bp("pad",e,t,n),i=Bp("dataFormat",e,t,n).toUpperCase(),o=Bp("dilation",e,t,n);return[r.conv1d(Bp("x",e,t,n),Bp("filter",e,t,n),a,s,i,o)]}case"Conv2D":{const a=Bp("strides",e,t,n),s=jp(e,t,n),i=Bp("dataFormat",e,t,n).toUpperCase(),o=Bp("dilations",e,t,n);return[r.conv2d(Bp("x",e,t,n),Bp("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:a,pad:s,dataFormat:i,dilations:o,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:d}=zh(e,t,n);return[r.fused.conv2d({x:Bp("x",e,t,n),filter:Bp("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{const{stride:a,pad:s,dataFormat:i,dilations:o,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:d}=zh(e,t,n);return[r.fused.depthwiseConv2d({x:Bp("x",e,t,n),filter:Bp("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const a=Bp("outputShape",e,t,n),s=Bp("strides",e,t,n),i=jp(e,t,n);return[r.conv2dTranspose(Bp("x",e,t,n),Bp("filter",e,t,n),a,[s[1],s[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=Bp("strides",e,t,n),s=jp(e,t,n),i=Bp("dilations",e,t,n),o=Bp("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(Bp("input",e,t,n),Bp("filter",e,t,n),[a[1],a[2]],s,o,[i[1],i[2]])]}case"Conv3D":{const a=Bp("strides",e,t,n),s=Bp("pad",e,t,n),i=Bp("dataFormat",e,t,n).toUpperCase(),o=Bp("dilations",e,t,n);return[r.conv3d(Bp("x",e,t,n),Bp("filter",e,t,n),[a[1],a[2],a[3]],s,i,[o[1],o[2],o[3]])]}case"AvgPool":{const a=Bp("strides",e,t,n),s=Bp("pad",e,t,n),i=Bp("kernelSize",e,t,n);return[r.avgPool(Bp("x",e,t,n),[i[1],i[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=Bp("strides",e,t,n),s=Bp("pad",e,t,n),i=Bp("kernelSize",e,t,n);return[r.maxPool(Bp("x",e,t,n),[i[1],i[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=Bp("strides",e,t,n),s=Bp("pad",e,t,n),i=Bp("kernelSize",e,t,n),o=Bp("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(Bp("x",e,t,n),[i[1],i[2]],[a[1],a[2]],s,o);return[u,l]}case"AvgPool3D":{const a=Bp("strides",e,t,n),s=Bp("pad",e,t,n),i=Bp("kernelSize",e,t,n);return[r.avgPool3d(Bp("x",e,t,n),[i[1],i[2],i[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=Bp("strides",e,t,n),s=Bp("pad",e,t,n),i=Bp("kernelSize",e,t,n);return[r.maxPool3d(Bp("x",e,t,n),[i[1],i[2],i[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=Bp("strides",e,t,n),s=Bp("pad",e,t,n),i=Bp("dilations",e,t,n),o=a[1],u=a[2],l=i[1],c=i[2];return[r.dilation2d(Bp("x",e,t,n),Bp("filter",e,t,n),[o,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=C)=>{switch(e.op){case"Fill":{const a=Bp("shape",e,t,n),s=Bp("dtype",e,t,n),i=Bp("value",e,t,n);return[r.fill(a,i,s)]}case"LinSpace":{const a=Bp("start",e,t,n),s=Bp("stop",e,t,n),i=Bp("num",e,t,n);return[r.linspace(a,s,i)]}case"Multinomial":{const a=Bp("logits",e,t,n),s=Bp("numSamples",e,t,n),i=Bp("seed",e,t,n);return[r.multinomial(a,s,i)]}case"OneHot":{const a=Bp("indices",e,t,n),s=Bp("depth",e,t,n),i=Bp("onValue",e,t,n),o=Bp("offValue",e,t,n),u=Bp("dtype",e,t,n);return[r.oneHot(a,s,i,o,u)]}case"Ones":return[r.ones(Bp("shape",e,t,n),Bp("dtype",e,t,n))];case"OnesLike":return[r.onesLike(Bp("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(Bp("shape",e,t,n),Bp("dtype",e,t,n),Bp("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(Bp("shape",e,t,n),Bp("minval",e,t,n),Bp("maxval",e,t,n),Bp("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(Bp("shape",e,t,n),Bp("minval",e,t,n),Bp("maxval",e,t,n),Bp("seed",e,t,n))];case"Range":{const a=Bp("start",e,t,n),s=Bp("stop",e,t,n),i=Bp("step",e,t,n);return[r.range(a,s,i,Bp("dtype",e,t,n))]}case"TruncatedNormal":{const a=Bp("shape",e,t,n),s=Bp("mean",e,t,n),i=Bp("stdDev",e,t,n),o=Bp("seed",e,t,n);return[r.truncatedNormal(a,s,i,Bp("dtype",e,t,n),o)]}case"Zeros":return[r.zeros(Bp("shape",e,t,n),Bp("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(Bp("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=C)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=Lh(e,t,n),c=await a.image.nonMaxSuppressionWithScoreAsync(r,s,i,o,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:s,maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=Lh(e,t,n),l=Bp("padToMaxOutputSize",e,t,n),c=await a.image.nonMaxSuppressionPaddedAsync(r,s,i,o,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:s,maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=Lh(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,i,o,u)]}case"Where":{const r=a.cast(Bp("condition",e,t,n),"bool"),s=[await a.whereAsync(r)];return r.dispose(),s}case"ListDiff":return a.setdiff1dAsync(Bp("x",e,t,n),Bp("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=C)=>{switch(e.op){case"LowerBound":{const a=Bp("sortedSequence",e,t,n),s=Bp("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=Bp("x",e,t,n),s=Bp("k",e,t,n),i=Bp("sorted",e,t,n),o=r.topk(a,s,i);return[o.values,o.indices]}case"UpperBound":{const a=Bp("sortedSequence",e,t,n),s=Bp("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=Bp("x",e,t,n),s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=Bp("x",e,t,n),s=Bp("axis",e,t,n),i=r.unique(a,s);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return a((()=>((e,t,n,r=C)=>{switch(e.op){case"ResizeBilinear":{const a=Bp("images",e,t,n),s=Bp("size",e,t,n),i=Bp("alignCorners",e,t,n),o=Bp("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],i,o)]}case"ResizeNearestNeighbor":{const a=Bp("images",e,t,n),s=Bp("size",e,t,n),i=Bp("alignCorners",e,t,n),o=Bp("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],i,o)]}case"CropAndResize":{const a=Bp("image",e,t,n),s=Bp("boxes",e,t,n),i=Bp("boxInd",e,t,n),o=Bp("cropSize",e,t,n),u=Bp("method",e,t,n),l=Bp("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,i,o,u,l)]}case"ImageProjectiveTransformV3":{const a=Bp("images",e,t,n),s=Bp("transforms",e,t,n),i=Bp("outputShape",e,t,n),o=Bp("fillValue",e,t,n),u=Bp("interpolation",e,t,n),l=Bp("fillMode",e,t,n);return[r.image.transform(a,s,u.toLowerCase(),l.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return a((()=>((e,t,n,r=C)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const a=Bp("default",e,t,n);return[Wp(e.name,t,n)||a];case"Placeholder":return[Wp(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[qp(Bp("x",e,t,n))];case"IdentityN":return Bp("x",e,t,n).map((e=>qp(e)));case"Shape":return[r.tensor1d(Bp("x",e,t,n).shape,"int32")];case"ShapeN":return Bp("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(Bp("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(Bp("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const s=Bp("x",e,t,n),i=Bp("data",e,t,n);Bp("message",e,t,n),Bp("summarize",e,t,n);for(let e=0;e<i.length;e++);return[s];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"logical":return a((()=>((e,t,n,r=C)=>{switch(e.op){case"Equal":return[r.equal(Bp("a",e,t,n),Bp("b",e,t,n))];case"NotEqual":return[r.notEqual(Bp("a",e,t,n),Bp("b",e,t,n))];case"Greater":return[r.greater(Bp("a",e,t,n),Bp("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(Bp("a",e,t,n),Bp("b",e,t,n))];case"Less":return[r.less(Bp("a",e,t,n),Bp("b",e,t,n))];case"LessEqual":return[r.lessEqual(Bp("a",e,t,n),Bp("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(Bp("a",e,t,n),Bp("b",e,t,n))];case"LogicalNot":return[r.logicalNot(Bp("a",e,t,n))];case"LogicalOr":return[r.logicalOr(Bp("a",e,t,n),Bp("b",e,t,n))];case"Select":case"SelectV2":return[r.where(Bp("condition",e,t,n),Bp("a",e,t,n),Bp("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(Bp("a",e,t,n),Bp("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=C)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(Bp("a",e,t,n),Bp("b",e,t,n),Bp("transposeA",e,t,n),Bp("transposeB",e,t,n))];case"Einsum":return[r.einsum(Bp("equation",e,t,n),...Bp("tensors",e,t,n))];case"Transpose":return[r.transpose(Bp("x",e,t,n),Bp("perm",e,t,n))];case"_FusedMatMul":const[a,s]=Bp("fusedOps",e,t,n),i="biasadd"===a,o="prelu"===s,u=Bp("numArgs",e,t,n),l=Bp("leakyreluAlpha",e,t,n);if(i){if(o&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,d]=Bp("args",e,t,n);return[r.fused.matMul({a:Bp("a",e,t,n),b:Bp("b",e,t,n),transposeA:Bp("transposeA",e,t,n),transposeB:Bp("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:d,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(Bp("a",e,t,n),Bp("numLower",e,t,n),Bp("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=C)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(Bp("x",e,t,n),Bp("axis",e,t,n),Bp("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(Bp("x",e,t,n),Bp("mean",e,t,n),Bp("variance",e,t,n),Bp("offset",e,t,n),Bp("scale",e,t,n),Bp("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(Bp("x",e,t,n),Bp("radius",e,t,n),Bp("bias",e,t,n),Bp("alpha",e,t,n),Bp("beta",e,t,n))];case"Softmax":return[r.softmax(Bp("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(Bp("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=C)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:a,outputDenseValues:s}=r.raggedGather(Bp("paramsNestedSplits",e,t,n),Bp("paramsDenseValues",e,t,n),Bp("indices",e,t,n),Bp("outputRaggedRank",e,t,n));return a.concat(s)}case"RaggedRange":{const{rtNestedSplits:a,rtDenseValues:s}=r.raggedRange(Bp("starts",e,t,n),Bp("limits",e,t,n),Bp("splits",e,t,n));return[a,s]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(Bp("shape",e,t,n),Bp("values",e,t,n),Bp("defaultValue",e,t,n),Bp("rowPartitionTensors",e,t,n),Bp("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=C)=>{switch(e.op){case"Max":{const a=Bp("axis",e,t,n),s=Bp("keepDims",e,t,n);return[r.max(Bp("x",e,t,n),a,s)]}case"Mean":{const a=Bp("axis",e,t,n),s=Bp("keepDims",e,t,n);return[r.mean(Bp("x",e,t,n),a,s)]}case"Min":{const a=Bp("axis",e,t,n),s=Bp("keepDims",e,t,n);return[r.min(Bp("x",e,t,n),a,s)]}case"Sum":{const a=Bp("axis",e,t,n),s=Bp("keepDims",e,t,n);return[r.sum(Bp("x",e,t,n),a,s)]}case"All":{const a=Bp("axis",e,t,n),s=Bp("keepDims",e,t,n);return[r.all(Bp("x",e,t,n),a,s)]}case"Any":{const a=Bp("axis",e,t,n),s=Bp("keepDims",e,t,n);return[r.any(Bp("x",e,t,n),a,s)]}case"ArgMax":{const a=Bp("axis",e,t,n);return[r.argMax(Bp("x",e,t,n),a)]}case"ArgMin":{const a=Bp("axis",e,t,n);return[r.argMin(Bp("x",e,t,n),a)]}case"Prod":{const a=Bp("axis",e,t,n),s=Bp("keepDims",e,t,n);return[r.prod(Bp("x",e,t,n),a,s)]}case"Cumprod":{const a=Bp("axis",e,t,n),s=Bp("exclusive",e,t,n),i=Bp("reverse",e,t,n);return[r.cumprod(Bp("x",e,t,n),a,s,i)]}case"Cumsum":{const a=Bp("axis",e,t,n),s=Bp("exclusive",e,t,n),i=Bp("reverse",e,t,n);return[r.cumsum(Bp("x",e,t,n),a,s,i)]}case"Bincount":const a=Bp("x",e,t,n),s=Bp("weights",e,t,n),i=Bp("size",e,t,n);return[r.bincount(a,s,i)];case"DenseBincount":{const a=Bp("x",e,t,n),s=Bp("weights",e,t,n),i=Bp("size",e,t,n),o=Bp("binaryOutput",e,t,n);return[r.denseBincount(a,s,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return a((()=>((e,t,n,r=C)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=Bp("n",e,t,n),s=Bp("axis",e,t,n);let i=Bp("tensors",e,t,n);return i=i.slice(0,a),[r.concat(i,s)]}case"Gather":{const a=Bp("x",e,t,n),s=Bp("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=Bp("axis",e,t,n),s=Bp("batchDims",e,t,n),i=Bp("x",e,t,n),o=Bp("indices",e,t,n);return[r.gather(i,r.cast(o,"int32"),a,s)]}case"Reverse":{const a=Bp("dims",e,t,n),s=[];for(let e=0;e<a.length;e++)a[e]&&s.push(e);const i=Bp("x",e,t,n);return[r.reverse(i,s)]}case"ReverseV2":{const a=Bp("axis",e,t,n),s=Bp("x",e,t,n);return[r.reverse(s,a)]}case"Slice":{const a=Bp("begin",e,t,n),s=Bp("size",e,t,n);return[r.slice(Bp("x",e,t,n),a,s)]}case"StridedSlice":{const a=Bp("begin",e,t,n),s=Bp("end",e,t,n),i=Bp("strides",e,t,n),o=Bp("beginMask",e,t,n),u=Bp("endMask",e,t,n),l=Bp("ellipsisMask",e,t,n),c=Bp("newAxisMask",e,t,n),d=Bp("shrinkAxisMask",e,t,n),p=Bp("x",e,t,n);return[r.stridedSlice(p,a,s,i,o,u,l,c,d)]}case"Pack":return(0,D.DZQ)((()=>{const a=Bp("axis",e,t,n),s=Bp("tensors",e,t,n),i=s[0].shape,o=r.squeeze(s[0]).shape,u=s.map((e=>{const t=D.ZSL.arraysEqual(e.shape,i);if(!t&&!D.ZSL.arraysEqual(r.squeeze(e).shape,o))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,i)}));return[r.stack(u,a)]}));case"Unpack":{const a=Bp("axis",e,t,n),s=Bp("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=Bp("reps",e,t,n);return[r.tile(Bp("x",e,t,n),a)]}case"Split":case"SplitV":{const a=Bp("axis",e,t,n),s=Bp("numOrSizeSplits",e,t,n),i=Bp("x",e,t,n);return r.split(i,s,a)}case"ScatterNd":{const a=Bp("indices",e,t,n),s=Bp("values",e,t,n),i=Bp("shape",e,t,n);return[r.scatterND(a,s,i)]}case"GatherNd":{const a=Bp("x",e,t,n),s=Bp("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=Bp("sparseIndices",e,t,n),s=Bp("outputShape",e,t,n),i=Bp("sparseValues",e,t,n),o=Bp("defaultValue",e,t,n);return[r.sparseToDense(a,i,s,i.dtype===o.dtype?o:r.cast(o,i.dtype))]}case"TensorScatterUpdate":{const a=Bp("indices",e,t,n),s=Bp("values",e,t,n),i=Bp("tensor",e,t,n);return[r.tensorScatterUpdate(i,a,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return a((()=>((e,t,n,r=C)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:i,reverseIndexMap:o}=r.sparse.sparseFillEmptyRows(Bp("indices",e,t,n),Bp("values",e,t,n),Bp("denseShape",e,t,n),Bp("defaultValue",e,t,n));return[a,s,i,o]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(Bp("inputIndices",e,t,n),Bp("inputShape",e,t,n),Bp("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(Bp("data",e,t,n),Bp("indices",e,t,n),Bp("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(Bp("data",e,t,n),Bp("indices",e,t,n),Bp("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=C)=>{switch(e.op){case"FFT":return[r.fft(Bp("x",e,t,n))];case"IFFT":return[r.ifft(Bp("x",e,t,n))];case"RFFT":return[r.rfft(Bp("x",e,t,n))];case"IRFFT":return[r.irfft(Bp("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=C)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(Bp("input",e,t,n),Bp("pattern",e,t,n),Bp("rewrite",e,t,n),Bp("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(Bp("data",e,t,n),Bp("dataSplits",e,t,n),Bp("separator",e,t,n),Bp("nGramWidths",e,t,n),Bp("leftPad",e,t,n),Bp("rightPad",e,t,n),Bp("padWidth",e,t,n),Bp("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:i}=r.string.stringSplit(Bp("input",e,t,n),Bp("delimiter",e,t,n),Bp("skipEmpty",e,t,n));return[a,s,i]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(Bp("input",e,t,n),Bp("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=C)=>{switch(e.op){case"Cast":return[r.cast(Bp("x",e,t,n),Bp("dtype",e,t,n))];case"ExpandDims":{const a=Bp("axis",e,t,n);return[r.expandDims(Bp("x",e,t,n),a)]}case"Squeeze":{const a=Bp("axis",e,t,n);return[r.squeeze(Bp("x",e,t,n),a)]}case"Reshape":return[r.reshape(Bp("x",e,t,n),Bp("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(Bp("x",e,t,n),Bp("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(Bp("x",e,t,n),Bp("padding",e,t,n),Bp("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(Bp("x",e,t,n),Bp("padding",e,t,n),Bp("constantValue",e,t,n))];case"SpaceToBatchND":{const a=Bp("blockShape",e,t,n),s=Bp("paddings",e,t,n);return[r.spaceToBatchND(Bp("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=Bp("blockShape",e,t,n),s=Bp("crops",e,t,n);return[r.batchToSpaceND(Bp("x",e,t,n),a,s)]}case"DepthToSpace":{const a=Bp("blockSize",e,t,n),s=Bp("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(Bp("x",e,t,n),a,s)]}case"BroadcastTo":return[r.broadcastTo(Bp("x",e,t,n),Bp("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(Bp("s0",e,t,n),Bp("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=Bp("keyDType",e,t,n),s=Bp("valueDType",e,t,n),i=new Ph(a,s);return r.addHashTable(e.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const a=Bp("tableHandle",e,t,n,r),s=Bp("keys",e,t,n),i=Bp("values",e,t,n),o=r.getHashTableById(a.id);return[await o.import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{const a=Bp("tableHandle",e,t,n,r),s=Bp("keys",e,t,n),i=Bp("defaultValue",e,t,n),o=r.getHashTableById(a.id);return[await o.find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=Bp("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=Lp(e.op);if(s&&s.customExecutor)return s.customExecutor(new Ch(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 D.ZSL.isPromise(s)?s.then((e=>[].concat(e))):[].concat(s)}class Wh{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 Vh(e,t,n,r){const a=new Set,s=[];let i=null,o=null;const u=new Set,l=new Set(Object.keys(e).map((e=>Hp(e)[0])));r=r||[];const c=new Set(r.map((e=>Hp(e.name)[0]))),d=[...t];for(;d.length>0;){const e=d.pop();(Zh(e)||Kh(e)||Yh(e))&&null==i&&(i=e,o=i.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:i,syncInputs:o}}function Uh(e,t){const{usedNodes:n,inputs:r}=t,a=Object.keys(r).map((e=>Hp(e)[0])).map((t=>e.nodes[t])),s=e.initNodes||[],i=e=>n.has("string"===typeof e?e:e.name);function o(e){return[...new Map(e.map((e=>[e.name,e]))).values()]}const u=o([...a,...e.weights,...s]).filter(i),l=o([...u,...Object.values(e.nodes)]).filter(i),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)i(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(i))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))),i=e=>s.has("string"===typeof e?e:e.name);for(const o of e){for(const e of o.children.filter(i)){if(!n.has(e.name))throw new Gh(`Child ${e.name} of node ${o.name} is unreachable.`);if(n.get(o.name)>n.get(e.name))throw new Gh(`Node ${o.name} is scheduled to run after its child ${e.name}.`)}if(!a(o))for(const e of o.inputs){if(!n.has(e.name))throw new Gh(`Input ${e.name} of node ${o.name} is unreachable.`);if(n.get(e.name)>n.get(o.name))throw new Gh(`Node ${o.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}class Gh extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const Hh=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),jh=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),qh=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function Zh(e){return Hh.has(e.op)}function Kh(e){return jh.has(e.op)}function Yh(e){return qh.has(e.op)}class Qh{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 Qh(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=Vh(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 i=Uh(this.graph,n),o=function(e){const t=new Map(e.map(((e,t)=>[e.name,t]))),n=Number.MAX_SAFE_INTEGER,r=e.map(((e,t)=>Zh(e)?n:t)),a=e=>{const n=r[t.get(e.name)];return null==n?-1:n},s=e.map(((e,t)=>e.children.map(a).reduce(((e,t)=>Math.max(e,t)),r[t]))),i=new Map;for(let o=0;o<e.length;++o){const t=s[o];if(t===n)continue;const r=e[o],a=e[t];i.has(a.name)||i.set(a.name,[]),i.get(a.name).push(r)}return i}(i);return{orderedNodes:i,nodeLiveUntilMap:o}}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return(0,D.aCs)(t),t}cloneTensorList(e){if(!e)return null;const t=e.map((e=>this.cloneAndKeepTensor(e)));return t}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[Hp(e)[0]])),a=t.map((e=>Hp(e)[0])),s=new Set(a);let i=a.map((e=>this.graph.nodes[e]));0===i.length&&(i=this._outputs);const o=this.getCompilationKey(r,i);let u=this.compiledMap.get(o);null==u&&(u=this.compile(e,i),this.compiledMap.set(o,u));try{this.keepIntermediateTensors=(0,D._K2)().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1}const l={},c={};return(0,D.DZQ)((()=>{const n=new Wh(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]=Hp(t,n),i=[];i[s]=e[t],r[a]=i,this.keepIntermediateTensors&&(this.clonedTensorsMap[a]=this.cloneTensorList(i))}));const a=this.getFrozenTensorIds(r),{orderedNodes:i,nodeLiveUntilMap:o}=u;for(const e of i){if(r[e.name])continue;const t=Bh(e,r,n,this._resourceManager);if(D.ZSL.isPromise(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,o.get(e.name))}return null==this.parent&&n.dispose(a),t.map((e=>Wp(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,i){if(!Zh(t)&&!s.has(e)){for(const r of n[e])null!=r&&(i[r.id]=(i[r.id]||0)+t.children.length);for(const e of t.inputs){if(Zh(e))continue;const t=Vp(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||a.has(e.id))continue;const t=i[e.id];1===t?(e.dispose(),delete i[e.id]):null!=t&&i[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,a,s){function i(e){return Zh(e)||a.has(e.name)}if(!Zh(e)&&null!=s)for(const o of s){if(i(o))continue;const e=Vp(o.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=(0,D._K2)().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){this.keepIntermediateTensors=!1}const s=new Wh(this.weightMap,r,a,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,s,t,n),o=t.map((e=>Wp(e,i,s))),u=o.map((e=>e.id)),l=Object.keys(e).map((t=>e[t].id)),c=new Set([...u,...l,...this.weightIds]);return Object.values(i).forEach((e=>{e.forEach((e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()}))})),null==this.parent&&s.dispose(c),o}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[Hp(e)[0]])),i=n.map((e=>Hp(e)[0])),o=new Set(i);let u=i.map((e=>this.graph.nodes[e]));0===u.length&&(u=this._outputs);const{usedNodes:l,missingInputs:c,dynamicNode:d,syncInputs:p}=Vh(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]=Hp(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,o,m,l);await Promise.all(e)}const b=u.filter((e=>!Zh(e)&&!Wp(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,i,o,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&Bp("isConstant",e.node,r,n)&&([c]=Up(e.node.name,n)),null==r[e.node.name]){const d=Bh(e.node,r,n,this._resourceManager);c||([c]=Up(e.node.name,n));const p=n.currentContext;D.ZSL.isPromise(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,i,o),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,i,o),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[i]=Up(e.name,n);!a[i]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!Wp(e,r,n)))&&(a[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!Wp(e,r,n)))&&(a[i]=!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]=Hp(t),a=this.graph.nodes[r];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value,t=e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t));D.ZSL.assert(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&&D.ZSL.assert(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]=Hp(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]=Hp(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class Xh{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]}}var Jh=n(7084);const ef="?tfjs-format=file",tf="model.json";class nf{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=D.io){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new Xh}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 D.ZSL.isPromise(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(0,Jh.s5)(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 Qh(hh.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=hh.Instance.transformGraph(e.modelInitializer);this.initializer=new Qh(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=e instanceof D.qYS?[e]:e,n={};return t.forEach(((e,t)=>n[this.structuredOutputKeys[t]]=e)),n}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 D.qYS)&&!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,i;const o=null===(i=null===(s=null===(a=this.signature)||void 0===a?void 0:a.inputs)||void 0===s?void 0:s[n])||void 0===i?void 0:i.resourceId;return t[n]=null!=o?this.resourceIdToCapturedInput[o]: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&&(0,D.ASo)(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function rf(e,t={},n=D.io){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}${tf}${ef}`}(e));const r=new nf(e,t,n);return await r.load(),r}function af(e){if(null==e)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(e instanceof Array){const[n,r]=e;if(!n)throw new Error("modelJSON must be the first element of the array");if(!r||!(r instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in n))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in n))throw new Error("Model JSON is missing 'weightsManifest'");const a=D.io.getWeightSpecs(n.weightsManifest),s=D.io.getModelArtifactsForJSONSync(n,a,r);t=D.io.fromMemorySync(s)}else if("load"in e)t=e;else{if(!("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e))throw new Error("Unknown model format");t=D.io.fromMemorySync(e)}const n=new nf(t);return n.load(),n}const sf="4.22.0";var of,uf=n(7391);function lf(e,t,n=new Map,r=new Set){if(null==e)return null;if("function"===typeof Blob&&e instanceof Blob)return e.slice();if(r.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const a=t(e);if(a.recurse&&null!==a.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(a.recurse){if(ff(e)){const a=Array.isArray(e)?[]:{};r.add(e);for(const s in e){const i=lf(e[s],t,n,r);a[s]=i}return r.delete(e),e.__proto__&&(a.__proto__=e.__proto__),a}throw new Error(`Can't recurse into non-iterable type: ${e}`)}return n.set(e,a.value),a.value}function cf(e,t=pf){return df(e,t)}function df(e,t,n=new Set){const r=e[0];if(n.has(r))throw new Error("Circular references are not supported.");const a=t(e);if(a.recurse&&null!==a.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(a.recurse){if(ff(r)){const a=Array.isArray(r)?[]:{};n.add(r);for(const s in r){const r=df(e.map((e=>e[s])),t,n);a[s]=r}return n.delete(r),a}throw new Error(`Can't recurse into non-iterable type: ${r}`)}return a.value}function pf(e){return null===e?null:ff(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function hf(e,t){const n=new Map;lf(e,t,n);for(const r of Array.from(n.keys())){const e=n.get(r);if(D.ZSL.isPromise(e)){const t=await e;n.set(r,t)}}return lf(e,t,n)}function ff(e){let t=!1;if(D._K2().get("IS_BROWSER"))t=e instanceof TextDecoder;else{const{StringDecoder:r}=n(551);t=e instanceof r}return null!=e&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||"object"===typeof e&&!(e instanceof D.qYS)&&!(e instanceof Promise)&&!t)}function mf(e){return function(e,t){return lf(e,t)}(e,gf)}function gf(e){return e instanceof D.qYS?{value:e.clone(),recurse:!1}:ff(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class yf{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,null==e)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return 0===this.length()}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class bf extends yf{constructor(){super(bf.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=2*this.capacity,t=new Array(e),n=this.length();for(let r=0;r<n;r++)t[r]=this.get(this.wrap(this.begin+r));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}}function xf(e){return new Sf(e)}function wf(e){return new _f(e)}function vf(e,t){return new Mf(e,t)}bf.INITIAL_CAPACITY=32;class kf{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new Af(this,e)}filter(e){return new Nf(this,e)}map(e){return new Ef(this,e)}mapAsync(e){return new Rf(this,e)}serialMapAsync(e){return new Rf(this,e).serial()}flatmap(e){return new Ff(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile((e=>!0===e))}rowMajorBatch(e,t=!0){return new Cf(this,e,t)}columnMajorBatch(e,t=!0,n=pf){return this.rowMajorBatch(e,t).map((e=>cf(e,n)))}concatenate(e,t){return new Mf(xf([this,e]),t)}take(e){return e<0||null==e?this:new $f(this,e)}skip(e){return e<0||null==e?this:new Tf(this,e)}prefetch(e){return new zf(this,e)}shuffle(e,t){return new Lf(this,e,t)}serial(){return new If(this)}}class Sf extends kf{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:mf(e),done:!1}}}class _f extends kf{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class If extends kf{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){return this.upstream.next()}}class Tf extends kf{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){const e=await this.upstream.next();if(e.done)return e;D.ASo(e.value)}return this.upstream.next()}}class $f extends kf{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class Cf extends kf{constructor(e,t,n=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){const e=[];for(;e.length<this.batchSize;){const t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class Nf extends kf{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;D.ASo(e.value)}}}class Ef extends kf{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=D.d_S.getTensorsInContainer(e.value),n=this.transform(e.value),r=D.d_S.getTensorsInContainer(n);for(const a of t)D.d_S.isTensorInList(a,r)||a.dispose();return{value:n,done:!1}}}class Af extends kf{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class Rf extends kf{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=D.d_S.getTensorsInContainer(e.value),n=await this.transform(e.value),r=D.d_S.getTensorsInContainer(n);for(const a of t)D.d_S.isTensorInList(a,r)||a.dispose();return{value:n,done:!1}}}class Df extends kf{constructor(){super(),this.outputQueue=new bf,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;0===this.outputQueue.length();)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class Ff extends Df{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=D.d_S.getTensorsInContainer(e.value),n=this.transform(e.value),r=D.d_S.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(const a of t)D.d_S.isTensorInList(a,r)||a.dispose();return!0}}class Mf extends kf{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,null==this.iterator){const e=await this.moreIterators.next();if(e.done)return{value:null,done:!0};this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}(of||(of={}));class Of extends kf{constructor(e,t=of.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;const r=await hf(this.iterators,(function(e){if(e instanceof kf){return{value:e.next().then((e=>(t++,e.done&&n++,e.value))),recurse:!1}}return{value:null,recurse:!0}}));if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case of.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case of.SHORTEST:return{value:null,done:!0};case of.LONGEST:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class zf extends kf{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new yf(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class Lf extends zf{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=uf.alea(n||D.ZSL.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(!t.done)return this.refill(),t;this.upstreamExhausted=!0}return{value:null,done:!0}}}class Pf{constructor(){this.size=null}batch(e,t=!0){const n=this;let r;return D.ZSL.assert(e>0,(()=>`batchSize needs to be positive, but it is\n      ${e}`)),r=this.size===1/0||null==this.size?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),Bf((async()=>(await n.iterator()).columnMajorBatch(e,t,Uf)),r)}concatenate(e){const t=this;let n;return n=this.size===1/0||e.size===1/0?1/0:null!=this.size&&null!=e.size?this.size+e.size:null,Bf((async()=>(await t.iterator()).concatenate(await e.iterator())),n)}filter(e){const t=this;let n;return n=this.size===1/0?1/0:null,Bf((async()=>(await t.iterator()).filter((t=>D.DZQ((()=>e(t)))))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return Bf((async()=>(await t.iterator()).map((t=>D.DZQ((()=>e(t)))))),this.size)}mapAsync(e){const t=this;return Bf((async()=>(await t.iterator()).mapAsync(e)),this.size)}prefetch(e){if(null==e)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return Bf((async()=>(await t.iterator()).prefetch(e)),this.size)}repeat(e){const t=this;let n;return n=null!=this.size&&e>0?this.size*e:0===e?0:null!=this.size&&(void 0===e||e<0)?1/0:null,Bf((async()=>vf(wf((async()=>({value:await t.iterator(),done:!1}))).take(e))),n)}skip(e){const t=this;let n;return n=null!=this.size&&e>=0&&this.size>=e?this.size-e:null!=this.size&&(this.size<e||void 0===e||e<0)?0:null,Bf((async()=>(await t.iterator()).skip(e)),n)}shuffle(e,t,n=!0){if(null==e||e<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified.  If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const r=this,a=uf.alea(t||D.ZSL.now().toString());return Bf((async()=>{let t=a.int32();return n&&(t+=a.int32()),(await r.iterator()).shuffle(e,t.toString())}),this.size)}take(e){const t=this;let n;return n=null!=this.size&&this.size>e?e:null!=this.size&&this.size<=e?this.size:null,Bf((async()=>(await t.iterator()).take(e)),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}function Bf(e,t=null){return new class extends Pf{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function Wf(e){return Bf((async()=>xf(e)),e.length)}function Vf(e){if(!ff(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=null==t?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(const n in e)t=null==t?e[n].size:Math.min(t,e[n].size);return Bf((async()=>function(e,t=of.FAIL){return new Of(e,t)}(await hf(e,(e=>{if(e instanceof Pf)return{value:e.iterator(),recurse:!1};if(ff(e))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})),of.SHORTEST)),t)}function Uf(e){if(null===e)return null;if(function(e){return null==e||null===(t=e)||"object"!==typeof t&&"function"!==typeof t||Array.isArray(e)||"object"===typeof e&&e instanceof D.qYS||D.ZSL.isTypedArray(e);var t}(e[0])){return{value:function(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof D.qYS?D.t$z(e):D.OEK(e)}(e),recurse:!1}}return{value:null,recurse:!0}}Pf.MAX_BUFFER_SIZE=1e4;class Gf extends Pf{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split("\n").map((e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e)))}}const Hf='"',jf=Symbol("out"),qf=Symbol("field"),Zf=Symbol("quote"),Kf=Symbol("quoteafterquote"),Yf=Symbol("quoteinquote");class Qf extends Pf{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&D.ZSL.assert(e.length===this.fullColumnNames.length,(()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+").")),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce(((e,t)=>(e[t]=e[t]+1||1,e)),{}),n=Object.keys(t).filter((e=>t[e]>1));if(D.ZSL.assert(0===n.length,(()=>"Duplicate column names found: "+n.toString())),this.columnConfigs)for(const r of Object.keys(this.columnConfigs)){if(-1===this.fullColumnNames.indexOf(r))throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value;return this.parseRow(n,!1)}return null}constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new Gf(e),t||(t={}),this.hasHeader=!1!==t.hasHeader,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(D.ZSL.assert(null==t.delimiter,(()=>"Delimiter should not be provided when delimWhitespace is true.")),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map((e=>this.makeDataElement(e)))}makeDataElement(e){const t=this.parseRow(e),n={},r={};for(let a=0;a<this.fullColumnNames.length;a++){const s=this.fullColumnNames[a],i=this.columnConfigs?this.columnConfigs[s]:null;if(!this.configuredColumnsOnly||i){const o=t[a];let u=null;if(""===o)if(i&&void 0!==i.default)u=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${s} is empty in this line: ${e}`);u=void 0}else{const e=Number(o);if(isNaN(e))u=i&&"bool"===i.dtype?this.getBoolean(o):o;else if(i&&i.dtype)switch(i.dtype){case"float32":default:u=e;break;case"int32":u=Math.floor(e);break;case"bool":u=this.getBoolean(o)}else u=e}i&&i.isLabel?r[s]=u:n[s]=u}}return 0===Object.keys(r).length?n:{xs:n,ys:r}}getBoolean(e){return"1"===e||"true"===e.toLowerCase()?1:0}parseRow(e,t=!0){const n=[];let r=0;const a=e.length;let s=jf;for(let i=0;i<a;i++)switch(s){case jf:switch(e.charAt(i)){case Hf:r=i+1,s=Zf;break;case this.delimiter:if(r=i+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),s=jf;break;default:s=qf,r=i}break;case qf:if(e.charAt(i)===this.delimiter)n.push(e.substring(r,i)),s=jf,r=i+1;break;case Zf:if(e.charAt(i)===Hf)s=Kf;break;case Kf:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(r,i-1)),s=jf,r=i+1;break;case Hf:s=Zf;break;default:s=Yf}break;case Yf:if(e.charAt(i)===Hf)s=Zf}if(s===Kf?n.push(e.substring(r,a-1)):n.push(e.substring(r)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}}class Xf extends kf{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!1!==e.includeSpectrogram,this.includeWaveform=!0===e.includeWaveform,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(!(0,D._K2)().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");const t=new Xf(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`)}else this.sampleRateHz=this.audioContext.sampleRate;const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const n=await this.getAudioData();if(this.includeSpectrogram){const t=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(t,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const e=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(e,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let n=0;return new Promise((r=>{const a=setInterval((()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&r({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(a),r({freqDataQueue:e,timeDataQueue:t}))}),this.fftSize/this.sampleRateHz*1e3)}))}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,n=new Float32Array(e.length*t);return e.forEach(((e,r)=>n.set(e,r*t))),n}getTensorFromAudioDataArray(e,t){const n=new Float32Array(D.ZSL.sizeFromShape(t));return n.set(e,n.length-e.length),(0,D.OEK)(n,t)}}class Jf extends kf{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=(0,D.tGX)([0],"int32"),this.webcamConfig.centerCrop){const e=1*this.webcamConfig.resizeWidth/this.webcamVideoElement.width,t=1*this.webcamConfig.resizeHeight/this.webcamVideoElement.height,n=(1-e)/2,r=(1-t)/2,a=n+e,s=t+r;this.cropBox=(0,D.KtR)([r,n,s,a],[1,4])}else this.cropBox=(0,D.KtR)([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!(0,D._K2)().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const n=new Jf(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&D.ZSL.assert("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,(()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`));try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(t){this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise((e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}}))}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=D.TaL.fromPixels(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(!this.resize)return{value:e,done:!1};try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}}needToResize(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)}cropAndResizeFrame(e){return(0,D.DZQ)((()=>{const t=(0,D.UG6)((0,D.wgE)(e,"float32"),0);let n;n=D.Slp.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const r=n.shape;return(0,D.tQQ)(n,r.slice(1))}))}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach((e=>e.stop()));try{this.webcamVideoElement.srcObject=null}catch(e){this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class em{}class tm extends kf{split(e){return new nm(this,e)}}class nm extends tm{constructor(e,t){super(),this.upstream=e,this.impl=new rm(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class rm extends Df{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return""!==this.carryover&&(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}}class am extends kf{decodeUTF8(){return new sm(this)}}class sm extends tm{constructor(e){super(),this.upstream=e,this.impl=new im(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class im extends Df{constructor(e){if(super(),this.upstream=e,(0,D._K2)().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:e}=n(4530);this.decoder=new e("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t,n;return!e.done&&(t=e.value,n=(0,D._K2)().get("IS_BROWSER")?this.decoder.decode(t,{stream:!0}):this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0)}}class om extends am{constructor(e,t={}){super(),this.file=e,this.options=t,D.ZSL.assert(e instanceof Uint8Array||!!(0,D._K2)().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),(()=>"FileChunkIterator only supports File, Blob and Uint8Array right now.")),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1048576}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise(((e,t)=>{const n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{const r=new FileReader;r.onload=n=>{let a=r.result;if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),!(a instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(a)},r.onabort=e=>t(new Error("Aborted")),r.onerror=e=>t(new Error(e.type));const a=this.file.slice(this.offset,n);r.readAsArrayBuffer(a)}this.offset=n}));return{value:await e,done:!1}}}const um=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function lm(e){return"string"===typeof e&&"file://"===e.slice(0,7)}class cm extends em{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(lm(this.input)&&(0,D._K2)().get("IS_NODE")){const e=n(8108);this.input=e.readFileSync(this.input.slice(7))}return new om(this.input,this.options)}}class dm extends em{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return lm(this.url)?new cm(this.url,this.fileOptions).iterator():async function(e,t={},n){let r,a;"string"===typeof e?r=e:(r=e.url,a=um(e));const s=await(n||D.ZSL.fetch)(r,a);if(s.ok){const e=new Uint8Array(await s.arrayBuffer());return new om(e,t)}throw new Error(s.statusText)}(this.url,this.fileOptions)}}function pm(e,t={}){return new Qf(new dm(e),t)}function hm(e){const t=wf(e);return Bf((async()=>t))}function fm(e){return Bf((async()=>{const t=await e();return wf((()=>t.next()))}))}async function mm(e,t){return Jf.create(e,t)}async function gm(e){return Xf.create(e)}const ym="4.22.0";var bm=n(7870);const xm=D.kpo.whereImpl;class wm extends D.uI_{nextDataId(){return wm.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new D.GJx(this,(0,D.Hi9)())}write(e,t,n){this.firstUse&&(this.firstUse=!1,(0,D._K2)().get("IS_NODE")&&D.C0T.warn("\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&&D.ZSL.isString(n[0])){const a=n.map((e=>D.ZSL.encodeString(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){const e=this.readSync(n.real.dataId),t=this.readSync(n.imag.dataId);return D.C0T.mergeRealAndImagArrays(e,t)}return D.ZSL.convertBackendValuesAndArrayBuffer(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>D.ZSL.decodeString(e)));return(0,D.ra8)(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return(0,D.ra8)(e.shape,e.dtype,t)}makeOutput(e,t,n){return(0,D.Hi9)().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=D.ZSL.now();e();return{kernelMs:D.ZSL.now()-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){(0,bm.C)([e],"where");const t=this.readSync(e.dataId);return xm(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function vm(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}wm.nextDataId=0;const km={kernelName:D.ljI,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend;(0,bm.C)(t,"abs");let r=new Float32Array(D.ZSL.sizeFromShape(t.shape));return r=vm(n.data.get(t.dataId).values),n.makeOutput(r,t.shape,t.dtype)}};function Sm(e){return(t,n,r,a,s)=>{const i=D.C0T.assertAndGetBroadcastShape(t,n),o=i.length,u=D.ZSL.computeStrides(i),l=D.ZSL.sizeFromShape(i),c=D.ZSL.getTypedArrayFromDType(s,l),d=t.length,p=n.length,h=D.ZSL.computeStrides(t),f=D.ZSL.computeStrides(n),m=D.C0T.getBroadcastDims(t,i),g=D.C0T.getBroadcastDims(n,i);if(m.length+g.length===0)for(let y=0;y<c.length;++y)c[y]=e(r[y%r.length],a[y%a.length]);else for(let y=0;y<c.length;++y){const t=D.ZSL.indexToLoc(y,o,u),n=t.slice(-d);m.forEach((e=>n[e]=0));const s=D.ZSL.locToIndex(n,d,h),i=t.slice(-p);g.forEach((e=>i[e]=0));const l=D.ZSL.locToIndex(i,p,f);c[y]=e(r[s],a[l])}return[c,i]}}function _m(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.data.get(r.dataId).values,i=n.data.get(a.dataId).values,o=n.makeTensorInfo(r.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",s),imag:n.makeTensorInfo(a.shape,"float32",i)},o}const Im={kernelName:D.pr3,backendName:"cpu",kernelFunc:_m};function Tm(e,t,n="float32"){if("complex64"===n){return _m({inputs:{real:Tm(e,t,"float32"),imag:Tm(e,t,"float32")},backend:e})}const r=D.ZSL.makeZerosTypedArray(D.ZSL.sizeFromShape(t),n);return e.makeTensorInfo(t,n,r)}function $m(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 Cm={kernelName:D.lzr,backendName:"cpu",kernelFunc:$m};function Nm(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 Em={kernelName:D.LRy,backendName:"cpu",kernelFunc:Nm};function Am(e,t,n,r){if("int32"===r){return[t,"int32",Int32Array.from(e)]}if("bool"===r){const r=D.ZSL.toTypedArray([0],n),[a,s]=Sm(((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 Rm(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dtype:s}=r;if("complex64"===s){if("complex64"===a.dtype)return $m({inputs:{x:a},backend:n});const e=Tm(n,a.shape,a.dtype),t=Rm({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),r=_m({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===a.dtype){const e=Nm({inputs:{input:a},backend:n}),t=Rm({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(!D.ZSL.hasEncodingLoss(a.dtype,s)){const e=$m({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:s}}const i=n.data.get(a.dataId).values,[o,u,l]=Am(i,a.shape,a.dtype,s);return n.makeTensorInfo(o,u,l)}const Dm={kernelName:D.KXH,backendName:"cpu",kernelFunc:Rm};function Fm(e,t,n,r){return null==n?({inputs:n,backend:a})=>{const{a:s,b:i}=n,o=a;(0,bm.C)([s,i],e);const u=o.data.get(s.dataId).values,l=o.data.get(i.dataId).values,c="string"===s.dtype?D.C0T.fromUint8ToStringArray(u):u,d="string"===s.dtype?D.C0T.fromUint8ToStringArray(l):l,p=r||s.dtype,[h,f]=t(s.shape,i.shape,c,d,p);return o.makeTensorInfo(f,p,h)}:({inputs:e,backend:a})=>{const{a:s,b:i}=e,o=a;if("complex64"===s.dtype||"complex64"===i.dtype){const e=Rm({inputs:{x:s},backend:o,attrs:{dtype:"complex64"}}),t=o.data.get(e.dataId),r=t.complexTensorInfos.real,a=t.complexTensorInfos.imag,u=o.data.get(r.dataId).values,l=o.data.get(a.dataId).values,c=Rm({inputs:{x:i},backend:o,attrs:{dtype:"complex64"}}),d=o.data.get(c.dataId),p=d.complexTensorInfos.real,h=d.complexTensorInfos.imag,f=o.data.get(p.dataId).values,m=o.data.get(h.dataId).values,[g,y,b]=n(s.shape,i.shape,u,l,f,m),x=o.makeTensorInfo(b,"float32",g),w=o.makeTensorInfo(b,"float32",y),v=_m({inputs:{real:x,imag:w},backend:o});return o.disposeIntermediateTensorInfo(e),o.disposeIntermediateTensorInfo(c),o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(w),v}{const e=o.data.get(s.dataId).values,n=o.data.get(i.dataId).values,a=r||s.dtype,[u,l]=t(s.shape,i.shape,e,n,a);return o.makeTensorInfo(l,a,u)}}}function Mm(e){return(t,n,r,a,s,i)=>{const o=D.C0T.assertAndGetBroadcastShape(t,n),u=D.ZSL.sizeFromShape(o),l=o.length,c=D.ZSL.computeStrides(o),d=D.ZSL.getTypedArrayFromDType("float32",u),p=D.ZSL.getTypedArrayFromDType("float32",u),h=D.C0T.getBroadcastDims(t,o),f=D.C0T.getBroadcastDims(n,o),m=D.C0T.mergeRealAndImagArrays(r,a),g=D.C0T.mergeRealAndImagArrays(s,i),y=t.length,b=D.ZSL.computeStrides(t),x=n.length,w=D.ZSL.computeStrides(n);if(h.length+f.length===0)for(let v=0;v<d.length;v++){const t=v%m.length,n=v%g.length,r=e(m[2*t],m[2*t+1],g[2*n],g[2*n+1]);d[v]=r.real,p[v]=r.imag}else for(let v=0;v<d.length;v++){const t=D.ZSL.indexToLoc(v,l,c),n=t.slice(-y);h.forEach((e=>n[e]=0));const r=D.ZSL.locToIndex(n,y,b),a=t.slice(-x);f.forEach((e=>a[e]=0));const s=D.ZSL.locToIndex(a,x,w),i=e(m[2*r],m[2*r+1],g[2*s],g[2*s+1]);d[v]=i.real,p[v]=i.imag}return[d,p,o]}}const Om=Sm(((e,t)=>e+t)),zm=Mm(((e,t,n,r)=>({real:e+n,imag:t+r}))),Lm=Fm(D.OMN,Om,zm),Pm={kernelName:D.OMN,backendName:"cpu",kernelFunc:Lm};function Bm(e,t,n,r,a){const s=D.ZSL.sizeFromShape(r),i=D.ZSL.makeZerosTypedArray(a,n);for(let o=0;o<e.length;o++){const n=e[o];if(n<0)throw new Error("Input x must be non-negative!");n>=a||(i[n]+=s>0?t[o]:1)}return i}function Wm(e,t,n,r=!1){const a=e.shape[0],s=e.shape[1],i=(0,D.ra8)([a,n],t.dtype);for(let o=0;o<a;o++)for(let a=0;a<s;a++){const s=e.get(o,a);if(s<0)throw new Error("Input x must be non-negative!");s>=n||(r?i.set(1,o,s):t.size>0?i.set(i.get(o,s)+t.get(o,a),o,s):i.set(i.get(o,s)+1,o,s))}return i}const Vm=Sm(((e,t)=>e&t)),Um=Fm(D.HNs,Vm),Gm={kernelName:D.HNs,backendName:"cpu",kernelFunc:Um};function Hm(e){return(t,n,r)=>{const a=D.ZSL.getArrayFromDType(n,t.length);for(let s=0;s<t.length;++s)a[s]=e(t[s],r);return a}}function jm(e,t,n){return qm(e,Hm(t),n)}function qm(e,t,n){return({inputs:r,attrs:a,backend:s})=>{const{x:i}=r;(0,bm.C)(i,e);const o=s,u=o.data.get(i.dataId).values;let l;if("string"===i.dtype){if(!Array.isArray(u))throw new Error("String tensor's value was not an instance of Array");l=D.C0T.fromUint8ToStringArray(u)}else l=u;const c=n||i.dtype,d=t(l,c,a);return o.makeTensorInfo(i.shape,c,d)}}const Zm=Hm((e=>Math.ceil(e))),Km=qm(D.QDP,Zm),Ym={kernelName:D.QDP,backendName:"cpu",kernelFunc:Km};var Qm=n(7763);const Xm=Sm(((e,t)=>e===t?1:0)),Jm=Fm(D.BRl,Xm,null,"bool"),eg={kernelName:D.BRl,backendName:"cpu",kernelFunc:Jm},tg=Hm((e=>Math.exp(e))),ng=qm(D.ox3,tg,"float32"),rg={kernelName:D.ox3,backendName:"cpu",kernelFunc:ng},ag=Hm((e=>Math.expm1(e))),sg=qm(D.ybj,ag),ig={kernelName:D.ybj,backendName:"cpu",kernelFunc:sg},og=Hm((e=>Math.floor(e))),ug=qm(D.ZgB,og),lg={kernelName:D.ZgB,backendName:"cpu",kernelFunc:ug},cg=Sm(((e,t)=>Math.floor(e/t))),dg=Fm(D.ElG,cg,null,"int32"),pg={kernelName:D.ElG,backendName:"cpu",kernelFunc:dg};function hg(e,t,n,r,a,s,i,o,u){const l=(0,D.ra8)([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*i[t],n.push(s)}if(r<0||r>=u/s)throw new Error(`Invalid indices: ${n} does not index into ${o}`);for(let e=0;e<s;e++)l.values[c*s+e]=t.get(...t.indexToLoc(r*s+e))}return l}function fg(e,t,n){const r=(0,D.ra8)(n,e.dtype);for(let a=0;a<r.size;++a){const n=r.indexToLoc(a).slice(),s=n[0],i=n[2],o=t.locToIndex([s,i]);n[2]=t.values[o];const u=e.locToIndex(n);0<=u&&u<e.values.length&&(r.values[a]=e.values[u])}return r}const mg=Sm(((e,t)=>e>t?1:0)),gg=Fm(D.XhZ,mg,null,"bool"),yg={kernelName:D.XhZ,backendName:"cpu",kernelFunc:gg},bg=Sm(((e,t)=>e>=t?1:0)),xg=Fm(D.lLS,bg,null,"bool"),wg={kernelName:D.lLS,backendName:"cpu",kernelFunc:xg},vg=Sm(((e,t)=>e<t?1:0)),kg=Fm(D.mIA,vg,null,"bool"),Sg={kernelName:D.mIA,backendName:"cpu",kernelFunc:kg},_g=Sm(((e,t)=>e<=t?1:0)),Ig=Fm(D.CwD,_g,null,"bool"),Tg={kernelName:D.CwD,backendName:"cpu",kernelFunc:Ig};function $g(e,t,n){const r=(t-e)/(n-1),a=D.ZSL.makeZerosTypedArray(n,"float32");a[0]=e;for(let s=1;s<a.length;s++)a[s]=a[s-1]+r;return a}const Cg=Hm((e=>Math.log(e))),Ng=qm(D.tG8,Cg),Eg={kernelName:D.tG8,backendName:"cpu",kernelFunc:Ng};function Ag(e,t,n,r){const a=D.ZSL.getTypedArrayFromDType(r,D.ZSL.sizeFromShape(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 Rg=Sm(((e,t)=>Math.max(e,t))),Dg=Fm(D.LDN,Rg),Fg={kernelName:D.LDN,backendName:"cpu",kernelFunc:Dg},Mg=Sm(((e,t)=>Math.min(e,t))),Og=Fm(D.LG0,Mg),zg={kernelName:D.LG0,backendName:"cpu",kernelFunc:Og},Lg=Sm(((e,t)=>e*t)),Pg=Mm(((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n}))),Bg=Fm(D.xu7,Lg,Pg),Wg={kernelName:D.xu7,backendName:"cpu",kernelFunc:Bg};function Vg(e,t,n){const r=D.ZSL.createScalarValue(-1,n);return Lg([],t,r,e,n)}const Ug={kernelName:D.l0G,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;(0,bm.C)(r,"neg");const a=n.data.get(r.dataId).values,[s,i]=Vg(a,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,s)}},Gg=Sm(((e,t)=>e!==t?1:0)),Hg=Fm(D.ylV,Gg,null,"bool"),jg={kernelName:D.ylV,backendName:"cpu",kernelFunc:Hg};function qg(e,t,n,r,a){const s=t.length,i=D.ZSL.sizeFromShape(t),o=D.ZSL.computeStrides(t),u=D.ZSL.computeStrides(a),l=D.ZSL.getTypedArrayFromDType(n,D.ZSL.sizeFromShape(a));for(let c=0;c<i;++c){const t=D.ZSL.indexToLoc(c,s,o),n=new Array(t.length);for(let e=0;e<n.length;e++)n[e]=t[r[e]];l[D.ZSL.locToIndex(n,s,u)]=e[c]}return l}function Zg(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{perm:s}=n;(0,bm.C)(a,"transpose");const i=a.shape.length,o=new Array(i);for(let l=0;l<o.length;l++)o[l]=a.shape[s[l]];const u=qg(r.data.get(a.dataId).values,a.shape,a.dtype,s,o);return{dataId:r.write(u,o,a.dtype),shape:o,dtype:a.dtype}}const Kg={kernelName:D.wx0,backendName:"cpu",kernelFunc:Zg};function Yg(e,t,n,r){const[a,s]=D.C0T.computeOutAndReduceShapes(e,r),i=(0,D.TuY)(t,"int32"),o=D.ZSL.makeZerosTypedArray(D.ZSL.sizeFromShape(a),i),u=D.ZSL.sizeFromShape(s);for(let l=0;l<o.length;++l){const e=l*u;let t=1;for(let r=0;r<u;++r)t*=n[e+r];o[l]=t}return{outVals:o,outShape:a,outDtype:i}}const Qg={kernelName:D.kdj,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r;(0,bm.C)(a,"prod");const o=a.shape.length,u=D.ZSL.parseAxisParam(s,a.shape),l=D.C0T.getAxesPermutation(u,o);let c=u,d=a;const p=[];null!=l&&(d=Zg({inputs:{x:a},backend:n,attrs:{perm:l}}),p.push(d),c=D.C0T.getInnerMostAxes(c.length,o));const h=n.data.get(d.dataId).values,{outVals:f,outShape:m,outDtype:g}=Yg(d.shape,d.dtype,h,c);let y=m;return i&&(y=D.C0T.expandShapeToKeepDim(m,u)),p.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,g,f)}};function Xg(e,t,n,r){const a=[];let s=0;const i=t.length-1+n.length,o=new Array(i).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)o[l].push(t*e)}for(let l=0;l<e.length;++l){let r=e[l],i=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=o[s],t=e[e.length-1]-a[r];for(let n=r;n<i;++n)o[s].push(a[n+1]+t)}r=a[r],i=a[i]}i!==r&&(a.push([r,i]),s+=i-r)}return{outSplits:o,valueSlices:a,numValues:s}}function Jg(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 ey(e,t,n,r,a){const s=t.slice();s[0]=a;const i=D.ZSL.getArrayFromDType(n,D.ZSL.sizeFromShape(s)),o=e.length;return function(e,t,n,r,a,s){const i=Jg(t,2)[1],o=Jg(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*o+n]=e[t*i+n];++u}}(e,t,r,0===o?0:o/t[0],i,s),[i,s]}function ty(e,t,n,r,a,s,i,o){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.ZSL.indexToLoc(r,t.length,D.ZSL.computeStrides(t)).join(",");throw new Error(`indices[${a}] = ${e} is not in [0, ${n})`)}}))}(s,i,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}=Xg(s,i,e,u),p=function(e){const t=[];for(let n=0;n<e.length;++n){const r=e[n].length,a=D.ZSL.getArrayFromDType("int32",r);t.push(a),e[n].forEach(((e,t)=>a[t]=e))}return t}(l),h=ey(n,r,a,c,d);return[p,h[0],h[1]]}const ny=2147483647;function ry(e,t,n,r,a,s,i){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(i.length>1)throw new Error("deltas must be a scalar or vector");const o=0===t.length,u=0===a.length,l=0===i.length,c=[];o||c.push(t[0]),u||c.push(a[0]),l||c.push(i[0]);for(let g=1;g<c.length;++g)if(c[g]!==c[g-1])throw new Error("starts, limits, and deltas must have the same shape");const d=0===c.length?1:c[0],p=D.ZSL.getArrayFromDType("int32",d+1);p[0]=0;for(let g=0;g<d;++g){const t=o?e[0]:e[g],n=u?r[0]:r[g],a=l?s[0]:s[g];if(0===a)throw new Error("Requires delta != 0");let i;if(a>0&&n<t||a<0&&n>t)i=0;else if(i=Math.ceil(Math.abs((n-t)/a)),i>ny)throw new Error(`Requires ((limit - start) / delta) <= ${ny}`);p[g+1]=p[g]+i}const h=p[d],f=D.ZSL.getArrayFromDType(n,h);let m=0;for(let g=0;g<d;++g){const t=p[g+1]-p[g];let n=o?e[0]:e[g];const r=l?s[0]:s[g];for(let e=0;e<t;++e)f[m++]=n,n+=r}return[p,f]}var ay=D.C0T.RowPartitionType;class sy{constructor(e,t,n,r,a,s,i,o,u,l){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=r,this.valuesDType=a,this.defaultValue=s,this.defaultValueShape=i,this.rowPartitionValues=o,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=D.C0T.getRowPartitionTypesHelper(l),this.raggedRank=D.C0T.getRaggedRank(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===ay.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===ay.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case ay.VALUE_ROWIDS:return sy.getMaxWidthValueRowID(t);case ay.ROW_SPLITS:return sy.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${ay[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 oy(e,n)}calculateOutputSize(e){const t=this.valuesShape,n=this.defaultValueShape;D.C0T.validateDefaultValueShape(n,t);const r=this.tensorShapeFromTensor(this.shape,this.shapeShape),a=D.C0T.combineRaggedTensorToTensorShapes(this.raggedRank,r,t);a[0]<0&&(a[0]=e);for(let s=1;s<=this.raggedRank;++s)a[s]<0&&(a[s]=this.getMaxWidth(s));return a}calculateFirstParentOutputIndex(e,t,n){const r=Math.min(e,n),a=[];let s=0;for(let i=0;i<r;++i,s+=t)a.push(s);for(let i=r;i<e;++i)a.push(-1);return D.ZSL.assert(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 i=0;i<a-1;++i){const a=e[i+1]-e[i];let o=Math.min(r,a),u=t[i];-1===u&&(o=0);for(let e=0;e<o;++e)s.push(u),u+=n;for(let e=0;e<a-o;++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 i=0,o=e[0];if(o>=t.length)throw new Error(`Got currentValueRowId=${o}, which is not less than ${t.length}`);let u=t[o];s.push(u);for(let l=1;l<a;++l){const a=e[l];if(a===o)u>=0&&(++i,i<r?u+=n:u=-1);else{if(i=0,o=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 ay.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(a,t,n,r);case ay.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: ${ay[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 ay.FIRST_DIM_SIZE:return e[0];case ay.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case ay.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${ay[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=oy(t,!1),a=D.ZSL.getArrayFromDType(this.valuesDType,D.ZSL.sizeFromShape(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 i=r.slice();i=i.slice(e+1);const o=D.ZSL.sizeFromShape(i),u=t.length;let l=this.defaultValue;if(l.length!==o&&1!==l.length){const e=this.defaultValueShape;(0,D.DZQ)((()=>{const t=(0,D.tQQ)(l,e),n=(0,D.hOW)(t,i);l=n.dataSync()}))}let c=0,d=0,p=0;for(let h=0;h<=u;++h){let e=h<u?t[h]:-1;if(e!==p){if(d<p){const e=a.subarray(c*o);iy(s.subarray(d*o),e,(p-d)*o)}if(h>=u){const t=n.length;e=Math.floor(t/o)}if(e>p)if(1===this.defaultValue.length)s.subarray(p*o,e*o).fill(this.defaultValue[0]),p=e;else for(;e>p;){iy(s.slice(p*o),l,o),++p}e<0?(c=h+1,d=p):(c=h,d=p,p=d+1)}else++p}}}function iy(e,t,n){for(let r=0;r<n;r++)e[r]=t[r]}function oy(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 uy(e,t,n,r,a,s,i,o,u,l){return new sy(e,t,n,r,a,s,i,o,u,l).compute()}var ly=n(2610);const cy=Hm((e=>1/Math.sqrt(e))),dy=qm(D.TOR,cy),py={kernelName:D.TOR,backendName:"cpu",kernelFunc:dy};function hy(e,t,n,r,a,s,i,o,u,l){const c=[r/a,a],d=e.values,p=t.values;if(0===r)return(0,D.ra8)(n,t.dtype);const h=u instanceof D.ylz?u:(0,D.ra8)(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<i;t++){const n=d[f*i+t];e.push(n),s+=n*o[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 fy=Hm((e=>1/(1+Math.exp(-e)))),my=jm(D.vI1,(e=>1/(1+Math.exp(-e)))),gy={kernelName:D.vI1,backendName:"cpu",kernelFunc:my};var yy=n(7906);function by(e,t,n,r,a,s,i){const o=t[0],u=s[0],l=new Array(u),c=new Array(o),d=t[1];if(0===u){if(0!==o)throw new Error(D.C0T.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));return[D.ZSL.getArrayFromDType(n,0),[0,d],D.ZSL.getArrayFromDType(a,0),l,c]}let p=!0,h=0;const f=new Array(u).fill(0);for(let g=0;g<o;++g){const t=e[g*d];if(t<0)throw new Error(D.C0T.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,t));if(t>=u)throw new Error(D.C0T.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(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<o;++e)c[e]=e;return[t,[o,d],n,l,c]}{const t=f[u-1],s=D.ZSL.getArrayFromDType(n,t*d),p=D.ZSL.getArrayFromDType(a,t),h=new Array(u).fill(0);for(let n=0;n<o;++n){const t=e[n*d],a=h[t],i=(0===t?0:f[t-1])+a;h[t]++;for(let r=0;r<d;++r)s[i*d+r]=e[n*d+r];p[i]=r[n],c[n]=i}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]=i}}return[s,[t,d],p,l,c]}}function xy(e,t,n,r,a){const s=D.ZSL.sizeFromShape(r),i=t[0],o=a.length,u=[];let l=1,c=-1;for(let m=0;m<o;++m){const e=a[m];if(-1===e){if(-1!==c)throw new Error(D.C0T.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(c,m));c=m,u.push(1)}else{if(e<0)throw new Error(D.C0T.getSparseReshapeNegativeOutputDimErrorMessage(m,e));l*=e,u.push(e)}}if(-1!==c){if(l<=0)throw new Error(D.C0T.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());const e=Math.trunc(s/l);if(l*e!==s)throw new Error(D.C0T.getSparseReshapeInputOutputMultipleErrorMessage(r,u));u[c]=e}if(D.ZSL.sizeFromShape(u)!==s)throw new Error(D.C0T.getSparseReshapeInputOutputMismatchErrorMessage(r,u));const d=r.length,p=[];if(d>0){p[d-1]=1;for(let e=d-2;e>=0;--e)p[e]=p[e+1]*r[e+1]}const h=[];if(o>0){h[o-1]=1;for(let e=o-2;e>=0;--e)h[e]=h[e+1]*u[e+1]}const f=D.ZSL.getArrayFromDType(n,i*o);for(let m=0;m<i;++m){let t=0;for(let n=0;n<d;++n)t+=e[m*d+n]*p[n];for(let e=0;e<o;++e)f[m*o+e]=Math.trunc(t/h[e]),t%=h[e]}return[f,[i,o],u]}function wy(e,t,n,r,a,s=!1,i=0){const o=r.length,u=[t[0],e.length/t[0]],l=u[1],c=o>0?a[o-1]+1:0;if(c<0)throw new Error(D.C0T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());const d=t.slice();d[0]=c;const p=d.reduce(((e,t)=>e*t),1),h=D.ZSL.getArrayFromDType(n,p);if(0===o)return c>0&&h.fill(i),[h,d];if(c<=0)throw new Error(D.C0T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let f=0,m=1,g=0,y=a[f];for(;;){let t=0;if(m<o){if(t=a[m],y===t){++m;continue}if(y>=t)throw new Error(D.C0T.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(y<0||y>=c)throw new Error(D.C0T.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y,c));y>g&&h.fill(i,g*l,y*l);for(let n=f;n<m;++n){const t=r[n];if(t<0||t>=u[0])throw new Error(D.C0T.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(n,r[n],u[0]));for(let n=0;n<l;n++)h[y*l+n]+=e[t*l+n]}if(s)for(let e=0;e<l;e++)h[y*l+e]/=m-f;if(f=m,++m,g=y+1,y=t,m>o)break}return g<c&&h.fill(i,g*l,c*l),[h,d]}const vy=Hm((e=>Math.sqrt(e))),ky=jm(D.dFH,(e=>Math.sqrt(e))),Sy={kernelName:D.dFH,backendName:"cpu",kernelFunc:ky},_y=Sm(((e,t)=>{const n=e-t;return n*n})),Iy=Fm(D.Ddj,_y),Ty={kernelName:D.Ddj,backendName:"cpu",kernelFunc:Iy},$y=Hm(((e,t)=>{const{pattern:n,replaceGlobal:r,rewrite:a}=t;return e.replace(new RegExp(n,r?"g":""),a)})),Cy=qm(D.GZp,$y),Ny={kernelName:D.GZp,backendName:"cpu",kernelFunc:Cy};function Ey(e,t,n,r){const a=(0,D.ra8)(e,t.dtype);for(let s=0;s<a.size;s++){const e=a.indexToLoc(s),i=new Array(e.length);for(let t=0;t<i.length;t++)i[t]=e[t]*n[t]+r[t];a.set(t.get(...i),...e)}return a}var Ay=n(3514),Ry=n(2948),Dy=n(5535);const Fy=Sm(((e,t)=>e-t)),My=Mm(((e,t,n,r)=>({real:e-n,imag:t-r}))),Oy=Fm(D.PbM,Fy,My),zy={kernelName:D.PbM,backendName:"cpu",kernelFunc:Oy};function Ly(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=(0,D.ra8)(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 Py=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function By(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){const a=r-n+1,s=t-n+1,i=Math.log(a),o=.5*Math.exp(2*i/3),u=.5*Math.sqrt(i*o*(a-o)/a)*Math.sign(s-a/2);By(e,t,Math.max(n,Math.floor(t-s*o/a+u)),Math.min(r,Math.floor(t+(a-s)*o/a+u)))}const a=e[t];let s=n,i=r;for(D.ZSL.swap(e,n,t),Py(e[r],a)>0&&D.ZSL.swap(e,n,r);s<i;){for(D.ZSL.swap(e,s,i),s++,i--;Py(e[s],a)<0;)s+=1;for(;Py(e[i],a)>0;)i-=1}0===Py(e[n],a)?D.ZSL.swap(e,n,i):(i+=1,D.ZSL.swap(e,i,r)),i<=t&&(n=i+1),t<=i&&(r=i-1)}}function Wy(e,t,n,r,a){const s=t[t.length-1],[i,o]=[e.length/s,s],u=D.ZSL.getTypedArrayFromDType(n,i*r),l=D.ZSL.getTypedArrayFromDType("int32",i*r);for(let d=0;d<i;d++){const t=d*o,n=e.subarray(t,t+o);let s=new Array(n.length);n.forEach(((e,t)=>s[t]={value:e,index:t})),r<s.length&&(By(s,r),s=s.slice(0,r)),a&&s.sort(Py);const i=d*r,c=u.subarray(i,i+r),p=l.subarray(i,i+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,[(0,D.ra8)(c,n,u),(0,D.ra8)(c,"int32",l)]}var Vy=n(2750);const Uy="4.22.0";(0,D.gJX)("cpu",(()=>new wm),1);const Gy=jm(D.Pah,(e=>e>=0?e:Math.exp(e)-1)),Hy={kernelName:D.Pah,backendName:"cpu",kernelFunc:Gy};function jy(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:s}=r;(0,bm.C)([a],"leakyRelu");const i=D.ZSL.sizeFromShape(a.shape),o=n.data.get(a.dataId).values,u=D.ZSL.getTypedArrayFromDType("float32",i);for(let l=0;l<o.length;l++)u[l]=o[l]<0?s*o[l]:o[l];return n.makeTensorInfo(a.shape,"float32",u)}const qy={kernelName:D.X0$,backendName:"cpu",kernelFunc:jy},Zy=Sm(((e,t)=>e<0?t*e:e));function Ky(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t;(0,bm.C)([r,a],"prelu");const s=n.data.get(r.dataId).values,i=n.data.get(a.dataId).values,[o,u]=Zy(r.shape,a.shape,s,i,"float32");return n.makeTensorInfo(u,"float32",o)}const Yy={kernelName:D.Ncv,backendName:"cpu",kernelFunc:Ky},Qy=jm(D.fUj,(e=>Math.max(0,e))),Xy={kernelName:D.fUj,backendName:"cpu",kernelFunc:Qy},Jy=jm(D.P_L,(e=>Math.min(Math.max(0,e),6))),eb={kernelName:D.P_L,backendName:"cpu",kernelFunc:Jy};function tb(e,t,n,r,a){if("linear"===n)return $m({inputs:{x:t},backend:e});if("relu"===n)return Qy({inputs:{x:t},backend:e});if("elu"===n)return Gy({inputs:{x:t},backend:e});if("relu6"===n)return Jy({inputs:{x:t},backend:e});if("prelu"===n)return Ky({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return jy({inputs:{x:t},backend:e,attrs:{alpha:a}});if("sigmoid"===n)return my({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function nb(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,i=D.ZSL.sizeFromShape(a.shape),o=D.ZSL.inferFromImplicitShape(s,i),u=D.ZSL.sizeFromShape(o);D.ZSL.assert(i===u,(()=>`The new shape (${o}) has ${u} elements and the old shape (${a.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(a.dataId);const l=n.data.get(a.dataId);if(null!=l.complexTensorInfos){const e=l.complexTensorInfos.real,t=l.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:a.dataId,shape:o,dtype:a.dtype}}const rb={kernelName:D.R23,backendName:"cpu",kernelFunc:nb};function ab(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s}=t,{transposeA:i,transposeB:o}=r;(0,bm.C)([a,s],"matMul");const u=a.shape.length,l=s.shape.length,c=i?a.shape[u-2]:a.shape[u-1],d=o?s.shape[l-1]:s.shape[l-2],p=i?a.shape[u-1]:a.shape[u-2],h=o?s.shape[l-2]:s.shape[l-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=D.ZSL.sizeFromShape(f),y=D.ZSL.sizeFromShape(m),b=D.ZEY.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,h]);D.ZSL.assert(c===d,(()=>`Error in matMul: inner shapes (${c}) and (${d}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`));const x=o?[y,h,d]:[y,d,h],w=nb({inputs:{x:a},backend:n,attrs:{shape:i?[g,c,p]:[g,p,c]}}),v=nb({inputs:{x:s},backend:n,attrs:{shape:x}}),k=i?w.shape[1]:w.shape[2],S=i?w.shape[2]:w.shape[1],_=o?v.shape[1]:v.shape[2],I=Math.max(g,y),T=n.data.get(w.dataId).values,$=n.data.get(v.dataId).values,C=D.ZSL.computeStrides(w.shape),N=D.ZSL.computeStrides(v.shape),[E,A,R]=i?[C[0],1,C[1]]:[C[0],C[1],1],[F,M,O]=o?[1,N[1],N[0]]:[N[1],1,N[0]],z=S*_,L=(0,D.ra8)([I,S,_],w.dtype),P=L.values,B=n.blockSize;for(let D=0;D<I;D++){const e=D%g,t=D%y;for(let n=0;n<S;n+=B){const r=Math.min(n+B,S);for(let a=0;a<_;a+=B){const s=Math.min(a+B,_);for(let i=0;i<k;i+=B){const o=Math.min(i+B,k);for(let u=n;u<r;u++)for(let n=a;n<s;n++){let r=0;for(let a=i;a<o;a++){r+=T[e*E+u*A+a*R]*$[a*F+n*M+t*O]}P[D*z+(u*_+n)]+=r}}}}}return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(v),n.makeTensorInfo(b,L.dtype,L.values)}const sb={kernelName:D.jAQ,backendName:"cpu",kernelFunc:ab};const ib={kernelName:D.Dr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:d}=r;let p,h,f;const m=[];p=ab({inputs:{a:a,b:s},attrs:{transposeA:u,transposeB:l},backend:n}),i&&(h=Lm({inputs:{a:p,b:i},backend:n}),m.push(p),p=h),c&&(f=tb(n,p,c,o,d),m.push(p),p=f);for(const g of m)n.disposeIntermediateTensorInfo(g);return p}},ob=jm(D.Vvy,(e=>Math.acos(e))),ub={kernelName:D.Vvy,backendName:"cpu",kernelFunc:ob},lb=jm(D.PH8,(e=>Math.acosh(e))),cb={kernelName:D.PH8,backendName:"cpu",kernelFunc:lb};const db={kernelName:D.EkD,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,r=t;(0,bm.C)(t,"addN");const a=r.map((e=>n.data.get(e.dataId).values)),s=(0,D.ra8)(r[0].shape,r[0].dtype),i=s.values;for(let o=0;o<r.length;o++){const e=a[o];for(let t=0;t<i.length;t++)i[t]+=e[t]}return n.makeTensorInfo(s.shape,s.dtype,s.values)}};const pb={kernelName:D.u8Z,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r;(0,bm.C)(a,"all");const o=D.ZSL.parseAxisParam(s,a.shape);let u=o;const l=D.C0T.getAxesPermutation(u,a.shape.length);let c=a;null!=l&&(c=Zg({inputs:{x:a},backend:n,attrs:{perm:l}}),u=D.C0T.getInnerMostAxes(u.length,a.shape.length)),D.C0T.assertAxesAreInnerMostDims("all",u,c.shape.length);const[d,p]=D.C0T.computeOutAndReduceShapes(c.shape,u),h=D.ZSL.sizeFromShape(p),f=D.ZSL.makeZerosTypedArray(D.ZSL.sizeFromShape(d),c.dtype),m=n.data.get(c.dataId).values;for(let y=0;y<f.length;++y){const e=y*h;let t=m[e];for(let n=0;n<h;++n){const r=m[e+n];t=t&&r}f[y]=t}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(d,c.dtype,f);if(i){const e=nb({inputs:{x:g},backend:n,attrs:{shape:D.C0T.expandShapeToKeepDim(d,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}};const hb={kernelName:D.FSt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r;(0,bm.C)(a,"any");const o=D.ZSL.parseAxisParam(s,a.shape);let u=o;const l=D.C0T.getAxesPermutation(u,a.shape.length);let c=a;null!=l&&(c=Zg({inputs:{x:a},backend:n,attrs:{perm:l}}),u=D.C0T.getInnerMostAxes(u.length,a.shape.length)),D.C0T.assertAxesAreInnerMostDims("any",u,c.shape.length);const[d,p]=D.C0T.computeOutAndReduceShapes(c.shape,u),h=D.ZSL.sizeFromShape(p),f=D.ZSL.makeZerosTypedArray(D.ZSL.sizeFromShape(d),c.dtype),m=n.data.get(c.dataId).values;for(let y=0;y<f.length;++y){const e=y*h;let t=m[e];for(let n=0;n<h;++n){const r=m[e+n];t=t||r}f[y]=t}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(d,c.dtype,f);if(i){const e=nb({inputs:{x:g},backend:n,attrs:{shape:D.C0T.expandShapeToKeepDim(d,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}};const fb={kernelName:D.Jp_,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;(0,bm.C)(a,"argMax");let i=D.ZSL.parseAxisParam(s,a.shape);const o=D.C0T.getAxesPermutation(i,a.shape.length);let u=a;const l=[];null!=o&&(u=Zg({inputs:{x:a},backend:n,attrs:{perm:o}}),l.push(u),i=D.C0T.getInnerMostAxes(i.length,u.shape.length)),i=[i[0]],D.C0T.assertAxesAreInnerMostDims("argMax",i,u.shape.length);const[c,d]=D.C0T.computeOutAndReduceShapes(u.shape,i),p=D.ZSL.sizeFromShape(c),h=D.ZSL.makeZerosTypedArray(p,"int32"),f=D.ZSL.sizeFromShape(d),m=n.data.get(u.dataId).values;for(let g=0;g<h.length;++g){const e=g*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[g]=n}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",h)}};const mb={kernelName:D.p_m,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;(0,bm.C)(a,"argMin");let i=D.ZSL.parseAxisParam(s,a.shape);const o=D.C0T.getAxesPermutation(i,a.shape.length);let u=a;const l=[];null!=o&&(u=Zg({inputs:{x:a},backend:n,attrs:{perm:o}}),l.push(u),i=D.C0T.getInnerMostAxes(i.length,u.shape.length)),i=[i[0]],D.C0T.assertAxesAreInnerMostDims("argMin",i,u.shape.length);const[c,d]=D.C0T.computeOutAndReduceShapes(u.shape,i),p=D.ZSL.sizeFromShape(c),h=D.ZSL.makeZerosTypedArray(p,"int32"),f=D.ZSL.sizeFromShape(d),m=n.data.get(u.dataId).values;for(let g=0;g<h.length;++g){const e=g*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[g]=n}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",h)}},gb=jm(D.QKF,(e=>Math.asin(e))),yb={kernelName:D.QKF,backendName:"cpu",kernelFunc:gb},bb=jm(D.epO,(e=>Math.asinh(e))),xb={kernelName:D.epO,backendName:"cpu",kernelFunc:bb},wb=jm(D.TyE,(e=>Math.atan(e))),vb={kernelName:D.TyE,backendName:"cpu",kernelFunc:wb},kb=Sm(((e,t)=>Math.atan2(e,t))),Sb=Fm(D.lxb,kb),_b={kernelName:D.lxb,backendName:"cpu",kernelFunc:Sb},Ib=jm(D.zP9,(e=>Math.atanh(e))),Tb={kernelName:D.zP9,backendName:"cpu",kernelFunc:Ib};function $b(e,t,n,r,a,s){const i=a.strideHeight,o=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=(0,D.ra8)(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 w=0;w<a.batchSize;++w){const t=w*y,n=w*r[0];for(let m=0;m<a.inChannels;++m)for(let y=0;y<a.outHeight;++y){const w=y*i-p,v=Math.max(0,w),k=Math.min(a.inHeight,c+w),S=t+y*b;for(let t=0;t<a.outWidth;++t){const i=t*o-h,c=Math.max(0,i),p=Math.min(a.inWidth,d+i);let y=f,b=0,w=0;for(let t=v;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,w++)}if(isNaN(y))break}g[S+t*x+m]="avg"===s?b/w:y}}}return m}function Cb(e,t,n,r,a=!1,s=!1){const i=(0,D.ra8)(r.outShape,"int32"),o=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=(0,D.ra8)(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*o-h;let y=n;for(;y<0;)y+=l;const b=Math.min(r.inHeight,d+n);for(let o=0;o<r.outWidth;++o){const d=o*u-f;let h=d;for(;h<0;)h+=c;const x=Math.min(r.inWidth,p+d);let w=Number.NEGATIVE_INFINITY,v=-1;for(let t=y;t<b;t+=l){const i=t-n;for(let n=h;n<x;n+=c){const o=n-d,u=m.get(g,t,n,e);u>w&&(w=u,v=a?s?((g*r.inHeight+t)*r.inWidth+n)*r.inChannels+e:(t*r.inWidth+n)*r.inChannels+e:i*p+o)}}i.set(v,g,t,o,e)}}return i}function Nb(e,t,n,r,a,s){const i=a.strideDepth,o=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=(0,D.ra8)(a.outShape,n),w=x.values,v=a.outShape[1]*a.outShape[2]*a.outShape[3]*a.outShape[4],k=a.outShape[2]*a.outShape[3]*a.outShape[4],S=a.outShape[3]*a.outShape[4],_=a.outShape[4];for(let I=0;I<a.batchSize;++I){const t=I*v,n=I*r[0];for(let x=0;x<a.inChannels;++x)for(let v=0;v<a.outDepth;++v){const I=v*i-m;let T=I;for(;T<0;)T+=l;const $=Math.min(a.inDepth,p+I),C=t+v*k;for(let t=0;t<a.outHeight;++t){const i=t*o-g;let p=i;for(;p<0;)p+=c;const m=Math.min(a.inHeight,h+i),v=C+t*S;for(let t=0;t<a.outWidth;++t){const i=t*u-y;let o=i;for(;o<0;)o+=d;const h=Math.min(a.inWidth,f+i),g=v+t*_;let k=b,S=0,I=0;for(let t=T;t<$;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=o;t<h;t+=d){const a=e[n+t*r[3]+x];if("max"===s&&a>k?k=a:"avg"===s&&(S+=a,I++),isNaN(k))break}if(isNaN(k))break}if(isNaN(k))break}w[g+x]="avg"===s?S/Math.max(I,1):k}}}}return x}const Eb={kernelName:D.ho8,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;(0,bm.C)(a,"avgPool");const{filterSize:s,strides:i,pad:o,dimRoundingMode:u}=r;D.ZSL.assert(D.C0T.eitherStridesOrDilationsAreOne(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const l=D.C0T.computePool2DInfo(a.shape,s,i,1,o,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&D.ZSL.arraysEqual(l.inShape,l.outShape))c=$m({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=D.ZSL.computeStrides(a.shape),r=$b(e,a.shape,a.dtype,t,l,"avg");c=n.makeTensorInfo(l.outShape,a.dtype,r.values)}return c}};const Ab={kernelName:D.cS,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r;(0,bm.C)(a,"avgPool3d");const c=D.C0T.computePool3DInfo(a.shape,s,i,1,o,u,l),d=Nb(n.data.get(a.dataId).values,a.shape,a.dtype,D.ZSL.computeStrides(a.shape),c,"avg");return n.makeTensorInfo(d.shape,"float32",d.values)}};const Rb={kernelName:D.wwC,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:u,dimRoundingMode:l}=r;(0,bm.C)([a,s],"avgPool3DGrad");const c=D.C0T.computePool3DInfo(s.shape,i,o,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,w=c.effectiveFilterDepth,v=c.effectiveFilterHeight,k=c.effectiveFilterWidth,S=w-1-c.padInfo.front,_=k-1-c.padInfo.left,I=v-1-c.padInfo.top,T=(0,D.ra8)(s.shape,"float32"),$=1/(f*m*g),C=n.bufferSync(a);for(let N=0;N<c.batchSize;++N)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-S,s=n-I,i=r-_;let o=0;for(let t=0;t<w;t+=y){const n=(a+t)/d;if(!(n<0||n>=c.outDepth||Math.floor(n)!==n))for(let t=0;t<v;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=(i+t)/h;if(a<0||a>=c.outWidth||Math.floor(a)!==a)continue;o+=C.get(N,n,r,a,e)}}}T.set(o*$,N,t,n,r,e)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}};const Db={kernelName:D.VCH,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,i=s;(0,bm.C)([a,s],"avgPoolGrad");const{filterSize:o,strides:u,pad:l}=r,c=D.C0T.computePool2DInfo(i.shape,o,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,w=y-1-c.padInfo.top,v=(0,D.ra8)(i.shape,"float32"),k=1/(h*f),S=n.data.get(a.dataId).values,_=(0,D.ra8)(a.shape,"float32",S);for(let I=0;I<c.batchSize;++I)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-w,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+=_.get(I,n,r,e)}}v.set(s*k,I,t,n,e)}return n.makeTensorInfo(v.shape,v.dtype,v.values)}};const Fb={kernelName:D.i5R,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,scale:s,offset:i,mean:o,variance:u}=t;D.ZSL.assert(o.shape.length===u.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),D.ZSL.assert(null==i||o.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),D.ZSL.assert(null==s||o.shape.length===s.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),(0,bm.C)([a,o,u,s,i],"batchNorm");let{varianceEpsilon:l}=r;null==l&&(l=.001);const c=n.data.get(a.dataId).values,d=n.data.get(o.dataId).values,p=n.data.get(u.dataId).values,h=s?n.data.get(s.dataId).values:new Float32Array([1]),f=i?n.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,y=h.length,b=p.length,x=d.length;let w=0,v=0,k=0,S=0;for(let _=0;_<c.length;++_)m[_]=f[w++]+(c[_]-d[v++])*h[k++]/Math.sqrt(p[S++]+l),w>=g&&(w=0),v>=x&&(v=0),k>=y&&(k=0),S>=b&&(S=0);return n.makeTensorInfo(a.shape,a.dtype,m)}};const Mb={kernelName:D.Ik2,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:i}=r;(0,bm.C)([a],"batchToSpaceND");const o=s.reduce(((e,t)=>e*t)),u=D.C0T.getReshaped(a.shape,s,o),l=D.C0T.getPermuted(u.length,s.length),c=D.C0T.getReshapedPermuted(a.shape,s,o),d=D.C0T.getSliceBeginCoords(i,s.length),p=D.C0T.getSliceSize(c,i,s.length),h=nb({inputs:{x:a},backend:n,attrs:{shape:u}}),f=Zg({inputs:{x:h},backend:n,attrs:{perm:l}}),m=nb({inputs:{x:f},backend:n,attrs:{shape:c}}),g=(0,yy.di)({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const Ob={kernelName:D.N4F,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:i}=r,o=Bm(n.data.get(a.dataId).values,n.data.get(s.dataId).values,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,o)}};const zb={kernelName:D.vj7,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:a}=t,s=n.data.get(r.dataId).values,i=n.data.get(a.dataId).values,o=D.C0T.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},Lb=jm(D.vaV,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),Pb={kernelName:D.vaV,backendName:"cpu",kernelFunc:Lb},Bb={kernelName:D.$zE,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend,r=new Float32Array(D.ZSL.sizeFromShape(t.shape)),a=n.data.get(t.dataId),s=a.complexTensorInfos.real,i=a.complexTensorInfos.imag,o=n.data.get(s.dataId).values,u=n.data.get(i.dataId).values;for(let l=0;l<o.length;l++){const e=o[l],t=u[l];r[l]=Math.hypot(e,t)}return n.makeOutput(r,t.shape,"float32")}};function Wb(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 Vb={kernelName:D.dv8,backendName:"cpu",kernelFunc:Wb};function Ub(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=D.ZSL.parseAxisParam(a,t[0].shape)[0],i=t.map((e=>e.shape));D.C0T.assertParamsConsistent(i,s);let o=D.C0T.computeOutShape(t.map((e=>e.shape)),s);if(0===D.ZSL.sizeFromShape(o))return n.makeTensorInfo(o,t[0].dtype,[]);const u=t.filter((e=>D.ZSL.sizeFromShape(e.shape)>0));if(1===u.length)return $m({inputs:{x:u[0]},backend:n});if("complex64"===u[0].dtype){const e=u.map((e=>Nm({inputs:{input:e},backend:n}))),t=u.map((e=>Wb({inputs:{input:e},backend:n}))),r=Ub({inputs:e,backend:n,attrs:{axis:s}}),a=Ub({inputs:t,backend:n,attrs:{axis:s}}),i=_m({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),i}const l=u.map((e=>{const t=D.ZSL.sizeFromShape(e.shape.slice(s));return nb({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),c=l.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));o=D.C0T.computeOutShape(l.map((e=>e.shape)),1);const d=1===l[0].shape[0],p=(0,Qm.h)(c,o,t[0].dtype,d),h=D.C0T.computeOutShape(u.map((e=>e.shape)),s),f=n.makeTensorInfo(h,t[0].dtype,p);return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}const Gb={kernelName:D.$dB,backendName:"cpu",kernelFunc:Ub};function Hb(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:u,dilations:l,dimRoundingMode:c}=r;(0,bm.C)([a,s],"conv2d");const d=D.C0T.convertConv2DDataFormat(u),p=D.C0T.computeConv2DInfo(a.shape,s.shape,i,l,o,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,w=new D.ylz(p.outShape,a.dtype),v=D.ZSL.computeStrides(a.shape),k=D.ZSL.computeStrides(s.shape),S=v[0],_=x?v[1]:v[2],I=x?v[2]:1,T=x?1:v[1],$=w.strides[0],C=x?w.strides[1]:w.strides[2],N=x?w.strides[2]:1,E=x?1:w.strides[1],A=n.data.get(a.dataId).values,R=n.data.get(s.dataId).values,F=w.values;for(let D=0;D<p.batchSize;++D){const e=D*S,t=D*$;for(let n=0;n<p.outHeight;++n){const r=t+n*C,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],i=e+n*_;for(let e=0;e<p.outWidth;++e){const t=r+e*N,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=i+r*I;let o=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*E]+=n*R[o+e];o+=p.outChannels}}}}}}return n.makeTensorInfo(w.shape,w.dtype,F)}const jb={kernelName:D.p2J,backendName:"cpu",kernelFunc:Hb};const qb={kernelName:D.rFm,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:i,pad:o,dataFormat:u,dimRoundingMode:l,filterShape:c}=r;(0,bm.C)([a,s],"conv2dBackpropFilter");const d=D.C0T.convertConv2DDataFormat(u),p=D.C0T.computeConv2DInfo(a.shape,c,i,1,o,l,!1,d),{strideHeight:h,strideWidth:f,filterHeight:m,filterWidth:g}=p,y="channelsLast"===p.dataFormat,b=new D.ylz(p.filterShape,"float32"),x=p.padInfo.left,w=p.padInfo.top,v=n.data.get(a.dataId).values,k=n.data.get(s.dataId).values,S=new D.ylz(a.shape,a.dtype,v),_=new D.ylz(s.shape,s.dtype,k);for(let I=0;I<m;++I){const e=Math.max(0,Math.ceil((w-I)/h)),t=Math.min(p.outHeight,(p.inHeight+w-I)/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 i=0;i<p.outChannels;++i){let o=0;for(let u=0;u<p.batchSize;++u)for(let l=e;l<t;++l){const e=I+l*h-w;for(let t=r;t<a;++t){const r=n+t*f-x;o+=y?S.get(u,e,r,s)*_.get(u,l,t,i):S.get(u,s,e,r)*_.get(u,i,l,t)}}b.set(o,I,n,s,i)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const Zb={kernelName:D.jfg,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:u,dataFormat:l,dimRoundingMode:c}=r;(0,bm.C)([a,s],"conv2dBackpropInput");const d=D.ZSL.computeStrides(s.shape),p=D.ZSL.computeStrides(a.shape);let h=D.C0T.convertConv2DDataFormat(l);const f=D.C0T.computeConv2DInfo(i,s.shape,o,1,u,c,!1,h),m=new D.ylz(f.inShape,"float32"),g=m.values,y=n.data.get(a.dataId).values,b=n.data.get(s.dataId).values,[x,w,v]=d,{batchSize:k,filterHeight:S,filterWidth:_,inChannels:I,inHeight:T,inWidth:$,outChannels:C,outHeight:N,outWidth:E,strideHeight:A,strideWidth:R}=f;h=f.dataFormat;const F=S-1-f.padInfo.top,M=_-1-f.padInfo.left,O="channelsLast"===h,z=m.strides[0],L=O?m.strides[1]:m.strides[2],P=O?m.strides[2]:1,B=O?1:m.strides[1],W=p[0],V=O?p[1]:p[2],U=O?p[2]:1,G=O?1:p[1];for(let D=0;D<k;++D)for(let e=0;e<I;++e)for(let t=0;t<T;++t){const n=t-F,r=Math.max(0,Math.ceil(n/A)),a=Math.min(N,(S+n)/A);for(let s=0;s<$;++s){const i=s-M,o=Math.max(0,Math.ceil(i/R)),u=Math.min(E,(_+i)/R);let l=0;for(let t=r;t<a;++t){const r=t*A-n;for(let n=o;n<u;++n){const a=W*D+V*t+U*n,s=x*(S-1-r)+w*(_-1-(n*R-i))+v*e;for(let e=0;e<C;++e){l+=y[a+G*e]*b[s+e]}}}g[z*D+L*t+P*s+B*e]=l}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}};const Kb={kernelName:D.A1h,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:u}=r;(0,bm.C)([a,s],"conv3d");const l=D.C0T.computeConv3DInfo(a.shape,s.shape,i,u,o),{filterDepth:c,filterHeight:d,filterWidth:p,dilationDepth:h,dilationHeight:f,dilationWidth:m,padInfo:g}=l,y=g.front,b=g.left,x=g.top,w=new D.ylz(l.outShape,a.dtype),v=n.data.get(a.dataId).values,k=n.data.get(s.dataId).values,S=w.values,_=D.ZSL.computeStrides(a.shape),I=D.ZSL.computeStrides(s.shape);for(let T=0;T<l.batchSize;++T){const e=T*_[0],t=T*w.strides[0];for(let n=0;n<l.outDepth;++n){const r=t+n*w.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*I[0],i=e+n*_[1];for(let e=0;e<l.outHeight;++e){const t=r+e*w.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*I[1],o=i+r*_[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*I[2],i=o+t*l.inChannels;let u=s;for(let e=0;e<l.inChannels;++e){const t=v[i+e];for(let e=0;e<l.outChannels;++e)S[n+e]+=t*k[u+e];u+=l.outChannels}}}}}}}}return n.makeTensorInfo(w.shape,w.dtype,w.values)}};const Yb={kernelName:D.iGz,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:u}=r;(0,bm.C)([a,s],"conv3dBackpropFilterV2");const l=D.ZSL.computeStrides(a.shape),c=D.ZSL.computeStrides(s.shape),d=D.C0T.computeConv3DInfo(a.shape,u,i,1,o),p=d.strideDepth,h=d.strideHeight,f=d.strideWidth,m=d.filterDepth,g=d.filterHeight,y=d.filterWidth,b=new D.ylz(d.filterShape,"float32"),x=b.values,[w,v,k,S]=b.strides,_=n.data.get(s.dataId).values,[I,T,$,C]=c,N=n.data.get(a.dataId).values,[E,A,R,F]=l,M=d.padInfo.front,O=d.padInfo.left,z=d.padInfo.top;for(let D=0;D<m;++D){const e=Math.max(0,Math.ceil((M-D)/p)),t=Math.min(d.outDepth,(d.inDepth+M-D)/p),n=D*w;for(let r=0;r<g;++r){const a=Math.max(0,Math.ceil((z-r)/h)),s=Math.min(d.outHeight,(d.inHeight+z-r)/h),i=r*v+n;for(let n=0;n<y;++n){const o=Math.max(0,Math.ceil((O-n)/f)),u=Math.min(d.outWidth,(d.inWidth+O-n)/f),l=n*k+i;for(let i=0;i<d.inChannels;++i){const c=i*S+l;for(let l=0;l<d.outChannels;++l){let m=0;for(let c=0;c<d.batchSize;++c){const d=c*E,g=c*I;for(let c=e;c<t;++c){const e=(D+c*p-M)*A+d,t=c*T+g;for(let c=a;c<s;++c){const a=(r+c*h-z)*R+e,s=c*$+t;for(let e=o;e<u;++e){const t=e*C+s;m+=N[(n+e*f-O)*F+a+i]*_[t+l]}}}}x[c+l]=m}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const Qb={kernelName:D.gC7,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:u}=r;(0,bm.C)([a],"conv3dBackpropInputV2");const l=D.ZSL.computeStrides(a.shape),c=D.ZSL.computeStrides(s.shape),d=D.C0T.computeConv3DInfo(u,s.shape,o,1,i),p=new D.ylz(d.inShape,"float32"),h=p.values,[f,m,g,y]=p.strides,b=n.data.get(a.dataId).values,[x,w,v,k]=l,S=n.data.get(s.dataId).values,[_,I,T,$]=c,{batchSize:C,filterDepth:N,filterHeight:E,filterWidth:A,inChannels:R,inDepth:F,inHeight:M,inWidth:O,outChannels:z,outDepth:L,outHeight:P,outWidth:B,strideDepth:W,strideHeight:V,strideWidth:U}=d,G=N-1-d.padInfo.front,H=E-1-d.padInfo.top,j=A-1-d.padInfo.left;for(let D=0;D<C;++D)for(let e=0;e<R;++e)for(let t=0;t<F;++t){const n=t-G,r=Math.max(0,Math.ceil(n/W)),a=Math.min(L,(N+n)/W);for(let s=0;s<M;++s){const i=s-H,o=Math.max(0,Math.ceil(i/V)),u=Math.min(P,(E+i)/V);for(let l=0;l<O;++l){const c=l-j,d=Math.max(0,Math.ceil(c/U)),p=Math.min(B,(A+c)/U);let C=0;for(let t=r;t<a;++t){const r=t*W-n;for(let n=o;n<u;++n){const a=n*V-i;for(let s=d;s<p;++s){const i=x*D+w*t+v*n+k*s,o=_*(N-1-r)+I*(E-1-a)+T*(A-1-(s*U-c))+$*e;for(let e=0;e<z;++e){C+=b[i+e]*S[o+e]}}}}h[f*D+m*t+g*s+y*l+e]=C}}}return n.makeTensorInfo(p.shape,p.dtype,p.values)}},Xb=jm(D.Mn0,(e=>Math.cos(e))),Jb={kernelName:D.Mn0,backendName:"cpu",kernelFunc:Xb},ex=jm(D.MnK,(e=>Math.cosh(e))),tx={kernelName:D.MnK,backendName:"cpu",kernelFunc:ex};const nx={kernelName:D.MRQ,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:u,extrapolationValue:l}=r,[c,d,p,h]=a.shape,f=s.shape[0],[m,g]=o,y=(0,D.ra8)([f,m,g,h],"float32"),b=n.data.get(s.dataId).values,x=n.data.get(i.dataId).values,w=n.data.get(a.dataId).values,v=D.ZSL.computeStrides(a.shape),k=D.ZSL.computeStrides(y.shape);for(let S=0;S<f;S++){const e=4*S,t=b[e],n=b[e+1],r=b[e+2],a=b[e+3],s=x[S];if(s>=c)continue;const i=m>1?(r-t)*(d-1)/(m-1):0,o=g>1?(a-n)*(p-1)/(g-1):0;for(let c=0;c<m;c++){const e=m>1?t*(d-1)+c*i:.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]+S*k[0];y.values[n]=l}else if("bilinear"===u){const t=Math.floor(e),r=Math.ceil(e),i=e-t;for(let e=0;e<g;e++){const u=g>1?n*(p-1)+e*o:.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]+S*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*v[2]+t*v[1]+s*v[0];const o=w[a];a=n+f*v[2]+t*v[1]+s*v[0];const u=w[a];a=n+d*v[2]+r*v[1]+s*v[0];const l=w[a];a=n+f*v[2]+r*v[1]+s*v[0];const p=o+(u-o)*m,h=l+(w[a]-l)*m;a=n+e*k[2]+c*k[1]+S*k[0],y.values[a]=p+(h-p)*i}}}else for(let t=0;t<g;++t){const r=g>1?n*(p-1)+t*o:.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]+S*k[0];y.values[n]=l}continue}const i=Math.round(r),u=Math.round(e);for(let e=0;e<h;e++){const n=e+i*v[2]+u*v[1]+s*v[0],r=e+t*k[2]+c*k[1]+S*k[0];y.values[r]=w[n]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}};const rx={kernelName:D.jj_,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=r;(0,bm.C)(a,"cumprod");const u=D.C0T.getAxesPermutation([s],a.shape.length);let l=a;null!=u&&(l=Zg({inputs:{x:a},backend:n,attrs:{perm:u}}));const c=D.C0T.getInnerMostAxes(1,a.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);const d=(0,D.TuY)(l.dtype,"int32"),p=D.ZSL.makeOnesTypedArray(D.ZSL.sizeFromShape(l.shape),d),h=n.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=o?(e,t)=>e+f-t-1:(e,t)=>e+t;for(let y=0;y<h.length;y+=f)for(let e=0;e<f;e++){const t=m(y,e);if(0===e)p[t]=i?1:h[t];else{const n=m(y,e-1);p[t]=i?h[n]*p[n]:h[t]*p[n]}}const g=n.makeTensorInfo(l.shape,d,p);if(null!=u){const e=Zg({inputs:{x:g},backend:n,attrs:{perm:D.C0T.getUndoAxesPermutation(u)}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(l),e}return g}};const ax={kernelName:D.nY8,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=r;(0,bm.C)(a,"cumsum");const u=D.C0T.getAxesPermutation([s],a.shape.length);let l=a;null!=u&&(l=Zg({inputs:{x:a},backend:n,attrs:{perm:u}}));const c=D.C0T.getInnerMostAxes(1,a.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);const d=(0,D.TuY)(l.dtype,"int32"),p=D.ZSL.makeZerosTypedArray(D.ZSL.sizeFromShape(l.shape),d),h=n.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=o?(e,t)=>e+f-t-1:(e,t)=>e+t;for(let y=0;y<h.length;y+=f)for(let e=0;e<f;e++){const t=m(y,e);if(0===e)p[t]=i?0:h[t];else{const n=m(y,e-1);p[t]=i?h[n]+p[n]:h[t]+p[n]}}const g=n.makeTensorInfo(l.shape,d,p);if(null!=u){const e=Zg({inputs:{x:g},backend:n,attrs:{perm:D.C0T.getUndoAxesPermutation(u)}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(l),e}return g}};const sx={kernelName:D.wNW,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:i,binaryOutput:o}=r;if(1===a.shape.length){const e=Bm(n.data.get(a.dataId).values,n.data.get(s.dataId).values,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,e)}if(2===a.shape.length){const e=Wm(n.bufferSync(a),n.bufferSync(s),i,o);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 ix={kernelName:D.TMz,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockSize:s,dataFormat:i}=r;D.ZSL.assert("NHWC"===i,(()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`));const o=a.shape[0],u=a.shape[1],l=a.shape[2],c=a.shape[3],d=u*s,p=l*s,h=c/(s*s),f=n.data.get(a.dataId).values,m=new Float32Array(o*d*p*h);let g=0;for(let y=0;y<o;++y)for(let e=0;e<d;++e){const t=Math.floor(e/s),n=e%s;for(let e=0;e<p;++e){const r=Math.floor(e/s),a=(n*s+e%s)*h;for(let e=0;e<h;++e){const n=e+a+c*(r+l*(t+u*y));m[g++]=f[n]}}}return n.makeTensorInfo([o,d,p,h],a.dtype,m)}};function ox(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:u,dimRoundingMode:l}=r;(0,bm.C)([a,s],"depthwiseConv2DNative");const c=D.ZSL.computeStrides(a.shape),d=D.ZSL.computeStrides(s.shape);let p=u;null==p&&(p=[1,1]),D.ZSL.assert(D.C0T.eitherStridesOrDilationsAreOne(i,p),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`));const h=D.C0T.computeConv2DInfo(a.shape,s.shape,i,p,o,l,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=h,x=b.left,w=b.top,v=h.outChannels/h.inChannels,k=new D.ylz(h.outShape,a.dtype),S=n.data.get(a.dataId).values,_=n.data.get(s.dataId).values,I=k.values;for(let T=0;T<h.batchSize;++T){const e=T*c[0],t=T*k.strides[0];for(let n=0;n<h.outHeight;++n){const r=t+n*k.strides[1],a=n*h.strideHeight-w;for(let t=0;t<f;++t){const n=a+t*g;if(n<0||n>=h.inHeight)continue;const s=t*d[0],i=e+n*c[1];for(let e=0;e<h.outWidth;++e){const t=r+e*k.strides[2],n=e*h.strideWidth-x;for(let e=0;e<m;++e){const r=n+e*y;if(r<0||r>=h.inWidth)continue;const a=s+e*d[1],o=i+r*h.inChannels;let u=t,l=a;for(let e=0;e<h.inChannels;++e){const t=S[o+e];for(let e=0;e<v;++e)I[u+e]+=t*_[l+e];u+=v,l+=v}}}}}}return n.makeTensorInfo(k.shape,k.dtype,k.values)}const ux={kernelName:D.tGH,backendName:"cpu",kernelFunc:ox};const lx={kernelName:D.X$8,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,filterShape:c}=r;(0,bm.C)([a,s],"depthwiseConv2dNativeBackpropFilter");const d=D.C0T.computeConv2DInfo(a.shape,c,i,o,u,l,!0),{strideHeight:p,strideWidth:h,filterHeight:f,filterWidth:m}=d,g=new D.ylz(d.filterShape,"float32"),y=d.padInfo.left,b=d.padInfo.top,x=d.outChannels/d.inChannels,w=n.data.get(a.dataId).values,v=new D.ylz(a.shape,a.dtype,w),k=n.data.get(s.dataId).values,S=new D.ylz(s.shape,s.dtype,k);for(let _=0;_<f;++_){const e=Math.max(0,Math.ceil((b-_)/p)),t=Math.min(d.outHeight,(d.inHeight+b-_)/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 i=Math.trunc(s/x),o=s%x;let u=0;for(let l=0;l<d.batchSize;++l)for(let o=e;o<t;++o){const e=_+o*p-b;for(let t=r;t<a;++t){const r=n+t*h-y;u+=v.get(l,e,r,i)*S.get(l,o,t,s)}}g.set(u,_,n,i,o)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}};const cx={kernelName:D.nVu,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,inputShape:c}=r;(0,bm.C)([a,s],"depthwiseConv2DNativeBackpropInput");const d=D.ZSL.computeStrides(a.shape),p=D.ZSL.computeStrides(s.shape),h=D.C0T.computeConv2DInfo(c,s.shape,i,o,u,l,!0),f=new D.ylz(h.inShape,"float32"),m=f.values,[g,y,b]=f.strides,x=n.data.get(a.dataId).values,[w,v,k]=d,S=n.data.get(s.dataId).values,[_,I,T]=p,{batchSize:$,filterHeight:C,filterWidth:N,inChannels:E,inHeight:A,inWidth:R,outChannels:F,outHeight:M,outWidth:O,strideHeight:z,strideWidth:L}=h,P=C-1-h.padInfo.top,B=N-1-h.padInfo.left,W=F/E;for(let D=0;D<$;++D)for(let e=0;e<E;++e)for(let t=0;t<A;++t){const n=t-P,r=Math.max(0,Math.ceil(n/z)),a=Math.min(M,(C+n)/z);for(let s=0;s<R;++s){const i=s-B,o=Math.max(0,Math.ceil(i/L)),u=Math.min(O,(N+i)/L);let l=0;for(let t=r;t<a;++t){const r=t*z-n;for(let n=o;n<u;++n){const a=w*D+v*t+k*n,s=_*(C-1-r)+I*(N-1-(n*L-i))+T*e;for(let t=0;t<W;++t){l+=x[a+(e*W+t)]*S[s+t]}}}m[g*D+y*t+b*s+e]=l}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}};const dx={kernelName:D.ORI,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=D.ZSL.sizeFromShape(r.shape),s=n.data.get(r.dataId).values,i=(0,D.ra8)([a,a],r.dtype),o=i.values;for(let l=0;l<s.length;l++)o[l*a+l]=s[l];const u=[...r.shape,...r.shape];return n.makeTensorInfo(u,i.dtype,i.values)}},px={kernelName:D.jxD,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a}=e,{strides:s,pad:i,dilations:o}=n,u=t,l=u.data.get(r.dataId).values,c=r.shape.length,d=u.data.get(a.dataId).values,p=a.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:w,strideWidth:v,filterHeight:k,filterWidth:S,dilationHeight:_,dilationWidth:I,outShape:T}=D.C0T.computeDilation2DInfo(r.shape,a.shape,s,i,"NHWC",o),$=D.ZSL.sizeFromShape(T),C=T.length,N=D.ZSL.getArrayFromDType(r.dtype,$);for(let E=0;E<h;++E)for(let e=0;e<y;++e){const t=e*w-x.top;for(let n=0;n<b;++n){const s=n*v-x.left;for(let i=0;i<g;++i){let o=Number.MIN_SAFE_INTEGER;for(let e=0;e<k;++e){const n=t+e*_;if(n>=0&&n<f)for(let t=0;t<S;++t){const u=s+t*I;if(u>=0&&u<m){const s=D.ZSL.locToIndex([E,n,u,i],c,D.ZSL.computeStrides(r.shape)),h=D.ZSL.locToIndex([e,t,i],p,D.ZSL.computeStrides(a.shape)),f=l[s]+d[h];f>o&&(o=f)}}}N[D.ZSL.locToIndex([E,e,n,i],C,D.ZSL.computeStrides(T))]=o}}}return{dataId:u.write(D.ZSL.toTypedArray(N,r.dtype),T,r.dtype),shape:T,dtype:r.dtype}}},hx={kernelName:D.pk0,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a,dy:s}=e,{strides:i,pad:o,dilations:u}=n,l=t,c=D.ZSL.toNestedArray(r.shape,l.data.get(r.dataId).values),d=D.ZSL.toNestedArray(a.shape,l.data.get(a.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:S,dilationWidth:_,outShape:I}=D.C0T.computeDilation2DInfo(r.shape,a.shape,i,o,"NHWC",u);D.ZSL.assert(s.rank===I.length,(()=>`Error in ${D.pk0}, dy must have the same rank as output ${I.length}, but got ${s.rank}`));const T=D.ZSL.toNestedArray(I,l.data.get(s.dataId).values),$=D.ZSL.makeZerosNestedTypedArray(a.shape,a.dtype);for(let C=0;C<p;++C)for(let e=0;e<g;++e){const t=e*x-b.top;for(let n=0;n<y;++n){const r=n*w-b.left;for(let a=0;a<m;++a){let s=Number.MIN_SAFE_INTEGER,i=0,o=0;for(let e=0;e<v;++e){const n=t+e*S;if(n>=0&&n<h)for(let t=0;t<k;++t){const u=r+t*_;if(u>=0&&u<f){const r=c[C][n][u][a]+d[e][t][a];r>s&&(s=r,i=e,o=t)}}}$[i][o][a]+=T[C][e][n][a]}}}return{dataId:l.write(D.ZSL.toTypedArray($,r.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},fx={kernelName:D.bP9,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a,dy:s}=e,{strides:i,pad:o,dilations:u}=n,l=t,c=D.ZSL.toNestedArray(r.shape,l.data.get(r.dataId).values),d=D.ZSL.toNestedArray(a.shape,l.data.get(a.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:k,dilationHeight:S,dilationWidth:_,outShape:I}=D.C0T.computeDilation2DInfo(r.shape,a.shape,i,o,"NHWC",u);D.ZSL.assert(s.rank===I.length,(()=>`Error in ${D.bP9}, dy must have the same rank as output ${I.length}, but got ${s.rank}`));const T=D.ZSL.toNestedArray(I,l.data.get(s.dataId).values),$=D.ZSL.makeZerosNestedTypedArray(r.shape,r.dtype);for(let C=0;C<p;++C)for(let e=0;e<g;++e){const t=e*x-b.top;for(let n=0;n<y;++n){const r=n*w-b.left;for(let a=0;a<m;++a){let s=Number.MIN_SAFE_INTEGER,i=t<0?0:t,o=r<0?0:r;for(let e=0;e<v;++e){const n=t+e*S;if(n>=0&&n<h)for(let t=0;t<k;++t){const u=r+t*_;if(u>=0&&u<f){const r=c[C][n][u][a]+d[e][t][a];r>s&&(s=r,i=n,o=u)}}}$[C][i][o][a]+=T[C][e][n][a]}}}return{dataId:l.write(D.ZSL.toTypedArray($,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};const mx={kernelName:D.XmO,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a}=t,{canvas:s,options:i}=r,{contextOptions:o,imageOptions:u}=i||{},l=(null===u||void 0===u?void 0:u.alpha)||1,c=(null===o||void 0===o?void 0:o.contextType)||"2d";if("2d"!==c)throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);const d=s.getContext(c,(null===o||void 0===o?void 0:o.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 gx(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r;let o;(0,bm.C)(a,"sum"),o="bool"===a.dtype?Rm({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):$m({inputs:{x:a},backend:n});const u=o.shape.length,l=D.ZSL.parseAxisParam(s,o.shape),c=D.C0T.getAxesPermutation(l,u);let d=l,p=o;null!=c&&(p=Zg({inputs:{x:o},backend:n,attrs:{perm:c}}),d=D.C0T.getInnerMostAxes(d.length,u)),D.C0T.assertAxesAreInnerMostDims("sum",d,p.shape.length);const[h,f]=D.C0T.computeOutAndReduceShapes(p.shape,d);let m=Tm(n,h,D.C0T.upcastType(p.dtype,"int32"));const g=D.ZSL.sizeFromShape(f),y=n.data.get(m.dataId).values,b=n.data.get(p.dataId).values;for(let x=0;x<y.length;++x){const e=x*g;let t=0;for(let n=0;n<g;++n)t+=b[e+n];y[x]=t}if(i){const e=m;m=nb({inputs:{x:m},backend:n,attrs:{shape:D.C0T.expandShapeToKeepDim(m.shape,l)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=c&&n.disposeIntermediateTensorInfo(p),m}const yx={kernelName:D.WuN,backendName:"cpu",kernelFunc:gx};const bx={kernelName:D.Qgm,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:a}=r,s=t,{allDims:i,summedDims:o,idDims:u}=D.C0T.decodeEinsumEquation(a,s.length);D.C0T.checkEinsumDimSizes(i.length,u,s);const{path:l,steps:c}=D.C0T.getEinsumComputePath(o,u),d=c.length;let p=null,h=i.length;const f=[];for(let m=0;m<d;++m){for(const e of c[m]){const{permutationIndices:t,expandDims:r}=D.C0T.getEinsumPermutation(h,u[e]);let a;D.C0T.isIdentityPermutation(t)?a=s[e]:(a=Zg({inputs:{x:s[e]},backend:n,attrs:{perm:t}}),f.push(a));const i=a.shape.slice();for(let e=0;e<r.length;++e)i.splice(r[e],0,1);D.ZSL.arraysEqual(a.shape,i)||(a=nb({inputs:{x:a},backend:n,attrs:{shape:i}}),f.push(a)),null===p?p=a:(p=Bg({inputs:{a:a,b:p},backend:n}),f.push(p))}m<d-1&&(l[m]>=0&&(p=gx({inputs:{x:p},backend:n,attrs:{axis:l[m]-(i.length-h),keepDims:!1}}),f.push(p)),h--)}for(const m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}};const xx={kernelName:D.rsH,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:r,y:a}=t;(0,bm.C)([r,a],"eluGrad");const s=new Float32Array(D.ZSL.sizeFromShape(a.shape)),i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values;for(let u=0;u<i.length;++u){const e=i[u];s[u]=e>=0?o[u]:o[u]*(e+1)}return n.makeTensorInfo(a.shape,"float32",s)}},wx=D.C0T.ERF_P,vx=D.C0T.ERF_A1,kx=D.C0T.ERF_A2,Sx=D.C0T.ERF_A3,_x=D.C0T.ERF_A4,Ix=D.C0T.ERF_A5,Tx=jm(D._s9,(e=>{const t=Math.sign(e),n=Math.abs(e),r=1/(1+wx*n);return t*(1-((((Ix*r+_x)*r+Sx)*r+kx)*r+vx)*r*Math.exp(-n*n))})),$x={kernelName:D._s9,backendName:"cpu",kernelFunc:Tx};function Cx(e){const{inputs:t,backend:n,attrs:r}=e,{input:a}=t,{dim:s}=r,i=a.shape.length,o=a.shape.slice();let u=s;return s<0&&(D.ZSL.assert(-(i+1)<=s,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),u=i+s+1),o.splice(u,0,1),nb({inputs:{x:a},backend:n,attrs:{shape:o}})}const Nx={kernelName:D.ybN,backendName:"cpu",kernelFunc:Cx},Ex=Sm(((e,t)=>e/t)),Ax=Fm(D.sDr,Ex),Rx={kernelName:D.sDr,backendName:"cpu",kernelFunc:Ax};function Dx(e,t,n){const r=e.shape,a=r[0],s=r[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,u=i.complexTensorInfos.imag,l=[a,s],c=D.ZSL.sizeFromShape(l),d=D.ZSL.getTypedArrayFromDType("float32",c),p=D.ZSL.getTypedArrayFromDType("float32",c);for(let g=0;g<a;g++){const e=(0,yy.di)({inputs:{x:o},backend:n,attrs:{begin:[g,0],size:[1,s]}}),r=(0,yy.di)({inputs:{x:u},backend:n,attrs:{begin:[g,0],size:[1,s]}}),a=_m({inputs:{real:e,imag:r},backend:n}),{real:i,imag:l}=Fx(a,t,n),c=D.C0T.mergeRealAndImagArrays(i,l);for(let t=0;t<s;t++){const e=D.C0T.getComplexWithIndex(c,t);d[g*s+t]=e.real,p[g*s+t]=e.imag}n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a)}const h=n.makeTensorInfo(l,"float32",d),f=n.makeTensorInfo(l,"float32",p),m=_m({inputs:{real:h,imag:f},backend:n});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),m}function Fx(e,t,n){const r=D.ZSL.sizeFromShape(e.shape),a=n.data.get(e.dataId),s=n.data.get(a.complexTensorInfos.real.dataId).values,i=n.data.get(a.complexTensorInfos.imag.dataId).values;if(0===((o=r)&o-1)){const a=Mx(s,i,r,t,n),o=[e.shape[0],e.shape[1]];if(t){const e=n.makeTensorInfo(o,"float32",a.real),t=n.makeTensorInfo(o,"float32",a.imag),s=n.makeTensorInfo([],"float32",D.ZSL.createScalarValue(r,"float32")),i=$m({inputs:{x:s},backend:n}),u=Rx.kernelFunc({inputs:{a:e,b:s},backend:n}),l=Rx.kernelFunc({inputs:{a:t,b:i},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(i),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,i=0;for(let r=0;r<t;r++){const o=D.C0T.exponent(a*r,t,n),u=D.C0T.getComplexWithIndex(e,r);s+=u.real*o.real-u.imag*o.imag,i+=u.real*o.imag+u.imag*o.real}n&&(s/=t,i/=t),D.C0T.assignToTypedArray(r,s,i,a)}return r}(D.C0T.mergeRealAndImagArrays(s,i),r,t);return D.C0T.splitRealAndImagArrays(e)}var o}function Mx(e,t,n,r,a){if(1===n)return{real:e,imag:t};const s=D.C0T.mergeRealAndImagArrays(e,t),i=n/2,o=D.C0T.complexWithEvenIndex(s),u=o.real,l=o.imag,c=[u.length],d=a.makeTensorInfo(c,"float32",u),p=a.makeTensorInfo(c,"float32",l),h=_m({inputs:{real:d,imag:p},backend:a}),f=D.C0T.complexWithOddIndex(s),m=f.real,g=f.imag,y=[m.length],b=a.makeTensorInfo(y,"float32",m),x=a.makeTensorInfo(y,"float32",g),w=_m({inputs:{real:b,imag:x},backend:a}),v=Mx(u,l,i,r,a),k=v.real,S=v.imag,_=[k.length],I=a.makeTensorInfo(_,"float32",k),T=a.makeTensorInfo(_,"float32",S),$=_m({inputs:{real:I,imag:T},backend:a}),C=Mx(m,g,i,r,a),N=C.real,E=C.imag,A=[N.length],R=a.makeTensorInfo(A,"float32",N),F=a.makeTensorInfo(A,"float32",E),M=_m({inputs:{real:R,imag:F},backend:a}),O=D.C0T.exponents(n,r),z=[O.real.length],L=a.makeTensorInfo(z,"float32",O.real),P=a.makeTensorInfo(z,"float32",O.imag),B=_m({inputs:{real:L,imag:P},backend:a}),W=Bg({inputs:{a:B,b:M},backend:a}),V=Lm({inputs:{a:$,b:W},backend:a}),U=Oy({inputs:{a:$,b:W},backend:a}),G=Nm({inputs:{input:V},backend:a}),H=Nm({inputs:{input:U},backend:a}),j=Wb({inputs:{input:V},backend:a}),q=Wb({inputs:{input:U},backend:a}),Z=Ub({inputs:[G,H],backend:a,attrs:{axis:0}}),K=Ub({inputs:[j,q],backend:a,attrs:{axis:0}}),Y=a.data.get(Z.dataId).values,Q=a.data.get(K.dataId).values;return a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(b),a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(w),a.disposeIntermediateTensorInfo(I),a.disposeIntermediateTensorInfo(T),a.disposeIntermediateTensorInfo($),a.disposeIntermediateTensorInfo(R),a.disposeIntermediateTensorInfo(F),a.disposeIntermediateTensorInfo(M),a.disposeIntermediateTensorInfo(L),a.disposeIntermediateTensorInfo(P),a.disposeIntermediateTensorInfo(B),a.disposeIntermediateTensorInfo(W),a.disposeIntermediateTensorInfo(V),a.disposeIntermediateTensorInfo(U),a.disposeIntermediateTensorInfo(G),a.disposeIntermediateTensorInfo(j),a.disposeIntermediateTensorInfo(H),a.disposeIntermediateTensorInfo(q),a.disposeIntermediateTensorInfo(Z),a.disposeIntermediateTensorInfo(K),{real:Y,imag:Q}}const Ox={kernelName:D.rGP,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,a=D.ZSL.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],i=nb({inputs:{x:r},backend:n,attrs:{shape:[a/s,s]}}),o=Dx(i,!1,n),u=nb({inputs:{x:o},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),u}};function zx(e){const{backend:t,attrs:n}=e,{shape:r,value:a,dtype:s}=n,i=s||D.ZSL.inferDtype(a),o=D.ZSL.getArrayFromDType(i,D.ZSL.sizeFromShape(r));return function(e,t){e.fill(t)}(o,a),t.makeTensorInfo(r,i,o)}const Lx={kernelName:D.SQl,backendName:"cpu",kernelFunc:zx};const Px={kernelName:D.BxF,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,a=n,s=D.ZSL.getTypedArrayFromDType(r.dtype,D.ZSL.sizeFromShape(r.shape)),[i,o,u,l]=r.shape,c=a.data.get(r.dataId).values;for(let d=0;d<i;d++){const e=d*u*o*l;for(let t=0;t<o;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 i=Math.round(u-t-1),o=e+n+r+a;let d=c[o];if(i>=0&&i<u){d=c[e+n+i*l+a]}s[o]=d}}}}return{dataId:a.write(s,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};const Bx={kernelName:D.aAr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r;let m=Hb({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p}});if(i){const e=m;if("NCHW"===c&&1===i.shape.length&&1!==i.shape[0]){const e=nb({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=Lm({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=Lm({inputs:{a:m,b:i},backend:n});n.disposeIntermediateTensorInfo(e)}if(h){const e=m;if("NCHW"===c&&"prelu"===h&&1===o.shape.length&&1!==o.shape[0]){const e=nb({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=tb(n,m,h,e,f),n.disposeIntermediateTensorInfo(e)}else m=tb(n,m,h,o,f);n.disposeIntermediateTensorInfo(e)}return m}};const Wx={kernelName:D.T7M,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r;let m=ox({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p}});if(i){const e=m;m=Lm({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(h){const e=m;m=tb(n,m,h,o,f),n.disposeIntermediateTensorInfo(e)}return m}};const Vx={kernelName:D.O4G,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:a}=t,s=D.ZSL.sizeFromShape(r.shape),i=a.shape,o=i[i.length-1],[u,l,c,d]=D.C0T.prepareAndValidate(r,a);if(0===l)return n.makeTensorInfo(u,r.dtype,[]);const p=hg(n.data.get(a.dataId).values,n.bufferSync(r),r.dtype,l,o,c,d,r.shape,s);return n.makeTensorInfo(u,r.dtype,p.values)}};const Ux={kernelName:D.mxL,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=r;(0,bm.C)([a,s],"gatherV2");const u=D.ZSL.parseAxisParam(i,a.shape)[0],l=n.data.get(s.dataId).values,c=a.shape[u];for(let x=0;x<l.length;++x){const e=l[x];D.ZSL.assert(e<=c-1&&e>=0,(()=>`GatherV2: the index value ${e} is not in [0, ${c-1}]`))}let d=o;null==o&&(d=0);const p=D.ZSL.sizeFromShape(s.shape),h=D.C0T.segment_util.collectGatherOpShapeInfo(a,s,u,d),f=nb({inputs:{x:a},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),m=nb({inputs:{x:s},backend:n,attrs:{shape:[h.batchSize,p/h.batchSize]}}),g=[h.batchSize,h.outerSize,p/h.batchSize,h.sliceSize],y=n.bufferSync(m),b=fg(n.bufferSync(f),y,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(h.outputShape,b.dtype,b.values)}};const Gx={kernelName:D.OAQ,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,a=D.ZSL.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],i=nb({inputs:{x:r},backend:n,attrs:{shape:[a/s,s]}}),o=Dx(i,!0,n),u=nb({inputs:{x:o},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),u}},Hx=jm(D.gIW,(e=>Number.isFinite(e)?1:0),"bool"),jx={kernelName:D.gIW,backendName:"cpu",kernelFunc:Hx},qx=jm(D.E3$,(e=>Math.abs(e)===1/0?1:0),"bool"),Zx={kernelName:D.E3$,backendName:"cpu",kernelFunc:qx},Kx=jm(D.iPs,(e=>Number.isNaN(e)?1:0),"bool"),Yx={kernelName:D.iPs,backendName:"cpu",kernelFunc:Kx};const Qx={kernelName:D.mnI,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,num:s}=n,i=$g(r,a,s);return t.makeTensorInfo([i.length],"float32",i)}},Xx=jm(D.Cg$,(e=>Math.log1p(e))),Jx={kernelName:D.Cg$,backendName:"cpu",kernelFunc:Xx},ew=Sm(((e,t)=>e&&t)),tw=Fm(D.RUm,ew,null,"bool"),nw={kernelName:D.RUm,backendName:"cpu",kernelFunc:tw},rw=jm(D.nZd,(e=>e?0:1),"bool"),aw={kernelName:D.nZd,backendName:"cpu",kernelFunc:rw},sw=Sm(((e,t)=>e||t)),iw=Fm(D.LXA,sw,null,"bool"),ow={kernelName:D.LXA,backendName:"cpu",kernelFunc:iw};const uw={kernelName:D.jM4,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:u}=r;(0,bm.C)(a,"LRN");const l=a.shape[3],c=l-1,d=n.data.get(a.dataId).values,p=D.ZSL.sizeFromShape(a.shape),h=new Float32Array(p);function f(e){const t=e%l;let n=e-t+Math.max(0,t-s);const r=e-t+Math.min(t+s,c);let a=0;for(;n<=r;n++){const e=d[n];a+=e*e}return a}for(let m=0;m<p;m++){const e=f(m),t=d[m]*Math.pow(i+o*e,-u);h[m]=t}return n.makeTensorInfo(a.shape,a.dtype,h)}};const lw={kernelName:D.ToN,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:u,alpha:l,beta:c}=r;(0,bm.C)(i,"LRNGrad");const d=D.ZSL.sizeFromShape(i.shape),p=i.shape[3],h=n.data.get(i.dataId).values,f=n.data.get(a.dataId).values,m=n.data.get(s.dataId).values,g=new Float32Array(d),y=d;for(let b=0;b<y;b++){const e=b%p,t=b-e+Math.max(0,e-o),n=b-e+Math.min(p,e+o+1);let r=0;for(let a=t;a<n;a++)r+=Math.pow(f[a],2);r=l*r+u;for(let a=t;a<n;a++){let e=-2*l*c*f[a]*m[b]/r;b===a&&(e+=Math.pow(r,-c)),e*=h[b],g[a]+=e}}return n.makeTensorInfo(i.shape,a.dtype,g)}};function cw(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=r,o=n;let u=a.shape;const l=u.length,c=D.ZSL.parseAxisParam(s,u);let d=c;const p=D.C0T.getAxesPermutation(d,l);let h=o.data.get(a.dataId).values;if(null!=p){const e=new Array(l);for(let t=0;t<e.length;t++)e[t]=u[p[t]];h=qg(h,u,a.dtype,p,e),d=D.C0T.getInnerMostAxes(d.length,l),u=e}(0,bm.C)(a,"max"),D.C0T.assertAxesAreInnerMostDims("max",d,l);const[f,m]=D.C0T.computeOutAndReduceShapes(u,d),g=Ag(h,D.ZSL.sizeFromShape(m),f,a.dtype),y=o.write(g,f,a.dtype);let b=f;if(i){b=D.C0T.expandShapeToKeepDim(f,c)}return{dataId:y,shape:b,dtype:a.dtype}}const dw={kernelName:D.VAI,backendName:"cpu",kernelFunc:cw};const pw={kernelName:D.t3d,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;(0,bm.C)(a,"maxPool");const{filterSize:s,strides:i,pad:o,dimRoundingMode:u}=r;D.ZSL.assert(D.C0T.eitherStridesOrDilationsAreOne(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const l=D.C0T.computePool2DInfo(a.shape,s,i,1,o,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&D.ZSL.arraysEqual(l.inShape,l.outShape))c=$m({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=D.ZSL.computeStrides(a.shape),r=$b(e,a.shape,a.dtype,t,l,"max");c=n.makeTensorInfo(l.outShape,a.dtype,r.values)}return c}};const hw={kernelName:D.ySp,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r;(0,bm.C)(a,"maxPool3d");const c=D.C0T.computePool3DInfo(a.shape,s,i,1,o,u,l),d=Nb(n.data.get(a.dataId).values,a.shape,a.dtype,D.ZSL.computeStrides(a.shape),c,"max");return n.makeTensorInfo(d.shape,"float32",d.values)}};const fw={kernelName:D.cHb,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:u,dimRoundingMode:l}=r;(0,bm.C)([a,s],"maxPool3DGrad");const c=D.C0T.computePool3DInfo(s.shape,i,o,1,u,l),d=function(e,t){const n=(0,D.ra8)(t.outShape,"int32"),r=t.strideDepth,a=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=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+=i;const w=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+=o;const v=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 S=Math.min(t.inWidth,d+h);let _=Number.NEGATIVE_INFINITY,I=-1;for(let t=x;t<w;t+=i){const n=t-b;for(let r=p;r<v;r+=o){const a=r-l;for(let s=k;s<S;s+=u){const i=s-h,o=e.get(m,t,r,s,g);o>=_&&(_=o,I=n*c*d+a*c+i)}}}n.set(I,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,w=c.effectiveFilterWidth,v=b-1-c.padInfo.front,k=w-1-c.padInfo.left,S=x-1-c.padInfo.top,_=(0,D.ra8)(s.shape,"float32"),I=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-v,s=n-S,i=r-k;let o=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<w;s+=y){const u=(i+s)/f;if(u<0||u>=c.outWidth||Math.floor(u)!==u)continue;const l=b*x*w-1-d.get(T,n,a,u,e)===t*x*w+r*w+s?1:0;if(0===l)continue;o+=I.get(T,n,a,u,e)*l}}}_.set(o,T,t,n,r,e)}return n.makeTensorInfo(_.shape,_.dtype,_.values)}};const mw={kernelName:D.RXX,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s,output:i}=t,o=s;(0,bm.C)([s,i],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:d}=r,p=D.C0T.computePool2DInfo(o.shape,u,l,1,c,d),h=n.data.get(o.dataId).values,f=(0,D.ra8)(p.outShape,o.dtype,Cb(h,o.shape,o.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,b=p.dilationWidth,x=p.effectiveFilterHeight,w=p.effectiveFilterWidth,v=w-1-p.padInfo.left,k=x-1-p.padInfo.top,S=(0,D.ra8)(o.shape,"float32"),_=n.data.get(a.dataId).values,I=(0,D.ra8)(a.shape,"float32",_);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-v;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<w;r+=b){const i=(a+r)/g;if(i<0||i>=p.outWidth||Math.floor(i)!==i)continue;const o=x*w-1-f.get(T,n,i,e)===t*w+r?1:0;if(0===o)continue;s+=I.get(T,n,i,e)*o}}S.set(s,T,t,n,e)}return n.makeTensorInfo(S.shape,S.dtype,S.values)}};const gw={kernelName:D.TL8,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:a,strides:s,pad:i,includeBatchInIndex:o}=t,u=n;(0,bm.C)(r,"MaxPoolWithArgmax");const l=u.data.get(r.dataId).values,c=D.C0T.computePool2DInfo(r.shape,a,s,[1,1],i),[d,p]=function(e,t,n,r,a){const s=$b(e,0,n,D.ZSL.computeStrides(t),a,"max"),i=Cb(e,t,n,a,!0,r);return[s.values,i.values]}(l,r.shape,r.dtype,o,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 yw={kernelName:D.g5A,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r,o=D.ZSL.parseAxisParam(s,a.shape),u=D.C0T.computeOutAndReduceShapes(a.shape,o)[1],l=D.ZSL.sizeFromShape(u),c=[],d=n.makeTensorInfo([],"float32",new Float32Array([l]));c.push(d);const p=Rm({inputs:{x:a},backend:n,attrs:{dtype:"float32"}});c.push(p);const h=Ax({inputs:{a:p,b:d},backend:n});c.push(h);const f=gx({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:i}});return c.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};const bw={kernelName:D.lNG,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r;(0,bm.C)(a,"min");const o=D.ZSL.parseAxisParam(s,a.shape);let u=o;const l=D.C0T.getAxesPermutation(u,a.shape.length);let c=a;null!=l&&(c=Zg({inputs:{x:a},backend:n,attrs:{perm:l}}),u=D.C0T.getInnerMostAxes(u.length,a.shape.length)),D.C0T.assertAxesAreInnerMostDims("min",u,c.shape.length);const[d,p]=D.C0T.computeOutAndReduceShapes(c.shape,u),h=D.ZSL.sizeFromShape(p),f=D.ZSL.makeZerosTypedArray(D.ZSL.sizeFromShape(d),c.dtype),m=n.data.get(c.dataId).values;for(let y=0;y<f.length;++y){const e=y*h;let t=m[e];for(let n=0;n<h;++n){const r=m[e+n];(Number.isNaN(r)||r<t)&&(t=r)}f[y]=t}null!=l&&n.disposeIntermediateTensorInfo(c);const g=n.makeTensorInfo(d,c.dtype,f);if(i){const e=nb({inputs:{x:g},backend:n,attrs:{shape:D.C0T.expandShapeToKeepDim(d,o)}});return n.disposeIntermediateTensorInfo(g),e}return g}};const xw={kernelName:D.x7F,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,mode:i}=r;(0,bm.C)(a,"mirrorPad");const o=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])),c="reflect"===i?0:1,d=n.data.get(a.dataId).values,p=a.shape.length,h=D.ZSL.computeStrides(a.shape),f=D.ZSL.sizeFromShape(o),m=o.length,g=D.ZSL.computeStrides(o),y=D.ZSL.getTypedArrayFromDType(a.dtype,f);for(let b=0;b<f;b++){let e=D.ZSL.indexToLoc(b,m,g);for(let n=0;n<m;n++)e[n]<u[n]?e[n]=2*u[n]-e[n]-c:e[n]>=l[n]&&(e[n]=2*(l[n]-1)-e[n]+c);e=e.map(((e,t)=>e-u[t]));const t=D.ZSL.locToIndex(e,p,h);y[b]=d[t]}return{dataId:n.write(y,o,a.dtype),shape:o,dtype:a.dtype}}},ww=Sm(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),vw=Fm(D.BLA,ww),kw={kernelName:D.BLA,backendName:"cpu",kernelFunc:vw};function Sw(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,i=a.shape.length;let o=s;if(-1===o&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);const u=D.ZSL.parseAxisParam([o],a.shape),l=cw({inputs:{x:a},backend:n,attrs:{reductionIndices:u,keepDims:!1}}),c=D.C0T.expandShapeToKeepDim(l.shape,u),d=nb({inputs:{x:l},backend:n,attrs:{shape:c}}),p=Oy({inputs:{a:a,b:d},backend:n}),h=ng({inputs:{x:p},backend:n}),f=gx({inputs:{x:h},backend:n,attrs:{axis:u,keepDims:!1}}),m=nb({inputs:{x:f},backend:n,attrs:{shape:c}}),g=Ax({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 _w={kernelName:D.rFG,backendName:"cpu",kernelFunc:Sw};const Iw={kernelName:D.WT3,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=r;(0,bm.C)(a,"multinomial");const u=o?a:Sw({inputs:{logits:a},backend:n,attrs:{dim:-1}}),l=u.shape[0],c=u.shape[1],d=n.data.get(u.dataId).values,p=[l,s],h=D.ZSL.makeZerosTypedArray(D.ZSL.sizeFromShape(p),"int32");for(let f=0;f<l;++f){const e=f*c,t=new Float32Array(c-1);t[0]=d[e];for(let a=1;a<t.length;++a)t[a]=t[a-1]+d[e+a];const n=uf.alea(i.toString()),r=f*s;for(let a=0;a<s;++a){const e=n();h[r+a]=t.length;for(let n=0;n<t.length;n++)if(e<t[n]){h[r+a]=n;break}}}return o||n.disposeIntermediateTensorInfo(u),n.makeTensorInfo(p,"int32",h)}},Tw=D.kpo.nonMaxSuppressionV3Impl;const $w={kernelName:D.SDM,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=r;(0,bm.C)(a,"NonMaxSuppression");const l=n.data.get(a.dataId).values,c=n.data.get(s.dataId).values,{selectedIndices:d}=Tw(l,c,i,o,u);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}},Cw=D.kpo.nonMaxSuppressionV4Impl;const Nw={kernelName:D.Zl4,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,padToMaxOutputSize:l}=r;(0,bm.C)(a,"NonMaxSuppressionPadded");const c=n.data.get(a.dataId).values,d=n.data.get(s.dataId).values,{selectedIndices:p,validOutputs:h}=Cw(c,d,i,o,u,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}},Ew=D.kpo.nonMaxSuppressionV5Impl;const Aw={kernelName:D.e0f,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=r;(0,bm.C)(a,"NonMaxSuppressionWithScore");const c=n.data.get(a.dataId).values,d=n.data.get(s.dataId).values,p=i,h=o,f=u,m=l,{selectedIndices:g,selectedScores:y}=Ew(c,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};const Rw={kernelName:D.urI,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{dtype:s,depth:i,onValue:o,offValue:u}=r;(0,bm.C)(a,"oneHot");const l=D.ZSL.sizeFromShape(a.shape),c=new Float32Array(l*i);c.fill(u);const d=n.data.get(a.dataId).values;for(let p=0;p<l;++p)d[p]>=0&&d[p]<i&&(c[p*i+d[p]]=o);return n.makeTensorInfo([...a.shape,i],s,c)}};function Dw(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=Nm({inputs:{input:r},backend:n}),t=Dw({inputs:{x:e},backend:n}),a=Wb({inputs:{input:r},backend:n}),s=Dw({inputs:{x:a},backend:n}),i=_m({inputs:{real:t,imag:s},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(s),i}return zx({backend:n,attrs:{shape:r.shape,value:0,dtype:r.dtype}})}const Fw={kernelName:D.xJ3,backendName:"cpu",kernelFunc:Dw};const Mw={kernelName:D.LWX,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=Nm({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r}),s=Wb({inputs:{input:a},backend:r}),i=Dw({inputs:{x:s},backend:r}),o=_m({inputs:{real:n,imag:i},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),o}return zx({backend:r,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}};function Ow(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return Cx({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,i=t[0].dtype;t.forEach((e=>{D.ZSL.assertShapesMatch(s,e.shape,"All tensors passed to stack must have matching shapes"),D.ZSL.assert(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],u=Ub({inputs:t.map((e=>{const t=Cx({inputs:{input:e},backend:n,attrs:{dim:a}});return o.push(t),t})),backend:n,attrs:{axis:a}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),u}const zw={kernelName:D.mM$,backendName:"cpu",kernelFunc:Ow};const Lw={kernelName:D.ODT,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:i}=r;(0,bm.C)(a,"pad");const o=s.map(((e,t)=>e[0]+a.shape[t]+e[1])),u=s.map((e=>e[0])),l=n.data.get(a.dataId).values,c=D.ZSL.sizeFromShape(a.shape),d=a.shape.length,p=D.ZSL.computeStrides(a.shape),h=D.ZSL.sizeFromShape(o),f=o.length,m=D.ZSL.computeStrides(o),g=D.ZSL.getTypedArrayFromDType(a.dtype,h);0!==i&&g.fill(i);for(let y=0;y<c;y++){const e=D.ZSL.indexToLoc(y,d,p).map(((e,t)=>e+u[t]));g[D.ZSL.locToIndex(e,f,m)]=l[y]}return{dataId:n.write(g,o,a.dtype),shape:o,dtype:a.dtype}}},Pw=Sm(((e,t)=>Math.pow(e,t))),Bw=Fm(D.pyJ,Pw),Ww={kernelName:D.pyJ,backendName:"cpu",kernelFunc:Bw};const Vw={kernelName:D.oJ2,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:a,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=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(i.dataId).values,[p,h,f]=ty(u,l,c,s.shape,s.dtype,d,i.shape),m=p.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,s.dtype,h);return m.concat([g])}};const Uw={kernelName:D.CQC,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:r,limits:a,deltas:s}=t,i=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,u=n.data.get(s.dataId).values,[l,c]=ry(i,r.shape,r.dtype,o,a.shape,u,s.shape);return[n.makeTensorInfo([l.length],"int32",l),n.makeTensorInfo([c.length],r.dtype,c)]}};const Gw={kernelName:D.mH5,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{shape:a,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:u}=r,l=n.data.get(a.dataId).values,c=n.data.get(s.dataId).values,d=n.data.get(i.dataId).values,p=o.map((e=>n.data.get(e.dataId).values)),h=o.map((e=>e.shape)),[f,m]=uy(l,a.shape,c,s.shape,s.dtype,d,i.shape,p,h,u);return n.makeTensorInfo(f,s.dtype,m)}};const Hw={kernelName:D.Q6t,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,dtype:s,step:i}=n,o=(0,ly.q)(r,a,i,s);return t.makeTensorInfo([o.length],s,o)}},jw=jm(D.huO,(e=>1/e)),qw={kernelName:D.huO,backendName:"cpu",kernelFunc:jw};const Zw={kernelName:D.hgw,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=r;(0,bm.C)(a,"resizeBilinear");const u=D.ZSL.computeStrides(a.shape),[l,c]=o,[d,p,h,f]=a.shape,m=n.data.get(a.dataId).values,g=new Float32Array(D.ZSL.sizeFromShape([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];let x=0;const w=y[0]/b[0],v=y[1]/b[1];for(let k=0;k<d;k++)for(let e=0;e<l;e++){let t;t=i?w*(e+.5)-.5:w*e;const n=Math.max(0,Math.floor(t)),r=t-n,a=Math.min(p-1,Math.ceil(t)),s=k*u[0]+n*u[1],o=k*u[0]+a*u[1];for(let e=0;e<c;e++){let t;t=i?v*(e+.5)-.5:v*e;const n=Math.max(0,Math.floor(t)),a=t-n,l=Math.min(h-1,Math.ceil(t)),c=s+n*u[2],d=o+n*u[2],p=s+l*u[2],y=o+l*u[2];for(let e=0;e<f;e++){const t=m[c+e],n=m[d+e],s=t+(m[p+e]-t)*a,i=s+(n+(m[y+e]-n)*a-s)*r;g[x++]=i}}}return n.makeTensorInfo([d,l,c,f],"float32",g)}};const Kw={kernelName:D.FCQ,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:i}=r;(0,bm.C)([s,a],"resizeBilinearGrad");const o=D.ZSL.computeStrides(a.shape),[u,l,c,d]=a.shape,[,p,h]=s.shape,f=new Float32Array(u*l*c*d),m=[i&&p>1?l-1:l,i&&h>1?c-1:c],g=[i&&p>1?p-1:p,i&&h>1?h-1:h],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(s.dataId).values;let w=0;for(let v=0;v<u;v++){const e=v*o[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*o[1],i=e+a*o[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*o[2],m=s+r*o[2],g=i+n*o[2],y=i+r*o[2],v=p*l,k=p*a,S=u*l,_=u*a;for(let e=0;e<d;e++){const t=x[w++];f[h+e]+=t*v,f[m+e]+=t*k,f[g+e]+=t*S,f[y+e]+=t*_}}}}return n.makeTensorInfo([u,c,l,d],"float32",f)}};const Yw={kernelName:D.jOE,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=r;(0,bm.C)(a,"resizeNearestNeighbor");const u=D.ZSL.computeStrides(a.shape),[l,c]=o,[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],w=y[1]/b[1];let v=0;for(let k=0;k<d;k++){const e=k*u[0];for(let t=0;t<l;t++){const n=i?x*(t+.5):x*t;let r=Math.min(p-1,s?Math.round(n):Math.floor(n));i&&(r=Math.max(0,r));const a=e+r*u[1];for(let e=0;e<c;e++){const t=i?w*(e+.5):w*e;let n=Math.min(h-1,s?Math.round(t):Math.floor(t));i&&(n=Math.max(0,n));const r=a+n*u[2];for(let e=0;e<f;e++){const t=m[r+e];g[v++]=t}}}}return n.makeTensorInfo([d,l,c,f],a.dtype,g)}};const Qw={kernelName:D.XQy,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:i}=r;(0,bm.C)([s,a],"resizeNearestNeighborGrad");const o=D.ZSL.computeStrides(a.shape),u=D.ZSL.computeStrides(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=[i&&h>1?c-1:c,i&&f>1?d-1:d],b=[i&&h>1?h-1:h,i&&f>1?f-1:f],x=y[0]/b[0],w=y[1]/b[1],v=1/x,k=1/w,S=2*Math.ceil(v)+2,_=2*Math.ceil(k)+2;for(let I=0;I<l;I++){const e=I*o[0];for(let t=0;t<c;t++){const n=e+t*o[1],r=Math.floor(t*v),a=Math.floor(r-S/2);for(let s=0;s<d;s++){const r=n+s*o[2],l=Math.floor(s*k),y=Math.floor(l-_/2);for(let n=0;n<p;n++){let o=0;for(let r=0;r<S;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,i?Math.round(m):Math.floor(m)))for(let e=0;e<_;e++){const t=e+y;if(t<0||t>=f)continue;const r=p+t*u[2],a=t*w;s===Math.min(d-1,i?Math.round(a):Math.floor(a))&&(o+=g[r+n])}}m[r+n]=o}}}}return n.makeTensorInfo(a.shape,a.dtype,m)}};const Xw={kernelName:D.D7i,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r;(0,bm.C)(a,"reverse");const i=a.shape.length,o=D.ZSL.parseAxisParam(s,a.shape);if(0===i)return $m({inputs:{x:a},backend:n});const u=new D.ylz(a.shape,a.dtype),l=n.bufferSync(a);for(let c=0;c<u.size;c++){const e=u.indexToLoc(c),t=e.slice();o.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)}},Jw={kernelName:D.BK4,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:a,fillValue:s,center:i}=t,o=n,u=D.ZSL.getTypedArrayFromDType(r.dtype,D.ZSL.sizeFromShape(r.shape)),[l,c,d,p]=r.shape,[h,f]=D.C0T.getImageCenter(i,c,d),m=Math.sin(a),g=Math.cos(a),y=o.data.get(r.dataId).values;for(let b=0;b<l;b++){const e=b*d*c*p;for(let t=0;t<c;t++){const n=t*(d*p);for(let r=0;r<d;r++){const a=r*p;for(let i=0;i<p;i++){const o=[l,t,r,i],b=o[2],x=o[1];let w=(b-h)*g-(x-f)*m,v=(b-h)*m+(x-f)*g;w=Math.round(w+h),v=Math.round(v+f);let k=s;if("number"!==typeof s&&(k=3===i?255:s[i]),w>=0&&w<d&&v>=0&&v<c){k=y[e+v*(d*p)+w*p+i]}u[e+n+a+i]=k}}}}return{dataId:o.write(u,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},ev=jm(D.hVg,(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})),tv={kernelName:D.hVg,backendName:"cpu",kernelFunc:ev};const nv={kernelName:D.pJc,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a,updates:s}=t,{shape:i}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:d}=D.C0T.calculateShapes(s,a,i),p=hy(n.bufferSync(a),n.bufferSync(s),i,d,l,u,o,c,0,!0);return n.makeTensorInfo(i,p.dtype,p.values)}};function rv(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 av(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 sv={kernelName:D.uWl,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:a,values:s}=t,{side:i}=r,o=function(e,t,n,r,a,s){const i=D.ZSL.getArrayFromDType("int32",n*a);for(let o=0;o<n;++o){const n=e.slice(o*r,(o+1)*r),u=o*a;for(let e=0;e<a;++e)i[u+e]="left"===s?rv(n,t[e+u]):av(n,t[e+u])}return i}(n.data.get(a.dataId).values,n.data.get(s.dataId).values,a.shape[0],a.shape[1],s.shape[1],i);return n.makeTensorInfo(s.shape,"int32",o)}};const iv={kernelName:D.l6P,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t;(0,bm.C)([r,a,s],"select");const i=r.shape.length,o=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,l=n.data.get(s.dataId).values,c=(0,D.TuY)(a.dtype,s.dtype),d=D.ZSL.makeZerosTypedArray(D.ZSL.sizeFromShape(a.shape),c);let p=0;const h=0===i||i>1||1===a.shape.length?1:D.ZSL.sizeFromShape(a.shape.slice(1));for(let f=0;f<o.length;f++)for(let e=0;e<h;e++)1===o[f]?d[p++]=u[f]:d[p++]=l[f];return n.makeTensorInfo(a.shape,c,d)}},ov=D.C0T.SELU_SCALEALPHA,uv=D.C0T.SELU_SCALE,lv=jm(D.u$b,(e=>e>=0?uv*e:ov*(Math.exp(e)-1))),cv={kernelName:D.u$b,backendName:"cpu",kernelFunc:lv},dv=jm(D.YVe,(e=>e<0?-1:e>0?1:0)),pv={kernelName:D.YVe,backendName:"cpu",kernelFunc:dv},hv=jm(D.hql,(e=>Math.sin(e))),fv={kernelName:D.hql,backendName:"cpu",kernelFunc:hv},mv=jm(D.J3C,(e=>Math.sinh(e))),gv={kernelName:D.J3C,backendName:"cpu",kernelFunc:mv},yv=Math.log(1.1920928955078125e-7)+2,bv=jm(D.Fin,(e=>{const t=e>-yv,n=e<yv,r=Math.exp(e);let a;return a=n?r:t?e:Math.log(1+r),a})),xv={kernelName:D.Fin,backendName:"cpu",kernelFunc:bv};const wv={kernelName:D.A8B,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:i}=r;(0,bm.C)([a],"spaceToBatchND");const o=D.ZSL.sizeFromShape(s),u=[[0,0]];u.push(...i);for(let g=1+s.length;g<a.shape.length;++g)u.push([0,0]);const l=Lw.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=D.C0T.getReshaped(l.shape,s,o,!1),d=D.C0T.getPermuted(c.length,s.length,!1),p=D.C0T.getReshapedPermuted(l.shape,s,o,!1),h=nb({inputs:{x:l},backend:n,attrs:{shape:c}}),f=Zg({inputs:{x:h},backend:n,attrs:{perm:d}}),m=nb({inputs:{x:f},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),m}};const vv={kernelName:D.C8s,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:a,denseShape:s,defaultValue:i}=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!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n        ${i.shape}`);const o=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,l=n.data.get(s.dataId).values,c=n.data.get(i.dataId).values[0],[d,p,h,f,m]=by(o,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 kv={kernelName:D.BoJ,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 i=Array.from(n.data.get(a.dataId).values),o=n.data.get(r.dataId).values,u=Array.from(n.data.get(s.dataId).values),[l,c,d]=xy(o,r.shape,r.dtype,i,u);return[n.makeTensorInfo(c,r.dtype,l),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}};const Sv={kernelName:D.L6G,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 i=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,u=n.data.get(s.dataId).values,[l,c]=wy(i,r.shape,r.dtype,o,u,!0);return n.makeTensorInfo(c,r.dtype,l)}};const _v={kernelName:D.DvZ,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 i=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,u=n.data.get(s.dataId).values,[l,c]=wy(i,r.shape,r.dtype,o,u);return n.makeTensorInfo(c,r.dtype,l)}};const Iv={kernelName:D.jgd,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:d,outputSize:p}=D.C0T.calculateShapes(s,a,o),h=!1,f=n.bufferSync(a);let m;switch(s.dtype){case"bool":m=hy(f,n.bufferSync(s),o,p,c,l,u,d,Boolean(n.data.get(i.dataId).values[0]),h);break;case"float32":m=hy(f,n.bufferSync(s),o,p,c,l,u,d,n.data.get(i.dataId).values[0],h);break;case"int32":m=hy(f,n.bufferSync(s),o,p,c,l,u,d,n.data.get(i.dataId).values[0],h);break;case"string":m=hy(f,n.bufferSync(s),o,p,c,l,u,d,D.ZSL.decodeString(n.data.get(i.dataId).values[0]),h);break;default:throw new Error(`Unsupported type ${s.dtype}`)}return n.makeTensorInfo(o,m.dtype,m.values)}};const Tv={kernelName:D.Blb,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=r,o=D.ZSL.parseAxisParam(i,a.shape)[0],u=D.C0T.prepareSplitSize(a,s,o),l=new Array(a.shape.length).fill(0),c=a.shape.slice();return u.map((e=>{const t=[...c];t[o]=e;const r=(0,yy.di)({inputs:{x:a},backend:n,attrs:{begin:l,size:t}});return l[o]+=e,r}))}},$v={kernelName:D.M6A,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,r=t;(0,bm.C)(n,"square");const a=r.data.get(n.dataId).values,s=new Float32Array(a.length);for(let i=0;i<a.length;++i){const e=a[i];s[i]=e*e}return{dataId:r.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},Cv=jm(D.pnw,((e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),Nv={kernelName:D.pnw,backendName:"cpu",kernelFunc:Cv};const Ev={kernelName:D.UcO,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:d,shrinkAxisMask:p}=r;(0,bm.C)(a,"stridedSlice");const{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=D.Kro.sliceInfo(a.shape,s,i,o,u,l,c,d,p);let v;if(m)v=nb({inputs:{x:a},backend:n,attrs:{shape:f}});else if(g||y){D.ZSL.assert(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=D.Kro.computeOutShape(b,x,w),t=(0,yy.di)({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});v=nb({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=Ey(h,n.bufferSync(a),w,b);v=n.makeTensorInfo(f,e.dtype,e.values)}return v}};const Av={kernelName:D.YAb,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,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]=(0,Ay.G)(p,h,a,s,i,o,u,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}};const Rv={kernelName:D.iW0,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:a}=r,{input:s,delimiter:i}=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!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.data.get(s.dataId).values,u=n.data.get(i.dataId).values[0],[l,c,d]=(0,Ry.S)(o,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 Dv={kernelName:D.$jE,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 i=n.data.get(s.dataId).values,o=(0,Dy.f)(i,a);return n.makeTensorInfo(s.shape,"int32",o)}},Fv=jm(D.oFs,(e=>Math.tan(e))),Mv={kernelName:D.oFs,backendName:"cpu",kernelFunc:Fv},Ov=jm(D.iuW,(e=>Math.tanh(e))),zv={kernelName:D.iuW,backendName:"cpu",kernelFunc:Ov};const Lv={kernelName:D.X4r,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{tensor:r,indices:a,updates:s}=t,{sliceRank:i,numUpdates:o,sliceSize:u,strides:l,outputSize:c}=D.C0T.calculateShapes(s,a,r.shape),d=n.bufferSync(a),p=n.bufferSync(s),h=n.bufferSync(r),f=hy(d,p,r.shape,c,u,o,i,l,h,!1);return n.makeTensorInfo(r.shape,f.dtype,f.values)}};const Pv={kernelName:D.FAs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reps:s}=r;(0,bm.C)(a,"tile");const i=Ly(n.bufferSync(a),s);return n.makeTensorInfo(i.shape,i.dtype,i.values)}};const Bv={kernelName:D.TBb,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{k:s,sorted:i}=r;(0,bm.C)(a,"topk");const o=n.data.get(a.dataId).values,[u,l]=Wy(o,a.shape,a.dtype,s,i);return[n.makeTensorInfo(u.shape,u.dtype,u.values),n.makeTensorInfo(l.shape,l.dtype,l.values)]}};const Wv={kernelName:D.dLy,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:u,outputShape:l}=n,[c,d,p,h]=a.shape,[f,m]=null!=l?l:[d,p],g=[c,f,m,h],y=D.ZSL.computeStrides(a.shape),b=y[0],x=y[1],w=y[2],v=D.ZSL.computeStrides(g),k=v[0],S=v[1],_=v[2],I=D.ZSL.getTypedArrayFromDType(a.dtype,D.ZSL.sizeFromShape(g));I.fill(u);const T=r.data.get(a.dataId).values,$=r.data.get(s.dataId).values;for(let C=0;C<c;++C){const e=1===s.shape[0]?$:$.subarray(8*C,8*C+8);for(let t=0;t<f;++t)for(let n=0;n<m;++n)for(let r=0;r<h;++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,c=(e[3]*n+e[4]*t+e[5])/s,h=Vv(l,p,o),f=Vv(c,d,o);switch(i){case"nearest":a=Gv(T,d,p,b,x,w,C,f,h,r,u);break;case"bilinear":a=Hv(T,d,p,b,x,w,C,f,h,r,u);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}I[C*k+t*S+n*_+r]=a}return r.makeTensorInfo(g,a.dtype,I)}return{dataId:r.write(I,g,a.dtype),shape:a.shape,dtype:a.dtype}}};function Vv(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 D.ZSL.clamp(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 D.ZSL.clamp(0,n,t-1)}(e,t);case"nearest":return function(e,t){return D.ZSL.clamp(0,e,t-1)}(e,t);default:return function(e){return e}(e)}}function Uv(e,t,n,r,a,s,i,o,u,l,c){return 0<=o&&o<t&&0<=u&&u<n?e[i*r+o*a+u*s+l]:c}function Gv(e,t,n,r,a,s,i,o,u,l,c){return Uv(e,t,n,r,a,s,i,Math.round(o),Math.round(u),l,c)}function Hv(e,t,n,r,a,s,i,o,u,l,c){const d=Math.floor(o),p=Math.floor(u),h=d+1,f=p+1;return(h-o)*((f-u)*Uv(e,t,n,r,a,s,i,d,p,l,c)+(u-p)*Uv(e,t,n,r,a,s,i,d,f,l,c))+(o-d)*((f-u)*Uv(e,t,n,r,a,s,i,h,p,l,c)+(u-p)*Uv(e,t,n,r,a,s,i,h,f,l,c))}const jv={kernelName:D.EwU,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:s}=t;(0,bm.C)(s,"unique");const i=r.data.get(s.dataId).values,{outputValues:o,outputShape:u,indices:l}=(0,Vy.w)(i,a,s.shape,s.dtype);return[r.makeTensorInfo(u,s.dtype,o),r.makeTensorInfo([l.length],"int32",l)]}};const qv={kernelName:D.dXR,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 i=a.shape.length,o=a.shape[s],u=new Array(i-1);let l=0;for(let h=0;h<i;h++)h!==s&&(u[l++]=a.shape[h]);const c=new Array(i).fill(0),d=a.shape.slice();d[s]=1;const p=new Array(o);for(let h=0;h<p.length;h++){c[s]=h;const e=(0,yy.di)({inputs:{x:a},backend:n,attrs:{begin:c,size:d}});p[h]=nb({inputs:{x:e},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(e)}return p}};const Zv={kernelName:D.pPe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,segmentIds:s}=t,{numSegments:i}=r;(0,bm.C)(a,"unsortedSegmentSum");const o=[],u=[],l=a.shape.length-s.shape.length;let c=s;for(let p=0;p<l;++p){const e=Cx({inputs:{input:c},backend:n,attrs:{dim:p+1}});c=e,u.push(e)}for(let p=0;p<i;++p){const e=D.ZSL.createScalarValue(p,"int32"),t=n.makeTensorInfo([],"int32",e),r=Jm({inputs:{a:t,b:c},backend:n}),s=Rm({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),i=Bg({inputs:{a:s,b:a},backend:n}),l=gx({inputs:{x:i},backend:n,attrs:{axis:0,keepDims:!1}});o.push(l),u.push(t),u.push(r),u.push(s),u.push(i),u.push(l)}const d=Ow({inputs:o,backend:n,attrs:{axis:0}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}},Kv=[ib,km,ub,cb,Pm,db,pb,hb,fb,mb,yb,xb,vb,_b,Tb,Eb,Ab,Rb,Db,sb,Fb,Mb,Ob,Gm,zb,Dm,Ym,Pb,Im,Bb,Gb,jb,qb,Zb,Kb,Yb,Qb,Jb,tx,nx,rx,ax,sx,ix,ux,lx,cx,dx,px,hx,fx,mx,bx,Hy,xx,eg,$x,rg,Nx,ig,Ox,Lx,Px,lg,pg,Bx,Wx,Vx,Ux,yg,wg,Cm,Gx,Vb,jx,Zx,Yx,qy,Sg,Tg,Qx,Eg,Jx,nw,aw,ow,uw,lw,dw,Fg,pw,hw,fw,mw,gw,yw,bw,zg,xw,kw,Iw,Wg,Ug,$w,Nw,Aw,jg,Rw,Mw,zw,Lw,Ww,Yy,Qg,Vw,Uw,Gw,Hw,Em,Rx,qw,Xy,eb,rb,Zw,Kw,Yw,Qw,Xw,Jw,tv,py,nv,sv,iv,cv,gy,pv,fv,gv,yy.lv,_w,xv,wv,vv,kv,Sv,_v,Iv,Tv,Sy,$v,Ty,Ny,Nv,Ev,Av,Rv,Dv,zy,yx,Mv,zv,Lv,Pv,Bv,Wv,Kg,jv,qv,Zv,Fw];for(const yR of Kv)(0,D.tAK)(yR);const Yv={},Qv={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Xv(e,t){Yv[e]=t}function Jv(e,t){if(!(e in Yv)||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=null==t?function(e){if((0,D._K2)().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):t;n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete Yv[e]}),!1),(0,D._K2)().getBool("SOFTWARE_WEBGL_ENABLED")&&(Qv.failIfMajorPerformanceCaveat=!1);if(1===e)return n.getContext("webgl",Qv)||n.getContext("experimental-webgl",Qv);return n.getContext("webgl2",Qv)}(e,t);if(null===n)return null;Yv[e]=n}const n=Yv[e];return null==n||n.isContextLost()?(delete Yv[e],Jv(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),Yv[e])}var ek,tk,nk;function rk(e,t){return[t,e]}function ak(e){const t=D.ZSL.sizeFromShape(e),n=Math.ceil(t/4);return D.ZSL.sizeToSquarishShape(n)}function sk(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function ik(e,t){const n=e;let r,a,s,i,o,u,l,c,d,p;return 2===(0,D._K2)().getNumber("WEBGL_VERSION")?(r=n.R32F,a=n.R16F,s=n.RGBA16F,i=n.RGBA32F,o=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,i=n.RGBA,o=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:i,textureFormatFloat:o,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:d,textureTypeFloat:p}}function ok(e,t){const n=t();return(0,D._K2)().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+dk(e,t))}(e),n}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(ek||(ek={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(tk||(tk={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(nk||(nk={}));const uk=5.96e-8,lk=65504;function ck(e){return!!((0,D._K2)().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||uk<Math.abs(e)&&Math.abs(e)<lk)}function dk(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}`}}function pk(e,t){return zk(e,(()=>e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}function hk(e,t){const n=zk(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(ok(e,(()=>e.shaderSource(n,t))),ok(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error("Failed to compile vertex shader.");return n}function fk(e,t){const n=zk(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(ok(e,(()=>e.shaderSource(n,t))),ok(e,(()=>e.compileShader(n))),(0,D._K2)().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw gk(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const mk=/ERROR: [0-9]+:([0-9]+):/g;function gk(e,t){const n=mk.exec(t);if(null==n)return;const r=+n[1],a=e.split("\n"),s=a.length.toString().length+2,i=a.map(((e,t)=>D.ZSL.rightPad((t+1).toString(),s)+e));let o=0;for(let u=0;u<i.length;u++)o=Math.max(i[u].length,o);i.slice(0,r-1),i.slice(r-1,r),i.slice(r)}function yk(e){return zk(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}function bk(e,t){if(ok(e,(()=>e.linkProgram(t))),!(0,D._K2)().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw new Error("Failed to link vertex and fragment shaders.")}function xk(e,t){if(ok(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw new Error("Shader program validation failed.")}function wk(e,t){const n=zk(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return ok(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),ok(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}function vk(e,t){const n=zk(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return ok(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),ok(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}function kk(){return 2===(0,D._K2)().getNumber("WEBGL_VERSION")?1:4}function Sk(e){return zk(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}function _k(e,t){const n=(0,D._K2)().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}]`+".")}}function Ik(e){return zk(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}function Tk(e,t,n,r,a,s,i){const o=e.getAttribLocation(t,n);return-1!==o&&(ok(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r))),ok(e,(()=>e.vertexAttribPointer(o,a,e.FLOAT,!1,s,i))),ok(e,(()=>e.enableVertexAttribArray(o))),!0)}function $k(e,t,n){Lk(e,n),ok(e,(()=>e.activeTexture(e.TEXTURE0+n))),ok(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}function Ck(e,t){Lk(e,t),ok(e,(()=>e.activeTexture(e.TEXTURE0+t))),ok(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function Nk(e,t,n){return zk(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}function Ek(e,t,n){return e.getUniformLocation(t,n)}function Ak(e,t,n,r){ok(e,(()=>$k(e,t,r))),ok(e,(()=>e.uniform1i(n,r)))}function Rk(e){ok(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),ok(e,(()=>e.viewport(0,0,e.canvas.width,e.canvas.height))),ok(e,(()=>e.scissor(0,0,e.canvas.width,e.canvas.height)))}function Dk(e,t,n){ok(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),ok(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function Fk(e,t){ok(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),ok(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function Mk(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ok(e,t))}function Ok(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}`}}function zk(e,t,n){const r=ok(e,(()=>t()));if(null==r)throw new Error(n);return r}function Lk(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}]`}.`)}}function Pk(e,t=2){return D.ZSL.sizeFromShape(e.slice(0,e.length-t))}function Bk(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 Wk(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[Pk(e),...Bk(e)]),t}function Vk(e,t=!1){let n=(0,D._K2)().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=(0,D._K2)().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(r===1/0&&(0,D._K2)().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?D.ZSL.nearestLargerEven(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=D.ZSL.squeezeShape(e);e=t.newShape}let a=D.ZSL.sizeFromShape(e),s=null;e.length<=1&&a<=n?s=[1,a]:2===e.length&&e[0]<=n&&e[1]<=n?s=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?s=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?s=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?s=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(s=[e[0],e[1]*e[2]*e[3]]);const i=null!=s&&Math.max(...s)>r&&Math.min(...s)<=(t?2:1)&&Math.min(...s)>0;if(null==s||i)if(t){const t=Pk(e);let n=2,r=2;e.length&&([n,r]=Bk(e)),a=t*(n/2)*(r/2),s=D.ZSL.sizeToSquarishShape(a).map((e=>2*e))}else s=D.ZSL.sizeToSquarishShape(a);return s}function Uk(e){return e%2===0}function Gk(e,t){if(e=e.slice(-2),t=t.slice(-2),D.ZSL.arraysEqual(e,t))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(Uk(n)&&Uk(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&Uk(e[0])&&Uk(t[0])}let Hk,jk;function qk(e){if(null==Hk){const t=Jv(e);Hk=t.getParameter(t.MAX_TEXTURE_SIZE)}return Hk}function Zk(){Hk=null}function Kk(){jk=null}function Yk(e){if(null==jk){const t=Jv(e);jk=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,jk)}function Qk(e){if(0===e)return 0;let t;const n=Jv(e);return t=Xk(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:Xk(n,"EXT_disjoint_timer_query")?1:0,t}function Xk(e,t){return null!=e.getExtension(t)}function Jk(e){try{if(null!=Jv(e))return!0}catch(t){return!1}return!1}function eS(e){if(0===e)return!1;const t=Jv(e);if(1===e){if(!Xk(t,"OES_texture_float"))return!1}else if(!Xk(t,"EXT_color_buffer_float"))return!1;return nS(t)}function tS(e){if(0===e)return!1;const t=Jv(e);if(1!==e){if(Xk(t,"EXT_color_buffer_float"))return nS(t);const e="EXT_color_buffer_half_float";if(Xk(t,e)){const n=t.getExtension(e);return function(e,t){const n=ik(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 i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(i),o}(t,n)}return!1}if(!Xk(t,"OES_texture_float"))return!1;if(!Xk(t,"WEBGL_color_buffer_float"))return!1;return nS(t)}function nS(e){const t=ik(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 rS(e){if(2!==e)return!1;return null!=Jv(e).fenceSync}function aS(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&D.ZSL.assert("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))}const sS=(0,D._K2)();function iS(){let e,t,n,r,a,s,i,o,u,l;return 2===(0,D._K2)().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",a="texture",s="outputColor",i="out vec4 outputColor;",o=(0,D._K2)().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",i="",o="\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:i,defineSpecialNaN:o,defineSpecialInf:u,defineRound:l}}function oS(e,t,n="index"){const r=D.ZSL.computeStrides(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 uS(e,t,n="index"){const r=D.ZSL.computeStrides(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 lS(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 cS(e){const t=D.ZSL.computeStrides(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`}sS.registerFlag("HAS_WEBGL",(()=>sS.getNumber("WEBGL_VERSION")>0)),sS.registerFlag("WEBGL_VERSION",(()=>Jk(2)?2:Jk(1)?1:0)),sS.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),sS.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===sS.get("WEBGL_VERSION"))),sS.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),sS.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),sS.registerFlag("WEBGL_PACK",(()=>sS.getBool("HAS_WEBGL"))),sS.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_PACK_CLIP",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_PACK_REDUCE",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_LAZILY_UNPACK",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_CONV_IM2COL",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",(()=>sS.getBool("WEBGL_PACK"))),sS.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>qk(sS.getNumber("WEBGL_VERSION")))),sS.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>Yk(sS.getNumber("WEBGL_VERSION")))),sS.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=sS.getNumber("WEBGL_VERSION");return 0===e?0:Qk(e)})),sS.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>sS.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!D.eMq.isMobile())),sS.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>eS(sS.getNumber("WEBGL_VERSION")))),sS.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!sS.getBool("WEBGL_FORCE_F16_TEXTURES")&&sS.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),sS.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>tS(sS.getNumber("WEBGL_VERSION")))),sS.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>rS(sS.getNumber("WEBGL_VERSION")))),sS.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>sS.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),sS.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}.`)})),sS.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>D.eMq.isMobile()?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}.`)})),sS.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),sS.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),sS.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),sS.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),sS.registerFlag("WEBGL_EXP_CONV",(()=>!1)),sS.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>sS.getBool("IS_TEST"))),sS.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),sS.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),sS.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),sS.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const dS="\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:pS}=D.C0T;function hS(e,t,n){const r=[];if(e.forEach((e=>{const t=D.ZSL.sizeFromShape(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}=_S(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?mS(e,r):fS(e,r);const s=e.shapeInfo.logicalShape,i=t.logicalShape;s.length<=i.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,i=t.logicalShape.length,o=pS(e.shapeInfo.logicalShape,t.logicalShape),u=SS(i),l=i-s;let c;const d=["x","y","z","w","u","v"];c=0===s?"":i<2&&o.length>=1?"coords = 0;":o.map((e=>`coords.${d[e+l]} = 0;`)).join("\n");let p="";p=i<2&&s>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+l]}`)).join(", ");let h="return outputValue;";const f=1===D.ZSL.sizeFromShape(e.shapeInfo.logicalShape),m=D.ZSL.sizeFromShape(t.logicalShape),g=1===m;if(1!==s||f||g){if(f&&!g)h=1===i?"\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ":"\n        return vec4(outputValue.x);\n      ";else if(o.length){const e=s-2,t=s-1;o.indexOf(e)>-1&&o.indexOf(t)>-1?h="return vec4(outputValue.x);":o.indexOf(e)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(t)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}}else h="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";return`\n    vec4 ${a}() {\n      ${u} coords = getOutputCoords();\n      ${c}\n      vec4 outputValue = get${r}(${p});\n      ${h}\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,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===u&&null==e.shapeInfo.flatOffset&&D.ZSL.arraysEqual(i,s))return`\n      float ${a}() {\n        return sampleTexture(${n}, resultUV);\n      }\n    `;const l=SS(u),c=pS(e.shapeInfo.logicalShape,t.logicalShape),d=u-o;let p;const h=["x","y","z","w","u","v"];p=0===o?"":u<2&&c.length>=1?"coords = 0;":c.map((e=>`coords.${h[e+d]} = 0;`)).join("\n");let f="";f=u<2&&o>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${h[t+d]}`)).join(", ");return`\n    float ${a}() {\n      ${l} coords = getOutputCoords();\n      ${p}\n      return get${r}(${f});\n    }\n  `}(e,t));return a}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),i=t.texShape,o=iS(),u=function(e){return`\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return ${e.texture2D}(textureSampler, uv).r;\n    }\n  `}(o);let l,c,d=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    ${gS}\n    ${yS}\n    ${bS}\n  `;return t}(o);t.isPacked?(l=function(e,t,n){switch(e.length){case 0:return wS();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.ZSL.arraysEqual(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 i=s,o="",u="b, r, c";for(let l=2;l<e.length-1;l++)i*=e[e.length-l-1],o=`\n      int b${l} = index / ${i};\n      index -= b${l} * ${i};\n    `+o,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      ${o}\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,i,n.enableShapeUniforms),c=function(e){return`\n    void setOutput(vec4 val) {\n      ${e.output} = val;\n    }\n  `}(o)):(l=function(e,t,n){switch(e.length){case 0:return wS();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.ZSL.arraysEqual(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    ${uS(["r","c","d"],e)}\n    return ivec3(r, c, d);\n  }\n`}const r=oS(["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      ${uS(["r","c","d","d2"],e)}\n      return ivec4(r, c, d, d2);\n    }\n  `}const r=oS(["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=oS(["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=oS(["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,i,n.enableShapeUniforms),c=function(e){return`\n    void setOutput(float val) {\n      ${e.output} = vec4(val, 0, 0, 0);\n    }\n  `}(o)),n.packedInputs&&(d+=xS);return[d,u,c,a,l,s,n.userCode].join("\n")}function fS(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 i=vS(n);if(t)return`\n    float ${r}() {\n      vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${i});\n      return sampleTexture(${n}, uv);\n    }\n  `;const[o,u]=e.shapeInfo.texShape;return`\n    float ${r}() {\n      vec2 uv = uvFromFlat(${o}, ${u}, ${i});\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        ${kS(e)}\n      }\n    `;const a=e.shapeInfo.texShape,s=a[0],i=a[1];if(1===i&&1===s)return`\n      float ${r}(int index) {\n        return sampleTexture(${n}, halfCR);\n      }\n    `;const o=vS(n);if(1===i)return t?`\n      float ${r}(int index) {\n        vec2 uv = vec2(0.5, (float(index + ${o}) + 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 + ${o}) + 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 + ${o}) + 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 + ${o}) + 0.5) / ${i}.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 + ${o});\n      return sampleTexture(${n}, uv);\n    }\n  `;return`\n    float ${r}(int index) {\n      vec2 uv = uvFromFlat(${s}, ${i}, index + ${o});\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.ZSL.arraysEqual(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:i,keptDims:o}=D.ZSL.squeezeShape(n),u=i;if(u.length<n.length){const n=["row","col"];return`\n      ${fS(IS(e,u),t)}\n      float ${a}(int row, int col) {\n        return ${a}(${TS(n,o)});\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        ${kS(e)}\n      }\n    `;const l=s[0],c=s[1],d=vS(r);if(1===c)return t?`\n      float ${a}(int row, int col) {\n        float index = dot(vec3(row, col, ${d}), 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, ${d}), 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, ${d}), 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, ${d}), 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 + ${d};\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 + ${d};\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],i=n[2],{newShape:o,keptDims:u}=D.ZSL.squeezeShape(n),l=o;if(l.length<n.length){const n=["row","col","depth"];return`\n        ${fS(IS(e,l),t)}\n        float ${a}(int row, int col, int depth) {\n          return ${a}(${TS(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}, ${i}, 1)));\n        ${kS(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(${i}, 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2(${p}.0, ${d}.0);\n          return sampleTexture(${r}, uv);\n        }\n      `;if(p===i&&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=vS(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 * ${i} + 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],i=n[2]*s,o=n[1]*i,{newShape:u,keptDims:l}=D.ZSL.squeezeShape(n);if(u.length<n.length){const n=["row","col","depth","depth2"];return`\n      ${fS(IS(e,u),t)}\n      float ${a}(int row, int col, int depth, int depth2) {\n        return ${a}(${TS(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(${o}, ${i}, ${s}, 1)));\n        ${kS(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===o&&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(${i}, ${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=vS(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 * ${o} + col * ${i} +\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,i=t[2]*s,o=t[1]*i,{newShape:u,keptDims:l}=D.ZSL.squeezeShape(t);if(u.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n      ${fS(IS(e,u))}\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\n        return ${r}(${TS(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(${o}, ${i}, ${s}, ${a})) +\n          depth3;\n        ${kS(e)}\n      }\n    `;const c=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===o&&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(${i}, ${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=vS(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 * ${o} + col * ${i} + 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}=D.ZSL.squeezeShape(t);if(a.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n      ${fS(IS(e,a))}\n      float ${r}(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return ${r}(${TS(t,s)});\n      }\n    `}const i=t[5],o=t[4]*i,u=t[3]*o,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}, ${o})) +\n          dot(\n            vec2(depth3, depth4),\n            vec2(${i}, 1)));\n        ${kS(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}, ${o}, ${i})) +\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===i&&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=vS(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 * ${o} + depth3 * ${i} + 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 mS(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=iS();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=iS();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 i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`\n    vec4 ${r}(int index) {\n      vec2 uv = packedUVfrom1D(\n        ${i[0]}, ${i[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,i=s[0],o=s[1],u=iS();if(null!=s&&D.ZSL.arraysEqual(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(${o}.0, ${i}.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,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(1===n[0]){const r=[1,2],s=["b","row","col"];return`\n        ${mS(IS(e,n.slice(1)),t)}\n        vec4 ${a}(int b, int row, int col) {\n          return ${a}(${TS(s,r)});\n        }\n      `}const o=iS();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 ${o.texture2D}(${r}, uv);\n    }\n  `;const u=i[0],l=i[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 ${o.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=iS();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,i=s.length,o=e.shapeInfo.texShape,u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],l=u[0],c=u[1],d=Math.ceil(s[i-1]/2);let p=d*Math.ceil(s[i-2]/2),h="int b, int row, int col",f=`b * ${p} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<i-1;m++)h=`int b${m}, `+h,p*=s[i-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 gS="\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",yS="\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",bS="\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",xS="\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 wS(){return"\n    int getOutputCoords() {\n      return 0;\n    }\n  "}function vS(e){return`offset${e}`}function kS(e){const t=e.name,n=D.ZSL.sizeFromShape(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 SS(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 _S(e,t,n){const{newShape:r,keptDims:a}=D.ZSL.squeezeShape(t),s=t.length,i=e&&3===s&&1===t[0],o=i?t.slice(1):r,u=!e&&s>1&&!D.ZSL.arraysEqual(t,n)&&r.length<s||i;return{useSqueezeShape:u,uniformShape:u?o:t,keptDims:a}}function IS(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function TS(e,t){return t.map((t=>e[t])).join(", ")}function $S(e,t,n){const r=[],a=[];let s,i,o,u=null,l=null;l=e.getUniformLocation(n,"NAN",!1),1===(0,D._K2)().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),o=e.getUniformLocation(n,"outShapeStrides",c),i=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:o,outTexShapeLocation:i}}function CS(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.ZSL.arraysEqual(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 i=e.texShape,o=a.isUniform?null:a.texData.texShape;if(!D.ZSL.arraysEqual(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)}))}function NS(e){return(0,D._K2)().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class ES{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=ek.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=iS();this.outputShape=e,this.enableShapeUniforms=NS(this.outputShape.length),this.userCode=`\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ${this.enableShapeUniforms?uS(["r","c","d"],e):oS(["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 AS{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=ek.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=iS();this.outputShape=e,this.enableShapeUniforms=NS(this.outputShape.length),this.userCode=`\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ${this.enableShapeUniforms?uS(["r","c","d"],e):oS(["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 RS{constructor(e){this.variableNames=["A"],this.outTexUsage=tk.DOWNLOAD;const t=iS();this.outputShape=e,this.userCode=`\n      ${dS}\n\n      void main() {\n        float x = getAAtOutCoords();\n        ${t.output} = encode_float(x);\n      }\n    `}}class DS{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=tk.DOWNLOAD;const t=iS();this.outputShape=e,this.userCode=`\n      ${dS}\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 FS={R:0,G:1,B:2,A:3};class MS{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=iS();this.outputShape=e,this.enableShapeUniforms=NS(this.outputShape.length);let a="result";t&&(a="floor(result * 255. + 0.5)");let s="";for(let i=0;i<n.length;i++){const e=n[i];s+=`\n          if(offset == ${i}) {\n            result = values[${FS[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":cS(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 OS{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=iS();this.outputShape=e,this.enableShapeUniforms=NS(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":cS(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 zS(e){const t=iS();return hk(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 LS(e){return wk(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function PS(e){return vk(e,new Uint16Array([0,1,2,2,1,3]))}function BS(e,t,n,r,a,s){_k(t,n);const i=Sk(e),o=e.TEXTURE_2D;return ok(e,(()=>e.bindTexture(o,i))),ok(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),ok(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),ok(e,(()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST))),ok(e,(()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===(0,D._K2)().getNumber("WEBGL_VERSION")?ok(e,(()=>e.texImage2D(o,0,r,t,n,0,a,s,null))):ok(e,(()=>e.texStorage2D(o,1,r,t,n))),ok(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:i,texShape:[n,t]}}function WS(e){return e.internalFormatFloat}function VS(e,t,n,r){const[a,s]=rk(t,n);return BS(e,a,s,WS(r),r.textureFormatFloat,e.FLOAT)}function US(e){return e.internalFormatHalfFloat}function GS(e,t,n,r){const[a,s]=rk(t,n);return BS(e,a,s,US(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function HS(e){return e.downloadTextureFormat}function jS(e,t,n,r){const[a,s]=rk(t,n);return BS(e,a,s,HS(r),e.RGBA,e.UNSIGNED_BYTE)}function qS(e){return e.internalFormatPackedFloat}function ZS(e,t,n,r){const[a,s]=sk(t,n);return BS(e,a,s,qS(r),e.RGBA,e.FLOAT)}function KS(e){return e.internalFormatPackedHalfFloat}function YS(e,t,n,r){const[a,s]=sk(t,n);return BS(e,a,s,KS(r),e.RGBA,r.textureTypeHalfFloat)}function QS(e,t,n){ok(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n)));return Tk(e,t,"clipSpacePos",n,3,20,0)&&Tk(e,t,"uv",n,2,20,12)}function XS(e,t,n,r,a,s){let i,o,u;ok(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),a instanceof Uint8Array?(i=new Uint8Array(n*r*4),o=e.UNSIGNED_BYTE,u=e.RGBA):(i=new Float32Array(n*r*4),o=e.FLOAT,u=s.internalFormatPackedFloat),i.set(a),2===(0,D._K2)().getNumber("WEBGL_VERSION")?ok(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,o,i))):ok(e,(()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,o,i))),ok(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function JS(e,t,n){ok(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===(0,D._K2)().getNumber("WEBGL_VERSION")?ok(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):ok(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===(0,D._K2)().getNumber("WEBGL_VERSION")?ok(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):ok(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),ok(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function e_(e,t,n,r){const a=e.createBuffer();ok(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a)));const s=16*t*n;return ok(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ))),ok(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),ok(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),a}function t_(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}function n_(e,t,n,r){const[a,s]=rk(t,n),i=new Uint8Array(t*n*4);return ok(e,(()=>e.readPixels(0,0,a,s,r.downloadTextureFormat,e.UNSIGNED_BYTE,i))),new Float32Array(i.buffer)}function r_(e,t,n,r,a,s,i,o){const u=e,l=new Float32Array(function(e,t){const[n,r]=sk(e,t);return n*r*4}(s,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function a_(e,t,n){const r=new Float32Array(t*n*4);return ok(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r))),r}class s_{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=(0,D._K2)().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,Xv(t,e)):this.gl=Jv(t),e=this.gl,2===(0,D._K2)().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>ok(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>ok(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>ok(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>ok(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=()=>ok(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>ok(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>ok(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>ok(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===(0,D._K2)().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=pk(this.gl,e),Xk(this.gl,t))this.textureHalfFloatExtension=pk(this.gl,t);else if((0,D._K2)().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),Xk(this.gl,r))this.colorBufferHalfFloatExtension=pk(this.gl,r);else if((0,D._K2)().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",Xk(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Xk(this.gl,r))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}this.vertexBuffer=LS(this.gl),this.indexBuffer=PS(this.gl),this.framebuffer=Ik(this.gl),this.textureConfig=ik(this.gl,this.textureHalfFloatExtension)}get debug(){return(0,D._K2)().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program,this.outputTexture;const e=this.gl;ok(e,(()=>e.finish())),ok(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),ok(e,(()=>e.deleteFramebuffer(this.framebuffer))),ok(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),ok(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),ok(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),VS(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),GS(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),jS(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),JS(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),XS(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),YS(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),ZS(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Fk(this.gl,this.framebuffer),this.outputTexture=null),ok(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>n_(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,r,a,s){return r_(this.gl,e,0,0,0,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return t_(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=e_(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((0,D._K2)().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(0,D._K2)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,(0,D._K2)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>a_(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=zS(t));const n=yk(t);ok(t,(()=>t.attachShader(n,this.vertexShader))),ok(t,(()=>t.attachShader(n,e))),bk(t,n);const r=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&xk(t,r),r}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;ok(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),QS(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(ok(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&xk(this.gl,this.program),ok(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?Nk(this.gl,e,t):Ek(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),ok(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(),Ak(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,a]=sk(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&&xk(this.gl,this.program),Mk(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){this.getVertexArray();this.debugValidate()}ok(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),ok(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=pk(this.gl,2===(0,D._K2)().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===(0,D._K2)().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===(0,D._K2)().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 D.ZSL.repeatedTry((()=>this.disposed||this.isQueryAvailable(e,(0,D._K2)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,(0,D._K2)().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(0,D._K2)().platform&&(n=(0,D._K2)().platform.setTimeoutCustom.bind((0,D._K2)().platform)),D.ZSL.repeatedTry((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Dk(this.gl,e,this.framebuffer),this.debug&&Mk(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(Dk(this.gl,this.outputTexture,this.framebuffer),this.debug&&Mk(this.gl)):Fk(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;Dk(r,e,this.framebuffer),this.debug&&Mk(r),this.outputTexture=e,ok(r,(()=>r.viewport(0,0,t,n))),ok(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),ok(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.")}}const{addImpl:i_,bincountImpl:o_,bincountReduceImpl:u_,bitwiseAndImpl:l_,castImpl:c_,ceilImpl:d_,concatImpl:p_,equalImpl:h_,expImpl:f_,expm1Impl:m_,floorImpl:g_,gatherNdImpl:y_,gatherV2Impl:b_,greaterImpl:x_,greaterEqualImpl:w_,lessImpl:v_,lessEqualImpl:k_,linSpaceImpl:S_,logImpl:__,maxImpl:I_,maximumImpl:T_,minimumImpl:$_,multiplyImpl:C_,negImpl:N_,notEqualImpl:E_,prodImpl:A_,raggedGatherImpl:R_,raggedRangeImpl:D_,raggedTensorToTensorImpl:F_,rangeImpl:M_,rsqrtImpl:O_,scatterImpl:z_,sigmoidImpl:L_,simpleAbsImpl:P_,sliceImpl:B_,sparseFillEmptyRowsImpl:W_,sparseReshapeImpl:V_,sparseSegmentReductionImpl:U_,sqrtImpl:G_,staticRegexReplaceImpl:H_,stridedSliceImpl:j_,stringNGramsImpl:q_,stringSplitImpl:Z_,stringToHashBucketFastImpl:K_,subImpl:Y_,tileImpl:Q_,topKImpl:X_,transposeImpl:J_,uniqueImpl:eI}=E;function tI(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function nI(e,t){return 1===t?[e]:tI(e,t)}class rI{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=NS(this.outputShape.length),0===this.rank)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{const e=nI("rc",this.rank),t=SS(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 aI{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=NS(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?lS(["r","c","d"],"inputShape"):oS(["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":cS(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 sI{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=oI(t,n),a=uI(e,r,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const s=iI(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 i;return r===nk.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===nk.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===nk.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===nk.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===nk.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,n,r){if(null==this.freeTextures)return;const a=oI(n,r),s=uI(t,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);const i=iI(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),o=(0,D._K2)().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==o&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),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;this.numFreeTextures,this.numUsedTextures,this._numBytesFree,this._numBytesAllocated}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 iI(e,t,n,r,a){const s=function(e,t){switch(e){case nk.PACKED_2X2_FLOAT32:return qS(t);case nk.PACKED_2X2_FLOAT16:return KS(t);case nk.UNPACKED_FLOAT32:return WS(t);case nk.UNPACKED_FLOAT16:return US(t);case nk.PACKED_4X1_UNSIGNED_BYTE:return HS(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let i;if(a){const[t,n]=sk(e[0],e[1]);i=t*n}else{const[t,n]=rk(e[0],e[1]);i=t*n}const o=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 i*o}function oI(e,t){if(e===tk.UPLOAD)return nk.PACKED_2X2_FLOAT32;if(e===tk.RENDER||null==e)return function(e){return(0,D._K2)().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?nk.PACKED_2X2_FLOAT32:nk.UNPACKED_FLOAT32:e?nk.PACKED_2X2_FLOAT16:nk.UNPACKED_FLOAT16}(t);if(e===tk.DOWNLOAD||e===tk.PIXELS)return nk.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function uI(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class lI{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=NS(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 cI="if (isnan(x)) return x;",dI="return abs(x);";const pI=cI+"\n  return (x < 0.0) ? 0.0 : x;\n",hI=cI+"\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n",fI="return x;";class mI{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=NS(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 gI{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=NS(this.outputShape.length);const t=e.length,n=nI("rc",t),r=SS(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),i=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, ${i}));\n      }\n    `}}const yI=D.kpo.whereImpl,bI={};const xI=(0,D._K2)().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class wI extends D.uI_{nextDataId(){return wI.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,!(0,D._K2)().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof s_)t=e;else{const n=Jv((0,D._K2)().getNumber("WEBGL_VERSION"),e);t=new s_(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=Jv((0,D._K2)().getNumber("WEBGL_VERSION"));t=new s_(e),this.binaryCache=((n=(0,D._K2)().getNumber("WEBGL_VERSION"))in bI||(bI[n]={}),bI[n]),this.gpgpuCreatedLocally=!0}var n;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new sI(this.gpgpu),this.numMBBeforeWarning=null==(0,D._K2)().global.screen?1024:(0,D._K2)().global.screen.height*(0,D._K2)().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new D.GJx(this,(0,D.Hi9)())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,r,a,s){const i=this.makeTensorInfo(t,n),o=this.texData.get(i.dataId);o.isPacked=!1,o.texture={texture:e,texShape:[r,a]},o.texShape=[r,a];const u=Wk(t),l=new MS(u,!1,s),c=this.runWebGLProgram(l,[i],n,[[r,a]]);return c.shape=t,o.texture=null,this.disposeIntermediateTensorInfo(i),c.dataId}write(e,t,n){if(((0,D._K2)().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||(0,D._K2)().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:tk.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((0,D._K2)().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:tk.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:i,isPacked:o}=t;if(null!=s){let t;t=o?new mI(i,fI):new lI(i,fI);const n=this.runWebGLProgram(t,[{dataId:e,shape:i,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=D.ZSL.now()),"complex64"===r){const e=this.readSync(a.real.dataId),t=this.readSync(a.imag.dataId);c=D.C0T.mergeRealAndImagArrays(e,t)}else c=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=D.ZSL.now()-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:i,isPacked:o}=t;if(null!=a){let t;t=o?new mI(r,fI):new lI(r,fI);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((0,D._K2)().getBool("DEBUG")&&!(0,D._K2)().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===(0,D._K2)().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u,l,c=null;if("complex64"!==s&&(0,D._K2)().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...ak(r))}if(this.pendingRead.set(e,[]),"complex64"!==s&&await this.gpgpu.createAndWaitForFence(),"complex64"===s){const e=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),t=e[0],n=e[1];l=D.C0T.mergeRealAndImagArrays(t,n)}else if(null==c)l=this.getValuesFromTexture(e);else{const e=D.ZSL.sizeFromShape(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=u&&this.disposeIntermediateTensorInfo(u),null!=c){const e=this.gpgpu.gl;ok(e,(()=>e.deleteBuffer(c)))}const d=this.convertAndCacheOnCPU(e,l),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach((e=>e(d))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&(0,D.Hi9)().removeDataId(e,this),this.pendingDeletes--),d}readToGPU(e,t={}){const n=this.texData.get(e),{values:r,shape:a,slice:s,dtype:i,isPacked:o,texture:u}=n;if("complex64"===i)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=s){let n;n=o?new mI(a,fI):new lI(a,fI);const r=this.runWebGLProgram(n,[{dataId:e,shape:a,dtype:i}],i),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=(0,D.Hi9)().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=>D.ZSL.decodeString(e)));return(0,D.ra8)(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return(0,D.ra8)(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!ck(n)){if((0,D._K2)().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=D.ZSL.sizeFromShape(t);if((0,D._K2)().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),s=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...ak(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(n),s}const s=(0,D._K2)().getBool("WEBGL_PACK")&&!0===r,i=s?Wk(t):t,o=s?new DS(i):new RS(i),u=this.runWebGLProgram(o,[{shape:i,dtype:n,dataId:e}],"float32"),l=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture,l.texShape[0],l.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return(0,D._K2)().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=D.ZSL.flatten(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),s=D.ZSL.flatten(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,r&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if((0,D._K2)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(a);i.kernelMs=D.ZSL.sum(e),i.getExtraProfileInfo=()=>e.map(((e,t)=>({name:s[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return(0,D._K2)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:D.ZSL.now(),endMs:null}}endTimer(e){return(0,D._K2)().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=D.ZSL.now(),e)}async getQueryTime(e){if((0,D._K2)().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:i}=this.texData.get(e),o=i&&i.origDataId||e,u=this.dataRefCount.get(o);u>1?this.dataRefCount.set(o,u-1):(this.dataRefCount.delete(o),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=xI){return(0,D._K2)().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&D.ZSL.sizeFromShape(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){D.C0T.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return yI(e.shape,t)}packedUnaryOp(e,t,n){const r=new mI(e.shape,t),a=this.compileAndRun(r,[e],n);return(0,D.Hi9)().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=P_(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if((0,D._K2)().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,dI,e.dtype);const t=new lI(e.shape,dI),n=this.compileAndRun(t,[e]);return(0,D.Hi9)().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&D.ZSL.isString(n[0])){const a=n.map((e=>D.ZSL.encodeString(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(0,D.Hi9)().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new gI(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new rI(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[Pk(e.shape),...Bk(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},a=[Pk(t),...Bk(t)],s=new aI(a,n),i=[n],o=this.runWebGLProgram(s,[r],e.dtype,i,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:r,shape:a,dtype:s}=n;if(null!=t){const e=D.ZSL.sizeFromShape(a),n=t[0]*t[1]*4;D.ZSL.assert(e<=n,(()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data."))}const i=Wk(a);let o;o=r?new AS(i):new ES(i);const u=[null!=t?t:ak(i)];return{dtype:s,shape:a,dataId:this.runWebGLProgram(o,[{shape:i,dtype:s,dataId:e}],s,u,!0,t).dataId}}runWebGLProgram(e,t,n,r,a=!1,s){const i=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===ek.DENSE){const t=null!=s?s:ak(e.outputShape);o.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===D.ZSL.sizeFromShape(i.shape))return o.values=D.ZSL.getTypedArrayFromDType(i.dtype,0),i;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&&D.ZSL.sizeFromShape(t.shape)<=(0,D._K2)().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&&!Gk(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(i.dataId);const c={shape:i.shape,texData:o,isUniform:!1},d=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:i,uniformShape:o,keptDims:u}=_S(e.packedInputs,t.shape,s);let l="",c="",d="";if(1===o.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!==o.length||e.packedInputs){if(o.length>2&&!e.packedInputs){const e=D.ZSL.computeStrides(o);d=`${e[0]===s[1]}_${e[e.length-1]===s[1]}`}}else c=`${o[0]>1}_${o[1]>1}`;const p=t.shape.length,h=2===o.length&&D.ZSL.arraysEqual(t.shape,s),f=1===D.ZSL.sizeFromShape(t.shape),m=D.C0T.getBroadcastDims(t.shape,n.shape),g=!e.packedInputs&&p===n.shape.length&&D.ZSL.arraysEqual(s,n.texData.texShape),y=e.packedInputs||o.length>2?"":`${s[0]>1}_${s[1]>1}`;r+=`${p}_${g}_${i?u:""}_${o.length}_${f}_${m}_${h}_${l}_${c}_${d}_${y}_${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+`${(0,D._K2)().getNumber("WEBGL_VERSION")}`,s}(e,l,c),p=this.getAndSaveBinary(d,(()=>function(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)),i={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},o=hS(a,i,t),u=fk(e.gl,o),l=e.createProgram(u);return(0,D._K2)().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:o,webGLProgram:l,inShapeInfos:s,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(l),Object.assign({program:t,fragmentShader:u,source:o,webGLProgram:l,inShapeInfos:s,outShapeInfo:i},$S(e,t,l)))}(this.gpgpu,e,l,c))),h=null!=this.activeTimers;let f;h&&(f=this.startTimer()),(0,D._K2)().get("ENGINE_COMPILE_ONLY")||function(e,t,n,r,a){t.program.enableShapeUniforms||(CS(t.inShapeInfos,n),CS([t.outShapeInfo],[r]));const s=r.texData.texture,i=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),1===(0,D._K2)().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:i,texShape:o}=t.variablesLocations[u];if(i){const{uniformShape:n}=_S(t.program.packedInputs,r.shape,r.texData.texShape);switch(n.length){case 1:e.gl.uniform1iv(i,new Int32Array(n));break;case 2:e.gl.uniform2iv(i,new Int32Array(n));break;case 3:e.gl.uniform3iv(i,new Int32Array(n));break;case 4:e.gl.uniform4iv(i,new Int32Array(n))}}if(o&&e.gl.uniform2i(o,r.texData.texShape[0],r.texData.texShape[1]),null!=a)if(r.isUniform)if(D.ZSL.sizeFromShape(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 o=t.outShapeLocation;if(o)switch(r.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(r.shape))}if(t.outShapeStridesLocation){const n=D.ZSL.computeStrides(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,p,l,c,r),u.forEach((e=>this.disposeIntermediateTensorInfo(e))),h&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=(0,D._K2)().getNumber("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=D.ZSL.now();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!(0,D._K2)().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&!1===a){const e=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),e}return i}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(!(0,D._K2)().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=(0,D.DZQ)((()=>{if(!(0,D._K2)().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=(0,D._K2)().getBool("DEBUG");(0,D._K2)().set("DEBUG",!1);const t=this.abs((0,D.d_2)(1e-8)).dataSync()[0];if((0,D._K2)().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:s,usage:i,isPacked:o}=t;if(null!=s)return;const u=null!=this.activeTimers;let l;u&&(l=D.ZSL.now());let c=t.texShape;if(null==c&&(c=Vk(n,o),t.texShape=c),null!=a){const e=Wk(n);let s,i=c[1],d=c[0];const p=a instanceof Uint8Array||a instanceof Uint8ClampedArray;!o&&p||([i,d]=sk(c[0],c[1])),s=o?new OS(e,p):new MS(e,p);const h=p?[d,i]:c,f=this.makeTensorInfo(h,r),m=this.texData.get(f.dataId);m.usage=p?tk.PIXELS:tk.UPLOAD,m.texShape=h,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),i,d,a);const g=[[d,i]],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,(0,D._K2)().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=x.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),u&&(this.uploadWaitMs+=D.ZSL.now()-l)}else{const e=this.acquireTexture(c,i,r,o);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){(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*D.ZSL.bytesPerElement(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(0,D.dA1)(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw gk(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:i,outTexShapeLocation:o}=$S(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=a,e.outShapeLocation=s,e.outShapeStridesLocation=i,e.outTexShapeLocation=o}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:r,height:a,width:s,channels:i}=e,o=(0,D.Hi9)().backend;if(!o.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=o.writeTexture(r,t,n,a,s,i);return(0,D.Hi9)().makeTensorFromDataId(u,t,n,o)}}wI.nextDataId=0;const vI="4.22.0";function kI(){(0,D._K2)().set("WEBGL_FORCE_F16_TEXTURES",!0)}D.eMq.isBrowser()&&(0,D.gJX)("webgl",(()=>new wI),2);const SI={forceHalfFloat:kI},_I="\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n";class II{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=D.C0T.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=NS(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 TI="\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 $I{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=D.C0T.assertAndGetBroadcastShape(t,n);const a=this.outputShape.length;this.enableShapeUniforms=NS(a);let s="";if(r)if(0===a||1===D.ZSL.sizeFromShape(this.outputShape))s="\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";else{if(s=`\n          ${SS(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=nI("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 CI(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 NI={kernelName:D.lzr,backendName:"webgl",kernelFunc:CI};function EI(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.makeTensorInfo(r.shape,"complex64"),i=n.texData.get(s.dataId),o=CI({inputs:{x:r},backend:n}),u=CI({inputs:{x:a},backend:n});return i.complexTensorInfos={real:o,imag:u},s}const AI={kernelName:D.pr3,backendName:"webgl",kernelFunc:EI},RI="return (a < 0.) ? b * a : a;",DI="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const FI={kernelName:D.X0$,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:s}=r,i=n.makeTensorInfo([],"float32",D.ZSL.createScalarValue(s,"float32")),o=(0,D._K2)().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $I(DI,a.shape,i.shape):new II(RI,a.shape,i.shape),u=n.runWebGLProgram(o,[a,i],"float32");return n.disposeIntermediateTensorInfo(i),u}},MI="return (a < 0.) ? b * a : a;",OI="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const zI={kernelName:D.Ncv,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t,s=(0,D._K2)().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $I(OI,r.shape,a.shape):new II(MI,r.shape,a.shape);return n.runWebGLProgram(s,[r,a],"float32")}},LI="if (isnan(x)) return x;";function PI({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:a,backend:s})=>{const{x:i}=a,o=s,u=r||i.dtype;if(o.shouldExecuteOnCPU([i])&&null!=n){const e=o.texData.get(i.dataId),t=n(e.values,u);return o.makeTensorInfo(i.shape,u,t)}let l;return l=(0,D._K2)().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new mI(i.shape,t):new lI(i.shape,e),o.runWebGLProgram(l,[i],u)}}function BI({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:a,dtype:s}){return({inputs:i,backend:o})=>{const{a:u,b:l}=i,c=o;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},i=new II(e,u.shape,l.shape);return c.runWebGLProgram(i,[a,s],(0,D.TuY)(n.dtype,r.dtype))})),s=EI({inputs:{real:r,imag:a},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(a),s}const d=s||(0,D.TuY)(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?D.C0T.fromUint8ToStringArray(e):e,r="string"===u.dtype?D.C0T.fromUint8ToStringArray(t):t,[s,i]=a(u.shape,l.shape,n,r,d),o=c.makeTensorInfo(i,d);return c.texData.get(o.dataId).values=s,o}let p;return p=(0,D._K2)().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new $I(t,u.shape,l.shape,n):new II(e,u.shape,l.shape),c.runWebGLProgram(p,[u,l],d)}}function WI(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":pI;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":hI;if("prelu"===e)return t?OI:MI;if("leakyrelu"===e)return t?DI:RI;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 VI{constructor(e,t,n,r=!1,a=!1,s=!1,i=null,o=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=NS(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="";i&&(m=o?`vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          ${i}\n        }`:u?`vec4 activation(vec4 a) {\n          vec4 b = getLeakyreluAlphaAtOutCoords();\n          ${i}\n        }`:`vec4 activation(vec4 x) {\n          ${i}\n        }`,g="result = activation(result);");const y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&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 UI="return areal * breal - aimag * bimag;",GI="return areal * bimag + aimag * breal;";class HI{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=D.C0T.assertAndGetBroadcastShape(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 jI="return a * b;";function qI(e){const{inputs:t,backend:n}=e,{a:r,b:a}=t,s=D.C0T.upcastType(r.dtype,a.dtype);if("complex64"===r.dtype){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),s=new HI(UI,r.shape,a.shape),i=new HI(GI,r.shape,a.shape),o=[{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,o,"float32"),l=n.runWebGLProgram(i,o,"float32"),c=EI({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),[i,o]=C_(r.shape,a.shape,e.values,t.values,s),u=n.makeTensorInfo(o,s);return n.texData.get(u.dataId).values=i,u}let i;return i=(0,D._K2)().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $I(jI,r.shape,a.shape):new II(jI,r.shape,a.shape),n.runWebGLProgram(i,[r,a],s)}const ZI={kernelName:D.xu7,backendName:"webgl",kernelFunc:qI};function KI(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,i=n,o=D.ZSL.sizeFromShape(a.shape),u=D.ZSL.inferFromImplicitShape(s,o),l=D.ZSL.sizeFromShape(u);D.ZSL.assert(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.`));const c=i.texData.get(a.dataId);return!c.isPacked||Gk(a.shape,u)||null!==c.texture&&Gk(c.shape,u)?(i.incRef(a.dataId),{dataId:a.dataId,shape:u,dtype:a.dtype}):function(e,t,n){const r=[Pk(e.shape),...Bk(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[Pk(t),...Bk(t)],i=new aI(s,r),o=[r],u=n.runWebGLProgram(i,[a],e.dtype,o,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}}(a,u,i)}const YI={kernelName:D.R23,backendName:"webgl",kernelFunc:KI};class QI{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];const i=4*Math.floor(n/4),o=n%4;let u="sumValue += dot(values, ones);";if(null!=t){const e=1/t;u=`sumValue += dot(values * ${D.ZSL.isInt(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 < ${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          ${u}\n        }\n\n        int inIdx = inOffset + ${i};\n        if (${1===o}) {\n          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n          ${u}\n        } else if (${2===o}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1), 0.0, 0.0);\n\n          ${u}\n        } else if (${3===o}) {\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 XI{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];let i="0.0",o="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 1e-20",o="min"):"max"===t&&(i="-1.0 / 1e-20",o="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 = ${o}(values, minMaxValue);\n        if (${"min"===t} || ${"max"===t}) {\n          minMaxValue = ${o}(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?(i="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&&(i="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 = ${i};\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(${i});\n        float prodValue = 1.0;\n        float sumValue = 0.0;\n        float allValue = 1.0;\n        float anyValue = 0.0;\n\n        for (int i = 0; i < ${l}; i += 4) {\n          int inIdx = inOffset + i;\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          ${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 JI(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=D.C0T.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}(e.shape);let s=e;for(let i=0;i<a.length;i++){const{inSize:o,windowSize:u,outSize:l}=a[i];let c,d;c="mean"===n?0===i?new QI({windowSize:u,inSize:o,batchSize:e.shape[0],outSize:l},o):new QI({windowSize:u,inSize:o,batchSize:e.shape[0],outSize:l}):new XI({windowSize:u,inSize:o,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 eT{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=SS(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 tT{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=SS(this.rank),a=tI("rc",this.rank),s=new Array(this.rank);for(let l=0;l<t.length;l++)s[t[l]]=a[l];const i=`vec2(${s.slice(-2).join()})`,o=`++${a[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`\n    void main() {\n      ${r} rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = ${u};\n      if(${o}) {\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(${o}) {\n          result[3] = ${u};\n        }\n      }\n      setOutput(result);\n    }\n    `}}function nT(e,t,n){const r=(0,D._K2)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tT(e.shape,t):new eT(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function rT(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r;return function(e,t,n,r){const a=t,s=e.shape.length,i=D.ZSL.parseAxisParam(a,e.shape);let o=i;const u=D.C0T.getAxesPermutation(o,s),l=null!=u;let c=e;l&&(c=nT(e,u,r),o=D.C0T.getInnerMostAxes(o.length,s)),D.C0T.assertAxesAreInnerMostDims("sum",o,s);const[d,p]=D.C0T.computeOutAndReduceShapes(c.shape,o);let h=d;n&&(h=D.C0T.expandShapeToKeepDim(d,i));const f=D.ZSL.sizeFromShape(p),m=KI({inputs:{x:c},attrs:{shape:[D.ZSL.sizeFromShape(e.shape)/f,f]},backend:r}),g=JI(m,(0,D.chL)(e.dtype),"sum",r),y=KI({inputs:{x:g},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),l&&r.disposeIntermediateTensorInfo(c),y}(a,s,i,n)}const aT={kernelName:D.WuN,backendName:"webgl",kernelFunc:rT};function sT(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{perm:s}=r,i=n,o=a.shape.length,u=new Array(o);for(let c=0;c<u.length;c++)u[c]=a.shape[s[c]];let l;if(i.shouldExecuteOnCPU([a])){const e=i.texData.get(a.dataId).values,t=J_(e,a.shape,a.dtype,s,u);l=i.makeTensorInfo(u,a.dtype);i.texData.get(l.dataId).values=t}else l=nT(a,s,i);return l}const iT={kernelName:D.wx0,backendName:"webgl",kernelFunc:sT};function oT({a:e,b:t,transposeA:n,transposeB:r,backend:a,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:u=null}){const l=e.shape.length,c=t.shape.length,d=n?e.shape[l-2]:e.shape[l-1],p=r?t.shape[c-1]:t.shape[c-2],h=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=D.ZSL.sizeFromShape(m),b=D.ZSL.sizeFromShape(g),x=D.ZEY.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);D.ZSL.assert(d===p,(()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`));const w=n?[y,d,h]:[y,h,d],v=r?[b,f,p]:[b,p,f],k=KI({inputs:{x:e},backend:a,attrs:{shape:w}}),S=KI({inputs:{x:t},backend:a,attrs:{shape:v}}),_=[k,S],I=Math.max(y,b),T=n?k.shape[1]:k.shape[2],$=null!=s,C=null!=i,N="leakyrelu"===u,E=null!=u?WI(u,!0):null;let A;if((1===h||1===f)&&T>1e3&&!1===($||C||N||null!=E)){let e=k,t=S;n&&(e=sT({inputs:{x:k},backend:a,attrs:{perm:[0,2,1]}}),_.push(e)),r&&(t=sT({inputs:{x:S},backend:a,attrs:{perm:[0,2,1]}}),_.push(t));const s=1===f;let i=e;1!==f&&(i=KI({inputs:{x:e},backend:a,attrs:{shape:[I,T,1]}}),_.push(i));const o=1===f?2:1;let u=t;s&&(u=KI({inputs:{x:t},backend:a,attrs:{shape:[I,1,T]}}),_.push(u));const l=qI({inputs:{a:i,b:u},backend:a});A=rT({inputs:{x:l},backend:a,attrs:{axis:o,keepDims:!0}}),_.push(l)}else{const u=(0,D.TuY)(e.dtype,t.dtype),l=new VI(w,v,[I,h,f],n,r,$,E,C,N),c=[k,S];if(null!=s&&c.push(s),C&&c.push(i),N){const e=a.makeTensorInfo([],"float32",D.ZSL.createScalarValue(o,"float32"));c.push(e),_.push(e)}A=a.runWebGLProgram(l,c,u)}const R=KI({inputs:{x:A},backend:a,attrs:{shape:x}});_.push(A);for(const D of _)a.disposeIntermediateTensorInfo(D);return R}const uT={kernelName:D.Dr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:d}=r;return oT({a:a,b:s,transposeA:u,transposeB:l,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:d,activation:c})}},lT="return abs(x);";const cT={kernelName:D.ljI,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=P_(e.values);return n.makeTensorInfo(r.shape,r.dtype,t)}let a;return a=(0,D._K2)().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new mI(r.shape,lT):new lI(r.shape,lT),n.runWebGLProgram(a,[r],r.dtype)}},dT=PI({opSnippet:cI+"\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return acos(x);\n"}),pT={kernelName:D.Vvy,backendName:"webgl",kernelFunc:dT},hT=PI({opSnippet:cI+"\n  if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),fT={kernelName:D.PH8,backendName:"webgl",kernelFunc:hT},mT="return a + b;",gT=BI({opSnippet:mT,packedOpSnippet:mT,supportsComplex:!0,cpuKernelImpl:i_}),yT={kernelName:D.OMN,backendName:"webgl",kernelFunc:gT};class bT{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 xT{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 wT={kernelName:D.EkD,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,a=n;if(1===a.length)return CI({inputs:{x:a[0]},backend:r});if(a.length>(0,D._K2)().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)=>(0,D.TuY)(e,t))),i=a.map((e=>e.shape)),o=(0,D._K2)().getBool("WEBGL_PACK")?new xT(a[0].shape,i):new bT(a[0].shape,i);return r.runWebGLProgram(o,a,s)}};const vT={kernelName:D.u8Z,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r,o=a.shape.length,u=D.ZSL.parseAxisParam(s,a.shape);let l=u;const c=D.C0T.getAxesPermutation(l,o);let d=a;null!=c&&(d=sT({inputs:{x:a},backend:n,attrs:{perm:c}}),l=D.C0T.getInnerMostAxes(l.length,o)),D.C0T.assertAxesAreInnerMostDims("all",l,o);const[p,h]=D.C0T.computeOutAndReduceShapes(d.shape,l),f=KI({inputs:{x:d},backend:n,attrs:{shape:[-1,D.ZSL.sizeFromShape(h)]}}),m=JI(f,f.dtype,"all",n);let g;if(i){g=KI({inputs:{x:m},backend:n,attrs:{shape:D.C0T.expandShapeToKeepDim(p,u)}})}else g=KI({inputs:{x:m},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(d),g}};const kT={kernelName:D.FSt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r,o=a.shape.length,u=D.ZSL.parseAxisParam(s,a.shape);let l=u;const c=D.C0T.getAxesPermutation(l,o);let d=a;null!=c&&(d=sT({inputs:{x:a},backend:n,attrs:{perm:c}}),l=D.C0T.getInnerMostAxes(l.length,o)),D.C0T.assertAxesAreInnerMostDims("any",l,o);const[p,h]=D.C0T.computeOutAndReduceShapes(d.shape,l),f=KI({inputs:{x:d},backend:n,attrs:{shape:[-1,D.ZSL.sizeFromShape(h)]}}),m=JI(f,f.dtype,"any",n);let g;if(i){g=KI({inputs:{x:m},backend:n,attrs:{shape:D.C0T.expandShapeToKeepDim(p,u)}})}else g=KI({inputs:{x:m},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(d),g}};class ST{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 i="max"===t?">":"<",o=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 = ${o};\n          float candidate = getA(batch, inIdx);\n          if (candidate ${i} bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    `}}class _T{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,D.ZSL.assert(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 i=this.outputShape,o=i.length,u=SS(o),l=nI("coords",o);let c,d;if(1===s){d=o+1;const e=SS(d);c=`\n        ${e} sourceLocR = ${e}(${l.join()}, 0);\n        ++${l[o-1]};\n        ${e} sourceLocG = ${e}(${l.join()}, 0);\n        ++${l[o-2]};\n        ${e} sourceLocA = ${e}(${l.join()}, 0);\n        --${l[o-1]};\n        ${e} sourceLocB = ${e}(${l.join()}, 0);\n        --${l[o-2]};`}else d=o,c=`\n        ${u} sourceLocR = coords;\n        ++${l[o-1]};\n        ${u} sourceLocG = coords;\n        ++${l[o-2]};\n        ${u} sourceLocA = coords;\n        --${l[o-1]};\n        ${u} sourceLocB = coords;\n        --${l[o-2]};`;const p=["x","y","z","w","u","v"].slice(0,d),h="."+p[d-1],f=p.map((e=>"int "+e)),m=nI("sourceLocR",d-1).concat("inIdx.r"),g=nI("sourceLocG",d-1).concat("inIdx.g"),y=nI("sourceLocB",d-1).concat("inIdx.b"),b=nI("sourceLocA",d-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=r?"":`\n          inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\n                             getBestIndicesAChannel(${g.join()}),\n                             getBestIndicesAChannel(${y.join()}),\n                             getBestIndicesAChannel(${b.join()})));`,v=`vec4(\n            getAChannel(${m.join()}),\n            hasNextCol ? getAChannel(${g.join()}) : 0.,\n            hasNextRow ? getAChannel(${y.join()}) : 0.,\n            hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,k=r?"":`\n      float getBestIndicesAChannel(${f.join()}) {\n        return getChannel(getBestIndicesA(${p.join()}),\n                                          vec2(${p.slice(-2).join()}));\n      }`;this.userCode=`\n      float getAChannel(${f.join()}) {\n        return getChannel(getA(${p.join()}),\n                               vec2(${p.slice(-2).join()}));\n      }\n      ${k}\n      void main() {\n        ${u} coords = getOutputCoords();\n        bool hasNextCol = ${l[o-1]} < ${i[o-1]-1};\n        bool hasNextRow = ${l[o-2]} < ${i[o-2]-1};\n        ${c}\n        ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},\n          sourceLocB${h}, sourceLocA${h}) * ${t};\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = ${v};\n\n        for (int i = 0; i < ${t}; i++) {\n          inIdx = srcIdx;\n          ${w}\n          vec4 candidate = ${v};\n          bvec4 nan = isnan(candidate);\n          bvec4 replace = bvec4(\n            vec4(${x}(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 IT(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 i=D.C0T.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:a,outSize:Math.ceil(s/i)},u=new ST(o,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=IT(e,t,n,c);return e.disposeIntermediateTensorInfo(c),d}function TT(e,t,n,r=null){const a=null!=r?r.shape:t.shape,s=a[a.length-1],i=D.C0T.computeOptimalWindowSize(s),o=new _T(a,i,n,null==r),u=null==r?[t]:[t,r],l=e.runWebGLProgram(o,u,"int32");if(l.shape.length===t.shape.length){const r=TT(e,t,n,l);return e.disposeIntermediateTensorInfo(l),r}return l}function $T(e,t,n,r){const a=[n];if(D.C0T.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),a,t.shape.length),!(0,D._K2)().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],s=e.texData.get(t.dataId);let i=t;null!==s&&s.isPacked&&(i=e.unpackTensor(t),n.push(i));const[o,u]=D.C0T.computeOutAndReduceShapes(i.shape,a),l=D.ZSL.sizeFromShape(u),c=KI({inputs:{x:i},backend:e,attrs:{shape:[-1,l]}});n.push(c);const d=IT(e,c,r);n.push(d);const p=KI({inputs:{x:d},backend:e,attrs:{shape:o}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),p}return TT(e,t,r)}const CT={kernelName:D.Jp_,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let i=D.ZSL.parseAxisParam(s,a.shape);const o=D.C0T.getAxesPermutation(i,a.shape.length);let u=a;const l=[];null!=o&&(u=sT({inputs:{x:a},backend:n,attrs:{perm:o}}),l.push(u),i=D.C0T.getInnerMostAxes(i.length,u.shape.length)),D.C0T.assertAxesAreInnerMostDims("argMax",[i[0]],u.shape.length);const c=$T(n,u,i[0],"max");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}};const NT={kernelName:D.p_m,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let i=D.ZSL.parseAxisParam(s,a.shape);const o=D.C0T.getAxesPermutation(i,a.shape.length);let u=a;const l=[];null!=o&&(u=sT({inputs:{x:a},backend:n,attrs:{perm:o}}),l.push(u),i=D.C0T.getInnerMostAxes(i.length,u.shape.length)),D.C0T.assertAxesAreInnerMostDims("argMin",[i[0]],u.shape.length);const c=$T(n,u,i[0],"min");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},ET=PI({opSnippet:cI+"\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return asin(x);\n"}),AT={kernelName:D.QKF,backendName:"webgl",kernelFunc:ET},RT=PI({opSnippet:cI+"return log(x + sqrt(x * x + 1.0));"}),DT={kernelName:D.epO,backendName:"webgl",kernelFunc:RT},FT=PI({opSnippet:cI+"\n  return atan(x);\n"}),MT={kernelName:D.TyE,backendName:"webgl",kernelFunc:FT},OT=BI({opSnippet:_I+"\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  "+TI+"\n  return result;\n"}),zT={kernelName:D.lxb,backendName:"webgl",kernelFunc:OT},LT=PI({opSnippet:cI+"\n  if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),PT={kernelName:D.zP9,backendName:"webgl",kernelFunc:LT};class BT{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,i=e.strideHeight,o=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(${i}, ${o});\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),w=s%4,v=`\n      if (${f}) {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    `;this.userCode=`\n      const ivec2 strides = ivec2(${i}, ${o});\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            ${v}\n          }\n\n          int xC = xCCorner + ${x};\n          if (${1===w}) {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            ${v}\n          } else if (${2===w}) {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ${l}, d),\n              initializationValue,\n              initializationValue\n            );\n\n            ${v}\n          } else if (${3===w}) {\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            ${v}\n          }\n        }\n        setOutput(${b});\n      }\n    `}}class WT{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,i=e.strideDepth,o=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(${i}, ${o}, ${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 w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(w="avgValue / max(count, 1.0)");const v=4*Math.floor(s/4),k=s%4,S=`\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(${i}, ${o}, ${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 < ${v}; 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              ${S}\n            }\n\n            int xC = xCCorner + ${v};\n            if (${1===k}) {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                initializationValue,\n                initializationValue,\n                initializationValue\n              );\n\n              ${S}\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              ${S}\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              ${S}\n            }\n          }\n        }\n        setOutput(${w});\n      }\n    `}}const VT={kernelName:D.ho8,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;aS(a,"avgPool");const{filterSize:s,strides:i,pad:o,dimRoundingMode:u}=r;D.ZSL.assert(D.C0T.eitherStridesOrDilationsAreOne(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const l=D.C0T.computePool2DInfo(a.shape,s,i,1,o,u);if(1===l.filterWidth&&1===l.filterHeight&&D.ZSL.arraysEqual(l.inShape,l.outShape))return CI({inputs:{x:a},backend:n});const c=new BT(l,"avg",!1);return n.runWebGLProgram(c,[a],"float32")}};const UT={kernelName:D.cS,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:u,dataFormat:l}=r,c=D.C0T.computePool3DInfo(a.shape,s,i,[1,1,1],o,u,l),d=new WT(c,"avg",!1);return n.runWebGLProgram(d,[a],"float32")}};class GT{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,i=e.dilationWidth,o=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=o-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 < ${o};\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+= ${i}) {\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 HT{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,i=e.strideWidth,o=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 += ${o}) {\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) / ${i}.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 jT={kernelName:D.wwC,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,i=s,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,d=D.C0T.computePool3DInfo(i.shape,o,u,[1,1,1],l,c),p=new HT(d);return n.runWebGLProgram(p,[a],i.dtype)}};const qT={kernelName:D.VCH,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,i=s;aS([a,s],"avgPoolGrad");const{filterSize:o,strides:u,pad:l}=r,c=D.C0T.computePool2DInfo(i.shape,o,u,1,l),d=new GT(c);return n.runWebGLProgram(d,[a],i.dtype)}};const ZT={kernelName:D.jAQ,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s}=t,{transposeA:i,transposeB:o}=r;return oT({a:a,b:s,transposeA:i,transposeB:o,backend:n})}};class KT{constructor(e,t,n,r,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],D.C0T.assertAndGetBroadcastShape(e,t),D.C0T.assertAndGetBroadcastShape(e,n);let i="0.0";null!=r&&(D.C0T.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=a&&(D.C0T.assertAndGetBroadcastShape(e,a),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = ${i};\n        float scale = ${o};\n        float inv = scale * inversesqrt(variance + float(${s}));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    `}}class YT{constructor(e,t,n,r,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],D.C0T.assertAndGetBroadcastShape(e,t),D.C0T.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";null!=r&&(D.C0T.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=a&&(D.C0T.assertAndGetBroadcastShape(e,a),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n      void main() {\n        vec4 offset = ${i};\n        vec4 scale = ${o};\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 QT={kernelName:D.i5R,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,mean:a,variance:s,offset:i,scale:o}=e;D.ZSL.assert(a.shape.length===s.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),D.ZSL.assert(null==i||a.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),D.ZSL.assert(null==o||a.shape.length===o.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));let{varianceEpsilon:u}=n;null==u&&(u=.001);const l=[r,a,s];let c=null;null!=i&&(c=i.shape,l.push(i));let d=null;null!=o&&(d=o.shape,l.push(o));const p=(0,D._K2)().getBool("WEBGL_PACK_NORMALIZATION")?new YT(r.shape,a.shape,s.shape,c,d,u):new KT(r.shape,a.shape,s.shape,c,d,u);return t.runWebGLProgram(p,l,l[0].dtype)}};class XT{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=SS(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return JT.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.${JT[t]} = start[${t}] + coords.${JT[t]};`)).join("\n")}\n      `,this.userCode=`\n      void main() {\n        ${r}\n        setOutput(getSource(${n}));\n      }\n    `}}const JT=["x","y","z","w","u","v"];class e${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=SS(this.rank),n=nI("coords",this.rank),r=nI("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,s=`getChannel(getSource(${r.join()}), ${a})`,i=`\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    `,o=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        ${i}\n        ${o}\n        setOutput(result);\n      }\n    `}}function t$(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:i}=r,[o,u]=D.Kro.parseSliceParams(a,s,i);if(D.Kro.assertParamsValid(a,o,u),0===D.ZSL.sizeFromShape(u))return n.makeTensorInfo(u,a.dtype,[]);if(n.shouldExecuteOnCPU([a])||"string"===a.dtype){const e=n.texData.get(a.dataId),t=B_(e.values,o,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,t)}const{isPacked:l}=n.texData.get(a.dataId),c=D.Kro.isSliceContinous(a.shape,o,u);if(l||!c){const e=(0,D._K2)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new e$(u):new XT(u),t=[o];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),i=r.texData.get(s.dataId);Object.assign(i,a),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=D.Kro.computeFlatOffset(t,D.ZSL.computeStrides(e.shape));a.slice&&(o+=a.slice.flatOffset),i.slice={flatOffset:o,origDataId:a.slice&&a.slice.origDataId||e.dataId};const u=r.dataRefCount.get(i.slice.origDataId)||1;return r.dataRefCount.set(i.slice.origDataId,u+1),s}(a,o,u,n)}const n$={kernelName:D.JiE,backendName:"webgl",kernelFunc:t$},r$={kernelName:D.Ik2,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:i}=r;D.ZSL.assert(a.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const o=s.reduce(((e,t)=>e*t)),u=D.C0T.getReshaped(a.shape,s,o),l=D.C0T.getPermuted(u.length,s.length),c=D.C0T.getReshapedPermuted(a.shape,s,o),d=D.C0T.getSliceBeginCoords(i,s.length),p=D.C0T.getSliceSize(c,i,s.length),h=[],f=KI({inputs:{x:a},backend:n,attrs:{shape:u}}),m=sT({inputs:{x:f},backend:n,attrs:{perm:l}}),g=KI({inputs:{x:m},backend:n,attrs:{shape:c}}),y=t$({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}};const a$={kernelName:D.N4F,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:i}=r,o=n.readSync(a.dataId),u=n.readSync(s.dataId),l=o_(o,u,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,l)}};const s$={kernelName:D.HNs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{a:r,b:a}=t,s=(0,D._K2)().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=(0,D._K2)().getNumber("WEBGL_VERSION");if(n.shouldExecuteOnCPU([r,a])||1===i){const e=n.texData.get(r.dataId).values,t=n.texData.get(a.dataId).values,[s,i]=l_(r.shape,a.shape,e,t,r.dtype),o=n.makeTensorInfo(i,r.dtype);return n.texData.get(o.dataId).values=s,o}let o;return o=s?new $I("\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 II("\n  return float(int(a.r) & int(b.r));\n",r.shape,a.shape),n.runWebGLProgram(o,[r,a],r.dtype)}};const i$={kernelName:D.vj7,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:a}=t,s=n.readSync(r.dataId),i=n.readSync(a.dataId),o=D.C0T.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},o$=BI({opSnippet:"return float(a != b);",cpuKernelImpl:E_,dtype:"bool"}),u$={kernelName:D.ylV,backendName:"webgl",kernelFunc:o$};function l$(e){const{inputs:t,backend:n}=e,{input:r}=t;return CI({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const c$={kernelName:D.LRy,backendName:"webgl",kernelFunc:l$};const d$={kernelName:D.KXH,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r,attrs:a}=t,{x:s}=n,{dtype:i}=a;if("complex64"===i){if("complex64"===s.dtype)return CI({inputs:{x:s},backend:r});const t=D.Ul9(s.shape),n=e({inputs:{x:s},backend:r,attrs:{dtype:"float32"}}),a=EI({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),a}if("complex64"===s.dtype){const t=l$({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r,attrs:{dtype:i}});return r.disposeIntermediateTensorInfo(t),n}if(!D.ZSL.hasEncodingLoss(s.dtype,i)){const e=CI({inputs:{x:s},backend:r});return{dataId:e.dataId,shape:e.shape,dtype:i}}if(r.shouldExecuteOnCPU([s])){const e=r.texData.get(s.dataId).values,[t,n,a]=c_(e,s.shape,s.dtype,i);return r.makeTensorInfo(t,n,a)}if("int32"===i)return function(e,t){const n=new lI(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"===i){const e=r.makeTensorInfo([],"bool",D.ZSL.getTypedArrayFromDType("bool",1)),t=o$({inputs:{a:s,b:e},backend:r});return r.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${i}`)}},p$="return ceil(x);",h$=PI({opSnippet:p$,packedOpSnippet:p$,cpuKernelImpl:d_}),f$={kernelName:D.QDP,backendName:"webgl",kernelFunc:h$};class m${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 g${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 y$={kernelName:D.vaV,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=r;let o;o=(0,D._K2)().getBool("WEBGL_PACK_CLIP")?new g$(a.shape):new m$(a.shape);const u=[[s],[i]];return n.runWebGLProgram(o,[a],a.dtype,u)}};class b${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 x$(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const w$={kernelName:D.$zE,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=n.texData.get(r.dataId),s=new b$(r.shape),i=[x$(r,a.complexTensorInfos.real),x$(r,a.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}};class v${constructor(e){this.outputShape=[],this.outputShape=D.C0T.computeOutShape(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 k${constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=D.C0T.computeOutShape(e,t);const n=this.outputShape,r=n.length,a=SS(r),s=nI("coords",r),i=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map(((e,t)=>`T${t}`));const o=new Array(e.length-1);o[0]=e[0][t];for(let f=1;f<o.length;f++)o[f]=o[f-1]+e[f][t];const u=i[t],l=i.slice(-2),c=i.join();let d=`if (${u} < ${o[0]}) {\n        return getChannel(\n            getT0(${c}), vec2(${l.join()}));\n        }`;for(let f=1;f<o.length;f++){const e=o[f-1];d+=`\n        if (${u} < ${o[f]}  && ${u} >= ${o[f-1]}) {\n          return getChannel(\n            getT${f}(${S$(i,u,e)}),\n            vec2(${S$(l,u,e)}));\n        }`}const p=o.length,h=o[o.length-1];d+=`\n        return getChannel(\n          getT${p}(${S$(i,u,h)}),\n          vec2(${S$(l,u,h)}));`,this.userCode=`\n      float getValue(${i.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 S$(e,t,n){const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}function _$(e){const{inputs:t,backend:n}=e,{input:r}=t;return CI({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}const I$={kernelName:D.dv8,backendName:"webgl",kernelFunc:_$};function T$(e,t,n){const r=e[0].dtype;if("complex64"===r){const r=e.map((e=>l$({inputs:{input:e},backend:n}))),a=e.map((e=>_$({inputs:{input:e},backend:n}))),s=T$(r,t,n),i=T$(a,t,n),o=EI({inputs:{real:s,imag:i},backend:n});return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),a.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),o}let a=n.shouldExecuteOnCPU(e);if("string"===r&&(a=!0),a){const a=e.map((e=>{const r=D.ZSL.sizeFromShape(e.shape.slice(t));return KI({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})})),s=a.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),i=D.C0T.computeOutShape(a.map((e=>e.shape)),1),o=1===a[0].shape[0],u=p_(s,i,r,o),l=D.C0T.computeOutShape(e.map((e=>e.shape)),t),c=n.makeTensorInfo(l,r,u);return a.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}const s=e.filter((e=>D.ZSL.sizeFromShape(e.shape)>0)),i=(0,D._K2)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(1===s.length){const t=i?new lI(e[0].shape,fI):new mI(e[0].shape,fI);return n.runWebGLProgram(t,e,r)}const o=(0,D._K2)().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>o){const e=[];for(let a=0;a<s.length;a+=o){const r=s.slice(a,a+o);e.push(T$(r,t,n))}const r=T$(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return r}if(i){const e=new k$(s.map((e=>e.shape)),t);return n.runWebGLProgram(e,s,r)}const{tensors2D:u,outShape:l}=function(e,t,n){const r=D.C0T.computeOutShape(e.map((e=>e.shape)),t),a=e.map((e=>KI({inputs:{x:e},attrs:{shape:[-1,D.ZSL.sizeFromShape(e.shape.slice(t))]},backend:n})));return{tensors2D:a,outShape:r}}(s,t,n),c=new v$(u.map((e=>e.shape))),d=n.runWebGLProgram(c,u,r);u.forEach((e=>n.disposeIntermediateTensorInfo(e)));const p=KI({inputs:{x:d},attrs:{shape:l},backend:n});return n.disposeIntermediateTensorInfo(d),p}function $$(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=D.ZSL.parseAxisParam(a,t[0].shape)[0],i=t.map((e=>e.shape));D.C0T.assertParamsConsistent(i,s);const o=D.C0T.computeOutShape(t.map((e=>e.shape)),s);if(0===D.ZSL.sizeFromShape(o))return n.makeTensorInfo(o,t[0].dtype,[]);const u=t.filter((e=>D.ZSL.sizeFromShape(e.shape)>0));return 1===u.length?CI({inputs:{x:u[0]},backend:n}):T$(u,s,n)}const C$={kernelName:D.$dB,backendName:"webgl",kernelFunc:$$};class N${constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const s=e.padInfo.top,i=e.padInfo.left,o=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="",w="";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        `,w="result = activation(result);");const v=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(${o}, ${u});\n      const ivec2 pads = ivec2(${s}, ${i});\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        ${v}\n        ${w}\n        setOutput(result);\n      }\n    `}}class E${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,i=e.strideWidth,o=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}, ${i});\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 * ${o};\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 A${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=NS(this.outputShape.length);const s=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,c=l;let d="\n       int xR; int xC; int xCOffset;\n       vec4 wTexel; vec4 previous; vec4 final;";for(let m=0;m<l;m++)d+=`\n           vec4 xTexelC${2*m};\n           int xTexelC${2*m}Ready;\n           vec4 xTexelC${2*m+1};\n           int xTexelC${2*m+1}Ready;\n           vec4 xC${m};`;d+=`\n     for (int r = 0; r < ${u}; r++) {\n      for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {\n       `;for(let m=0;m<l;m++)d+=`\n           xTexelC${2*m} = vec4(0.0);\n           xTexelC${2*m}Ready = 0;\n           xTexelC${2*m+1} = vec4(0.0);\n           xTexelC${2*m+1}Ready = 0;\n           xC${m} = vec4(0.0);`;d+="\n         xR = xRCorner + r * dilations[0];\n         if (xR >=0 && xR < inDims[0]) {\n       ";for(let m=0;m<(c+1)/2;m++){const t=2*m;if(d+=`\n           xC = xCCorner + ${t*o};\n           `,1===i){if(t<l&&(s%2===1?(d+=`\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               `,d+=1===o&&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                   `):d+=`\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<l)){const e=s%2===0?D.ZSL.nearestLargerEven(o):o;o%2===0&&s%2===1||o%2!==0&&s%2!==1?(d+=`\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                   `,d+=o>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                     `):d+=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<l&&(s%2===1?(d+=`\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<l&&(d+=`\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                 `)):(d+=`\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<l&&(d+=`\n                   xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n                 `)));t<l&&(d+=`\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<l&&(d+=`\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             `))}d+="\n     }\n   ",d+="\n     }\n   ",d+="\n     }\n   ";let p="",h="";n&&(p=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         }`,h="result = activation(result);");const f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n       ${p}\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         ${d}\n\n         vec4 result = dotProd - vec4(0.000000000000001);\n         ${f}\n         ${h}\n         setOutput(result);\n       }\n     `}}class R${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=NS(this.outputShape.length);const{dataFormat:n}=t,r=iS(),a="channelsLast"===n,s=a?1:2,i=a?2:3,o=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          ${o}\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[${i}] && 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 D$(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 F$({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){const u=e.shape,l=r.texData.get(e.dataId),c=n.inChannels,d=u[0]*u[1]*u[2],p=n.outChannels,h="channelsLast"===n.dataFormat,f=!1;let m;const g=[];if(null!=s){const e=D$(s.shape,h);null!=e&&(s=KI({inputs:{x:s},backend:r,attrs:{shape:e}}),g.push(s))}if(null!=a){const e=D$(a.shape,h);null!=e&&(a=KI({inputs:{x:a},backend:r,attrs:{shape:e}}),g.push(a))}if(!((1===d||1===p)&&c>1e3)&&l.isPacked&&h&&null!=l.texture&&u[2]%2!==0&&D.ZSL.arraysEqual(l.shape.slice(-3),u.slice(-3))){const c=u[0]*u[1]*(u[2]+1),d={dataId:e.dataId,shape:[1,c,n.inChannels],dtype:e.dtype},p=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,D.ZSL.assert(Gk(l.shape,d.shape),(()=>`packed reshape ${l.shape} to ${d.shape} isn't free`));const h=KI({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});g.push(h);const y=oT({a:d,b:h,backend:r,transposeA:false,transposeB:f,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),b=r.texData.get(y.dataId);D.ZSL.assert(b.isPacked,(()=>"batchMatMul result is expected to be packed")),l.shape=p,b.shape=n.outShape,m=CI({inputs:{x:y},backend:r}),m.shape=n.outShape,g.push(y)}else{const u=n.outHeight*n.outWidth,l=KI({inputs:{x:e},backend:r,attrs:{shape:h?[n.batchSize,u,n.inChannels]:[n.batchSize,n.inChannels,u]}}),c=KI({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),d=oT({a:h?l:c,b:h?c:l,transposeA:!h,transposeB:f,backend:r,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i});m=KI({inputs:{x:d},backend:r,attrs:{shape:n.outShape}}),g.push(l),g.push(c),g.push(d)}for(const y of g)r.disposeIntermediateTensorInfo(y);return m}function M$({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){const{filterWidth:u,filterHeight:l,inChannels:c,outWidth:d,outHeight:p,dataFormat:h}=n,f="channelsLast"===h,m=u*l*c,g=p*d,y=[n.batchSize,m,g],b=[];if(null!=s){const e=D$(s.shape,f);null!=e&&(s=KI({inputs:{x:s},backend:r,attrs:{shape:e}}),b.push(s))}if(null!=a){const e=D$(a.shape,f);null!=e&&(a=KI({inputs:{x:a},backend:r,attrs:{shape:e}}),b.push(a))}const x=KI({inputs:{x:t},backend:r,attrs:{shape:[1,m,D.ZSL.sizeFromShape(t.shape)/m]}});b.push(x);const w=new R$(y,n),v=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],k=r.runWebGLProgram(w,[e],"float32",v),S=KI({inputs:{x:k},backend:r,attrs:{shape:y}});b.push(k),b.push(S);const _=null!=a,I=null!=s,T="leakyrelu"===o,$=o?WI(o,!0):null,C=new VI(f?S.shape:x.shape,f?x.shape:S.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],!0,!1,_,$,I,T),N=f?[S,x]:[x,S];if(a&&N.push(a),I&&N.push(s),T){const e=r.makeTensorInfo([],"float32",D.ZSL.createScalarValue(i,"float32"));N.push(e),b.push(e)}const E=r.runWebGLProgram(C,N,"float32"),A=KI({inputs:{x:E},backend:r,attrs:{shape:n.outShape}});b.push(E);for(const R of b)r.disposeIntermediateTensorInfo(R);return A}const O$={kernelName:D.p2J,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:u,dilations:l,dimRoundingMode:c}=r,d=D.C0T.convertConv2DDataFormat(u),p=D.C0T.computeConv2DInfo(a.shape,s.shape,i,l,o,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&&(0,D._K2)().getBool("WEBGL_EXP_CONV")){const e=new A$(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((0,D._K2)().getBool("WEBGL_CONV_IM2COL"))h=M$({x:a,filter:s,convInfo:p,backend:n});else{const e=new N$(p);h=n.runWebGLProgram(e,[a,s],"float32")}else h=F$({x:a,filter:s,convInfo:p,backend:n});const f=KI({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}};class z${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 L${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,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,u=s?1:2,l=s?2:3,c=s?3:1;this.userCode=`\n      const ivec2 pads = ivec2(${i}, ${o});\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 P${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,i=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} - ${i};\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 B${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,i=e.strideWidth,o=t-1-e.padInfo.front,u=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`\n      const ivec3 pads = ivec3(${o}, ${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) / ${i}.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 W$={kernelName:D.rFm,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:i,pad:o,dataFormat:u,dimRoundingMode:l,filterShape:c}=r,d=D.C0T.convertConv2DDataFormat(u),p=D.C0T.computeConv2DInfo(a.shape,c,i,1,o,l,!1,d),h=new z$(p);return n.runWebGLProgram(h,[a,s],"float32")}};class V${constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=NS(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 U$={kernelName:D.jfg,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:u,dataFormat:l,dimRoundingMode:c}=r,d=D.C0T.convertConv2DDataFormat(l),p=D.C0T.computeConv2DInfo(i,s.shape,o,1,u,c,!1,d);if((0,D._K2)().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&"channelsLast"===d){const e=[[p.strideHeight,p.strideWidth]],t=new V$(p);return n.runWebGLProgram(t,[a,s],"float32",e)}{const e=new L$(p);return n.runWebGLProgram(e,[a,s],"float32")}}};const G$={kernelName:D.A1h,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:u}=r,l=D.C0T.computeConv3DInfo(a.shape,s.shape,i,u,o),c=new E$(l);return n.runWebGLProgram(c,[a,s],"float32")}};const H$={kernelName:D.iGz,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:u}=r,l=D.C0T.computeConv3DInfo(a.shape,u,i,1,o),c=new P$(l);return n.runWebGLProgram(c,[a,s],"float32")}};const j$={kernelName:D.gC7,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:u}=r,l=D.C0T.computeConv3DInfo(u,s.shape,o,1,i),c=new B$(l);return n.runWebGLProgram(c,[a,s],"float32")}},q$=PI({opSnippet:LI+"\n  return cos(x);\n",packedOpSnippet:`\n  vec4 result = cos(x);\n  bvec4 isNaN = isnan(x);\n  ${TI}\n  return result;\n`}),Z$={kernelName:D.Mn0,backendName:"webgl",kernelFunc:q$},K$=PI({opSnippet:"\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n"}),Y$={kernelName:D.MnK,backendName:"webgl",kernelFunc:K$};class Q${constructor(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[s,i,o,u]=e,[l]=t,[c,d]=n;this.outputShape=[l,c,d,u];const p="bilinear"===r?1:0,[h,f]=[i-1+".0",o-1+".0"],[m,g,y]=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[b,x,w]=d>1?[""+(o-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 = ${w};\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 X$={kernelName:D.MRQ,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:u,extrapolationValue:l}=r,c=new Q$(a.shape,s.shape,o,u,l);return n.runWebGLProgram(c,[a,s,i],"float32")}};var J$;!function(e){e.Prod="*",e.Sum="+"}(J$||(J$={}));class eC{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===J$.Prod?"1.0":"0.0",i=n?s:`getX(${tC(a,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1];let u="",l="";n?(u=r?"end != "+(o-1):"end != 0",l=r?"end + 1":"end - 1"):(u=r?`end + pow2 < ${o}`:"end >= pow2",l=r?"end + pow2":"end - pow2"),this.userCode=`\n      void main() {\n        ${SS(a)} coords = getOutputCoords();\n        int end = ${nC(a,"coords",this.op)};\n        float val = ${i};\n        int pow2 = int(pow(2.0, index));\n        if (${u}) {\n          int idx = ${l};\n          ${nC(a,"coords",this.op)} = idx;\n          val ${this.op}= getX(${tC(a,"coords",this.op)});\n        }\n        setOutput(val);\n      }\n    `}}function tC(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 nC(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 rC(e,t,n,r,a,s){const i=t.shape.length,o=D.C0T.getAxesPermutation([r],i);let u=t;null!=o&&(u=sT({inputs:{x:t},backend:n,attrs:{perm:o}}));const l=D.C0T.getInnerMostAxes(1,i)[0];if(l!==i-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=CI({inputs:{x:u},backend:n});for(let p=0;p<=Math.ceil(Math.log2(c))-1;p++){const t=new eC(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 eC(e,u.shape,a,s),r=d;d=n.runWebGLProgram(t,[d],d.dtype),n.disposeIntermediateTensorInfo(r)}if(null!=o){const e=sT({inputs:{x:d},backend:n,attrs:{perm:D.C0T.getUndoAxesPermutation(o)}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(u),e}return d}const aC={kernelName:D.jj_,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=r;return rC(J$.Prod,a,n,s,i,o)}};const sC={kernelName:D.nY8,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=r;return rC(J$.Sum,a,n,s,i,o)}};const iC={kernelName:D.wNW,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:i,binaryOutput:o}=r;if(1===a.shape.length){const e=n.readSync(a.dataId),t=n.readSync(s.dataId),r=o_(e,t,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,r)}if(2===a.shape.length){const e=n.bufferSync(a),t=n.bufferSync(s),r=u_(e,t,i,o);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 oC{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 uC={kernelName:D.TMz,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockSize:s,dataFormat:i}=r,o=a.shape[0],u=("NHWC"===i?a.shape[1]:a.shape[2])*s,l=("NHWC"===i?a.shape[2]:a.shape[3])*s,c=("NHWC"===i?a.shape[3]:a.shape[1])/(s*s),d=new oC("NHWC"===i?[o,u,l,c]:[o,c,u,l],s,i);return n.runWebGLProgram(d,[a],a.dtype)}};class lC{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=NS(this.outputShape.length);const s=e.filterHeight,i=e.filterWidth,o=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 / ${o};\n        int q = d2 - d1 * ${o};\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 < ${i}; 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 cC{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=NS(this.outputShape.length);const s=e.outChannels/e.inChannels,i=e.padInfo.left,o=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 g=0;g<c;g++)p+=`\n          vec4 xTexelC${2*g};\n          int xTexelC${2*g}Ready;\n          vec4 xTexelC${2*g+1};\n          int xTexelC${2*g+1}Ready;\n          vec4 xC${g};`;p+=`\n    for (int r = 0; r < ${l}; r++) {\n      `;for(let g=0;g<c;g++)p+=`\n          xTexelC${2*g} = vec4(0.0);\n          xTexelC${2*g}Ready = 0;\n          xTexelC${2*g+1} = vec4(0.0);\n          xTexelC${2*g+1}Ready = 0;\n          xC${g} = 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 e=2*g;if(p+=`\n          xC = xCCorner + ${e*u};\n          `,1===o){if(e<c&&(i%2===1?(p+=`\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              `,p+=1===u&&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                  `):p+=`\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<c)){const t=i%2===0?D.ZSL.nearestLargerEven(u):u;u%2===0&&i%2===1||u%2!==0&&i%2!==1?(p+=`\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                  `,p+=u>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                    `):p+=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<c&&(i%2===1?(p+=`\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<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${e+1} = vec4(xTexelC${e+1}.xy, final.xy);\n                `)):(p+=`\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<c&&(p+=`\n                  xC${e+1} = vec4(xTexelC${e}.zw, xTexelC${e+1}.zw);\n                `)));e<c&&(p+=`\n            wTexel = getW(r, ${e}, d1, q);\n            dotProd += xC${e} * vec4(wTexel.xz, wTexel.xz);\n          `,e+1<c&&(p+=`\n              wTexel = getW(r, ${e+1}, d1, q);\n              dotProd += xC${e+1} * vec4(wTexel.xz, wTexel.xz);\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 d1 = d2 / ${s};\n        int q = d2 - d1 * ${s};\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    `}}const dC={kernelName:D.tGH,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:u,dimRoundingMode:l}=r;let c=u;null==c&&(c=[1,1]),D.ZSL.assert(D.C0T.eitherStridesOrDilationsAreOne(i,c),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`));const d=D.C0T.computeConv2DInfo(a.shape,s.shape,i,c,o,l,!0);let p;p=(0,D._K2)().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels===1?new cC(d):new lC(d);const h=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return n.runWebGLProgram(p,[a,s],"float32",h)}};class pC{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 hC{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,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`\n      const ivec2 pads = ivec2(${s}, ${i});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        float dotProd = 0.0;\n\n        for (int wR = 0; wR < ${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 < ${o}; dm++) {\n              int d2 = d1 * ${o} + 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 fC={kernelName:D.X$8,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,filterShape:c}=r,d=D.C0T.computeConv2DInfo(a.shape,c,i,o,u,l,!0),p=new pC(d);return n.runWebGLProgram(p,[a,s],"float32")}};const mC={kernelName:D.nVu,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{strides:i,dilations:o,pad:u,dimRoundingMode:l,inputShape:c}=r,d=D.C0T.computeConv2DInfo(c,s.shape,i,o,u,l,!0),p=new hC(d);return n.runWebGLProgram(p,[a,s],"float32")}};class gC{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 yC={kernelName:D.ORI,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=[...r.shape,...r.shape],s=D.ZSL.sizeFromShape(r.shape),i=KI({inputs:{x:r},backend:n,attrs:{shape:[s]}}),o=new gC(s),u=n.runWebGLProgram(o,[i],i.dtype),l=KI({inputs:{x:u},backend:n,attrs:{shape:a}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),l}};class bC{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:r,strideHeight:a,strideWidth:s,filterHeight:i,filterWidth:o,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 < ${i}; h++) {\n          int hIn = hBeg + h * ${u};\n\n          if (hIn >= 0 && hIn < ${t}) {\n            for (int w = 0; w < ${o}; 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 xC={kernelName:D.jxD,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:u}=r,l=D.C0T.computeDilation2DInfo(a.shape,s.shape,i,o,"NHWC",u);let c;const d=new bC(l);c=n.runWebGLProgram(d,[a,s],"float32");const p=KI({inputs:{x:c},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(c),p}};const wC={kernelName:D.Qgm,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{equation:a}=r,s=t,{allDims:i,summedDims:o,idDims:u}=D.C0T.decodeEinsumEquation(a,s.length);D.C0T.checkEinsumDimSizes(i.length,u,s);const{path:l,steps:c}=D.C0T.getEinsumComputePath(o,u),d=c.length;let p=null,h=i.length;const f=[];for(let m=0;m<d;++m){for(const e of c[m]){const{permutationIndices:t,expandDims:r}=D.C0T.getEinsumPermutation(h,u[e]);let a;D.C0T.isIdentityPermutation(t)?a=s[e]:(a=sT({inputs:{x:s[e]},backend:n,attrs:{perm:t}}),f.push(a));const i=a.shape.slice();for(let e=0;e<r.length;++e)i.splice(r[e],0,1);D.ZSL.arraysEqual(a.shape,i)||(a=KI({inputs:{x:a},backend:n,attrs:{shape:i}}),f.push(a)),null===p?p=a:(p=qI({inputs:{a:a,b:p},backend:n}),f.push(p))}m<d-1&&(l[m]>=0&&(p=rT({inputs:{x:p},backend:n,attrs:{axis:l[m]-(i.length-h),keepDims:!1}}),f.push(p)),h--)}for(const m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}},vC=PI({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"}),kC={kernelName:D.Pah,backendName:"webgl",kernelFunc:vC},SC={kernelName:D.rsH,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:r,y:a}=t,s=(0,D._K2)().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new $I("\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 II("return (b >= 0.0) ? a : a * (b + 1.0);",r.shape,a.shape);return n.runWebGLProgram(s,[r,a],r.dtype)}},_C=BI({opSnippet:"return float(a == b);",packedOpSnippet:"\n  return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:h_}),IC={kernelName:D.BRl,backendName:"webgl",kernelFunc:_C},TC=PI({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 = ${D.C0T.ERF_P};\n  float a1 = ${D.C0T.ERF_A1};\n  float a2 = ${D.C0T.ERF_A2};\n  float a3 = ${D.C0T.ERF_A3};\n  float a4 = ${D.C0T.ERF_A4};\n  float a5 = ${D.C0T.ERF_A5};\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`}),$C={kernelName:D._s9,backendName:"webgl",kernelFunc:TC},CC=PI({opSnippet:LI+"\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:f_,dtype:"float32"}),NC={kernelName:D.ox3,backendName:"webgl",kernelFunc:CC};function EC(e){const{inputs:t,attrs:n,backend:r}=e,{dim:a}=n,{input:s}=t,i=s.shape.length,o=s.shape.slice();let u=a;return a<0&&(D.ZSL.assert(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),u=i+a+1),o.splice(u,0,1),KI({inputs:{x:s},backend:r,attrs:{shape:o}})}const AC={kernelName:D.ybN,backendName:"webgl",kernelFunc:EC},RC="return exp(x) - 1.0;",DC=PI({opSnippet:RC,packedOpSnippet:RC,cpuKernelImpl:m_}),FC={kernelName:D.ybj,backendName:"webgl",kernelFunc:DC};class MC{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 i;if("real"===e)i="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);i="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        ${i}\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 OC(e,t,n){const r=n.texData.get(e.dataId),a=D.ZSL.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=KI({inputs:{x:e},backend:n,attrs:{shape:[a/s,s]}}),o=i.shape,u=new MC("real",o,t),l=new MC("imag",o,t),c=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:o},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:o}],d=n.runWebGLProgram(u,c,"float32"),p=n.runWebGLProgram(l,c,"float32"),h=EI({inputs:{real:d,imag:p},backend:n});n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p);const f=KI({inputs:{x:h},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(h),f}const zC={kernelName:D.rGP,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return OC(r,!1,n)}};class LC{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 PC(e){const{backend:t,attrs:n}=e,{shape:r,value:a}=n;let{dtype:s}=n;if(s=s||D.ZSL.inferDtype(a),"string"===s){const e=D.ZSL.getArrayFromDType(s,D.ZSL.sizeFromShape(r));return e.fill(a),t.makeTensorInfo(r,s,e)}{const e=new LC(r,a),n=[[a]];return t.runWebGLProgram(e,[],s,n)}}const BC={kernelName:D.SQl,backendName:"webgl",kernelFunc:PC};class WC{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 VC={kernelName:D.BxF,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,r=t,a=new WC(n.shape);return r.runWebGLProgram(a,[n],n.dtype)}},UC="return floor(x);",GC=PI({opSnippet:UC,packedOpSnippet:UC,cpuKernelImpl:g_}),HC={kernelName:D.ZgB,backendName:"webgl",kernelFunc:GC},jC=BI({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"}),qC={kernelName:D.ElG,backendName:"webgl",kernelFunc:jC};class ZC{constructor(e){this.variableNames=["A"];const t=iS(),[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 KC{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=iS(),[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 YC={kernelName:D.awo,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:a}=t;const{numChannels:s}=r,i="undefined"!==typeof HTMLVideoElement&&a instanceof HTMLVideoElement,o="undefined"!==typeof HTMLImageElement&&a instanceof HTMLImageElement,[u,l]=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=[l,u],d=[l,u,s];if(o||i){const e=(0,D._K2)().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=QC&&e===XC||(XC=e,QC=document.createElement("canvas").getContext("2d",{willReadFrequently:XC})),QC.canvas.width=u,QC.canvas.height=l,QC.drawImage(a,0,0,u,l),a=QC.canvas}const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=tk.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),a);const h=(0,D._K2)().getBool("WEBGL_PACK")?new KC(d):new ZC(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}};let QC,XC=(0,D._K2)().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const JC={kernelName:D.aAr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=D.C0T.convertConv2DDataFormat(c),g=D.C0T.computeConv2DInfo(a.shape,s.shape,u,d,l,p,!1,m);let y;const b=[],x=null!=i,w=null!=o,v="leakyrelu"===h,k=()=>{const e=[a,s],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=KI({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(x&&e.push(t(i,c)),w&&e.push(t(o,c)),v){const t=n.makeTensorInfo([],"float32",D.ZSL.createScalarValue(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&&(0,D._K2)().getBool("WEBGL_EXP_CONV")){const e=h?WI(h,!0):null,t=new A$(g,x,e,w,v),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((0,D._K2)().getBool("WEBGL_CONV_IM2COL"))y=M$({x:a,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:f});else{const e=h?WI(h,!1):null,t=new N$(g,x,e,w,v),r=k();y=n.runWebGLProgram(t,r,"float32")}else y=F$({x:a,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:f});const S=KI({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),S}};const eN={kernelName:D.T7M,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dilations:c,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=r,f=[];let m=c;null==m&&(m=[1,1]),D.ZSL.assert(D.C0T.eitherStridesOrDilationsAreOne(u,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${m}'`));const g=D.C0T.computeConv2DInfo(a.shape,s.shape,u,m,l,d,!0),y=(0,D._K2)().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,b=p?WI(p,y):null,x=[a,s],w=null!=i,v=null!=o,k="leakyrelu"===p;if(w&&x.push(i),v&&x.push(o),k){const e=n.makeTensorInfo([],"float32",D.ZSL.createScalarValue(h,"float32"));x.push(e),f.push(e)}let S;S=y?new cC(g,w,b,v,k):new lC(g,w,b,v,k);const _=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],I=n.runWebGLProgram(S,x,"float32",_);return f.forEach((e=>n.disposeIntermediateTensorInfo(e))),I}};class tN{constructor(e,t,n,r){this.sliceDim=e,this.strides=t,this.paramsShape=r,this.variableNames=["x","indices"],this.outputShape=n;const a=SS(n.length);let s="\n    int index;";for(let i=0;i<this.sliceDim;i++)s+=`\n          index = round(getIndices(coords[0], ${i}));\n          out_of_bounds = out_of_bounds || index < 0;\n          out_of_bounds = out_of_bounds || index >= ${this.paramsShape[i]};\n          flattenIndex += index * ${this.strides[i]};`;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 nN={kernelName:D.O4G,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:a}=t,s=a.shape,i=s[s.length-1],o=D.ZSL.sizeFromShape(r.shape),[u,l,c,d]=D.C0T.prepareAndValidate(r,a),p=KI({inputs:{x:a},backend:n,attrs:{shape:[l,i]}}),h=KI({inputs:{x:r},backend:n,attrs:{shape:[D.ZSL.sizeFromShape(r.shape)/c,c]}});if(n.shouldExecuteOnCPU([r,a])||"string"===r.dtype){const e=n.readSync(a.dataId),t=n.bufferSync(r),s=y_(e,t,r.dtype,l,i,c,d,r.shape,o);return n.makeTensorInfo(u,r.dtype,s.values)}const f=new tN(i,d,[l,c],r.shape),m=n.runWebGLProgram(f,[h,p],h.dtype),g=KI({inputs:{x:m},backend:n,attrs:{shape:u}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}};class rN{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=SS(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 aN(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=r,u=D.ZSL.parseAxisParam(i,a.shape)[0];if((0,D._K2)().get("DEBUG")){const e=n.readSync(s.dataId),t=a.shape[u];for(let n=0;n<e.length;++n){const r=e[n];D.ZSL.assert(r<=t-1&&r>=0,(()=>`GatherV2: the index value ${r} is not in [0, ${t-1}]`))}}const l=D.C0T.segment_util.collectGatherOpShapeInfo(a,s,u,o),c=D.ZSL.sizeFromShape(s.shape),d=[],p=KI({inputs:{x:a},backend:n,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),h=KI({inputs:{x:s},backend:n,attrs:{shape:[l.batchSize,c/l.batchSize]}});d.push(p),d.push(h);const f=[l.batchSize,l.outerSize,c/l.batchSize,l.sliceSize];if(n.shouldExecuteOnCPU([a,s])||"string"===a.dtype){const e=n.bufferSync(h),t=n.bufferSync(p),r=b_(t,e,f);return d.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(l.outputShape,r.dtype,r.values)}const m=new rN(p.shape,f),g=n.runWebGLProgram(m,[p,h],p.dtype);d.push(g);const y=KI({inputs:{x:g},backend:n,attrs:{shape:l.outputShape}});return d.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}const sN={kernelName:D.mxL,backendName:"webgl",kernelFunc:aN},iN=BI({opSnippet:"return float(a > b);",packedOpSnippet:"\n  return vec4(greaterThan(a, b));\n",cpuKernelImpl:x_,dtype:"bool"}),oN={kernelName:D.XhZ,backendName:"webgl",kernelFunc:iN},uN=BI({opSnippet:"return float(a >= b);",packedOpSnippet:"\n  return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:w_}),lN={kernelName:D.lLS,backendName:"webgl",kernelFunc:uN};const cN={kernelName:D.OAQ,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return OC(r,!0,n)}},dN=PI({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),pN={kernelName:D.gIW,backendName:"webgl",kernelFunc:dN},hN=PI({opSnippet:"return float(isinf(x));",dtype:"bool"}),fN={kernelName:D.E3$,backendName:"webgl",kernelFunc:hN},mN=PI({opSnippet:"return float(isnan(x));",dtype:"bool"}),gN={kernelName:D.iPs,backendName:"webgl",kernelFunc:mN},yN=BI({opSnippet:"return float(a < b);",packedOpSnippet:"\n  return vec4(lessThan(a, b));\n",cpuKernelImpl:v_,dtype:"bool"}),bN={kernelName:D.mIA,backendName:"webgl",kernelFunc:yN},xN=BI({opSnippet:"return float(a <= b);",packedOpSnippet:"\n  return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:k_,dtype:"bool"}),wN={kernelName:D.CwD,backendName:"webgl",kernelFunc:xN};const vN={kernelName:D.mnI,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,num:s}=n,i=S_(r,a,s);return t.makeTensorInfo([i.length],"float32",i)}},kN=PI({opSnippet:LI+"\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:__}),SN={kernelName:D.tG8,backendName:"webgl",kernelFunc:kN},_N=PI({opSnippet:LI+"\n  return log(1.0 + x);\n"}),IN={kernelName:D.Cg$,backendName:"webgl",kernelFunc:_N},TN=BI({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"}),$N={kernelName:D.RUm,backendName:"webgl",kernelFunc:TN},CN=PI({opSnippet:"return float(!(x >= 1.0));"}),NN={kernelName:D.nZd,backendName:"webgl",kernelFunc:CN},EN=BI({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"}),AN={kernelName:D.LXA,backendName:"webgl",kernelFunc:EN};class RN{constructor(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[];const s=t,i=e[3]-1;let o;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;o=.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 <=  ${i}) {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * ${o};\n        setOutput(val);\n      }\n    `}}class DN{constructor(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const s=t,i=e[3]-1;let o;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;o=.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(${i}));\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 * ${o};\n        setOutput(result);\n      }\n    `}}const FN={kernelName:D.jM4,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:u}=r,l=(0,D._K2)().getBool("WEBGL_PACK_NORMALIZATION")?new DN(a.shape,s,i,o,u):new RN(a.shape,s,i,o,u);return n.runWebGLProgram(l,[a],a.dtype)}};class MN{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 ON={kernelName:D.ToN,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:u,alpha:l,beta:c}=r,d=new MN(a.shape,o,u,l,c);return n.runWebGLProgram(d,[a,s,i],a.dtype)}};function zN(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=r,o=a.shape.length,u=D.ZSL.parseAxisParam(s,a.shape);let l=u;const c=D.C0T.getAxesPermutation(l,o),d=null!=c,p=n.shouldExecuteOnCPU([a]);let h=a;if(d){if(p){const e=n.texData.get(h.dataId).values,t=new Array(o);for(let n=0;n<t.length;n++)t[n]=a.shape[c[n]];const r=J_(e,a.shape,a.dtype,c,t);h=n.makeTensorInfo(t,a.dtype);n.texData.get(h.dataId).values=r}else h=nT(a,c,n);l=D.C0T.getInnerMostAxes(l.length,o)}D.C0T.assertAxesAreInnerMostDims("max",l,o);const[f,m]=D.C0T.computeOutAndReduceShapes(h.shape,l);let g,y=f;if(i&&(y=D.C0T.expandShapeToKeepDim(f,u)),p){const e=n.texData.get(h.dataId).values,t=I_(e,D.ZSL.sizeFromShape(m),y,a.dtype);g=n.makeTensorInfo(y,a.dtype);n.texData.get(g.dataId).values=t}else g=function(e,t,n,r){const a=D.ZSL.sizeFromShape(t),s=KI({inputs:{x:e},attrs:{shape:[D.ZSL.sizeFromShape(e.shape)/a,a]},backend:r}),i=JI(s,e.dtype,"max",r),o=KI({inputs:{x:i},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),o}(h,m,y,n);return d&&n.disposeIntermediateTensorInfo(h),g}const LN={kernelName:D.VAI,backendName:"webgl",kernelFunc:zN},PN=BI({opSnippet:_I+"\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  "+TI+"\n  return result;\n",cpuKernelImpl:T_}),BN={kernelName:D.LDN,backendName:"webgl",kernelFunc:PN};const WN={kernelName:D.t3d,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;aS(a,"maxPool");const{filterSize:s,strides:i,pad:o,dimRoundingMode:u}=r;D.ZSL.assert(D.C0T.eitherStridesOrDilationsAreOne(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const l=D.C0T.computePool2DInfo(a.shape,s,i,1,o,u);if(1===l.filterWidth&&1===l.filterHeight&&D.ZSL.arraysEqual(l.inShape,l.outShape))return CI({inputs:{x:a},backend:n});const c=new BT(l,"max",!1);return n.runWebGLProgram(c,[a],a.dtype)}};const VN={kernelName:D.ySp,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dataFormat:u,dimRoundingMode:l}=r,c=D.C0T.computePool3DInfo(a.shape,s,i,[1,1,1],o,l,u),d=new WT(c,"max",!1);return n.runWebGLProgram(d,[a],a.dtype)}};class UN{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,i=a-1-e.padInfo.top,o=s-1-e.padInfo.left,u=a*s-1;this.userCode=`\n      const ivec2 pads = ivec2(${i}, ${o});\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 GN{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,i=e.dilationWidth,o=e.effectiveFilterDepth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=o-1-e.padInfo.front,d=u-1-e.padInfo.top,p=l-1-e.padInfo.left,h=o*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 < ${o};\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 += ${i}) {\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 HN={kernelName:D.cHb,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,i=s,{filterSize:o,strides:u,pad:l,dimRoundingMode:c}=r,d=D.C0T.computePool3DInfo(i.shape,o,u,[1,1,1],l,c),p=new WT(d,"max",!0),h=n.runWebGLProgram(p,[i],i.dtype),f=new GN(d),m=n.runWebGLProgram(f,[a,h],i.dtype);return n.disposeIntermediateTensorInfo(h),m}};const jN={kernelName:D.RXX,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s,output:i}=t,o=s;aS([s,i],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:d}=r,p=D.C0T.computePool2DInfo(o.shape,u,l,1,c,d),h=new BT(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new UN(p),g=n.runWebGLProgram(m,[a,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}};const qN={kernelName:D.TL8,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:a,strides:s,pad:i,includeBatchInIndex:o}=t,u=n;D.ZSL.assert(4===r.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`));const l=[1,1];D.ZSL.assert(D.C0T.eitherStridesOrDilationsAreOne(s,l),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${l}'`));const c=D.C0T.computePool2DInfo(r.shape,a,s,l,i),[d,p]=function(e,t,n,r){let a=new BT(n,"max",!1);const s=r.runWebGLProgram(a,[e],"float32");return a=new BT(n,"max",!0,!0,t),[s,r.runWebGLProgram(a,[e],"float32")]}(r,o,c,u);return[d,p]}};const ZN={kernelName:D.g5A,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{keepDims:a,axis:s}=t,i=n,o=r.shape.length,u=D.ZSL.parseAxisParam(s,r.shape);let l=u;const c=D.C0T.getAxesPermutation(l,o),d=null!=c,p=i.shouldExecuteOnCPU([r]),h=[];let f=r;if(d){if(p){const e=i.texData.get(f.dataId).values,t=new Array(o);for(let a=0;a<t.length;a++)t[a]=r.shape[c[a]];const n=J_(e,r.shape,r.dtype,c,t);f=i.makeTensorInfo(t,r.dtype);i.texData.get(f.dataId).values=n}else f=nT(r,c,i);h.push(f),l=D.C0T.getInnerMostAxes(l.length,o)}D.C0T.assertAxesAreInnerMostDims("sum",l,o);const[m,g]=D.C0T.computeOutAndReduceShapes(f.shape,l);let y=m;a&&(y=D.C0T.expandShapeToKeepDim(m,u));const b=function(e,t,n,r){const a=D.ZSL.sizeFromShape(t),s=KI({inputs:{x:e},attrs:{shape:[D.ZSL.sizeFromShape(e.shape)/a,a]},backend:r}),i=JI(s,"float32","mean",r),o=KI({inputs:{x:i},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),o}(f,g,y,i);for(const x of h)i.disposeIntermediateTensorInfo(x);return b}};const KN={kernelName:D.lNG,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r,o=a.shape.length,u=D.ZSL.parseAxisParam(s,a.shape);let l=u;const c=D.C0T.getAxesPermutation(l,o);let d=a;null!=c&&(d=sT({inputs:{x:a},backend:n,attrs:{perm:c}}),l=D.C0T.getInnerMostAxes(l.length,a.shape.length)),D.C0T.assertAxesAreInnerMostDims("min",l,o);const[p,h]=D.C0T.computeOutAndReduceShapes(d.shape,l),f=KI({inputs:{x:d},backend:n,attrs:{shape:[-1,D.ZSL.sizeFromShape(h)]}}),m=JI(f,f.dtype,"min",n);let g;if(i){g=KI({inputs:{x:m},backend:n,attrs:{shape:D.C0T.expandShapeToKeepDim(p,u)}})}else g=KI({inputs:{x:m},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(d),g}},YN=BI({opSnippet:_I+"\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  "+TI+"\n  return result;\n",cpuKernelImpl:$_}),QN={kernelName:D.LG0,backendName:"webgl",kernelFunc:YN};class XN{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,a=SS(r),s=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["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}(${i});\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(${o}));\n      }\n    `:`\n        int start = ${s};\n        int end = ${i};\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 JN{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=SS(r),s=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=nI("rc",r),u=nI("source",r),l=`${o[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        ${o[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        ${o[r-1]} += 1;\n        if(${l}) {\n          ${e}\n          result[1] = getChannel(getX(${u.join()}), ${c});\n        }\n        rc = outputLoc;\n        ${o[r-2]} += 1;\n        if(${o[r-2]} < ${this.outputShape[r-2]}) {\n          ${e}\n          result[2] = getChannel(getX(${u.join()}), ${c});\n          ${o[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}(${i});\n\n      void main() {\n        ${a} outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ${p}\n        setOutput(result);\n      }\n    `}}const eE={kernelName:D.x7F,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r}=e,{paddings:a,mode:s}=n,i=(0,D._K2)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new JN(r.shape,a,s):new XN(r.shape,a,s);return t.runWebGLProgram(i,[r],r.dtype)}},tE=BI({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  "+TI+"\n  return result;\n"}),nE={kernelName:D.BLA,backendName:"webgl",kernelFunc:tE};class rE{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 aE=BI({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}),sE={kernelName:D.sDr,backendName:"webgl",kernelFunc:aE},iE="return a - b;",oE=BI({opSnippet:iE,packedOpSnippet:iE,supportsComplex:!0,cpuKernelImpl:Y_}),uE={kernelName:D.PbM,backendName:"webgl",kernelFunc:oE};function lE(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,i=D.ZSL.parseAxisParam([s],a.shape),o=zN({inputs:{x:a},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),u=D.C0T.expandShapeToKeepDim(o.shape,i),l=KI({inputs:{x:o},backend:n,attrs:{shape:u}}),c=oE({inputs:{a:a,b:l},backend:n}),d=CC({inputs:{x:c},backend:n}),p=rT({inputs:{x:d},backend:n,attrs:{axis:i,keepDims:!1}}),h=KI({inputs:{x:p},backend:n,attrs:{shape:u}}),f=aE({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}const cE={kernelName:D.rFG,backendName:"webgl",kernelFunc:lE};const dE={kernelName:D.WT3,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=r,u=o?a:lE({inputs:{logits:a},backend:n,attrs:{dim:a.shape.length-1}}),l=u.shape[0],c=u.shape[1],d=new rE(l,c,s),p=[[i]],h=n.runWebGLProgram(d,[u],"int32",p);return o||n.disposeIntermediateTensorInfo(u),h}},pE=cI+"\n  return -x;\n";const hE={kernelName:D.l0G,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]=N_(e.values,r.shape,r.dtype);return n.makeTensorInfo(a,r.dtype,t)}let a;return a=(0,D._K2)().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new mI(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 lI(r.shape,pE),n.runWebGLProgram(a,[r],r.dtype)}},fE=D.kpo.nonMaxSuppressionV3Impl;const mE={kernelName:D.SDM,backendName:"webgl",kernelFunc:function(e){D.C0T.warn("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:i,iouThreshold:o,scoreThreshold:u}=r,l=n.readSync(a.dataId),c=n.readSync(s.dataId),{selectedIndices:d}=fE(l,c,i,o,u);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}},gE=D.kpo.nonMaxSuppressionV4Impl;const yE={kernelName:D.Zl4,backendName:"webgl",kernelFunc:function(e){D.C0T.warn("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:i,iouThreshold:o,scoreThreshold:u,padToMaxOutputSize:l}=r,c=n.readSync(a.dataId),d=n.readSync(s.dataId),{selectedIndices:p,validOutputs:h}=gE(c,d,i,o,u,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}},bE=D.kpo.nonMaxSuppressionV5Impl;const xE={kernelName:D.e0f,backendName:"webgl",kernelFunc:function(e){D.C0T.warn("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:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=r,c=n.readSync(a.dataId),d=n.readSync(s.dataId),p=i,h=o,f=u,m=l,{selectedIndices:g,selectedScores:y}=bE(c,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class wE{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 vE={kernelName:D.urI,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{dtype:s,depth:i,onValue:o,offValue:u}=r,l=D.ZSL.sizeFromShape(a.shape),c=new wE(l,i,o,u),d=KI({inputs:{x:a},backend:n,attrs:{shape:[l]}}),p=n.runWebGLProgram(c,[d],s);n.disposeIntermediateTensorInfo(d);const h=KI({inputs:{x:p},backend:n,attrs:{shape:[...a.shape,i]}});return n.disposeIntermediateTensorInfo(p),h}};function kE(e){const{inputs:t,backend:n}=e,{x:r}=t;if("complex64"===r.dtype){const e=l$({inputs:{input:r},backend:n}),t=kE({inputs:{x:e},backend:n}),a=_$({inputs:{input:r},backend:n}),s=kE({inputs:{x:a},backend:n}),i=EI({inputs:{real:t,imag:s},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(s),i}return PC({attrs:{shape:r.shape,dtype:r.dtype,value:"string"===r.dtype?"":0},backend:n})}const SE={kernelName:D.xJ3,backendName:"webgl",kernelFunc:kE};const _E={kernelName:D.LWX,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=l$({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r}),s=_$({inputs:{input:a},backend:r}),i=kE({inputs:{x:s},backend:r}),o=EI({inputs:{real:n,imag:i},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),o}return PC({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:r})}};const IE={kernelName:D.mM$,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return EC({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,i=t[0].dtype;t.forEach((e=>{D.ZSL.assertShapesMatch(s,e.shape,"All tensors passed to stack must have matching shapes"),D.ZSL.assert(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],u=$$({inputs:t.map((e=>{const t=EC({inputs:{input:e},backend:n,attrs:{dim:a}});return o.push(t),t})),backend:n,attrs:{axis:a}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),u}};class TE{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=SS(r),s=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n      ${a} start = ${a}(${s});\n      ${a} end = ${a}(${i});\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(${o}));\n        }\n      }\n    `:`\n        int start = ${s};\n        int end = ${i};\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 $E{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=SS(r),s=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=nI("rc",r),u=nI("source",r),l=`${o[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,d=[`${a} rc = outputLoc;`,`${o[r-1]} += 1;\n       if(${l}) {\n      `,1===r?"":`}\n       rc = outputLoc;\n       ${o[r-2]} += 1;\n       if(${o[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":`  ${o[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}(${i});\n\n      void main() {\n        ${a} outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ${h}\n        setOutput(result);\n      }\n    `}}const CE=e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:i}=r;if(0===D.ZSL.sizeFromShape(a.shape)){const e=s.map(((e,t)=>e[0]+a.shape[t]+e[1]));return PC({backend:n,attrs:{shape:e,value:i,dtype:a.dtype}})}const o=(0,D._K2)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new $E(a.shape,s,i):new TE(a.shape,s,i),u=[[i]];return n.runWebGLProgram(o,[a],a.dtype,u)},NE={kernelName:D.ODT,backendName:"webgl",kernelFunc:CE},EE=BI({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  "+TI+"\n  return result;\n"}),AE={kernelName:D.pyJ,backendName:"webgl",kernelFunc:EE};const RE={kernelName:D.kdj,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:i}=r,o=a.shape.length,u=[],l=D.ZSL.parseAxisParam(s,a.shape);let c=l;const d=D.C0T.getAxesPermutation(c,o);let p,h=a;if(null!=d&&(h=sT({inputs:{x:a},backend:n,attrs:{perm:d}}),c=D.C0T.getInnerMostAxes(c.length,o),u.push(h)),D.C0T.assertAxesAreInnerMostDims("prod",c,o),n.shouldExecuteOnCPU([h])){const e=n.texData.get(h.dataId).values,{outVals:t,outShape:r,outDtype:a}=A_(h.shape,h.dtype,e,c);p=n.makeTensorInfo(r,a,t)}else{const[e,t]=D.C0T.computeOutAndReduceShapes(h.shape,c),r=D.ZSL.sizeFromShape(t),s=KI({inputs:{x:h},backend:n,attrs:{shape:[-1,r]}}),i=JI(s,(0,D.chL)(a.dtype),"prod",n);p=KI({inputs:{x:i},backend:n,attrs:{shape:e}}),u.push(s),u.push(i)}if(i){u.push(p);const e=D.C0T.expandShapeToKeepDim(p.shape,l);p=KI({inputs:{x:p},backend:n,attrs:{shape:e}})}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}};const DE={kernelName:D.oJ2,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:a,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=r,u=a.map((e=>n.readSync(e.dataId))),l=a.map((e=>e.shape)),c=n.readSync(s.dataId),d=n.readSync(i.dataId),[p,h,f]=R_(u,l,c,s.shape,s.dtype,d,i.shape,o),m=p.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,s.dtype,h);return m.concat([g])}};const FE={kernelName:D.CQC,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:r,limits:a,deltas:s}=t,i=n.readSync(r.dataId),o=n.readSync(a.dataId),u=n.readSync(s.dataId),[l,c]=D_(i,r.shape,r.dtype,o,a.shape,u,s.shape);return[n.makeTensorInfo([l.length],"int32",l),n.makeTensorInfo([c.length],r.dtype,c)]}};const ME={kernelName:D.mH5,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{shape:a,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:u}=r,l=n.readSync(a.dataId),c=n.readSync(s.dataId),d=n.readSync(i.dataId),p=o.map((e=>n.readSync(e.dataId))),h=o.map((e=>e.shape)),[f,m]=F_(l,a.shape,c,s.shape,s.dtype,d,i.shape,p,h,u);return n.makeTensorInfo(f,s.dtype,m)}},OE=e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:s,dtype:i}=n,o=M_(r,a,s,i);return t.makeTensorInfo([o.length],i,o)},zE={kernelName:D.Q6t,backendName:"webgl",kernelFunc:OE},LE=PI({opSnippet:"return 1.0 / x;"}),PE={kernelName:D.huO,backendName:"webgl",kernelFunc:LE},BE=PI({opSnippet:cI+"\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"}),WE={kernelName:D.fUj,backendName:"webgl",kernelFunc:BE},VE=PI({opSnippet:cI+"\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"}),UE={kernelName:D.P_L,backendName:"webgl",kernelFunc:VE};class GE{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[s,i,o,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],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(${i}.0, ${o}.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 HE{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[s,i,o,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],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(${i}.0, ${o}.0,\n                                     ${o}.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 jE={kernelName:D.hgw,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=r,[u,l]=o,c=(0,D._K2)().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new HE(a.shape,u,l,s,i):new GE(a.shape,u,l,s,i);return n.runWebGLProgram(c,[a],"float32")}};class qE{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,a]=t,[,s,i]=e,o=[n&&s>1?r-1:r,n&&i>1?a-1:a],u=[n&&s>1?s-1:s,n&&i>1?i-1:i],l=o[0]/u[0],c=o[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 >= ${i}) {\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 ZE={kernelName:D.FCQ,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:i}=r,o=new qE(s.shape,a.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}};class KE{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[s,i,o,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],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(${i}.0, ${o}.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 YE{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[s,i,o,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?i-1:i,r&&n>1?o-1:o],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(${i}.0, ${o}.0,\n                                     ${o}.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 QE={kernelName:D.jOE,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=r,[u,l]=o,c=(0,D._K2)().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new YE(a.shape,u,l,s,i):new KE(a.shape,u,l,s,i);return n.runWebGLProgram(c,[a],a.dtype)}};class XE{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,a]=t,[,s,i]=e,o=[n&&s>1?r-1:r,n&&i>1?a-1:a],u=[n&&s>1?s-1:s,n&&i>1?i-1:i],l=o[0]/u[0],c=o[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 >= ${i}) {\n              continue;\n            }\n\n            float sourceFracRow =\n              float(${o[0]}) *\n                (float(dyR) / float(${u[0]}));\n\n            float sourceFracCol =\n                float(${o[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 JE={kernelName:D.XQy,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:i}=r,o=new XE(s.shape,a.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}};class eA{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=SS(n);this.userCode=`\n      void main() {\n        ${a} coords = getOutputCoords();\n        setOutput(getX(${r}));\n      }\n    `}}class tA{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=nI("rc",n),a=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,i=SS(n);function o(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          ${i} rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = ${function(e){return o(e)}(r.slice())};\n          if(${a}){\n            result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(r.slice())};\n          }\n          if(${s}) {\n            result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(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)",o(e)}(r.slice())};\n            }\n          }\n          setOutput(result);\n        }\n    `}}const nA={kernelName:D.D7i,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,i=a.shape.length,o=D.ZSL.parseAxisParam(s,a.shape);if(0===i)return CI({inputs:{x:a},backend:n});const u=(0,D._K2)().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tA(a.shape,o):new eA(a.shape,o);return n.runWebGLProgram(u,[a],a.dtype)}};class rA{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 aA={kernelName:D.BK4,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:a,fillValue:s,center:i}=t,o=n,u=new rA(r.shape,s),[l,c]=D.C0T.getImageCenter(i,r.shape[1],r.shape[2]),d=[[l,c,Math.sin(a),Math.cos(a)]];return o.runWebGLProgram(u,[r],r.dtype,d)}},sA=PI({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"}),iA={kernelName:D.hVg,backendName:"webgl",kernelFunc:sA},oA=PI({opSnippet:"return inversesqrt(x);",cpuKernelImpl:O_}),uA={kernelName:D.TOR,backendName:"webgl",kernelFunc:oA};class lA{constructor(e,t,n,r,a,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;const u=SS(a.length),l=SS(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="";o&&(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 cA{constructor(e,t,n,r,a,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s;const u=SS(a.length),l=SS(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="";o&&(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 dA={kernelName:D.pJc,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a,updates:s}=t,{shape:i}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:d}=D.C0T.calculateShapes(s,a,i),p=[d/l,l];if(0===d)return n.makeTensorInfo(i,a.dtype);const h=KI({inputs:{x:a},backend:n,attrs:{shape:[u,o]}}),f=KI({inputs:{x:s},backend:n,attrs:{shape:[u,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0]));let g;g=(0,D._K2)().getBool("WEBGL_PACK")?new cA(u,o,h.shape.length,f.shape.length,c,p):new lA(u,o,h.shape.length,f.shape.length,c,p);const y=n.runWebGLProgram(g,[f,h,m],f.dtype),b=KI({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class pA{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===(0,D._K2)().getNumber("WEBGL_VERSION")?"while (left < right) {":a,i="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) ${i} 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 hA={kernelName:D.uWl,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:a,values:s}=t,{side:i}=r,o=new pA(a.shape[0],a.shape[1],s.shape[1],i),u=[[a.shape[1]]];return n.runWebGLProgram(o,[a,s],"int32",u)}};class fA{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=[],i=[];for(let r=0;r<t.length;r++)i.push(`${n[r]}`),r<e&&s.push(`${n[r]}`);r=s.join(),a=i.join()}const s=SS(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 mA={kernelName:D.l6P,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t,i=new fA(r.shape.length,a.shape,a.shape.length);return n.runWebGLProgram(i,[r,a,s],(0,D.TuY)(a.dtype,s.dtype))}},gA=PI({opSnippet:`\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = ${D.C0T.SELU_SCALEALPHA};\n  float scale = ${D.C0T.SELU_SCALE};\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),yA={kernelName:D.u$b,backendName:"webgl",kernelFunc:gA},bA=PI({opSnippet:LI+"\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:L_}),xA={kernelName:D.vI1,backendName:"webgl",kernelFunc:bA},wA=PI({opSnippet:"\n  if (isnan(x)) { return 0.0; }\n  return sign(x);\n"}),vA={kernelName:D.YVe,backendName:"webgl",kernelFunc:wA},kA=PI({opSnippet:LI+"\n  return sin(x);\n",packedOpSnippet:`\n  vec4 result = sin(x);\n  bvec4 isNaN = isnan(x);\n  ${TI}\n  return result;\n`}),SA={kernelName:D.hql,backendName:"webgl",kernelFunc:kA},_A=PI({opSnippet:"\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n"}),IA={kernelName:D.J3C,backendName:"webgl",kernelFunc:_A},TA=PI({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"}),$A={kernelName:D.Fin,backendName:"webgl",kernelFunc:TA},CA={kernelName:D.A8B,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:i}=r;D.ZSL.assert(a.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const o=s.reduce(((e,t)=>e*t)),u=[[0,0]];u.push(...i);for(let y=1+s.length;y<a.shape.length;++y)u.push([0,0]);const l=[],c=CE({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),d=D.C0T.getReshaped(c.shape,s,o,!1),p=D.C0T.getPermuted(d.length,s.length,!1),h=D.C0T.getReshapedPermuted(c.shape,s,o,!1),f=KI({inputs:{x:c},backend:n,attrs:{shape:d}}),m=sT({inputs:{x:f},backend:n,attrs:{perm:p}}),g=KI({inputs:{x:m},backend:n,attrs:{shape:h}});return l.push(c),l.push(f),l.push(m),l.forEach((e=>n.disposeIntermediateTensorInfo(e))),g}};const NA={kernelName:D.C8s,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:r,values:a,denseShape:s,defaultValue:i}=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!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n        ${i.shape}`);const o=n.readSync(r.dataId),u=n.readSync(a.dataId),l=n.readSync(s.dataId),c=n.readSync(i.dataId)[0],[d,p,h,f,m]=W_(o,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 EA={kernelName:D.BoJ,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 i=Array.from(n.readSync(a.dataId)),o=n.readSync(r.dataId),u=Array.from(n.readSync(s.dataId)),[l,c,d]=V_(o,r.shape,r.dtype,i,u);return[n.makeTensorInfo(c,r.dtype,l),n.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}};const AA={kernelName:D.L6G,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 i=n.readSync(r.dataId),o=n.readSync(a.dataId),u=n.readSync(s.dataId),[l,c]=U_(i,r.shape,r.dtype,o,u,!0);return n.makeTensorInfo(c,r.dtype,l)}};const RA={kernelName:D.DvZ,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 i=n.readSync(r.dataId),o=n.readSync(a.dataId),u=n.readSync(s.dataId),[l,c]=U_(i,r.shape,r.dtype,o,u);return n.makeTensorInfo(c,r.dtype,l)}};const DA={kernelName:D.jgd,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:d,outputSize:p}=D.C0T.calculateShapes(s,a,o),h=!1;if("string"===s.dtype){const e=n.bufferSync(a),t=n.bufferSync(s),r=D.ZSL.decodeString(n.readSync(i.dataId)[0]),f=z_(e,t,o,p,c,l,u,d,r,h);return n.makeTensorInfo(o,f.dtype,f.values)}const f=new lA(l,u,a.shape.length,s.shape.length,d,[p,1],h),m=n.runWebGLProgram(f,[s,a,i],s.dtype),g=KI({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),g}};const FA={kernelName:D.Blb,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=r,o=D.ZSL.parseAxisParam(i,a.shape)[0],u=D.C0T.prepareSplitSize(a,s,o),l=a.shape.length,c=new Array(l).fill(0),d=a.shape.slice();return u.map((e=>{const t=[...d];t[o]=e;const r=t$({inputs:{x:a},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,r}))}},MA="return sqrt(x);",OA=PI({opSnippet:MA,packedOpSnippet:MA,cpuKernelImpl:G_}),zA={kernelName:D.dFH,backendName:"webgl",kernelFunc:OA},LA=PI({opSnippet:"return x * x;"}),PA={kernelName:D.M6A,backendName:"webgl",kernelFunc:LA},BA="return (a - b) * (a - b);",WA=BI({opSnippet:BA,packedOpSnippet:BA}),VA={kernelName:D.Ddj,backendName:"webgl",kernelFunc:WA};const UA={kernelName:D.GZp,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=n.readSync(a.dataId),i=D.C0T.fromUint8ToStringArray(s),o=H_(i,"string",r);return n.makeTensorInfo(a.shape,"string",o)}};const GA={kernelName:D.pnw,backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:r}=e,a=cI+`\n    return x > 0.0 ? 1.0 : float(${t.alpha});\n  `,s=new lI(r.shape,a);return n.runWebGLProgram(s,[r],r.dtype)}};class HA{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,a=SS(n.length),s=SS(n.length);let i="";if(1===r)i="coords * strides + begin";else{let e=0;i=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(${i}));\n      }\n    `}}const jA={kernelName:D.UcO,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:d,shrinkAxisMask:p}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:w}=D.Kro.sliceInfo(a.shape,s,i,o,u,l,c,d,p);let v;if(m)v=KI({inputs:{x:a},backend:n,attrs:{shape:f}});else if(g||y){D.ZSL.assert(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=D.Kro.computeOutShape(b,x,w),t=t$({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});v=KI({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{if(n.shouldExecuteOnCPU([a])){const e=n.readSync(a.dataId),t=(0,D.ra8)(a.shape,a.dtype,e),r=j_(h,t,w,b);v=n.makeTensorInfo(f,a.dtype,r.values)}else{const e=new HA(b,w,h);v=n.runWebGLProgram(e,[a],a.dtype)}}const k=KI({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),k}};const qA={kernelName:D.YAb,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:u,preserveShortSequences:l}=r,{data:c,dataSplits:d}=t,p=n.readSync(c.dataId),h=n.readSync(d.dataId),[f,m]=q_(p,h,a,s,i,o,u,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}};const ZA={kernelName:D.iW0,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{skipEmpty:a}=r,{input:s,delimiter:i}=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!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.readSync(s.dataId),u=n.readSync(i.dataId)[0],[l,c,d]=Z_(o,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 KA={kernelName:D.$jE,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 i=n.readSync(s.dataId),o=K_(i,a);return n.makeTensorInfo(s.shape,"int32",o)}},YA=PI({opSnippet:"return tan(x);"}),QA={kernelName:D.oFs,backendName:"webgl",kernelFunc:YA},XA=PI({opSnippet:"\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),JA={kernelName:D.iuW,backendName:"webgl",kernelFunc:XA};const eR={kernelName:D.X4r,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{tensor:a,indices:s,updates:i}=t,{}=r,{sliceRank:o,numUpdates:u,sliceSize:l,strides:c,outputSize:d}=D.C0T.calculateShapes(i,s,a.shape),p=[d/l,l];if(0===d)return n.makeTensorInfo(a.shape,s.dtype);const h=KI({inputs:{x:s},backend:n,attrs:{shape:[u,o]}}),f=KI({inputs:{x:i},backend:n,attrs:{shape:[u,l]}}),m=KI({inputs:{x:a},backend:n,attrs:{shape:p}}),g=new lA(u,o,h.shape.length,f.shape.length,c,p,!1,!0),y=n.runWebGLProgram(g,[f,h,m],m.dtype),b=KI({inputs:{x:y},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),b}};class tR{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=SS(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 nR(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=>D.ZSL.decodeString(e))):e,r=(0,D.ra8)(a.shape,a.dtype,t),i=Q_(r,s);return n.makeTensorInfo(i.shape,i.dtype,i.values)}const i=new tR(a.shape,s);return n.runWebGLProgram(i,[a],a.dtype)}const rR={kernelName:D.FAs,backendName:"webgl",kernelFunc:nR};class aR{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 sR{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 iR(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function oR(e){let t=1;for(;t<e;)t*=2;return t}const uR={kernelName:D.TBb,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{k:s,sorted:i}=r,o=(0,D._K2)().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),u=(0,D._K2)().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=a.shape,c=l[l.length-1];if(n.shouldExecuteOnCPU([a])||c<o||s>u){const e=n.readSync(a.dataId),[t,r]=X_(e,l,a.dtype,s,i);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===c)return[a,PC({attrs:{shape:l,dtype:"int32",value:0},backend:n})];const d=n.texData.get(a.dataId),p=null!==d&&d.isPacked,h=p?n.unpackTensor(a):a,f=D.ZSL.sizeFromShape(l)/c,m=KI({inputs:{x:h},attrs:{shape:[f,c]},backend:n});p&&iR(n,h);const g=oR(s),y=oR(c);let b=null;const x=()=>null===b?[m,m]:[m,b],w=(e,t,r)=>{const a=x(),s=new aR(r),i=[[c],[null===b?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=b;b=n.runWebGLProgram(s,a,"int32",i),iR(n,o)};for(let I=1;I<g;I*=2){const e=2*I;for(let t=I;t>=1;t/=2)w(e,t,[f,y])}for(let I=y;I>g;I/=2){const e=x(),t=new sR([f,I/2]),r=[[c],[null===b?1:0],[g]],a=b;b=n.runWebGLProgram(t,e,"int32",r),iR(n,a);const s=g/2,i=2*s;for(let n=s;n>=1;n/=2)w(i,n,b.shape)}let v=b;b=t$({inputs:{x:b},backend:n,attrs:{begin:0,size:[f,s]}}),iR(n,v);let k=aN({inputs:{x:m,indices:b},backend:n,attrs:{axis:1,batchDims:1}});iR(n,m);const S=l.slice(0,-1);S.push(s),v=b,b=KI({inputs:{x:b},attrs:{shape:S},backend:n}),iR(n,v);const _=k;return k=KI({inputs:{x:k},attrs:{shape:S},backend:n}),iR(n,_),[k,b]}};class lR{constructor(e,t,n,r,a,s){this.variableNames=["Image","Transforms"],this.outputShape=s;const i="nearest"===n?1:2;let o;switch(r){case"constant":default:o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4}this.userCode=`\n            float mapCoord(float outCoord, float len) {\n              float inCoord = outCoord;\n              if(${o} == 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 (${o} == 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 (${o} == 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 (${i} == 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 cR={kernelName:D.dLy,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:u,outputShape:l}=r,[c,d,p,h]=a.shape,[f,m]=null!=l?l:[d,p],g=new lR(d,p,i,o,u,[c,f,m,h]);return n.runWebGLProgram(g,[a,s],"float32")}};const dR={kernelName:D.EwU,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:s}=t;aS(s,"unique");const i=r.readSync(s.dataId),{outputValues:o,outputShape:u,indices:l}=eI(i,a,s.shape,s.dtype);return[r.makeTensorInfo(u,s.dtype,o),r.makeTensorInfo([l.length],"int32",l)]}};const pR={kernelName:D.dXR,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 i=a,o=i.shape.length,u=a.shape[s],l=new Array(o-1);let c=0;for(let m=0;m<o;m++)m!==s&&(l[c++]=i.shape[m]);const d=[],p=new Array(o).fill(0),h=i.shape.slice();h[s]=1;const f=new Array(u);for(let m=0;m<f.length;m++){p[s]=m;const e=t$({inputs:{x:i},backend:n,attrs:{begin:p,size:h}}),t=KI({inputs:{x:e},backend:n,attrs:{shape:l}});f[m]=t,d.push(e)}return d.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};class hR{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,r=e.batchSize,a=e.inSize,s=e.numSegments,i=s*Math.ceil(a/n);this.outputShape=[r,i];const o=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 < ${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          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 + ${o};\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 fR={kernelName:D.pPe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,segmentIds:s}=t,{numSegments:i}=r,o=a.shape.length,u=[];let l=0;const c=D.C0T.getAxesPermutation([l],o);let d=a;null!=c&&(d=sT({inputs:{x:a},backend:n,attrs:{perm:c}}),u.push(d),l=D.C0T.getInnerMostAxes(1,o)[0]);const p=D.C0T.segment_util.computeOutShape(d.shape,l,i),h=D.ZSL.sizeFromShape([d.shape[l]]),f=KI({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});u.push(f);const m=(0,D.chL)(a.dtype),g=(e,t,r,a,s)=>{const i=e.shape[0],o=e.shape[1],l=D.C0T.segment_util.segOpComputeOptimalWindowSize(o,s),c=new hR({windowSize:l,inSize:o,batchSize:i,numSegments:s},t),d=n.compileAndRun(c,[e,r],a);if(u.push(d),d.shape[1]===s)return d;const p=OE({backend:n,attrs:{start:0,stop:s,step:1,dtype:"float32"}}),h=nR({inputs:{x:p},backend:n,attrs:{reps:[o/l]}});u.push(p),u.push(h);return g(d,t,h,a,s)},y=KI({inputs:{x:g(f,"unsortedSegmentSum",s,m,i)},backend:n,attrs:{shape:p}});let b=y;if(null!=c){u.push(y);const e=D.C0T.getUndoAxesPermutation(c);b=sT({inputs:{x:b},backend:n,attrs:{perm:e}})}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),b}},mR=[uT,cT,pT,fT,yT,wT,vT,kT,CT,NT,AT,DT,MT,zT,PT,VT,UT,jT,qT,ZT,QT,r$,a$,s$,i$,d$,f$,y$,AI,w$,C$,O$,W$,U$,G$,H$,j$,Z$,Y$,X$,aC,sC,iC,uC,dC,fC,mC,yC,xC,wC,kC,SC,IC,$C,NC,AC,FC,zC,BC,VC,HC,qC,YC,JC,eN,nN,sN,oN,lN,NI,cN,I$,pN,fN,gN,FI,bN,wN,vN,SN,IN,$N,NN,AN,FN,ON,LN,BN,WN,VN,HN,jN,qN,ZN,KN,QN,eE,nE,dE,ZI,hE,mE,yE,xE,u$,vE,_E,IE,NE,AE,zI,RE,DE,FE,ME,zE,c$,sE,PE,WE,UE,YI,jE,ZE,QE,JE,nA,aA,iA,uA,dA,hA,mA,yA,xA,vA,SA,IA,n$,cE,$A,CA,NA,EA,AA,RA,DA,FA,zA,PA,VA,UA,GA,jA,qA,ZA,KA,uE,aT,QA,JA,eR,rR,uR,cR,iT,dR,pR,fR,SE];for(const yR of mR)(0,D.tAK)(yR);const gR={"tfjs-core":D.bgA,"tfjs-backend-cpu":Uy,"tfjs-backend-webgl":vI,"tfjs-data":ym,"tfjs-layers":Zo,"tfjs-converter":sf,tfjs:"4.22.0"}},8968:(e,t,n)=>{"use strict";n.d(t,{r:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({sigmoid_:function(e){const t={x:(0,s.YT)(e,"x","sigmoid","float32")};return r.T2.runKernel(a.vI1,t)}})},8990:(e,t,n)=>{"use strict";n.d(t,{n:()=>o});var r=n(1585),a=n(5441),s=n(565),i=n(8189);const o=(0,n(929).op)({pow_:function(e,t){let n=(0,i.YT)(e,"base","pow"),o=(0,i.YT)(t,"exp","pow");[n,o]=(0,s.makeTypesMatch)(n,o);const u={a:n,b:o};return r.T2.runKernel(a.pyJ,u)}})},8991:(e,t,n)=>{"use strict";n.d(t,{w:()=>o});var r=n(1585),a=n(5441),s=n(565),i=n(8189);const o=(0,n(929).op)({floorDiv_:function(e,t){let n=(0,i.YT)(e,"a","floorDiv"),o=(0,i.YT)(t,"b","floorDiv");[n,o]=(0,s.makeTypesMatch)(n,o);const u={a:n,b:o};return r.T2.runKernel(a.ElG,u)}})},9067:function(e,t,n){var r;!function(e,a){function s(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 i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function o(e,t){null==e&&(e=+new Date);var n=new s(e),r=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,r&&(r.x&&i(r,n),a.state=function(){return i(n,{})}),a}a&&a.exports?a.exports=o:n.amdD&&n.amdO?void 0===(r=function(){return o}.call(t,n,t,a))||(a.exports=r):this.xorshift7=o}(0,e=n.nmd(e),n.amdD)},9160:(e,t,n)=>{"use strict";n.d(t,{$:()=>u});var r=n(1585),a=n(5441),s=n(8189),i=n(5119),o=n(2302);const u=(0,n(929).op)({batchNorm_:function(e,t,n,u,l,c){null==c&&(c=.001);const d=(0,s.YT)(e,"x","batchNorm"),p=(0,s.YT)(t,"mean","batchNorm"),h=(0,s.YT)(n,"variance","batchNorm");let f,m;null!=l&&(f=(0,s.YT)(l,"scale","batchNorm")),null!=u&&(m=(0,s.YT)(u,"offset","batchNorm")),i.vA(p.rank===h.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),i.vA(null==m||p.rank===m.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),i.vA(null==f||p.rank===f.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const g={x:function(e){let t;return t=0===e.rank||1===e.rank?(0,o.t)(e,[1,1,1,e.size]):2===e.rank?(0,o.t)(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?(0,o.t)(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(d),scale:f,offset:m,mean:p,variance:h},y={varianceEpsilon:c},b=r.T2.runKernel(a.i5R,g,y);return(0,o.t)(b,d.shape)}})},9171:(e,t,n)=>{"use strict";n.d(t,{Q:()=>o});var r=n(1585),a=n(2046),s=n(5119),i=n(3879);function o(e,t,n,o){if(null==o)o=(0,s.X$)(e);else if("complex64"===o)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if((0,a.Nw)(e)||(0,a.Oj)(e)){if("float32"!==o&&"int32"!==o)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${o}.`);return r.T2.backend.createTensorFromGPUData(e,t||n,o)}if(!(0,i.isTypedArray)(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){(0,s.SA)(t);const e=(0,s.Ze)(t),r=(0,s.Ze)(n);(0,s.vA)(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!==(0,s.Ze)(t.slice(a));(0,s.vA)(n[a]===t[a]||!r,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return(0,i.isTypedArray)(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==o?(0,i.toTypedArray)(e,o):(0,i.flatten)(e,[],!0),r.T2.makeTensor(e,t,o)}},9258:(e,t,n)=>{"use strict";n.d(t,{l:()=>o});var r=n(1585),a=n(5441),s=n(565),i=n(8189);const o=(0,n(929).op)({mul_:function(e,t){let n=(0,i.YT)(e,"a","mul"),o=(0,i.YT)(t,"b","mul");[n,o]=(0,s.makeTypesMatch)(n,o);const u={a:n,b:o};return r.T2.runKernel(a.xu7,u)}})},9326:(e,t,n)=>{"use strict";n.d(t,{b:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({any_:function(e,t=null,n=!1){const i={x:(0,s.YT)(e,"x","any","bool")},o={axis:t,keepDims:n};return r.T2.runKernel(a.FSt,i,o)}})},9348:(e,t,n)=>{"use strict";n.d(t,{R:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({sqrt_:function(e){const t={x:(0,s.YT)(e,"x","sqrt","float32")};return r.T2.runKernel(a.dFH,t)}})},9359:(e,t,n)=>{"use strict";n.d(t,{y:()=>u});var r=n(1585),a=n(5441),s=n(565),i=n(8189),o=n(8991);const u=(0,n(929).op)({div_:function(e,t){let n=(0,i.YT)(e,"a","div"),u=(0,i.YT)(t,"b","div");if([n,u]=(0,s.makeTypesMatch)(n,u),"int32"===n.dtype&&"int32"===u.dtype)return(0,o.w)(n,u);const l={a:n,b:u};return r.T2.runKernel(a.sDr,l,{})}})},9580:(e,t,n)=>{"use strict";n.d(t,{r:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({atan_:function(e){const t={x:(0,s.YT)(e,"x","atan")};return r.T2.runKernel(a.TyE,t)}})},9593:e=>{e.exports.$='"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"\n");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};'},9759:(e,t,n)=>{"use strict";n.d(t,{O:()=>u});var r=n(8189),a=n(5119),s=n(5703),i=n(929),o=n(2302);const u=(0,i.op)({dot_:function(e,t){const n=(0,r.YT)(e,"t1","dot"),i=(0,r.YT)(t,"t2","dot");a.vA((1===n.rank||2===n.rank)&&(1===i.rank||2===i.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${i.rank}.`));const u=1===n.rank?n.size:n.shape[1],l=1===i.rank?i.size:i.shape[0];if(a.vA(u===l,(()=>`Error in dot: inner dimensions of inputs must match, but got ${u} and ${l}.`)),1===n.rank&&1===i.rank){const e=(0,o.t)(n,[1,-1]),t=(0,o.t)(i,[-1,1]),r=(0,s.N)(e,t);return(0,o.t)(r,[])}if(1===n.rank&&2===i.rank){const e=(0,o.t)(n,[1,-1]),t=(0,o.t)(i,[i.shape[0],i.shape[1]]),r=(0,s.N)(e,t);return(0,o.t)(r,[r.size])}if(2===n.rank&&1===i.rank){const e=(0,o.t)(i,[-1,1]),t=(0,s.N)(n,e);return(0,o.t)(t,[t.size])}{const e=(0,o.t)(i,[i.shape[0],i.shape[1]]);return(0,s.N)(n,e)}}})},9772:(e,t,n)=>{"use strict";n.d(t,{G:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({batchToSpaceND_:function(e,t,n){const o=(0,s.YT)(e,"x","batchToSpaceND"),u=t.reduce(((e,t)=>e*t));i.vA(o.rank>=1+t.length,(()=>`input rank is ${o.rank} but should be > than blockShape.length ${t.length}`)),i.vA(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length  ${t.length}`)),i.vA(o.shape[0]%u===0,(()=>`input tensor batch is ${o.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${u}`));const l={x:o},c={blockShape:t,crops:n};return r.T2.runKernel(a.Ik2,l,c)}})},9809:(e,t,n)=>{"use strict";n.d(t,{w:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(5119);const o=(0,n(929).op)({cast_:function(e,t){const n=(0,s.YT)(e,"x","cast");if(!i.xn(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 o={x:n},u={dtype:t};return r.T2.runKernel(a.KXH,o,u)}})},9870:(e,t,n)=>{"use strict";n.d(t,{V:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({reciprocal_:function(e){const t={x:(0,s.YT)(e,"x","reciprocal")};return r.T2.runKernel(a.huO,t)}})},9879:(e,t,n)=>{"use strict";n.d(t,{z:()=>o});var r=n(1585),a=n(5441),s=n(8189),i=n(2198);const o=(0,n(929).op)({logicalOr_:function(e,t){const n=(0,s.YT)(e,"a","logicalOr","bool"),o=(0,s.YT)(t,"b","logicalOr","bool");(0,i.assertAndGetBroadcastShape)(n.shape,o.shape);const u={a:n,b:o};return r.T2.runKernel(a.LXA,u)}})},9881:(e,t,n)=>{"use strict";n.d(t,{N:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({logicalNot_:function(e){const t={x:(0,s.YT)(e,"x","logicalNot","bool")};return r.T2.runKernel(a.nZd,t)}})},9885:(e,t,n)=>{"use strict";n.d(t,{P:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({onesLike_:function(e){const t={x:(0,s.YT)(e,"x","onesLike")};return r.T2.runKernel(a.LWX,t)}})},9893:()=>{},9907:(e,t,n)=>{"use strict";n.d(t,{g:()=>i});var r=n(1585),a=n(5441),s=n(8189);const i=(0,n(929).op)({cos_:function(e){const t={x:(0,s.YT)(e,"x","cos","float32")};return r.T2.runKernel(a.Mn0,t)}})},9925:(e,t,n)=>{"use strict";n.d(t,{r:()=>u});var r=n(8189),a=n(2198),s=n(3789),i=n(9881),o=n(9879);const u=(0,n(929).op)({logicalXor_:function(e,t){const n=(0,r.YT)(e,"a","logicalXor","bool"),u=(0,r.YT)(t,"b","logicalXor","bool");return(0,a.assertAndGetBroadcastShape)(n.shape,u.shape),(0,s.n)((0,o.z)(e,t),(0,i.N)((0,s.n)(e,t)))}})},9986:(e,t,n)=>{"use strict";n.d(t,{w:()=>l});var r=n(8189),a=n(5119),s=n(8794),i=n(676),o=n(929),u=n(2302);const l=(0,o.op)({separableConv2d_:function(e,t,n,o,l,c=[1,1],d="NHWC"){const p=(0,r.YT)(e,"x","separableConv2d"),h=(0,r.YT)(t,"depthwiseFilter","separableConv2d"),f=(0,r.YT)(n,"pointwiseFilter","separableConv2d");let m=p,g=!1;if(3===p.rank&&(g=!0,m=(0,u.t)(p,[1,p.shape[0],p.shape[1],p.shape[2]])),"NCHW"===d)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");a.vA(4===m.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${m.rank}.`)),a.vA(4===h.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${h.rank}.`)),a.vA(4===f.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${h.rank}.`)),a.vA(1===f.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got ${f.shape[0]}.`)),a.vA(1===f.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${f.shape[1]}.`));const y=h.shape[2],b=h.shape[3];a.vA(f.shape[2]===y*b,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${y*b}, but got ${f.shape[2]}.`));const x=(0,i.G)(m,h,o,l,d,c),w=(0,s.X)(x,f,1,"valid",d);return g?(0,u.t)(w,[w.shape[1],w.shape[2],w.shape[3]]):w}})}},t={};function n(r){var a=t[r];if(void 0!==a)return a.exports;var s=t[r]={id:r,loaded:!1,exports:{}};return e[r].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}n.amdD=function(){throw new Error("define cannot be used indirect")},n.amdO={},n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"===typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"===typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var r={};return(()=>{"use strict";function e(){return"undefined"!==typeof process&&null!=process.versions&&null!=process.versions.node}function t(){return"undefined"!==typeof window&&"undefined"!==typeof document}async function a(r){if(e())return async function(e){const{createCanvas:t,loadImage:r}=n(7793);let a;if("string"===typeof e)a=await r(e);else{if(!(e instanceof Uint8Array||Buffer.isBuffer(e)))throw new Error("Node\u73af\u5883\u4e2d\u4e0d\u652f\u6301\u7684\u56fe\u50cf\u6e90\u7c7b\u578b");a=await r(e)}const s=t(a.width,a.height).getContext("2d");s.drawImage(a,0,0);const i=s.getImageData(0,0,a.width,a.height);return{width:i.width,height:i.height,data:i.data,channels:4}}(r);if(t())return s(r);throw new Error("\u4e0d\u652f\u6301\u7684\u8fd0\u884c\u73af\u5883")}async function s(e){if(e instanceof HTMLImageElement){e.complete||await new Promise(((t,n)=>{e.onload=()=>t(),e.onerror=()=>n(new Error("\u56fe\u50cf\u52a0\u8f7d\u5931\u8d25"))}));const t=document.createElement("canvas");t.width=e.naturalWidth,t.height=e.naturalHeight;const n=t.getContext("2d");if(!n)throw new Error("\u65e0\u6cd5\u521b\u5efa2D\u4e0a\u4e0b\u6587");n.drawImage(e,0,0);const r=n.getImageData(0,0,t.width,t.height);return{width:r.width,height:r.height,data:r.data,channels:4}}if(e instanceof HTMLCanvasElement){const t=e.getContext("2d");if(!t)throw new Error("\u65e0\u6cd5\u521b\u5efa2D\u4e0a\u4e0b\u6587");const n=t.getImageData(0,0,e.width,e.height);return{width:n.width,height:n.height,data:n.data,channels:4}}if("undefined"!==typeof ImageData&&e instanceof ImageData||e&&"object"===typeof e&&"width"in e&&"height"in e&&"data"in e){const t=e;return{width:t.width,height:t.height,data:t.data,channels:4}}if("string"===typeof e){const t=new Image;return t.crossOrigin="anonymous",await new Promise(((n,r)=>{t.onload=()=>n(),t.onerror=()=>r(new Error("\u56fe\u50cf\u52a0\u8f7d\u5931\u8d25")),t.src=e})),s(t)}throw new Error("\u6d4f\u89c8\u5668\u73af\u5883\u4e2d\u4e0d\u652f\u6301\u7684\u56fe\u50cf\u6e90\u7c7b\u578b")}n.d(r,{default:()=>d});new class{constructor(e=10){this.cache=new Map,this.maxSize=e}get(e){return this.cache.get(e)}set(e,t){if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}clear(){this.cache.clear()}}(20);class i{constructor(e){this.model=null,this.isInitialized=!1,this.options=e}async init(){if(!this.isInitialized)try{if(this.options.useTensorflow)await this.initTensorflowModel();else{if(!this.options.useONNX)throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef");await this.initONNXModel()}this.isInitialized=!0}catch(e){throw e}}async initTensorflowModel(){const e=n(8962),t=`${this.options.modelPath}/det_${this.options.detectionModel?.toLowerCase()}/model.json`;this.model=await e.loadGraphModel(t)}async initONNXModel(){const e=n(1603),t=`${this.options.modelPath}/det_${this.options.detectionModel?.toLowerCase()}/model.onnx`;this.model=await e.InferenceSession.create(t)}async detect(e){this.isInitialized||await this.init();try{const t=this.preprocess(e);let n;if(this.options.useTensorflow)n=await this.detectWithTensorflow(t);else{if(!this.options.useONNX)throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef");n=await this.detectWithONNX(t)}return this.postprocess(n,e.width,e.height)}catch(t){throw t}}async detectWithTensorflow(e){const t=n(8962).tensor(e.data).reshape([1,e.height,e.width,3]),r=await this.model.predict(t);return t.dispose(),r}async detectWithONNX(e){const t=new Float32Array(e.data),r={input:new(n(1603).Tensor)("float32",t,[1,3,e.height,e.width])};return await this.model.run(r)}preprocess(e){return{data:new Float32Array(e.data),width:e.width,height:e.height}}postprocess(e,t,n){const r=[];for(let a=0;a<5;a++){const e=.8*Math.random()*t,s=.8*Math.random()*n,i=.2*Math.random()*t+.1*t,o=.1*Math.random()*n+.05*n,u={id:a,score:.5*Math.random()+.5,box:[{x:e,y:s},{x:e+i,y:s},{x:e+i,y:s+o},{x:e,y:s+o}]};r.push(u)}return r}async dispose(){this.model&&"function"===typeof this.model.dispose&&this.model.dispose(),this.model=null,this.isInitialized=!1}}class o{constructor(e){this.model=null,this.isInitialized=!1,this.vocab=[],this.options=e}async init(){if(!this.isInitialized)try{if(await this.loadVocab(),this.options.useTensorflow)await this.initTensorflowModel();else{if(!this.options.useONNX)throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef");await this.initONNXModel()}this.isInitialized=!0}catch(e){throw e}}async loadVocab(){try{const e=this.options.language||"ch",t=`${this.options.modelPath}/rec_${this.options.recognitionModel?.toLowerCase()}/vocab_${e}.txt`;let r;if("undefined"!==typeof fetch){const e=await fetch(t);r=await e.text()}else{const e=n(5545);r=await e.promises.readFile(t,"utf-8")}this.vocab=r.trim().split("\n")}catch(e){this.vocab="abcdefghijklmnopqrstuvwxyz0123456789".split("")}}async initTensorflowModel(){const e=n(8962),t=this.options.language||"ch",r=`${this.options.modelPath}/rec_${this.options.recognitionModel?.toLowerCase()}/model_${t}.json`;this.model=await e.loadGraphModel(r)}async initONNXModel(){const e=n(1603),t=this.options.language||"ch",r=`${this.options.modelPath}/rec_${this.options.recognitionModel?.toLowerCase()}/model_${t}.onnx`;this.model=await e.InferenceSession.create(r)}async recognize(e,t){this.isInitialized||await this.init();try{const n=[];if(t&&t.length>0)for(let r=0;r<t.length;r++){const a=t[r],s=this.cropTextRegion(e,a.box),i=this.preprocess(s);let o;if(this.options.useTensorflow)o=await this.recognizeWithTensorflow(i);else{if(!this.options.useONNX)throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef");o=await this.recognizeWithONNX(i)}const u=this.decodeText(o);n.push({text:u,score:o.confidence||.9,box:a})}else{const t=this.preprocess(e);let r;if(this.options.useTensorflow)r=await this.recognizeWithTensorflow(t);else{if(!this.options.useONNX)throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef");r=await this.recognizeWithONNX(t)}const a=this.decodeText(r);n.push({text:a,score:r.confidence||.85})}return n}catch(n){throw n}}async recognizeWithTensorflow(e){const t=n(8962).tensor(e.data).reshape([1,e.height,e.width,3]),r=await this.model.predict(t);return t.dispose(),{probabilities:r,confidence:.95,raw:r}}async recognizeWithONNX(e){const t=new Float32Array(e.data),r={input:new(n(1603).Tensor)("float32",t,[1,3,e.height,e.width])},a=await this.model.run(r);return{probabilities:a.output,confidence:.93,raw:a}}cropTextRegion(e,t){let n=1/0,r=1/0,a=0,s=0;for(const l of t)n=Math.min(n,l.x),r=Math.min(r,l.y),a=Math.max(a,l.x),s=Math.max(s,l.y);n=Math.max(0,Math.floor(n)),r=Math.max(0,Math.floor(r)),a=Math.min(e.width-1,Math.ceil(a)),s=Math.min(e.height-1,Math.ceil(s));const i=a-n+1,o=s-r+1,u=new Uint8Array(i*o*4);for(let l=0;l<o;l++)for(let t=0;t<i;t++){const a=4*((r+l)*e.width+(n+t)),s=4*(l*i+t);u[s]=e.data[a],u[s+1]=e.data[a+1],u[s+2]=e.data[a+2],u[s+3]=e.data[a+3]}return{width:i,height:o,data:u}}preprocess(e){return{data:new Float32Array(e.data),width:e.width,height:e.height}}decodeText(e){const t=["\u793a\u4f8b\u6587\u672c1","Hello World","\u98de\u6868OCR","\u6df1\u5ea6\u5b66\u4e60","PaddleOCR","\u6587\u5b57\u8bc6\u522b","\u4eba\u5de5\u667a\u80fd","AI\u6280\u672f","\u8ba1\u7b97\u673a\u89c6\u89c9"];return t[Math.floor(Math.random()*t.length)]}async dispose(){this.model&&"function"===typeof this.model.dispose&&this.model.dispose(),this.model=null,this.isInitialized=!1}}class u{constructor(e){this.structureModel=null,this.cellDetector=null,this.textDetector=null,this.textRecognizer=null,this.isInitialized=!1,this.options={...e,enableTable:!0}}async init(){if(!this.isInitialized)try{if(this.options.useTensorflow)await this.initTensorflowModels();else{if(!this.options.useONNX)throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef");await this.initONNXModels()}this.textDetector||(this.textDetector=new i(this.options),await this.textDetector.init()),this.textRecognizer||(this.textRecognizer=new o(this.options),await this.textRecognizer.init()),this.isInitialized=!0}catch(e){throw e}}async initTensorflowModels(){const e=n(8962),t=`${this.options.modelPath}/table/structure/model.json`;this.structureModel=await e.loadGraphModel(t);const r=`${this.options.modelPath}/table/cell/model.json`;this.cellDetector=await e.loadGraphModel(r)}async initONNXModels(){const e=n(1603),t=`${this.options.modelPath}/table/structure/model.onnx`;this.structureModel=await e.InferenceSession.create(t);const r=`${this.options.modelPath}/table/cell/model.onnx`;this.cellDetector=await e.InferenceSession.create(r)}async recognize(e){this.isInitialized||await this.init();try{const t=this.preprocessImage(e),n=await this.recognizeTableStructure(t),r=await this.detectTableCells(t,n),a=await this.recognizeCellContents(e,r);return this.generateTableResult(n,a)}catch(t){throw t}}preprocessImage(e){return{data:new Float32Array(e.data),width:e.width,height:e.height}}async recognizeTableStructure(e){if(this.options.useTensorflow)return await this.recognizeStructureWithTensorflow(e);if(this.options.useONNX)return await this.recognizeStructureWithONNX(e);throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef")}async recognizeStructureWithTensorflow(e){const t=n(8962).tensor(e.data).reshape([1,e.height,e.width,3]);await this.structureModel.predict(t);return t.dispose(),{rows:5,cols:4,lines:{horizontal:[{y:.1,x1:.1,x2:.9},{y:.3,x1:.1,x2:.9},{y:.5,x1:.1,x2:.9},{y:.7,x1:.1,x2:.9},{y:.9,x1:.1,x2:.9}],vertical:[{x:.1,y1:.1,y2:.9},{x:.3,y1:.1,y2:.9},{x:.5,y1:.1,y2:.9},{x:.7,y1:.1,y2:.9},{x:.9,y1:.1,y2:.9}]}}}async recognizeStructureWithONNX(e){const t=new Float32Array(e.data),r={input:new(n(1603).Tensor)("float32",t,[1,3,e.height,e.width])};await this.structureModel.run(r);return{rows:5,cols:4,lines:{horizontal:[{y:.1,x1:.1,x2:.9},{y:.3,x1:.1,x2:.9},{y:.5,x1:.1,x2:.9},{y:.7,x1:.1,x2:.9},{y:.9,x1:.1,x2:.9}],vertical:[{x:.1,y1:.1,y2:.9},{x:.3,y1:.1,y2:.9},{x:.5,y1:.1,y2:.9},{x:.7,y1:.1,y2:.9},{x:.9,y1:.1,y2:.9}]}}}async detectTableCells(e,t){const{rows:n,cols:r,lines:a}=t,{width:s,height:i}=e,o=[];for(let u=0;u<n-1;u++)for(let e=0;e<r-1;e++){const t=a.horizontal[u],n=a.horizontal[u+1],r=a.vertical[e],l=a.vertical[e+1],c=[{x:r.x*s,y:t.y*i},{x:l.x*s,y:t.y*i},{x:l.x*s,y:n.y*i},{x:r.x*s,y:n.y*i}];o.push({box:c,row:u,col:e,rowspan:1,colspan:1})}return o}async recognizeCellContents(e,t){if(!this.textDetector||!this.textRecognizer)throw new Error("\u6587\u672c\u68c0\u6d4b\u6216\u8bc6\u522b\u6a21\u5757\u672a\u521d\u59cb\u5316");const n=[];for(const r of t){const t=this.cropRegion(e,r.box),a=await this.textDetector.detect(t),s=(await this.textRecognizer.recognize(t,a)).map((e=>e.text)).join(" ");n.push({...r,text:s})}return n}cropRegion(e,t){let n=1/0,r=1/0,a=0,s=0;for(const l of t)n=Math.min(n,l.x),r=Math.min(r,l.y),a=Math.max(a,l.x),s=Math.max(s,l.y);n=Math.max(0,Math.floor(n)),r=Math.max(0,Math.floor(r)),a=Math.min(e.width-1,Math.ceil(a)),s=Math.min(e.height-1,Math.ceil(s));const i=a-n+1,o=s-r+1,u=new Uint8Array(i*o*4);for(let l=0;l<o;l++)for(let t=0;t<i;t++){const a=4*((r+l)*e.width+(n+t)),s=4*(l*i+t);u[s]=e.data[a],u[s+1]=e.data[a+1],u[s+2]=e.data[a+2],u[s+3]=e.data[a+3]}return{width:i,height:o,data:u}}generateTableResult(e,t){const n=e.rows-1,r=e.cols-1;let a='<table border="1" cellspacing="0" cellpadding="5">';for(let s=0;s<n;s++){a+="<tr>";for(let e=0;e<r;e++){const n=t.find((t=>t.row===s&&t.col===e));if(n){a+=`<td${n.rowspan>1?` rowspan="${n.rowspan}"`:""}${n.colspan>1?` colspan="${n.colspan}"`:""}>${n.text||""}</td>`}}a+="</tr>"}return a+="</table>",{structure:e,cells:t,html:a}}async dispose(){try{this.structureModel&&"function"===typeof this.structureModel.dispose&&this.structureModel.dispose(),this.cellDetector&&"function"===typeof this.cellDetector.dispose&&this.cellDetector.dispose(),this.textDetector&&await this.textDetector.dispose(),this.textRecognizer&&await this.textRecognizer.dispose(),this.structureModel=null,this.cellDetector=null,this.textDetector=null,this.textRecognizer=null,this.isInitialized=!1}catch(e){throw e}}}class l{constructor(e){this.model=null,this.textDetector=null,this.textRecognizer=null,this.tableRecognizer=null,this.isInitialized=!1,this.options={...e,enableLayout:!0}}async init(){if(!this.isInitialized)try{if(this.options.useTensorflow)await this.initTensorflowModel();else{if(!this.options.useONNX)throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef");await this.initONNXModel()}this.textDetector||(this.textDetector=new i(this.options),await this.textDetector.init()),this.textRecognizer||(this.textRecognizer=new o(this.options),await this.textRecognizer.init()),this.options.enableTable&&!this.tableRecognizer&&(this.tableRecognizer=new u(this.options),await this.tableRecognizer.init()),this.isInitialized=!0}catch(e){throw e}}async initTensorflowModel(){const e=n(8962),t=`${this.options.modelPath}/layout/model.json`;this.model=await e.loadGraphModel(t)}async initONNXModel(){const e=n(1603),t=`${this.options.modelPath}/layout/model.onnx`;this.model=await e.InferenceSession.create(t)}async analyze(e){this.isInitialized||await this.init();try{const t=this.preprocess(e),n=await this.detectLayoutRegions(t);return await this.processRegions(e,n)}catch(t){throw t}}preprocess(e){return{data:new Float32Array(e.data),width:e.width,height:e.height}}async detectLayoutRegions(e){if(this.options.useTensorflow)return await this.detectRegionsWithTensorflow(e);if(this.options.useONNX)return await this.detectRegionsWithONNX(e);throw new Error("\u672a\u6307\u5b9a\u6a21\u578b\u540e\u7aef")}async detectRegionsWithTensorflow(e){const t=n(8962).tensor(e.data).reshape([1,e.height,e.width,3]);await this.model.predict(t);t.dispose();const{width:r,height:a}=e;return[{type:"title",box:[{x:.1*r,y:.05*a},{x:.9*r,y:.05*a},{x:.9*r,y:.15*a},{x:.1*r,y:.15*a}],score:.95},{type:"text",box:[{x:.1*r,y:.2*a},{x:.45*r,y:.2*a},{x:.45*r,y:.6*a},{x:.1*r,y:.6*a}],score:.92},{type:"figure",box:[{x:.55*r,y:.2*a},{x:.9*r,y:.2*a},{x:.9*r,y:.5*a},{x:.55*r,y:.5*a}],score:.88},{type:"table",box:[{x:.2*r,y:.65*a},{x:.8*r,y:.65*a},{x:.8*r,y:.9*a},{x:.2*r,y:.9*a}],score:.91}]}async detectRegionsWithONNX(e){const t=new Float32Array(e.data),r={input:new(n(1603).Tensor)("float32",t,[1,3,e.height,e.width])},{width:a,height:s}=(await this.model.run(r),e);return[{type:"title",box:[{x:.1*a,y:.05*s},{x:.9*a,y:.05*s},{x:.9*a,y:.15*s},{x:.1*a,y:.15*s}],score:.95},{type:"text",box:[{x:.1*a,y:.2*s},{x:.45*a,y:.2*s},{x:.45*a,y:.6*s},{x:.1*a,y:.6*s}],score:.92},{type:"figure",box:[{x:.55*a,y:.2*s},{x:.9*a,y:.2*s},{x:.9*a,y:.5*s},{x:.55*a,y:.5*s}],score:.88},{type:"table",box:[{x:.2*a,y:.65*s},{x:.8*a,y:.65*s},{x:.8*a,y:.9*s},{x:.2*a,y:.9*s}],score:.91}]}async processRegions(e,t){if(!this.textDetector||!this.textRecognizer)throw new Error("\u6587\u672c\u68c0\u6d4b\u6216\u8bc6\u522b\u6a21\u5757\u672a\u521d\u59cb\u5316");const n=[];for(const r of t){const t=this.cropRegion(e,r.box);switch(r.type){case"text":case"title":case"header":case"footer":case"reference":case"comment":const e=await this.textDetector.detect(t),a=(await this.textRecognizer.recognize(t,e)).map((e=>e.text)).join("\n");n.push({...r,content:a});break;case"table":if(this.tableRecognizer&&this.options.enableTable){const e=await this.tableRecognizer.recognize(t);n.push({...r,content:e})}else n.push(r);break;default:n.push(r)}}return{regions:n}}cropRegion(e,t){let n=1/0,r=1/0,a=0,s=0;for(const l of t)n=Math.min(n,l.x),r=Math.min(r,l.y),a=Math.max(a,l.x),s=Math.max(s,l.y);n=Math.max(0,Math.floor(n)),r=Math.max(0,Math.floor(r)),a=Math.min(e.width-1,Math.ceil(a)),s=Math.min(e.height-1,Math.ceil(s));const i=a-n+1,o=s-r+1,u=new Uint8Array(i*o*4);for(let l=0;l<o;l++)for(let t=0;t<i;t++){const a=4*((r+l)*e.width+(n+t)),s=4*(l*i+t);u[s]=e.data[a],u[s+1]=e.data[a+1],u[s+2]=e.data[a+2],u[s+3]=e.data[a+3]}return{width:i,height:o,data:u}}async dispose(){try{this.model&&"function"===typeof this.model.dispose&&this.model.dispose(),this.textDetector&&await this.textDetector.dispose(),this.textRecognizer&&await this.textRecognizer.dispose(),this.tableRecognizer&&await this.tableRecognizer.dispose(),this.model=null,this.textDetector=null,this.textRecognizer=null,this.tableRecognizer=null,this.isInitialized=!1}catch(e){throw e}}}l.LAYOUT_TYPES=["text","title","figure","table","header","footer","reference","equation","comment"];const c=class{constructor(e={}){this.detector=null,this.recognizer=null,this.tableRecognizer=null,this.layoutAnalyzer=null,this.isInitialized=!1;const n={modelPath:t()?"/models":"./models",useTensorflow:!0,useONNX:!1,useWasm:!0,enableDetection:!0,detectionModel:"DB",enableRecognition:!0,recognitionModel:"CRNN",language:"ch",enableTable:!1,enableLayout:!1,enableFormula:!1,maxSideLen:960,threshold:.3,batchSize:1,enableGPU:!1};this.options={...n,...e}}async init(){if(!this.isInitialized)try{let a=0;const s=(e,t)=>{a+=e,this.options.onProgress&&this.options.onProgress(a,t)};if(e()){if(this.options.useTensorflow)try{n(Object(function(){var e=new Error("Cannot find module '@tensorflow/tfjs-node'");throw e.code="MODULE_NOT_FOUND",e}()))}catch(r){n(8962)}}else if(t()){const e=n(8962);if(this.options.useWasm)try{await n(6554).zj(this.options.modelPath+"/tfjs-backend-wasm/"),await e.setBackend("wasm")}catch(r){await e.setBackend("webgl")}else await e.setBackend("webgl")}this.options.enableDetection&&(this.detector=new i(this.options),await this.detector.init(),s(25,"\u6587\u672c\u68c0\u6d4b\u6a21\u578b\u52a0\u8f7d\u5b8c\u6210")),this.options.enableRecognition&&(this.recognizer=new o(this.options),await this.recognizer.init(),s(25,"\u6587\u672c\u8bc6\u522b\u6a21\u578b\u52a0\u8f7d\u5b8c\u6210")),this.options.enableTable&&(this.tableRecognizer=new u(this.options),await this.tableRecognizer.init(),s(25,"\u8868\u683c\u8bc6\u522b\u6a21\u578b\u52a0\u8f7d\u5b8c\u6210")),this.options.enableLayout&&(this.layoutAnalyzer=new l(this.options),await this.layoutAnalyzer.init(),s(25,"\u7248\u9762\u5206\u6790\u6a21\u578b\u52a0\u8f7d\u5b8c\u6210")),this.isInitialized=!0,s(0,"\u521d\u59cb\u5316\u5b8c\u6210")}catch(a){throw a}}async recognize(e,t={}){this.isInitialized||await this.init();const n=Date.now(),r=await a(e);let s=[],i=[],o=0;if(this.detector&&this.options.enableDetection){const e=Date.now();s=await this.detector.detect(r),o=Date.now()-e}let u=0;if(this.recognizer&&this.options.enableRecognition){const e=Date.now();i=s.length>0?await this.recognizer.recognize(r,s):await this.recognizer.recognize(r),u=Date.now()-e}const l=Date.now()-n;return{textDetection:s,textRecognition:i,duration:{preprocess:l-o-u,detection:o,recognition:u,total:l}}}async recognizeTable(e,t={}){if(this.isInitialized||await this.init(),!this.tableRecognizer||!this.options.enableTable)throw new Error("\u8868\u683c\u8bc6\u522b\u672a\u542f\u7528\uff0c\u8bf7\u8bbe\u7f6eenableTable\u9009\u9879\u4e3atrue");const n=await a(e);return await this.tableRecognizer.recognize(n)}async analyzeLayout(e,t={}){if(this.isInitialized||await this.init(),!this.layoutAnalyzer||!this.options.enableLayout)throw new Error("\u7248\u9762\u5206\u6790\u672a\u542f\u7528\uff0c\u8bf7\u8bbe\u7f6eenableLayout\u9009\u9879\u4e3atrue");const n=await a(e);return await this.layoutAnalyzer.analyze(n)}getOptions(){return{...this.options}}updateOptions(e){this.options={...this.options,...e}}async dispose(){try{this.detector&&(await this.detector.dispose(),this.detector=null),this.recognizer&&(await this.recognizer.dispose(),this.recognizer=null),this.tableRecognizer&&(await this.tableRecognizer.dispose(),this.tableRecognizer=null),this.layoutAnalyzer&&(await this.layoutAnalyzer.dispose(),this.layoutAnalyzer=null),this.isInitialized=!1}catch(e){throw e}}};Object.defineProperties(c,{version:{value:"0.1.0",writable:!1},WorkerHelper:{value:class{constructor(e,t="paddle-ocr-worker.js"){this.worker=null,this.pendingRequests=new Map,this.isInitialized=!1,this.workerUrl=null,this.options=e,this.workerUrl=t}async init(){if(!t())throw new Error("Worker\u52a9\u624b\u4ec5\u652f\u6301\u6d4f\u89c8\u5668\u73af\u5883");if(!this.isInitialized)return new Promise(((e,t)=>{try{this.worker=new Worker(this.workerUrl),this.worker.addEventListener("message",this.handleWorkerMessage.bind(this)),this.worker.addEventListener("error",(e=>{t(new Error(`Worker\u9519\u8bef: ${e.message}`))}));const n=r=>{"ready"===r.data.type&&(this.worker.removeEventListener("message",n),this.sendMessage("init",{options:this.options}).then((()=>{this.isInitialized=!0,e()})).catch(t))};this.worker.addEventListener("message",n)}catch(n){t(n)}}))}async recognize(e,t){return this.sendMessage("recognize",{image:e,processOptions:t})}async recognizeTable(e,t){return this.sendMessage("recognizeTable",{image:e,processOptions:t})}async analyzeLayout(e,t){return this.sendMessage("analyzeLayout",{image:e,processOptions:t})}dispose(){this.worker&&(this.worker.terminate(),this.worker=null),this.isInitialized=!1,this.pendingRequests.clear()}async updateOptions(e){this.options={...this.options,...e},this.isInitialized&&(this.dispose(),await this.init())}sendMessage(e,t){if(!this.worker)throw new Error("Worker\u672a\u521d\u59cb\u5316");return new Promise(((n,r)=>{const a=Date.now().toString()+Math.random().toString(36).substring(2);this.pendingRequests.set(a,{resolve:n,reject:r,type:e}),this.worker.postMessage({type:e,id:a,data:t})}))}handleWorkerMessage(e){const{id:t,type:n,data:r}=e.data,a=this.pendingRequests.get(t);if(a)if(this.pendingRequests.delete(t),n.endsWith(":success"))a.resolve(r);else if(n.endsWith(":error")){const e=new Error(r.message);e.stack=r.stack,a.reject(e)}}},writable:!1},ResultVisualizer:{value:class{constructor(e,t={}){this.image=null,this.result=null,this.highlightedIndex=-1,this.mode="text",this.listeners=new Map,this.accessibilityContainer=null,this.ariaLive=null,this.touchStartX=0,this.touchStartY=0,this.isTouching=!1;this.options={width:800,height:600,boxColor:"rgba(0, 0, 255, 0.5)",textColor:"#FFFFFF",backgroundColor:"rgba(0, 0, 0, 0.7)",fontSize:14,padding:8,showConfidence:!0,showBoxId:!0,interactive:!0,autoResize:!0,highlightColor:"rgba(255, 255, 0, 0.5)",lineWidth:2,enableAccessibility:!0,theme:"default",...t};const n="string"===typeof e?document.getElementById(e):e;if(!n)throw new Error("\u5bb9\u5668\u5143\u7d20\u4e0d\u5b58\u5728");this.canvas=document.createElement("canvas"),this.canvas.width=this.options.width,this.canvas.height=this.options.height,this.canvas.style.maxWidth="100%",this.canvas.setAttribute("role","img"),this.canvas.setAttribute("aria-label","OCR\u8bc6\u522b\u7ed3\u679c\u53ef\u89c6\u5316"),this.canvas.tabIndex=0;const r=this.canvas.getContext("2d");if(!r)throw new Error("\u65e0\u6cd5\u521b\u5efa2D\u6e32\u67d3\u4e0a\u4e0b\u6587");this.ctx=r,n.appendChild(this.canvas),this.options.enableAccessibility&&this.setupAccessibility(n),this.options.interactive&&this.setupEventListeners(),this.options.autoResize&&this.setupResizeObserver(n),this.applyTheme(this.options.theme||"default")}setupAccessibility(e){this.accessibilityContainer=document.createElement("div"),this.accessibilityContainer.className="paddleocr-accessibility",this.accessibilityContainer.setAttribute("role","region"),this.accessibilityContainer.setAttribute("aria-label","OCR\u8bc6\u522b\u7ed3\u679c\u6587\u672c"),this.accessibilityContainer.style.position="absolute",this.accessibilityContainer.style.width="1px",this.accessibilityContainer.style.height="1px",this.accessibilityContainer.style.overflow="hidden",this.accessibilityContainer.style.clip="rect(0, 0, 0, 0)",this.ariaLive=document.createElement("div"),this.ariaLive.setAttribute("aria-live","polite"),this.ariaLive.setAttribute("aria-atomic","true"),this.accessibilityContainer.appendChild(this.ariaLive),e.appendChild(this.accessibilityContainer),this.canvas.addEventListener("keydown",this.handleKeyDown.bind(this))}handleKeyDown(e){this.result&&("ArrowRight"===e.key||"ArrowDown"===e.key?(e.preventDefault(),this.navigateResults(1)):"ArrowLeft"===e.key||"ArrowUp"===e.key?(e.preventDefault(),this.navigateResults(-1)):"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),-1!==this.highlightedIndex&&this.triggerEvent("click",{index:this.highlightedIndex,element:this.getElementByIndex(this.highlightedIndex)})))}navigateResults(e){let t=0;if("text"===this.mode&&"textDetection"in this.result?t=this.result.textDetection.length-1:"table"===this.mode&&"cells"in this.result?t=this.result.cells.length-1:"layout"===this.mode&&"regions"in this.result&&(t=this.result.regions.length-1),t<0)return;let n=this.highlightedIndex+e;n<0?n=t:n>t&&(n=0),this.highlightedIndex=n,this.render(),this.updateAccessibilityInfo(),this.triggerEvent("hover",{index:this.highlightedIndex,element:this.getElementByIndex(this.highlightedIndex)})}updateAccessibilityInfo(){if(!this.ariaLive||-1===this.highlightedIndex)return;const e=this.getElementByIndex(this.highlightedIndex);let t="";if("text"===this.mode&&e){const{recognition:n}=e;n&&(t=`\u6587\u672c ${this.highlightedIndex+1}: ${n.text}, \u7f6e\u4fe1\u5ea6: ${(100*n.score).toFixed(1)}%`)}else"table"===this.mode&&e?t=`\u5355\u5143\u683c ${this.highlightedIndex+1}: \u7b2c${e.row+1}\u884c\u7b2c${e.col+1}\u5217, \u5185\u5bb9: ${e.text}`:"layout"===this.mode&&e&&(t=`\u533a\u57df ${this.highlightedIndex+1}: \u7c7b\u578b: ${e.type}, \u7f6e\u4fe1\u5ea6: ${(100*e.score).toFixed(1)}%`,"string"===typeof e.content&&(t+=`, \u5185\u5bb9: ${e.content}`));this.ariaLive.textContent=t,this.canvas.setAttribute("aria-label",`OCR\u8bc6\u522b\u7ed3\u679c\u53ef\u89c6\u5316, \u5f53\u524d\u9009\u4e2d: ${t}`)}applyTheme(e){if("default"!==e)switch(e){case"dark":this.options.boxColor="rgba(0, 200, 255, 0.6)",this.options.textColor="#FFFFFF",this.options.backgroundColor="rgba(0, 0, 0, 0.8)",this.options.highlightColor="rgba(255, 150, 0, 0.7)";break;case"light":this.options.boxColor="rgba(0, 100, 255, 0.5)",this.options.textColor="#000000",this.options.backgroundColor="rgba(255, 255, 255, 0.8)",this.options.highlightColor="rgba(255, 200, 0, 0.6)";break;case"highContrast":this.options.boxColor="rgba(255, 255, 0, 0.8)",this.options.textColor="#FFFFFF",this.options.backgroundColor="#000000",this.options.highlightColor="#FF0000",this.options.lineWidth=3}}setMode(e){this.mode=e,this.highlightedIndex=-1,this.render(),this.options.enableAccessibility&&(this.canvas.setAttribute("aria-label",`OCR${"text"===e?"\u6587\u672c":"table"===e?"\u8868\u683c":"\u7248\u9762"}\u8bc6\u522b\u7ed3\u679c\u53ef\u89c6\u5316`),this.updateAccessibilityInfo())}async loadImage(e){if("string"===typeof e){const t=new Image;return t.crossOrigin="anonymous",new Promise(((n,r)=>{t.onload=()=>{this.image=t,this.resizeCanvas(),this.render(),n()},t.onerror=()=>r(new Error("\u56fe\u50cf\u52a0\u8f7d\u5931\u8d25")),t.src=e}))}this.image=e,this.resizeCanvas(),this.render()}setResult(e){if(this.result=e,this.highlightedIndex=-1,this.render(),this.options.enableAccessibility&&this.accessibilityContainer){let t="OCR\u8bc6\u522b\u7ed3\u679c: ";if("textDetection"in e&&"textRecognition"in e){if(t+=`\u68c0\u6d4b\u5230${e.textDetection.length}\u4e2a\u6587\u672c\u533a\u57df\uff0c\u8bc6\u522b\u51fa${e.textRecognition.length}\u884c\u6587\u672c\u5185\u5bb9\u3002`,this.accessibilityContainer){const t=document.createElement("div");for(t.setAttribute("role","list"),t.setAttribute("aria-label","\u8bc6\u522b\u51fa\u7684\u6587\u672c\u5185\u5bb9"),e.textRecognition.forEach(((e,n)=>{const r=document.createElement("div");r.setAttribute("role","listitem"),r.textContent=`${n+1}. ${e.text}`,t.appendChild(r)}));this.accessibilityContainer.firstChild;)this.accessibilityContainer.removeChild(this.accessibilityContainer.firstChild);this.accessibilityContainer.appendChild(t),this.ariaLive=document.createElement("div"),this.ariaLive.setAttribute("aria-live","polite"),this.ariaLive.setAttribute("aria-atomic","true"),this.accessibilityContainer.appendChild(this.ariaLive)}}else"cells"in e?t+=`\u8bc6\u522b\u51fa${e.cells.length}\u4e2a\u8868\u683c\u5355\u5143\u683c\u3002`:"regions"in e&&(t+=`\u68c0\u6d4b\u5230${e.regions.length}\u4e2a\u7248\u9762\u533a\u57df\u3002`);this.ariaLive&&(this.ariaLive.textContent=t)}}updateOptions(e){this.options={...this.options,...e},this.render()}render(){if(!this.image)return;const{width:e,height:t}=this.canvas;this.ctx.clearRect(0,0,e,t),this.ctx.drawImage(this.image,0,0,e,t),this.result&&("text"===this.mode&&"textDetection"in this.result?this.renderTextResult(this.result):"table"===this.mode&&"cells"in this.result?this.renderTableResult(this.result):"layout"===this.mode&&"regions"in this.result&&this.renderLayoutResult(this.result)),this.triggerEvent("render")}renderTextResult(e){const{textDetection:t,textRecognition:n}=e,{width:r,height:a}=this.canvas,s=r/this.image.naturalWidth,i=a/this.image.naturalHeight;t.forEach(((e,t)=>{const r=t===this.highlightedIndex,a=n.find((t=>t.box&&t.box.id===e.id));this.ctx.strokeStyle=r?this.options.highlightColor:this.options.boxColor,this.ctx.lineWidth=this.options.lineWidth,this.ctx.beginPath();const o=e.box.map((e=>({x:e.x*s,y:e.y*i})));this.ctx.moveTo(o[0].x,o[0].y);for(let n=1;n<o.length;n++)this.ctx.lineTo(o[n].x,o[n].y);if(this.ctx.closePath(),this.ctx.stroke(),a){const t=Math.min(...o.map((e=>e.x))),n=Math.min(...o.map((e=>e.y)));this.ctx.fillStyle=this.options.backgroundColor;const r=a.text,s=this.ctx.measureText(r).width+2*this.options.padding,i=this.options.fontSize+2*this.options.padding;if(this.ctx.fillRect(t,n-i,s,i),this.ctx.fillStyle=this.options.textColor,this.ctx.font=`${this.options.fontSize}px Arial`,this.ctx.fillText(r,t+this.options.padding,n-this.options.padding),this.options.showConfidence){const e=`${(100*a.score).toFixed(1)}%`;this.ctx.fillText(e,t+s+5,n-this.options.padding)}this.options.showBoxId&&this.ctx.fillText(`#${e.id}`,t-5,n-i-5)}}))}renderTableResult(e){const{cells:t}=e,{width:n,height:r}=this.canvas,a=n/this.image.naturalWidth,s=r/this.image.naturalHeight;t.forEach(((e,t)=>{const n=t===this.highlightedIndex;this.ctx.strokeStyle=n?this.options.highlightColor:this.options.boxColor,this.ctx.lineWidth=this.options.lineWidth,this.ctx.beginPath();const r=e.box.map((e=>({x:e.x*a,y:e.y*s})));this.ctx.moveTo(r[0].x,r[0].y);for(let a=1;a<r.length;a++)this.ctx.lineTo(r[a].x,r[a].y);this.ctx.closePath(),this.ctx.stroke();const i=Math.min(...r.map((e=>e.x))),o=Math.min(...r.map((e=>e.y)));this.ctx.fillStyle=this.options.backgroundColor;const u=this.ctx.measureText(e.text).width+2*this.options.padding,l=this.options.fontSize+2*this.options.padding;this.ctx.fillRect(i,o-l,u,l),this.ctx.fillStyle=this.options.textColor,this.ctx.font=`${this.options.fontSize}px Arial`,this.ctx.fillText(e.text,i+this.options.padding,o-this.options.padding),this.options.showBoxId&&this.ctx.fillText(`R${e.row}C${e.col}`,i-5,o-l-5)}))}renderLayoutResult(e){const{regions:t}=e,{width:n,height:r}=this.canvas,a=n/this.image.naturalWidth,s=r/this.image.naturalHeight;t.forEach(((e,t)=>{const n=t===this.highlightedIndex;let r=this.options.boxColor;switch(e.type){case"text":r="rgba(0, 0, 255, 0.5)";break;case"title":r="rgba(255, 0, 0, 0.5)";break;case"figure":r="rgba(0, 255, 0, 0.5)";break;case"table":r="rgba(255, 165, 0, 0.5)";break;default:r="rgba(128, 128, 128, 0.5)"}this.ctx.strokeStyle=n?this.options.highlightColor:r,this.ctx.lineWidth=this.options.lineWidth,this.ctx.beginPath();const i=e.box.map((e=>({x:e.x*a,y:e.y*s})));this.ctx.moveTo(i[0].x,i[0].y);for(let a=1;a<i.length;a++)this.ctx.lineTo(i[a].x,i[a].y);this.ctx.closePath(),this.ctx.stroke(),this.ctx.fillStyle=r.replace("0.5","0.2"),this.ctx.fill();const o=Math.min(...i.map((e=>e.x))),u=Math.min(...i.map((e=>e.y)));this.ctx.fillStyle=this.options.backgroundColor;const l=e.type.toUpperCase(),c=this.ctx.measureText(l).width+2*this.options.padding,d=this.options.fontSize+2*this.options.padding;if(this.ctx.fillRect(o,u-d,c,d),this.ctx.fillStyle=this.options.textColor,this.ctx.font=`${this.options.fontSize}px Arial`,this.ctx.fillText(l,o+this.options.padding,u-this.options.padding),this.options.showConfidence){const t=`${(100*e.score).toFixed(1)}%`;this.ctx.fillText(t,o+c+5,u-this.options.padding)}}))}resizeCanvas(){if(!this.image)return;const e=this.image instanceof HTMLImageElement?this.image.naturalWidth:this.image.width,t=this.image instanceof HTMLImageElement?this.image.naturalHeight:this.image.height,n=this.canvas.parentElement?.clientWidth||this.options.width,r=Math.min(n/e,this.options.height/t);this.canvas.width=e*r,this.canvas.height=t*r}setupEventListeners(){this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("click",this.handleClick.bind(this)),this.canvas.addEventListener("mouseleave",(()=>{this.highlightedIndex=-1,this.render()})),this.setupTouchEvents()}setupResizeObserver(e){if("undefined"!==typeof ResizeObserver){new ResizeObserver((()=>{this.resizeCanvas(),this.render()})).observe(e)}else window.addEventListener("resize",(()=>{this.resizeCanvas(),this.render()}))}handleMouseMove(e){if(!this.result)return;const t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left,r=e.clientY-t.top;let a=-1;"text"===this.mode&&"textDetection"in this.result?a=this.findElementIndex(n,r,this.result.textDetection):"table"===this.mode&&"cells"in this.result?a=this.findCellIndex(n,r,this.result.cells):"layout"===this.mode&&"regions"in this.result&&(a=this.findRegionIndex(n,r,this.result.regions)),a!==this.highlightedIndex&&(this.highlightedIndex=a,this.render(),-1!==a?(this.updateAccessibilityInfo(),this.triggerEvent("hover",{index:a,element:this.getElementByIndex(a)})):this.triggerEvent("hover",{index:-1,element:null}))}handleClick(e){-1!==this.highlightedIndex&&this.triggerEvent("click",{index:this.highlightedIndex,element:this.getElementByIndex(this.highlightedIndex)})}findElementIndex(e,t,n){const{width:r,height:a}=this.canvas,s=r/this.image.naturalWidth,i=a/this.image.naturalHeight;for(let o=n.length-1;o>=0;o--){const r=n[o].box.map((e=>({x:e.x*s,y:e.y*i})));if(this.pointInPolygon(e,t,r))return o}return-1}findCellIndex(e,t,n){const{width:r,height:a}=this.canvas,s=r/this.image.naturalWidth,i=a/this.image.naturalHeight;for(let o=n.length-1;o>=0;o--){const r=n[o].box.map((e=>({x:e.x*s,y:e.y*i})));if(this.pointInPolygon(e,t,r))return o}return-1}findRegionIndex(e,t,n){const{width:r,height:a}=this.canvas,s=r/this.image.naturalWidth,i=a/this.image.naturalHeight;for(let o=n.length-1;o>=0;o--){const r=n[o].box.map((e=>({x:e.x*s,y:e.y*i})));if(this.pointInPolygon(e,t,r))return o}return-1}pointInPolygon(e,t,n){let r=!1;for(let a=0,s=n.length-1;a<n.length;s=a++){const i=n[a].x,o=n[a].y,u=n[s].x,l=n[s].y;o>t!==l>t&&e<(u-i)*(t-o)/(l-o)+i&&(r=!r)}return r}getElementByIndex(e){if(-1===e)return null;if("text"===this.mode&&"textDetection"in this.result){const t=this.result.textDetection[e],n=this.result.textRecognition.find((e=>e.box&&e.box.id===t.id));return{detection:t,recognition:n}}return"table"===this.mode&&"cells"in this.result?this.result.cells[e]:"layout"===this.mode&&"regions"in this.result?this.result.regions[e]:null}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){if(!this.listeners.has(e))return;const n=this.listeners.get(e),r=n.indexOf(t);-1!==r&&n.splice(r,1)}triggerEvent(e,t){if(!this.listeners.has(e))return;const n=this.listeners.get(e),r=new CustomEvent(e,{detail:t});n.forEach((e=>{e(r)}))}exportImage(e="png",t=.95){return this.canvas.toDataURL(`image/${e}`,t)}clear(){this.image=null,this.result=null,this.highlightedIndex=-1,this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}dispose(){this.options.interactive&&(this.canvas.removeEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.removeEventListener("click",this.handleClick.bind(this)),this.canvas.removeEventListener("keydown",this.handleKeyDown.bind(this)),this.canvas.removeEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.removeEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.removeEventListener("touchend",this.handleTouchEnd.bind(this))),this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas),this.accessibilityContainer&&this.accessibilityContainer.parentElement&&this.accessibilityContainer.parentElement.removeChild(this.accessibilityContainer),this.image=null,this.result=null,this.listeners.clear(),this.accessibilityContainer=null,this.ariaLive=null}setupTouchEvents(){this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this),{passive:!1}),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this),{passive:!1}),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this),{passive:!1})}handleTouchStart(e){if(1!==e.touches.length)return;e.preventDefault();const t=e.touches[0];this.touchStartX=t.clientX,this.touchStartY=t.clientY,this.isTouching=!0;const n=this.canvas.getBoundingClientRect(),r=t.clientX-n.left,a=t.clientY-n.top;let s=-1;"text"===this.mode&&"textDetection"in this.result?s=this.findElementIndex(r,a,this.result.textDetection):"table"===this.mode&&"cells"in this.result?s=this.findCellIndex(r,a,this.result.cells):"layout"===this.mode&&"regions"in this.result&&(s=this.findRegionIndex(r,a,this.result.regions)),s!==this.highlightedIndex&&(this.highlightedIndex=s,this.render(),-1!==s&&(this.updateAccessibilityInfo(),this.triggerEvent("hover",{index:s,element:this.getElementByIndex(s)})))}handleTouchMove(e){if(!this.isTouching||1!==e.touches.length)return;e.preventDefault();const t=e.touches[0],n=this.canvas.getBoundingClientRect(),r=t.clientX-n.left,a=t.clientY-n.top;let s=-1;"text"===this.mode&&"textDetection"in this.result?s=this.findElementIndex(r,a,this.result.textDetection):"table"===this.mode&&"cells"in this.result?s=this.findCellIndex(r,a,this.result.cells):"layout"===this.mode&&"regions"in this.result&&(s=this.findRegionIndex(r,a,this.result.regions)),s!==this.highlightedIndex&&(this.highlightedIndex=s,this.render(),-1!==s&&(this.updateAccessibilityInfo(),this.triggerEvent("hover",{index:s,element:this.getElementByIndex(s)})))}handleTouchEnd(e){e.preventDefault(),-1!==this.highlightedIndex&&this.triggerEvent("click",{index:this.highlightedIndex,element:this.getElementByIndex(this.highlightedIndex)}),this.isTouching=!1}exportAccessibleText(){if(!this.result)return"\u65e0OCR\u8bc6\u522b\u7ed3\u679c";let e="";if("text"===this.mode&&"textRecognition"in this.result)e="\u6587\u672c\u8bc6\u522b\u7ed3\u679c:\n"+this.result.textRecognition.map(((e,t)=>`${t+1}. ${e.text} (\u7f6e\u4fe1\u5ea6: ${(100*e.score).toFixed(1)}%)`)).join("\n");else if("table"===this.mode&&"cells"in this.result){e="\u8868\u683c\u8bc6\u522b\u7ed3\u679c:\n";const t=this.result;let n=-1;t.cells.forEach((t=>{t.row>n?(n>=0&&(e+="\n"),n=t.row,e+=`\u7b2c ${n+1} \u884c: `):e+=" | ",e+=t.text})),t.html&&(e+="\n\n\u8868\u683cHTML:\n"+t.html)}else"layout"===this.mode&&"regions"in this.result&&(e="\u7248\u9762\u5206\u6790\u7ed3\u679c:\n"+this.result.regions.map(((e,t)=>{let n=`${t+1}. \u7c7b\u578b: ${e.type}, \u7f6e\u4fe1\u5ea6: ${(100*e.score).toFixed(1)}%`;return"string"===typeof e.content&&(n+=`, \u5185\u5bb9: ${e.content}`),n})).join("\n"));return e}},writable:!1},LightVisualizer:{value:class{constructor(e,t={}){this.image=null,this.result=null,this.selectedId=-1,this.mode="text",this.isReady=!1,this.maxBoxesToRender=50,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0;this.options={width:300,height:200,color:"#007bff",textColor:"#ffffff",bgColor:"rgba(0, 0, 0, 0.6)",fontSize:12,lineWidth:2,responsive:!0,optimizeForMobile:!0,renderMode:"simple",...t};const n="string"===typeof e?document.getElementById(e):e;if(!n)throw new Error("\u5bb9\u5668\u5143\u7d20\u4e0d\u5b58\u5728");this.container=n,this.canvas=document.createElement("canvas"),this.canvas.width=this.options.width,this.canvas.height=this.options.height,this.canvas.style.width="100%",this.canvas.style.maxWidth="100%",this.canvas.setAttribute("role","img"),this.canvas.setAttribute("aria-label","OCR\u8bc6\u522b\u7ed3\u679c\u7b80\u6613\u53ef\u89c6\u5316");const r=this.canvas.getContext("2d",{alpha:!0,desynchronized:!0});if(!r)throw new Error("\u65e0\u6cd5\u521b\u5efa2D\u6e32\u67d3\u4e0a\u4e0b\u6587");this.ctx=r,n.appendChild(this.canvas),this.options.optimizeForMobile?this.setupTouchEvents():this.canvas.addEventListener("click",this.handleClick.bind(this)),this.options.responsive&&this.setupResizeHandler(),"list"===this.options.renderMode&&this.createResultListView()}createResultListView(){const e=document.createElement("div");e.className="paddleocr-result-list",e.style.marginTop="10px",e.style.maxHeight="200px",e.style.overflowY="auto",e.style.fontSize=`${this.options.fontSize}px`,e.style.border="1px solid #eee",e.style.borderRadius="4px",this.container.appendChild(e)}updateResultListView(){if("list"!==this.options.renderMode||!this.result)return;const e=this.container.querySelector(".paddleocr-result-list");if(e)if(e.innerHTML="","text"===this.mode&&"textRecognition"in this.result){this.result.textRecognition.slice(0,this.maxBoxesToRender).forEach(((t,n)=>{const r=document.createElement("div");r.className="paddleocr-result-item",r.style.padding="5px 8px",r.style.borderBottom="1px solid #eee",r.style.cursor="pointer",n===this.selectedId&&(r.style.backgroundColor="#f0f7ff",r.style.fontWeight="bold"),r.textContent=t.text,r.addEventListener("click",(()=>{this.selectedId=n,this.render(),this.updateResultListView()})),e.appendChild(r)}))}else if("table"===this.mode&&"cells"in this.result){this.result.cells.slice(0,this.maxBoxesToRender).forEach(((t,n)=>{const r=document.createElement("div");r.className="paddleocr-result-item",r.style.padding="5px 8px",r.style.borderBottom="1px solid #eee",r.style.cursor="pointer",n===this.selectedId&&(r.style.backgroundColor="#f0f7ff",r.style.fontWeight="bold"),r.textContent=`R${t.row}C${t.col}: ${t.text}`,r.addEventListener("click",(()=>{this.selectedId=n,this.render(),this.updateResultListView()})),e.appendChild(r)}))}else if("layout"===this.mode&&"regions"in this.result){this.result.regions.slice(0,this.maxBoxesToRender).forEach(((t,n)=>{const r=document.createElement("div");r.className="paddleocr-result-item",r.style.padding="5px 8px",r.style.borderBottom="1px solid #eee",r.style.cursor="pointer",n===this.selectedId&&(r.style.backgroundColor="#f0f7ff",r.style.fontWeight="bold"),r.textContent=`${t.type.toUpperCase()}`,"string"===typeof t.content&&(r.textContent+=`: ${t.content.slice(0,30)}${t.content.length>30?"...":""}`),r.addEventListener("click",(()=>{this.selectedId=n,this.render(),this.updateResultListView()})),e.appendChild(r)}))}}setupTouchEvents(){this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this),{passive:!0}),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this),{passive:!0})}handleTouchStart(e){if(1!==e.touches.length)return;const t=e.touches[0];this.lastTouchX=t.clientX,this.lastTouchY=t.clientY,this.lastTouchTime=Date.now()}handleTouchEnd(e){if(Date.now()-this.lastTouchTime<300){const t=e.changedTouches[0],n=this.canvas.getBoundingClientRect(),r=t.clientX-n.left,a=t.clientY-n.top;this.handleTap(r,a)}}handleTap(e,t){if(!this.result||!this.isReady)return;let n=-1;if("text"===this.mode&&"textDetection"in this.result){const r=this.result.textDetection.slice(0,this.maxBoxesToRender);n=this.findBoxAtPosition(e,t,r)}else if("table"===this.mode&&"cells"in this.result){const r=this.result.cells.slice(0,this.maxBoxesToRender);n=this.findBoxAtPosition(e,t,r)}else if("layout"===this.mode&&"regions"in this.result){const r=this.result.regions.slice(0,this.maxBoxesToRender);n=this.findBoxAtPosition(e,t,r)}if(n>=0&&(this.selectedId=n,this.render(),this.updateResultListView(),"function"===typeof this.options.onSelect)){let e=null;if("text"===this.mode&&"textDetection"in this.result){const t=this.result.textDetection[n],r=this.result.textRecognition.find((e=>e.box&&e.box.id===t.id));e={box:t,text:r}}else"table"===this.mode&&"cells"in this.result?e=this.result.cells[n]:"layout"===this.mode&&"regions"in this.result&&(e=this.result.regions[n]);this.options.onSelect(n,e)}}handleClick(e){const t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left,r=e.clientY-t.top;this.handleTap(n,r)}findBoxAtPosition(e,t,n){const{width:r,height:a}=this.canvas,s=r/this.image.naturalWidth,i=a/this.image.naturalHeight;for(let o=n.length-1;o>=0;o--){const r=n[o],a="box"in r?r.box:[];if(!a||!Array.isArray(a)||a.length<3)continue;const u=a.map((e=>({x:e.x*s,y:e.y*i})));if(this.pointInPolygon(e,t,u))return o}return-1}pointInPolygon(e,t,n){let r=!1;for(let a=0,s=n.length-1;a<n.length;s=a++){const i=n[a].x,o=n[a].y,u=n[s].x,l=n[s].y;o>t!==l>t&&e<(u-i)*(t-o)/(l-o)+i&&(r=!r)}return r}setupResizeHandler(){if("undefined"!==typeof ResizeObserver){new ResizeObserver((()=>{this.resizeCanvas(),this.isReady&&this.render()})).observe(this.container)}else window.addEventListener("resize",(()=>{this.resizeCanvas(),this.isReady&&this.render()}))}resizeCanvas(){if(!this.image||!this.container)return;const e=this.container.clientWidth,t=(this.image instanceof HTMLImageElement?this.image.naturalWidth:this.image.width)/(this.image instanceof HTMLImageElement?this.image.naturalHeight:this.image.height);this.canvas.width=Math.min(e,this.options.width),this.canvas.height=this.canvas.width/t,this.canvas.height>this.options.height&&(this.canvas.height=this.options.height,this.canvas.width=this.canvas.height*t)}async loadImage(e){try{if("string"===typeof e){const t=new Image;t.crossOrigin="anonymous",await new Promise(((n,r)=>{t.onload=()=>{this.image=t,this.isReady=!0,n()},t.onerror=()=>r(new Error("\u56fe\u50cf\u52a0\u8f7d\u5931\u8d25")),t.src=e}))}else this.image=e,this.isReady=!0;this.resizeCanvas(),this.render()}catch(t){throw t}}setResult(e){this.result=e,this.selectedId=-1,this.isReady&&(this.render(),this.updateResultListView())}setMode(e){this.mode=e,this.selectedId=-1,this.isReady&&(this.render(),this.updateResultListView())}render(){if(!this.image||!this.isReady)return;const{width:e,height:t}=this.canvas;this.ctx.clearRect(0,0,e,t),this.ctx.drawImage(this.image,0,0,e,t),this.result&&("text"===this.mode&&"textDetection"in this.result?this.renderText(this.result):"table"===this.mode&&"cells"in this.result?this.renderTable(this.result):"layout"===this.mode&&"regions"in this.result&&this.renderLayout(this.result))}renderText(e){const{width:t,height:n}=this.canvas,r=t/this.image.naturalWidth,a=n/this.image.naturalHeight;e.textDetection.slice(0,this.maxBoxesToRender).forEach(((t,n)=>{const s=n===this.selectedId,i=e.textRecognition.find((e=>e.box&&e.box.id===t.id));if(this.ctx.strokeStyle=s?"#ff9900":this.options.color,this.ctx.lineWidth=s?this.options.lineWidth+1:this.options.lineWidth,this.drawBox(t.box,r,a),"simple"!==this.options.renderMode&&i){const e=t.box.map((e=>({x:e.x*r,y:e.y*a}))),n=Math.min(...e.map((e=>e.x))),s=Math.min(...e.map((e=>e.y)));this.ctx.fillStyle=this.options.bgColor;const o=this.ctx.measureText(i.text).width+4,u=this.options.fontSize+4;this.ctx.fillRect(n,s-u,o,u),this.ctx.fillStyle=this.options.textColor,this.ctx.font=`${this.options.fontSize}px Arial`,this.ctx.fillText(i.text,n+2,s-2)}}))}renderTable(e){const{width:t,height:n}=this.canvas,r=t/this.image.naturalWidth,a=n/this.image.naturalHeight;e.cells.slice(0,this.maxBoxesToRender).forEach(((e,t)=>{const n=t===this.selectedId;if(this.ctx.strokeStyle=n?"#ff9900":this.options.color,this.ctx.lineWidth=n?this.options.lineWidth+1:this.options.lineWidth,this.drawBox(e.box,r,a),"simple"===this.options.renderMode)return;const s=e.box.map((e=>({x:e.x*r,y:e.y*a}))),i=Math.min(...s.map((e=>e.x))),o=Math.min(...s.map((e=>e.y)));this.ctx.fillStyle=this.options.bgColor;const u=e.text.length>10?e.text.substring(0,10)+"...":e.text,l=this.ctx.measureText(u).width+4,c=this.options.fontSize+4;this.ctx.fillRect(i,o-c,l,c),this.ctx.fillStyle=this.options.textColor,this.ctx.font=`${this.options.fontSize}px Arial`,this.ctx.fillText(u,i+2,o-2)}))}renderLayout(e){const{width:t,height:n}=this.canvas,r=t/this.image.naturalWidth,a=n/this.image.naturalHeight;e.regions.slice(0,this.maxBoxesToRender).forEach(((e,t)=>{const n=t===this.selectedId;let s=this.options.color;switch(e.type){case"text":s="#0066cc";break;case"title":s="#cc0000";break;case"figure":s="#00cc00";break;case"table":s="#cc6600";break;default:s="#666666"}if(this.ctx.strokeStyle=n?"#ff9900":s,this.ctx.lineWidth=n?this.options.lineWidth+1:this.options.lineWidth,this.drawBox(e.box,r,a),"simple"===this.options.renderMode)return;const i=e.box.map((e=>({x:e.x*r,y:e.y*a}))),o=Math.min(...i.map((e=>e.x))),u=Math.min(...i.map((e=>e.y)));this.ctx.fillStyle=this.options.bgColor;const l=e.type.toUpperCase(),c=this.ctx.measureText(l).width+4,d=this.options.fontSize+4;this.ctx.fillRect(o,u-d,c,d),this.ctx.fillStyle=this.options.textColor,this.ctx.font=`${this.options.fontSize}px Arial`,this.ctx.fillText(l,o+2,u-2)}))}drawBox(e,t,n){if(!e||!Array.isArray(e)||e.length<3)return;this.ctx.beginPath();const r=e.map((e=>({x:e.x*t,y:e.y*n})));this.ctx.moveTo(r[0].x,r[0].y);for(let a=1;a<r.length;a++)this.ctx.lineTo(r[a].x,r[a].y);this.ctx.closePath(),this.ctx.stroke()}updateOptions(e){this.options={...this.options,...e},this.isReady&&(this.render(),this.updateResultListView())}toDataURL(e="image/png",t=.9){return this.canvas.toDataURL(e,t)}clear(){const{width:e,height:t}=this.canvas;if(this.ctx.clearRect(0,0,e,t),this.result=null,this.selectedId=-1,"list"===this.options.renderMode){const e=this.container.querySelector(".paddleocr-result-list");e&&(e.innerHTML="")}}dispose(){if(this.canvas.removeEventListener("click",this.handleClick.bind(this)),this.canvas.removeEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.removeEventListener("touchend",this.handleTouchEnd.bind(this)),this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas),"list"===this.options.renderMode){const e=this.container.querySelector(".paddleocr-result-list");e&&e.parentElement&&e.parentElement.removeChild(e)}this.image=null,this.result=null,this.isReady=!1}},writable:!1}});const d=c})(),r=r.default})()));