diff --git "a/web/910.c72829e7a46b4712.js" "b/web/910.c72829e7a46b4712.js" deleted file mode 100644--- "a/web/910.c72829e7a46b4712.js" +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunkviewer=self.webpackChunkviewer||[]).push([[910],{7060:(_t,ct,W)=>{"use strict";W.d(ct,{Y:()=>Ms,w:()=>i8});var F={};W.r(F),W.d(F,{assertParamsValid:()=>Rp,computeFlatOffset:()=>Op,computeOutShape:()=>$p,getNormalizedAxes:()=>RC,isSliceContinous:()=>Dp,maskToAxes:()=>AC,parseSliceParams:()=>ac,sliceInfo:()=>Pp,startForAxis:()=>iy,startIndicesWithElidedDims:()=>ny,stopForAxis:()=>ay,stopIndicesWithElidedDims:()=>sy,stridesForAxis:()=>ry,stridesWithElidedDims:()=>Jx});var Re={};W.r(Re),W.d(Re,{collectGatherOpShapeInfo:()=>Of,computeOutShape:()=>ub,segOpComputeOptimalWindowSize:()=>lb});var Ke={};W.r(Ke),W.d(Ke,{ERF_A1:()=>vf,ERF_A2:()=>wf,ERF_A3:()=>_f,ERF_A4:()=>Tf,ERF_A5:()=>Sf,ERF_P:()=>bf,PARALLELIZE_THRESHOLD:()=>ff,RowPartitionType:()=>lr,SELU_SCALE:()=>Sc,SELU_SCALEALPHA:()=>Tc,applyActivation:()=>yc,assertAndGetBroadcastShape:()=>ht,assertAxesAreInnerMostDims:()=>Fn,assertParamsConsistent:()=>pf,assignToTypedArray:()=>jy,axesAreInnerMostDims:()=>Gp,calculateShapes:()=>Mi,checkEinsumDimSizes:()=>Nf,checkPadOnDimRoundingMode:()=>qn,combineLocations:()=>gy,combineRaggedTensorToTensorShapes:()=>My,complexWithEvenIndex:()=>Gy,complexWithOddIndex:()=>Hy,computeConv2DInfo:()=>Nn,computeConv3DInfo:()=>qr,computeDefaultPad:()=>Lp,computeDilation2DInfo:()=>tl,computeOptimalWindowSize:()=>_c,computeOutAndReduceShapes:()=>An,computeOutShape:()=>or,computePool2DInfo:()=>ks,computePool3DInfo:()=>Tr,convertConv2DDataFormat:()=>Sr,decodeEinsumEquation:()=>Ef,eitherStridesOrDilationsAreOne:()=>Pn,expandShapeToKeepDim:()=>hn,exponent:()=>Ky,exponents:()=>Xy,fromStringArrayToUint8:()=>cb,fromUint8ToStringArray:()=>Ar,getAxesPermutation:()=>rn,getBroadcastDims:()=>ga,getComplexWithIndex:()=>Cf,getEinsumComputePath:()=>Af,getEinsumPermutation:()=>kf,getFusedBiasGradient:()=>xc,getFusedDyActivation:()=>gc,getImageCenter:()=>mf,getInnerMostAxes:()=>dn,getPermuted:()=>fl,getRaggedRank:()=>zy,getReductionAxes:()=>bn,getReshaped:()=>pl,getReshapedPermuted:()=>ml,getRowPartitionTypesHelper:()=>Vy,getSliceBeginCoords:()=>gf,getSliceSize:()=>xf,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>Yy,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>Qy,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>Jy,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>nb,getSparseReshapeInputOutputMismatchErrorMessage:()=>rb,getSparseReshapeInputOutputMultipleErrorMessage:()=>sb,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>eb,getSparseReshapeNegativeOutputDimErrorMessage:()=>tb,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>ob,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>Df,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>ib,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>ab,getUndoAxesPermutation:()=>Yr,isIdentityPermutation:()=>Rf,log:()=>B1,mergeRealAndImagArrays:()=>Nr,prepareAndValidate:()=>yf,prepareSplitSize:()=>$f,segment_util:()=>Re,shouldFuse:()=>bc,slice_util:()=>F,splitRealAndImagArrays:()=>Wy,stridesOrDilationsArePositive:()=>Di,tupleValuesAreOne:()=>Zr,upcastType:()=>ls,validateDefaultValueShape:()=>By,validateInput:()=>$N,validateUpdateShape:()=>Uy,warn:()=>fs});var Tt={};W.r(Tt),W.d(Tt,{mx:()=>Fw,XI:()=>Um,Nk:()=>Uw,f6:()=>Ww,ct:()=>Pw,YG:()=>Gw,hH:()=>Hw,z3:()=>Kw,sG:()=>Zw,uM:()=>Qw,vS:()=>t_,qB:()=>n_,GG:()=>s_,lg:()=>i_,rq:()=>r_,cu:()=>o_,WR:()=>a_,GE:()=>l_,px:()=>u_,jC:()=>c_,He:()=>d_,hE:()=>p_,BF:()=>Wm,Dk:()=>m_,cl:()=>g_,_B:()=>v_,ub:()=>__,_f:()=>S_,Ku:()=>E_,qy:()=>k_,Zy:()=>N_,bu:()=>Ki,zv:()=>fP,dH:()=>Mw,HS:()=>Bw,yH:()=>R_,l3:()=>$_,z9:()=>qm,x6:()=>B3,_m:()=>D_,eW:()=>O_,GK:()=>P_,SP:()=>F_,yr:()=>L_,dl:()=>Jw,Dw:()=>M_,xT:()=>z_,_X:()=>zm,wz:()=>U_});var nt=W(7673),Xe=W(4572),st=W(6648),Ce=W(8141),q=W(9437),de=W(1397),_e=W(5964),ue=W(9852),fe=W(6594),Pe=W(6354),Te=W(6173),lt=W(3993),Ht=W(9974),at=W(4360),jt=W(3669),Ee=W(1584),Be=W(8750),et=W(1985),N=W(467);class we{constructor(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}get(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)}set(t,e){this.dataIdsCount++,this.data.set(t,e)}has(t){return this.data.has(t)}delete(t){return this.dataIdsCount--,this.data.delete(t)}numDataIds(){return this.dataIdsCount}}class Fe{refCount(t){return $e("refCount")}incRef(t){return $e("incRef")}timerAvailable(){return!0}time(t){return $e("time")}read(t){return $e("read")}readSync(t){return $e("readSync")}readToGPU(t,e){return $e("readToGPU")}numDataIds(){return $e("numDataIds")}disposeData(t,e){return $e("disposeData")}write(t,e,s){return $e("write")}move(t,e,s,r,i){return $e("move")}createTensorFromGPUData(t,e,s){return $e("createTensorFromGPUData")}memory(){return $e("memory")}floatPrecision(){return $e("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return $e("dispose")}}function $e(n){throw new Error(`'${n}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function qe(n){let t=n.length,e=0;for(;t>0;)e=Math.random()*t|0,t--,M(n,t,e)}function G(n,t,e){return Math.max(n,Math.min(t,e))}function C(n){return n%2==0?n:n+1}function M(n,t,e){const s=n[t];n[t]=n[e],n[e]=s}function T(n,t){if(!n)throw new Error("string"==typeof t?t:t())}function Me(n,t,e=""){T(rt(n,t),()=>e+` Shapes ${n} and ${t} must match`)}function Ye(n){T(null!=n,()=>"The input to the tensor constructor must be a non-null value.")}function K(n){if(0===n.length)return 1;let t=n[0];for(let e=1;e0,e,s){return new Promise((r,i)=>{let a=0;const o=()=>{if(n())return void r();a++;const l=t(a);null!=e&&a>=e?i():null!=s?s(o,l):setTimeout(o,l)};o()})}function It(n,t){let e=1,s=-1;for(let i=0;i=0)e*=n[i];else if(-1===n[i]){if(-1!==s)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${i}`);s=i}else if(n[i]<0)throw Error(`Shapes can not be < 0. Found ${n[i]} at dim ${i}`);if(-1===s){if(t>0&&t!==e)throw Error(`Size(${t}) must match the product of shape ${n}`);return n}if(0===e)throw Error(`Cannot infer the missing size in [${n}] when there are 0 elements`);if(t%e!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${e}`);const r=n.slice();return r[s]=t/e,r}function pt(n,t){const e=t.length;return T((n=null==n?t.map((s,r)=>r):[].concat(n)).every(s=>s>=-e&&s`All values in axis param must be in range [-${e}, ${e}) but got axis ${n}`),T(n.every(s=>St(s)),()=>`All values in axis param must be integers but got axis ${n}`),n.map(s=>s<0?e+s:s)}function Qs(n,t){const e=[],s=[],r=null!=t&&Array.isArray(t)&&0===t.length,i=null==t||r?null:pt(t,n).sort();let a=0;for(let o=0;oo)&&1===n[o]&&(e.push(n[o]),s.push(o)),i[a]<=o&&a++}1!==n[o]&&(e.push(n[o]),s.push(o))}return{newShape:e,keptDims:s}}function Cn(n,t){return $t(n,t)}function $t(n,t){let e=null;if(null==n||"float32"===n)e=new Float32Array(t);else if("int32"===n)e=new Int32Array(t);else if("bool"===n)e=new Uint8Array(t);else{if("string"!==n)throw new Error(`Unknown data type ${n}`);e=new Array(t)}return e}function Ve(n,t){return!("complex64"===t||"float32"===t&&"complex64"!==n||"int32"===t&&"float32"!==n&&"complex64"!==n||"bool"===t&&"bool"===n)}function ra(n){if("float32"===n||"int32"===n)return 4;if("complex64"===n)return 8;if("bool"===n)return 1;throw new Error(`Unknown dtype ${n}`)}function os(n){return"string"==typeof n||n instanceof String}function ia(n){return"number"==typeof n}function vr(n){return Array.isArray(n)?vr(n[0]):n instanceof Float32Array?"float32":n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray?"int32":ia(n)?"float32":os(n)?"string":function ln(n){return"boolean"==typeof n}(n)?"bool":"float32"}function Cs(n){return!!(n&&n.constructor&&n.call&&n.apply)}function vi(n,t){for(let e=t;e=0;--s)e[s]=e[s+1]*n[s+1];return e}function jl(n,t,e,s=!1){const r=new Array;if(1===t.length){const i=t[0]*(s?2:1);for(let a=0;al*u)*(s?2:1);for(let l=0;lr*i)*(e?2:1);if(0===s)return[];if(s!==t.length)throw new Error(`[${n}] does not match the input size ${t.length}${e?" for a complex tensor":""}.`);return jl(0,n,t,e)}function Vr(n,t){const e=yn(n,t);for(let s=0;ss*r,1);if(null==t||"float32"===t)return ds(n,new Float32Array(e));if("int32"===t)return ds(n,new Int32Array(e));if("bool"===t)return ds(n,new Uint8Array(e));throw new Error(`Unknown data type ${t}`)}function Js(n){n.forEach(t=>{T(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${n}].`)})}function Is(n,t,e){if(0===t)return 0;if(1===t)return n[0];let s=n[n.length-1];for(let r=0;r"u"||typeof this.global.location>"u"||typeof this.global.location.search>"u")return;const t=this.getQueryParams(this.global.location.search);ve in t&&t[ve].split(",").forEach(s=>{const[r,i]=s.split(":");this.urlFlags[r]=function H(n,t){const e=t.toLowerCase();return"true"===e||"false"===e?"true"===e:""+ +e===e?+e:t}(0,i)})}}function _(n){const t={};return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...s)=>(function A(n,t,e){n[decodeURIComponent(t)]=decodeURIComponent(e||"")}(t,s[0],s[1]),s.join("="))),t}function E(){return ye}let gt,ye=null;function zt(){if(null==gt){let n;if(typeof window<"u")n=window;else if(typeof global<"u")n=global;else if(typeof process<"u")n=process;else{if(!(typeof self<"u"))throw new Error("Could not find a global object");n=self}gt=n}return gt}function xn(n,t){const e=function bt(){const n=zt();return null==n._tfGlobals&&(n._tfGlobals=new Map),n._tfGlobals}();if(e.has(n))return e.get(n);{const s=t();return e.set(n,s),e.get(n)}}const In="Abs",jn="Acos",ps="Acosh",oa="Add",ed="AddN",Kl="ArgMax",ql="ArgMin",Qa="Asin",Ja="Asinh",eo="Atan",to="Atanh",no="Atan2",Zl="AvgPool",sd="AvgPoolGrad",Yl="AvgPool3D",rd="AvgPool3DGrad",Ql="BatchMatMul",Jl="BatchToSpaceND",id="Bincount",ad="BitwiseAnd",Fg="BroadcastArgs",so="Cast",ro="Ceil",ao="ClipByValue",od="Complex",eu="ComplexAbs",tu="Concat",nu="Conv2D",ld="Conv2DBackpropFilter",su="Conv2DBackpropInput",ru="Conv3D",ud="Conv3DBackpropFilterV2",cd="Conv3DBackpropInputV2",oo="Cos",lo="Cosh",hd="Cumprod",iu="Cumsum",dd="CropAndResize",pd="DenseBincount",fd="DepthToSpace",au="DepthwiseConv2dNative",md="DepthwiseConv2dNativeBackpropFilter",gd="DepthwiseConv2dNativeBackpropInput",ou="Dilation2D",xd="Dilation2DBackpropInput",yd="Dilation2DBackpropFilter",uo="RealDiv",vd="Einsum",co="Elu",wd="EluGrad",ho="Erf",lu="Equal",po="Exp",uu="ExpandDims",fo="Expm1",Td="Fill",Sd="FlipLeftRight",mo="Floor",go="FloorDiv",cu="FusedBatchNorm",hu="GatherV2",Mg="GatherNd",du="Greater",xo="GreaterEqual",yo="Identity",Cd="IFFT",Id="Imag",bo="IsFinite",vo="IsInf",wo="IsNan",pu="LeakyRelu",fu="Less",mu="LessEqual",Vg="LinSpace",_o="Log",To="Log1p",gu="LogicalAnd",xu="LogicalNot",yu="LogicalOr",bu="LRN",Ed="LRNGrad",vu="Max",So="Maximum",wu="MaxPool",kd="MaxPoolGrad",_u="MaxPool3D",Nd="MaxPool3DGrad",zg="MaxPoolWithArgmax",Tu="Mean",Su="Min",Co="Minimum",Cu="MirrorPad",Io="Mod",Bg="Multinomial",Eo="Multiply",Iu="Neg",Eu="NotEqual",Ad="NonMaxSuppressionV3",Rd="NonMaxSuppressionV4",$d="NonMaxSuppressionV5",ku="OnesLike",Nu="OneHot",Au="Pack",Ru="PadV2",ko="Pow",$u="Prelu",Du="Prod",Ug="RaggedGather",Wg="RaggedRange",Gg="RaggedTensorToTensor",Dd="Range",Od="Real",No="Reciprocal",Ao="Relu",Ou="Reshape",Pu="ResizeNearestNeighbor",Pd="ResizeNearestNeighborGrad",Fu="ResizeBilinear",Fd="ResizeBilinearGrad",Ro="Relu6",Lu="Reverse",$o="Round",Do="Rsqrt",Hg="ScatterNd",jg="TensorScatterUpdate",Xg="SearchSorted",Mu="Select",Oo="Selu",Vu="Slice",Po="Sin",Fo="Sinh",Lo="Sign",Mo="Sigmoid",Vo="Softplus",zo="Sqrt",zu="Sum",Bu="SpaceToBatchND",Uu="SplitV",Wu="Softmax",Ld="SparseFillEmptyRows",Md="SparseReshape",Vd="SparseSegmentMean",zd="SparseSegmentSum",Kg="SparseToDense",Bo="SquaredDifference",Bd="Square",Gu="StaticRegexReplace",Ud="StridedSlice",Wd="StringNGrams",Gd="StringSplit",Hd="StringToHashBucketFast",Uo="Sub",Wo="Tan",Go="Tanh",Ho="Tile",jd="TopK",Xd="Transform",la="Transpose",Kd="Unique",Hu="Unpack",ju="UnsortedSegmentSum",Xu="ZerosLike",jo="Step",Zd="RotateWithOffset",Ku="_FusedMatMul",qu="FusedConv2D",Zu="FusedDepthwiseConv2D";function fs(...n){E().getBool("IS_TEST")||E().getBool("PROD")||console.warn(...n)}function B1(...n){E().getBool("IS_TEST")||E().getBool("PROD")||console.log(...n)}const ua=xn("kernelRegistry",()=>new Map),Xo=xn("gradRegistry",()=>new Map);function Yu(n,t){const e=Jd(n,t);return ua.get(e)}function qg(n){return Xo.get(n)}function Yd(n){const t=ua.entries(),e=[];for(;;){const{done:s,value:r}=t.next();if(s)break;const[i,a]=r,[o]=i.split("_");o===n&&e.push(a)}return e}function Qd(n){const{kernelName:t,backendName:e}=n,s=Jd(t,e);ua.has(s)&&fs(`The kernel '${t}' for backend '${e}' is already registered`),ua.set(s,n)}function U1(n){const{kernelName:t}=n;Xo.has(t)&&E().getBool("DEBUG")&&fs(`Overriding the gradient for '${t}'`),Xo.set(t,n)}function Jd(n,t){return`${t}_${n}`}function Zg(n){return n instanceof Float32Array||n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray}var Yg=W(1929);const wi=W.n(Yg)()||Yg;function Qu(n){return wi.fromString(n,!0,16)}const Qg=Qu("c3a5c85c97cb3127"),_i=Qu("b492b66fbe98f273"),Xn=Qu("9ae16a3b2f90404f");function ep(n){return n.xor(n.shru(47))}function Jg(n,t,e){const s=n.slice(t,t+e);return wi.fromBytes(Array.from(s),!0,!0)}function Xt(n,t){return Jg(n,t,8)}function ex(n,t){return Jg(n,t,4)}function En(n,t){return 0===t?n:n.shru(t).or(n.shl(64-t))}function zr(n,t,e=Qu("9ddfea08eb382d69")){let s=n.xor(t).mul(e);s=s.xor(s.shru(47));let r=t.xor(s).mul(e);return r=r.xor(r.shru(47)),r=r.mul(e),r}function Ju(n,t,e,s){return function G1(n,t,e,s,r,i){r=r.add(n),i=En(i.add(r).add(s),21);const a=r;return r=(r=r.add(t)).add(e),i=i.add(En(r,44)),[r.add(s),i.add(a)]}(Xt(n,t),Xt(n,t+8),Xt(n,t+16),Xt(n,t+24),e,s)}function K1(n,t=n.length){const e=wi.fromNumber(81,!0);if(t<=32)return t<=16?function H1(n,t=n.length){if(t>=8){const e=Xn.add(2*t),s=Xt(n,0).add(Xn),r=Xt(n,t-8);return zr(En(r,37).mul(e).add(s),En(s,25).add(r).mul(e),e)}if(t>=4){const e=Xn.add(2*t);return zr(ex(n,0).shl(3).add(t),ex(n,t-4),e)}if(t>0){const a=t+(n[t-1]<<2);return ep(Xn.mul(n[0]+(n[t>>1]<<8)).xor(Qg.mul(a))).mul(Xn)}return Xn}(n,t):function j1(n,t=n.length){const e=Xn.add(2*t),s=Xt(n,0).mul(_i),r=Xt(n,8),i=Xt(n,t-8).mul(e),a=Xt(n,t-16).mul(Xn);return zr(En(s.add(r),43).add(En(i,30)).add(a),s.add(En(r.add(Xn),18)).add(i),e)}(n,t);if(t<=64)return function X1(n,t=n.length){const e=Xn.add(2*t),s=Xt(n,0).mul(Xn),r=Xt(n,8),i=Xt(n,t-8).mul(e),a=Xt(n,t-16).mul(Xn),o=En(s.add(r),43).add(En(i,30)).add(a),l=zr(o,s.add(En(r.add(Xn),18)).add(i),e),u=Xt(n,16).mul(e),c=Xt(n,24),h=o.add(Xt(n,t-32)).mul(e),d=l.add(Xt(n,t-24)).mul(e);return zr(En(u.add(c),43).add(En(h,30)).add(d),u.add(En(c.add(s),18)).add(h),e)}(n,t);let s=e,r=e.mul(_i).add(113),i=ep(r.mul(Xn).add(113)).mul(Xn),a=[wi.UZERO,wi.UZERO],o=[wi.UZERO,wi.UZERO];s=s.mul(Xn).add(Xt(n,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{s=En(s.add(r).add(a[0]).add(Xt(n,l+8)),37).mul(_i),r=En(r.add(a[1]).add(Xt(n,l+48)),42).mul(_i),s=s.xor(o[1]),r=r.add(a[0]).add(Xt(n,l+40)),i=En(i.add(o[0]),33).mul(_i),a=Ju(n,l,a[1].mul(_i),s.add(o[0])),o=Ju(n,l+32,i.add(o[1]),r.add(Xt(n,l+16))),[i,s]=[s,i],l+=64}while(l!==u);const h=_i.add(i.and(255).shl(1));return l=c,o[0]=o[0].add(t-1&63),a[0]=a[0].add(o[0]),o[0]=o[0].add(a[0]),s=En(s.add(r).add(a[0]).add(Xt(n,l+8)),37).mul(h),r=En(r.add(a[1]).add(Xt(n,l+48)),42).mul(h),s=s.xor(o[1].mul(9)),r=r.add(a[0].mul(9).add(Xt(n,l+40))),i=En(i.add(o[0]),33).mul(h),a=Ju(n,l,a[1].mul(h),s.add(o[0])),o=Ju(n,l+32,i.add(o[1]),r.add(Xt(n,l+16))),[i,s]=[s,i],zr(zr(a[0],o[0],h).add(ep(r).mul(Qg)).add(i),zr(a[1],o[1],h).add(s),h)}function Br(n,t){return"string"===t?Ur(n):Ti([n],t)}function Ti(n,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=Si(n)),E().getBool("DEBUG")&&function sa(n,t){for(let e=0;e{r=s()};let a;const o=Vn();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(i);else{i();for(const u of r)u.dataSync();a=Promise.resolve({kernelMs:Vn()-o})}if(E().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let u=0;u{Q1(h,c.dtype,t)})}return{kernelName:t,outputs:r,inputs:e,timeMs:a.then(u=>u.kernelMs),extraInfo:a.then(u=>null!=u.getExtraProfileInfo?u.getExtraProfileInfo():"")}}logKernelProfile(t){const{kernelName:e,outputs:s,timeMs:r,inputs:i,extraInfo:a}=t;s.forEach(o=>{Promise.all([o.data(),r,a]).then(l=>{this.logger.logKernelProfile(e,o,l[0],l[1],i,l[2])})})}}function Q1(n,t,e){if("float32"!==t)return!1;for(let s=0;s0?g:""} `}}console.log(`%c${l}\t%c${o}\t%c${u}D ${h}\t%c${c}\t%c${d}\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function nS(n,t,e,s){const r=Ue(t),i=function sS(n,t,e,s){const r=K(t),i=s[s.length-1],a=new Array(i).fill(0),o=t.length,l="complex64"===e?Zo(n):n;if(o>1)for(let u=0;u" "+u).join("\n")),l.join("\n")}function qo(n,t,e){let s;return s=Array.isArray(n)?`${parseFloat(n[0].toFixed(7))} + ${parseFloat(n[1].toFixed(7))}j`:os(n)?`'${n}'`:"bool"===e?nx(n):parseFloat(n.toFixed(7)).toString(),zs(s,t)}function nx(n){return 0===n?"false":"true"}function ec(n,t,e,s,r,i=!0){const a="complex64"===e?2:1,o=t[0],l=t.length;if(0===l)return"complex64"===e?[qo(Zo(n)[0],0,e)]:"bool"===e?[nx(n[0])]:[n[0].toString()];if(1===l){if(o>20){let x=Array.from(n.slice(0,3*a)),y=Array.from(n.slice((o-3)*a,o*a));return"complex64"===e&&(x=Zo(x),y=Zo(y)),["["+x.map((b,v)=>qo(b,r[v],e)).join(", ")+", ..., "+y.map((b,v)=>qo(b,r[o-3+v],e)).join(", ")+"]"]}return["["+("complex64"===e?Zo(n):Array.from(n)).map((m,x)=>qo(m,r[x],e)).join(", ")+"]"]}const u=t.slice(1),c=s.slice(1),h=s[0]*a,d=[];if(o>20){for(let g=0;g<3;g++){const m=g*h;d.push(...ec(n.slice(m,m+h),u,e,c,r,!1))}d.push("...");for(let g=o-3;g0?d[0]+p:"");for(let g=1;g`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=s||$t(e,this.size),this.strides=Ue(t)}set(t,...e){0===e.length&&(e=[0]),T(e.length===this.rank,()=>`The number of provided coordinates (${e.length}) must match the rank (${this.rank})`);const s=this.locToIndex(e);this.values[s]=t}get(...t){0===t.length&&(t=[0]);let e=0;for(const r of t){if(r<0||r>=this.shape[e])throw new Error(`Requested out of range element at ${t}. Buffer shape=${this.shape}`);e++}let s=t[t.length-1];for(let r=0;rWr(r))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e})()}dataToGPU(t){return this.throwIfDisposed(),Bs().readToGPU(this.dataId,t)}dataSync(){this.throwIfDisposed();const t=Bs().readSync(this.dataId);if("string"===this.dtype)try{return t.map(e=>Wr(e))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t}bytes(){var t=this;return(0,N.A)(function*(){t.throwIfDisposed();const e=yield Bs().read(t.dataId);return"string"===t.dtype?e:new Uint8Array(e.buffer)})()}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Bs().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(t=!1){return ca.print(this,t)}clone(){return this.throwIfDisposed(),ca.clone(this)}toString(t=!1){return nS(this.dataSync(),this.shape,this.dtype,t)}cast(t){return this.throwIfDisposed(),ca.cast(this,t)}variable(t=!0,e,s){return this.throwIfDisposed(),Bs().makeVariable(this,t,e,s)}}function ne(){return xn("Tensor",()=>Qt)}Object.defineProperty(Qt,Symbol.hasInstance,{value:n=>!!n&&null!=n.data&&null!=n.dataSync&&null!=n.throwIfDisposed}),ne();class tc extends Qt{constructor(t,e,s,r){super(t.shape,t.dtype,t.dataId,r),this.trainable=e,this.name=s}assign(t){if(t.dtype!==this.dtype)throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);if(!rt(t.shape,this.shape))throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);Bs().disposeTensor(this),this.dataId=t.dataId,Bs().incRef(this,null)}dispose(){Bs().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(tc,Symbol.hasInstance,{value:n=>n instanceof Qt&&null!=n.assign&&n.assign instanceof Function});var rx=function(n){return n.float32="float32",n.int32="int32",n.bool="int32",n.complex64="complex64",n}(rx||{}),ix=function(n){return n.float32="float32",n.int32="int32",n.bool="bool",n.complex64="complex64",n}(ix||{}),ax=function(n){return n.float32="float32",n.int32="float32",n.bool="float32",n.complex64="complex64",n}(ax||{}),ox=function(n){return n.float32="complex64",n.int32="complex64",n.bool="complex64",n.complex64="complex64",n}(ox||{});const lS={float32:ax,int32:rx,bool:ix,complex64:ox};function ls(n,t){if("string"===n||"string"===t){if("string"===n&&"string"===t)return"string";throw new Error(`Can not upcast ${n} with ${t}`)}return lS[n][t]}function np(n){return ls(n,"int32")}function lx(n){return null!=n&&"object"==typeof n&&"texture"in n&&n.texture instanceof WebGLTexture}function ux(n){return typeof GPUBuffer<"u"&&null!=n&&"object"==typeof n&&"buffer"in n&&n.buffer instanceof GPUBuffer}function un(n,t){if(n.dtype===t.dtype)return[n,t];const e=ls(n.dtype,t.dtype);return[n.cast(e),t.cast(e)]}function Gr(n){const t=[];return cx(n,t,new Set),t}function cx(n,t,e){if(null==n)return;if(n instanceof Qt)return void t.push(n);if(!function uS(n){return Array.isArray(n)||"object"==typeof n}(n))return;const s=n;for(const r in s){const i=s[r];e.has(i)||(e.add(i),cx(i,t,e))}}function rp(n){return null!=n.kernelName}class hx{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(t=>t.name)))}}}dispose(){for(const t in this.registeredVariables)this.registeredVariables[t].dispose()}}let cS=(()=>{class n{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new hx}ready(){var e=this;return(0,N.A)(function*(){if(null!=e.pendingBackendInit)return e.pendingBackendInit.then(()=>{});if(null!=e.backendInstance)return;const s=e.getSortedBackends();for(let r=0;r{null!=s.setupFunc&&s.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Yd(e).forEach(r=>{null!=r.disposeFunc&&r.disposeFunc(this.registry[e])})}initializeBackend(e){const s=this.registryFactory[e];if(null==s)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const r=s.factory();if(!r||r instanceof Fe||"function"!=typeof r.then)return this.registry[e]=r,{success:!0,asyncInit:!1};{const i=++this.pendingBackendInitId,a=r.then(o=>!(i(ithis.registryFactory[s].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let s=0;sthis.startScope(r),()=>this.endScope(i),()=>(i=s(),i instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),i))}scopedRun(e,s,r){e();try{const i=r();return s(),i}catch(i){throw s(),i}}nextTensorId(){return n.nextTensorId++}nextVariableId(){return n.nextVariableId++}clone(e){const s=V.runKernel(yo,{x:e});return this.addTapeNode(this.state.activeScope.name,{x:e},[s],o=>({x:()=>V.runKernel(so,{x:o},{dtype:"float32"})}),[],{}),s}runKernel(e,s,r){if(null==Yu(e,this.backendName))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:s,attrs:r})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,s,r){const i=this.backend.numDataIds();let a=0;r.forEach(u=>{a+="complex64"===u.dtype?3:1});const l=i-s-a-this.state.numDataMovesStack[this.state.numDataMovesStack.length-1];if(l>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${l} data ids) after running '${e}'`)}runKernelFunc(e){let s,r=[];const i=this.isTapeOn(),a=this.state.numBytes,o=this.state.numTensors;let l,u;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);const c=rp(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(rp(e)){const{kernelName:g,inputs:m,attrs:x}=e,y=Yu(g,this.backendName);T(null!=y,()=>`Cannot find registered kernel '${g}' for backend '${this.backendName}'`),l=()=>{const b=this.backend.numDataIds();u=y.kernelFunc({inputs:m,attrs:x,backend:this.backend});const v=Array.isArray(u)?u:[u];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(g,b,v);const w=v.map(S=>null!=S.rank?S:this.makeTensorFromTensorInfo(S));if(i){const S=this.getTensorsForGradient(g,m,w);r=this.saveTensorsForBackwardMode(S)}return w}}else{const{forwardFunc:g}=e,m=x=>{i&&(r=x.map(y=>this.keep(this.clone(y))))};l=()=>{const x=this.backend.numDataIds();u=this.tidy(()=>g(this.backend,m));const y=Array.isArray(u)?u:[u];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,x,y),y}}const{inputs:h,attrs:d}=e,p=rp(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(c,h,()=>l()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),s=f.outputs):s=l()}),i&&this.addTapeNode(c,h,s,p,r,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:c,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-o,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(h).map(g=>null!=h[g]?h[g].shape:null),outputShapes:s.map(g=>g.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(u)?s:s[0]}saveTensorsForBackwardMode(e){return e.map(r=>this.keep(this.clone(r)))}getTensorsForGradient(e,s,r){const i=qg(e);if(null!=i){const a=i.inputsToSave||[],o=i.outputsToSave||[];let l;i.saveAllInputs?(T(Array.isArray(s),()=>"saveAllInputs is true, expected inputs to be an array."),l=Object.keys(s).map(c=>s[c])):l=a.map(c=>s[c]);const u=r.filter((c,h)=>o[h]);return l.concat(u)}return[]}makeTensor(e,s,r,i){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");i=i||this.backend;let a=e;"string"===(r=r||"float32")&&os(e[0])&&(a=e.map(u=>Ur(u)));const o=i.write(a,s,r),l=new Qt(s,r,o,this.nextTensorId());if(this.trackTensor(l,i),"string"===r){const u=this.state.tensorInfo.get(o),c=function ce(n){if(null==n)return 0;let t=0;return n.forEach(e=>t+=e.length),t}(a);this.state.numBytes+=c-u.bytes,u.bytes=c}return l}makeTensorFromDataId(e,s,r,i){return this.makeTensorFromTensorInfo({dataId:e,shape:s,dtype:r=r||"float32"},i)}makeTensorFromTensorInfo(e,s){const{dataId:r,shape:i,dtype:a}=e,o=new Qt(i,a,r,this.nextTensorId());return this.trackTensor(o,s),o}makeVariable(e,s=!0,r,i){r=r||this.nextVariableId().toString(),null!=i&&i!==e.dtype&&(e=e.cast(i));const a=new tc(e,s,r,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,s){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let r=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(r=e.size*ra(e.dtype)),this.state.numBytes+=r,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:s||this.backend,dtype:e.dtype,shape:e.shape,bytes:r})),e instanceof tc||this.track(e)}incRef(e,s){this.trackTensor(e,s),this.backend.incRef(e.dataId)}removeDataId(e,s){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===s&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const s=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=s.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const r=e.size*ra(e.dtype);this.state.numBytes-=r}s.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,s.backend)}disposeVariables(){for(const e in this.state.registeredVariables)this.disposeVariable(this.state.registeredVariables[e])}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}profile(e){var s=this;return(0,N.A)(function*(){s.state.profiling=!0;const r=s.state.numBytes,i=s.state.numTensors;s.state.activeProfile.kernels=[],s.state.activeProfile.result=yield e(),s.state.profiling=!1,s.state.activeProfile.peakBytes=Math.max(...s.state.activeProfile.kernels.map(a=>a.totalBytesSnapshot)),s.state.activeProfile.newBytes=s.state.numBytes-r,s.state.activeProfile.newTensors=s.state.numTensors-i;for(const a of s.state.activeProfile.kernels)a.kernelTimeMs=yield a.kernelTimeMs,a.extraInfo=yield a.extraInfo;return s.state.activeProfile})()}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,s,r,i,a,o){const l={id:this.state.nextTapeNodeId++,kernelName:e,inputs:s,outputs:r,saved:a},u=qg(e);null!=u&&(i=u.gradFunc),null!=i&&(l.gradient=c=>(c=c.map((h,d)=>{if(null==h){const p=r[d],f=yn(p.size,p.dtype);return this.makeTensor(f,p.shape,p.dtype)}return h}),i(c.length>1?c:c[0],a,o))),this.state.activeTape.push(l)}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 s={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(s.name=e),this.state.scopeStack.push(s),this.state.activeScope=s}endScope(e){const s=Gr(e),r=new Set(s.map(a=>a.id));for(let a=0;a{!a.kept&&a.scopeId===i.id&&this.track(a)})}gradients(e,s,r,i=!1){if(T(s.length>0,()=>"gradients() received an empty list of xs."),null!=r&&"float32"!==r.dtype)throw new Error(`dy must have 'float32' dtype, but has '${r.dtype}'`);const a=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));T(a instanceof Qt,()=>"The result y returned by f() must be a tensor.");const o=function eS(n,t,e){const s={},r={};for(let l=0;ls[g.id]=!0),p=!0,r[u.id]=!0;break}if(p)break}}const i={};i[e.id]=!0;const a={};for(let l=n.length-1;l>=0;l--){const u=n[l],c=u.inputs;for(let h=0;h0)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 l={};l[a.id]=r??function hS(n){const t=Vr(K(n),"float32");return V.makeTensor(t,n,"float32")}(a.shape),function tS(n,t,e,s){for(let r=t.length-1;r>=0;r--){const i=t[r],a=[];if(i.outputs.forEach(l=>{const u=n[l.id];a.push(null!=u?u:null)}),null==i.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${i.kernelName}.`);const o=i.gradient(a);for(const l in i.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);const u=e(()=>o[l]());if("float32"!==u.dtype)throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);const c=i.inputs[l];if(!rt(u.shape,c.shape))throw new Error(`Error in gradient for op ${i.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`);if(null==n[c.id])n[c.id]=u;else{const h=n[c.id];n[c.id]=s(h,u),h.dispose()}}}}(l,o,c=>this.tidy(c),dS);const u=s.map(c=>l[c.id]);return 0===this.state.gradientDepth&&(this.state.activeTape.forEach(c=>{for(const h of c.saved)h.dispose()}),this.state.activeTape=null),{value:a,grads:u}})}customGrad(e){return T(Cs(e),()=>"The f passed in customGrad(f) must be a function."),(...s)=>{let r;T(s.every(l=>l instanceof Qt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");const i={};return s.forEach((l,u)=>{i[u]=l}),this.runKernelFunc({forwardFunc:(l,u)=>(r=e(...s,u),T(r.value instanceof Qt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),T(Cs(r.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),r.value),backwardsFunc:(l,u)=>{const c=r.gradFunc(l,u),h=Array.isArray(c)?c:[c];T(h.length===s.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(...)."),T(h.every(p=>p instanceof Qt),()=>"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 d={};return h.forEach((p,f)=>{d[f]=()=>p}),d},inputs:i})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,s){return this.state.tensorInfo.get(e).backend.readToGPU(e,s)}time(e){var s=this;return(0,N.A)(function*(){const r=Vn(),i=yield s.backend.time(e);return i.wallMs=Vn()-r,i})()}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 hx;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}}return n.nextTensorId=0,n.nextVariableId=0,n})();function dx(){const n=zt();if(null==n._tfengine){const t=new Oe(n);n._tfengine=new cS(t)}return function Je(n){ye=n}(n._tfengine.ENV),function rS(n){Bs=n}(()=>n._tfengine),n._tfengine}const V=dx();function dS(n,t){return V.runKernel(oa,{a:n,b:t})}function px(n){if(n||function pS(){return typeof navigator<"u"&&null!=navigator}()){if(n||(n=navigator),"ReactNative"===n.product)return!0;const t=n.userAgent||n.vendor||(typeof window<"u"?window.opera:"");return t?/(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)):n.userAgentData&&n.userAgentData.mobile}return!1}function fx(){return typeof window<"u"&&null!=window.document||typeof WorkerGlobalScope<"u"}const ns=E();function Yo(n,t){let e=n;if(ms(n))return"string"===t?[]:[n.length];if(lx(n))return[n.height,n.width*(n.channels||"RGBA").length];if(ux(n))return[n.buffer.size/(null==t?4:ra(t))];if(!Array.isArray(n))return[];const s=[];for(;Array.isArray(e)||ms(e)&&"string"!==t;)s.push(e.length),e=e[0];return Array.isArray(n)&&E().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&mx(n,s,[]),s}function mx(n,t,e){if(e=e||[],!Array.isArray(n)&&!ms(n))return void T(0===t.length,()=>`Element arr[${e.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);T(t.length>0,()=>`Element arr[${e.join("][")}] should be a primitive, but is an array of ${n.length} elements`),T(n.length===t[0],()=>`Element arr[${e.join("][")}] should have ${t[0]} elements, but has ${n.length} elements`);const s=t.slice(1);for(let r=0;r=0&&(r=s),gx(s,r,t,e),null==n||!ms(n)&&!Array.isArray(n)&&"number"!=typeof n&&"boolean"!=typeof n&&"string"!=typeof n)throw new Error(`Argument '${t}' passed to '${e}' must be a Tensor or TensorLike, but got '${null==n?"null":n.constructor.name}'`);const i=Yo(n,r);!ms(n)&&!Array.isArray(n)&&(n=[n]);const o="string"!==r?Ti(n,r):Si(n,[],!0);return V.makeTensor(o,i,r)}function xx(n,t,e,s="numeric"){if(!Array.isArray(n))throw new Error(`Argument ${t} passed to ${e} must be a \`Tensor[]\` or \`TensorLike[]\``);return n.map((i,a)=>$(i,`${t}[${a}]`,e,s))}function U(n){const t=Object.keys(n);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 e=t[0];const s=n[e];e.endsWith("_")&&(e=e.substring(0,e.length-1)),e+="__op";const r=(...i)=>{V.startScope(e);try{const a=s(...i);return aa(a)&&console.error("Cannot return a Promise inside of tidy."),V.endScope(a),a}catch(a){throw V.endScope(null),a}};return Object.defineProperty(r,"name",{value:e,configurable:!0}),r}ns.registerFlag("DEBUG",()=>!1,n=>{n&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),ns.registerFlag("IS_BROWSER",()=>fx()),ns.registerFlag("IS_NODE",()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"),ns.registerFlag("IS_CHROME",()=>typeof navigator<"u"&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),ns.registerFlag("IS_SAFARI",()=>typeof navigator<"u"&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor)),ns.registerFlag("PROD",()=>!1),ns.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>ns.getBool("DEBUG")),ns.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),ns.registerFlag("IS_TEST",()=>!1),ns.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>ns.getBool("DEBUG")),ns.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1),ns.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1),ns.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);const Ci=U({complex_:function mS(n,t){const e=$(n,"real","complex"),s=$(t,"imag","complex");return Me(e.shape,s.shape,`real and imag shapes, ${e.shape} and ${s.shape}, must match in call to tf.complex().`),V.runKernel(od,{real:e,imag:s})}});function Qo(n,t,e,s){if(null==s)s=vr(n);else if("complex64"===s)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(ux(n)||lx(n)){if("float32"!==s&&"int32"!==s)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);return V.backend.createTensorFromGPUData(n,t||e,s)}if(!ms(n)&&!Array.isArray(n)&&"number"!=typeof n&&"boolean"!=typeof n&&"string"!=typeof n)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){Js(t);const r=K(t),i=K(e);T(r===i,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${i}`);for(let a=0;a`Error creating a new Tensor. Inferred shape (${e}) does not match the provided shape (${t}). `)}}return!ms(n)&&!Array.isArray(n)&&(n=[n]),t=t||e,n="string"!==s?Ti(n,s):Si(n,[],!0),V.makeTensor(n,t,s)}function Ii(n,t,e){return Qo(n,t,Yo(n,e),e)}class er{static join(t){return new er(t).slice()}constructor(t){if(this.shards=[],this.previousShardIndex=0,null==t||(t instanceof Array||(t=[t]),0===(t=t.map(s=>ms(s)?s.buffer:s)).length))return;this.bufferUniformSize=t[0].byteLength;let e=0;for(let s=0;s=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(t/this.bufferUniformSize),this.previousShardIndex;function e(r){return t=r.end?1:0}if(0===e(this.shards[this.previousShardIndex]))return this.previousShardIndex;const s=function gS(n,t){let e=0,s=n.length;for(;e<=s;){const r=Math.floor((s-e)/2)+e,i=t(n[r]);if(0===i)return r;i<0?s=r:e=r+1}return-1}(this.shards,e);return-1===s?-1:(this.previousShardIndex=s,this.previousShardIndex)}}function tr(){return V}function ap(){return V.memory()}function Z(n,t){return V.tidy(n,t)}function xt(n){Gr(n).forEach(e=>e.dispose())}function nr(n){return V.keep(n)}function yx(n,t,e=1){return V.registerBackend(n,t,e)}function vx(n,t){return op.apply(this,arguments)}function op(){return op=(0,N.A)(function*(n,t){const e=[],s=[],r=Array.isArray(n)?n.map(a=>a.name):Object.keys(n);for(let a=0;ax+y.length,0)+4*p.length,g=new Uint8Array(f);let m=0;for(let x=0;x{if(t+=i.byteLength,e.push(i.byteLength===i.buffer.byteLength?i:new i.constructor(i)),!(i instanceof Float32Array||i instanceof Int32Array||i instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${i.constructor.name}`)});const s=new Uint8Array(t);let r=0;return e.forEach(i=>{s.set(new Uint8Array(i.buffer),r),r+=i.byteLength}),s.buffer}!function aS(n){sx=n}(function xS(n){E().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")});const hp=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function Tx(n){return hp?Buffer.byteLength(n,"utf8"):new Blob([n]).size}function Cx(n,t){const e={modelTopology:n.modelTopology,format:n.format,generatedBy:n.generatedBy,convertedBy:n.convertedBy,weightsManifest:t};return null!=n.signature&&(e.signature=n.signature),null!=n.userDefinedMetadata&&(e.userDefinedMetadata=n.userDefinedMetadata),null!=n.modelInitializer&&(e.modelInitializer=n.modelInitializer),null!=n.initializerSignature&&(e.initializerSignature=n.initializerSignature),null!=n.trainingConfig&&(e.trainingConfig=n.trainingConfig),e}function dp(){return(dp=(0,N.A)(function*(n,t){let e,s;return null!=n.weightsManifest&&([e,s]=yield t(n.weightsManifest)),function IS(n,t,e){const s={modelTopology:n.modelTopology,format:n.format,generatedBy:n.generatedBy,convertedBy:n.convertedBy};if(null!=n.trainingConfig&&(s.trainingConfig=n.trainingConfig),null!=n.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!e)throw new Error("modelJSON has weightsManifest but weightData is null");s.weightSpecs=t,s.weightData=e}return null!=n.signature&&(s.signature=n.signature),null!=n.userDefinedMetadata&&(s.userDefinedMetadata=n.userDefinedMetadata),null!=n.modelInitializer&&(s.modelInitializer=n.modelInitializer),null!=n.initializerSignature&&(s.initializerSignature=n.initializerSignature),s}(n,e,s)})).apply(this,arguments)}function nc(n){if(n.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==n.modelTopology?0:Tx(JSON.stringify(n.modelTopology)),weightSpecsBytes:null==n.weightSpecs?0:Tx(JSON.stringify(n.weightSpecs)),weightDataBytes:null==n.weightData?0:new er(n.weightData).byteLength}}function Ex(n){const t=[];for(const e of n)t.push(...e.weights);return t}class sn{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==sn.instance&&(sn.instance=new sn),sn.instance}static registerSaveRouter(t){sn.getInstance().saveRouters.push(t)}static registerLoadRouter(t){sn.getInstance().loadRouters.push(t)}static getSaveHandlers(t){return sn.getHandlers(t,"save")}static getLoadHandlers(t,e){return sn.getHandlers(t,"load",e)}static getHandlers(t,e,s){const r=[];return("load"===e?sn.getInstance().loadRouters:sn.getInstance().saveRouters).forEach(a=>{const o=a(t,s);null!==o&&r.push(o)}),r}}const sc="tensorflowjs",ki="models_store",jr="model_info_store";function mp(){if(!E().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const n=typeof window>"u"?self:window,t=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function gp(n){const t=n.result;t.createObjectStore(ki,{keyPath:"modelPath"}),t.createObjectStore(jr,{keyPath:"modelPath"})}let ha=(()=>{class n{constructor(e){if(this.indexedDB=mp(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}save(e){var s=this;return(0,N.A)(function*(){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return s.databaseAction(s.modelPath,e)})()}load(){var e=this;return(0,N.A)(function*(){return e.databaseAction(e.modelPath)})()}databaseAction(e,s){return new Promise((r,i)=>{const a=this.indexedDB.open(sc,1);a.onupgradeneeded=()=>gp(a),a.onsuccess=()=>{const o=a.result;if(null==s){const l=o.transaction(ki,"readonly"),c=l.objectStore(ki).get(this.modelPath);c.onsuccess=()=>{if(null==c.result)return o.close(),i(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));r(c.result.modelArtifacts)},c.onerror=h=>(o.close(),i(c.error)),l.oncomplete=()=>o.close()}else{s.weightData=er.join(s.weightData);const l=nc(s),u=o.transaction(jr,"readwrite");let h,d,c=u.objectStore(jr);try{h=c.put({modelPath:this.modelPath,modelArtifactsInfo:l})}catch(p){return i(p)}h.onsuccess=()=>{d=o.transaction(ki,"readwrite");const p=d.objectStore(ki);let f;try{f=p.put({modelPath:this.modelPath,modelArtifacts:s,modelArtifactsInfo:l})}catch(g){return i(g)}f.onsuccess=()=>r({modelArtifactsInfo:l}),f.onerror=g=>{c=u.objectStore(jr);const m=c.delete(this.modelPath);m.onsuccess=()=>(o.close(),i(f.error)),m.onerror=x=>(o.close(),i(f.error))}},h.onerror=p=>(o.close(),i(h.error)),u.oncomplete=()=>{null==d?o.close():d.oncomplete=()=>o.close()}}},a.onerror=o=>i(a.error)})}}return n.URL_SCHEME="indexeddb://",n})();const kx=n=>E().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(ha.URL_SCHEME)?function $S(n){return new ha(n)}(n.slice(ha.URL_SCHEME.length)):null;sn.registerSaveRouter(kx),sn.registerLoadRouter(kx);class OS{constructor(){this.indexedDB=mp()}listModels(){var t=this;return(0,N.A)(function*(){return new Promise((e,s)=>{const r=t.indexedDB.open(sc,1);r.onupgradeneeded=()=>gp(r),r.onsuccess=()=>{const i=r.result,a=i.transaction(jr,"readonly"),l=a.objectStore(jr).getAll();l.onsuccess=()=>{const u={};for(const c of l.result)u[c.modelPath]=c.modelArtifactsInfo;e(u)},l.onerror=u=>(i.close(),s(l.error)),a.oncomplete=()=>i.close()},r.onerror=i=>s(r.error)})})()}removeModel(t){var e=this;return(0,N.A)(function*(){return t=function DS(n){return n.startsWith(ha.URL_SCHEME)?n.slice(ha.URL_SCHEME.length):n}(t),new Promise((s,r)=>{const i=e.indexedDB.open(sc,1);i.onupgradeneeded=()=>gp(i),i.onsuccess=()=>{const a=i.result,o=a.transaction(jr,"readwrite"),l=o.objectStore(jr),u=l.get(t);let c;u.onsuccess=()=>{if(null==u.result)return a.close(),r(new Error(`Cannot find model with path '${t}' in IndexedDB.`));{const h=l.delete(t),d=()=>{c=a.transaction(ki,"readwrite");const f=c.objectStore(ki).delete(t);f.onsuccess=()=>s(u.result.modelArtifactsInfo),f.onerror=g=>r(u.error)};h.onsuccess=d,h.onerror=p=>(d(),a.close(),r(u.error))}},u.onerror=h=>(a.close(),r(u.error)),o.oncomplete=()=>{null==c?a.close():c.oncomplete=()=>a.close()}},i.onerror=a=>r(i.error)})})()}}const sr="/",Ni="tensorflowjs_models",Nx="info",PS="model_topology",FS="weight_specs",LS="weight_data",MS="model_metadata";function Ax(n){return{info:[Ni,n,Nx].join(sr),topology:[Ni,n,PS].join(sr),weightSpecs:[Ni,n,FS].join(sr),weightData:[Ni,n,LS].join(sr),modelMetadata:[Ni,n,MS].join(sr)}}function Rx(n){for(const t of Object.values(n))window.localStorage.removeItem(t)}function $x(n){const t=n.split(sr);if(t.length<3)throw new Error(`Invalid key format: ${n}`);return t.slice(1,t.length-1).join(sr)}let da=(()=>{class n{constructor(e){if(!E().getBool("IS_BROWSER")||typeof window>"u"||typeof window.localStorage>"u")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=Ax(this.modelPath)}save(e){var s=this;return(0,N.A)(function*(){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const r=JSON.stringify(e.modelTopology),i=JSON.stringify(e.weightSpecs),a=nc(e),o=er.join(e.weightData);try{return s.LS.setItem(s.keys.info,JSON.stringify(a)),s.LS.setItem(s.keys.topology,r),s.LS.setItem(s.keys.weightSpecs,i),s.LS.setItem(s.keys.weightData,function TS(n){if(hp)return Buffer.from(n).toString("base64");const t=new Uint8Array(n);let e="";for(let s=0,r=t.length;sE().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(da.URL_SCHEME)?function zS(n){return new da(n)}(n.slice(da.URL_SCHEME.length)):null;sn.registerSaveRouter(Dx),sn.registerLoadRouter(Dx);class BS{constructor(){T(E().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),T(typeof window>"u"||typeof window.localStorage<"u",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}listModels(){var t=this;return(0,N.A)(function*(){const e={},s=Ni+sr,r=sr+Nx;for(let i=0;i"scheme must not be undefined or null."),t.endsWith("://")&&(t=t.slice(0,t.indexOf("://"))),T(t.length>0,()=>"scheme must not be an empty string.");const s=Kn.getInstance();T(null==s.managers[t],()=>`A model store manager is already registered for scheme '${t}'.`),s.managers[t]=e}static getManager(t){const e=Kn.getInstance().managers[t];if(null==e)throw new Error(`Cannot find model manager for scheme '${t}'`);return e}static getSchemes(){return Object.keys(Kn.getInstance().managers)}}class US{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(t,e){return fetch(t,e)}now(){return performance.now()}encode(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error(`Browser's encoder only supports utf-8, but got ${e}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)}decode(t,e){return new TextDecoder(e).decode(t)}setTimeoutCustom(t,e){typeof window>"u"||!E().getBool("USE_SETTIMEOUTCUSTOM")?setTimeout(t,e):(this.functionRefs.push(t),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},e),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",s=>{s.source===window&&s.data.name===this.messageName&&(s.stopPropagation(),(0,this.functionRefs[s.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0))},!0)))}isTypedArray(t){return Zg(t)}}if(E().get("IS_BROWSER")){E().setPlatform("browser",new US);try{Kn.registerManager(da.URL_SCHEME,new BS)}catch{}try{Kn.registerManager(ha.URL_SCHEME,new OS)}catch{}}let fa;function vt(n,t="float32",e){return t=t||"float32",Js(n),new On(n,t,e)}E().get("IS_NODE")&&!E().get("IS_BROWSER")&&E().setPlatform("node",new class GS{constructor(){this.util=W(8590),this.textEncoder=new this.util.TextEncoder}fetch(t,e){return null!=E().global.fetch?E().global.fetch(t,e):(null==fa&&(fa=W(5817)),fa(t,e))}now(){const t=process.hrtime();return 1e3*t[0]+t[1]/1e6}encode(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error(`Node built-in encoder only supports utf-8, but got ${e}`);return this.textEncoder.encode(t)}decode(t,e){return 0===t.length?"":new this.util.TextDecoder(e).decode(t)}isTypedArray(t){return this.util.types.isFloat32Array(t)||this.util.types.isInt32Array(t)||this.util.types.isUint8Array(t)||this.util.types.isUint8ClampedArray(t)}});const ke=U({cast_:function HS(n,t){const e=$(n,"x","cast");if(!function Hl(n){return"bool"===n||"complex64"===n||"float32"===n||"int32"===n||"string"===n}(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==e.dtype||"string"!==t&&"string"===e.dtype)throw new Error("Only strings can be casted to strings");return V.runKernel(so,{x:e},{dtype:t})}}),Ai=U({clone_:function jS(n){const e={x:$(n,"x","clone","string_or_numeric")};return V.runKernel(yo,e)}});dx(),function iS(n){ca=n}({buffer:vt,cast:ke,clone:Ai,print:function XS(n,t=!1){console.log(n.toString(t))}});const me=U({add_:function KS(n,t){let e=$(n,"a","add"),s=$(t,"b","add");return[e,s]=un(e,s),V.runKernel(oa,{a:e,b:s})}}),Px=U({floorDiv_:function qS(n,t){let e=$(n,"a","floorDiv"),s=$(t,"b","floorDiv");return[e,s]=un(e,s),V.runKernel(go,{a:e,b:s})}}),je=U({div_:function ZS(n,t){let e=$(n,"a","div"),s=$(t,"b","div");return[e,s]=un(e,s),"int32"===e.dtype&&"int32"===s.dtype?Px(e,s):V.runKernel(uo,{a:e,b:s},{})}}),L=U({mul_:function YS(n,t){let e=$(n,"a","mul"),s=$(t,"b","mul");return[e,s]=un(e,s),V.runKernel(Eo,{a:e,b:s})}}),zn=U({sqrt_:function QS(n){const e={x:$(n,"x","sqrt","float32")};return V.runKernel(zo,e)}}),Kt=U({square_:function JS(n){const t=$(n,"x","square");return V.runKernel("Square",{x:t},{})}}),Et=U({zerosLike_:function eC(n){const e={x:$(n,"x","zerosLike")};return V.runKernel(Xu,e)}});function _r(n){return V.customGrad(n)}function ut(n,t){if((ms(n)&&"string"!==t||Array.isArray(n))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&ms(n)&&!(n instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Qo(n,[],[],t)}const nC=new Map,_p=new Map;class ma{getClassName(){return this.constructor.className}static fromConfig(t,e){return new t(e)}}class Es{constructor(){this.classNameMap={}}static getMap(){return null==Es.instance&&(Es.instance=new Es),Es.instance}static register(t){Es.getMap().classNameMap[t.className]=[t,t.fromConfig]}}function pe(n,t,e){T(null!=n.className,()=>"Class being registered does not have the static className property defined."),T("string"==typeof n.className,()=>"className is required to be a string, but got type "+typeof n.className),T(n.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof t>"u"&&(t="Custom"),typeof e>"u"&&(e=n.className);const r=t+">"+e;return Es.register(n),nC.set(r,n),_p.set(n,r),n}class Xr extends ma{minimize(t,e=!1,s){const{value:r,grads:i}=this.computeGradients(t,s);if(null!=s){const a=s.map(o=>({name:o.name,tensor:i[o.name]}));this.applyGradients(a)}else this.applyGradients(i);return xt(i),e?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(t,e){return function tC(n,t){T(Cs(n),()=>"The f passed in variableGrads(f) must be a function"),T(null==t||Array.isArray(t)&&t.every(u=>u instanceof tc),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const e=null!=t;if(!e){t=[];for(const u in V.registeredVariables)t.push(V.registeredVariables[u])}const s=e?t.filter(u=>!u.trainable):null,r=t.length;T((t=t.filter(u=>u.trainable)).length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);const{value:a,grads:o}=V.gradients(n,t,null,!0);T(o.some(u=>null!=u),()=>"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()."),T(0===a.rank,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const l={};return t.forEach((u,c)=>{null!=o[c]&&(l[u.name]=o[c])}),s?.forEach(u=>l[u.name]=null),{value:a,grads:l}}(t,e)}dispose(){null!=this.iterations_&&xt(this.iterations_)}saveIterations(){var t=this;return(0,N.A)(function*(){return null==t.iterations_&&(t.iterations_=0),{name:"iter",tensor:ut(t.iterations_,"int32")}})()}getWeights(){return(0,N.A)(function*(){throw new Error("getWeights() is not implemented for this optimizer yet.")})()}setWeights(t){var e=this;return(0,N.A)(function*(){throw new Error(`setWeights() is not implemented for this optimizer class ${e.getClassName()}`)})()}extractIterations(t){var e=this;return(0,N.A)(function*(){return e.iterations_=(yield t[0].tensor.data())[0],t.slice(1)})()}}Object.defineProperty(Xr,Symbol.hasInstance,{value:n=>null!=n.minimize&&null!=n.computeGradients&&null!=n.applyGradients});class Fx extends Xr{static get className(){return"Adadelta"}constructor(t,e,s=null){super(),this.learningRate=t,this.rho=e,this.epsilon=s,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==s&&(this.epsilon=V.backend.epsilon())}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,r)=>{const i=V.registeredVariables[s],a=!1;null==this.accumulatedGrads[r]&&(this.accumulatedGrads[r]={originalName:`${s}/accum_grad`,variable:Z(()=>Et(i).variable(a))}),null==this.accumulatedUpdates[r]&&(this.accumulatedUpdates[r]={originalName:`${s}/accum_var`,variable:Z(()=>Et(i).variable(a))});const o=Array.isArray(t)?t[r].tensor:t[s];if(null==o)return;const l=this.accumulatedGrads[r].variable,u=this.accumulatedUpdates[r].variable;Z(()=>{const c=me(L(l,this.rho),L(Kt(o),1-this.rho)),h=L(je(zn(me(u,this.epsilon)),zn(me(l,this.epsilon))),o),d=me(L(u,this.rho),L(Kt(h),1-this.rho));l.assign(c),u.assign(d);const p=me(L(h,-this.learningRate),i);i.assign(p)})}),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(xt(this.accumulatedGrads.map(t=>t.variable)),xt(this.accumulatedUpdates.map(t=>t.variable)))}getWeights(){var t=this;return(0,N.A)(function*(){const e=[...t.accumulatedGrads,...t.accumulatedUpdates];return[yield t.saveIterations()].concat(e.map(s=>({name:s.originalName,tensor:s.variable})))})()}setWeights(t){var e=this;return(0,N.A)(function*(){const s=(t=yield e.extractIterations(t)).length/2,r=!1;e.accumulatedGrads=t.slice(0,s).map(i=>({originalName:i.name,variable:i.tensor.variable(r)})),e.accumulatedUpdates=t.slice(s,2*s).map(i=>({originalName:i.name,variable:i.tensor.variable(r)}))})()}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(t,e){return new t(e.learningRate,e.rho,e.epsilon)}}function Jo(n,t,e){return Js(n),e=e||vr(t),V.runKernel(Td,{},{shape:n,value:t,dtype:e})}class Lx extends Xr{static get className(){return"Adagrad"}constructor(t,e=.1){super(),this.learningRate=t,this.initialAccumulatorValue=e,this.accumulatedGrads=[]}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,r)=>{const i=V.registeredVariables[s];null==this.accumulatedGrads[r]&&(this.accumulatedGrads[r]={originalName:`${s}/accumulator`,variable:Z(()=>Jo(i.shape,this.initialAccumulatorValue).variable(!1))});const a=Array.isArray(t)?t[r].tensor:t[s];if(null==a)return;const o=this.accumulatedGrads[r].variable;Z(()=>{const l=me(o,Kt(a));o.assign(l);const u=me(L(je(a,zn(me(l,V.backend.epsilon()))),-this.learningRate),i);i.assign(u)})}),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&xt(this.accumulatedGrads.map(t=>t.variable))}getWeights(){var t=this;return(0,N.A)(function*(){return[yield t.saveIterations()].concat(t.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))})()}setWeights(t){var e=this;return(0,N.A)(function*(){t=yield e.extractIterations(t),e.accumulatedGrads=t.map(r=>({originalName:r.name,variable:r.tensor.variable(!1)}))})()}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(t,e){return new t(e.learningRate,e.initialAccumulatorValue)}}const Ri=U({pow_:function sC(n,t){let e=$(n,"base","pow"),s=$(t,"exp","pow");return[e,s]=un(e,s),V.runKernel(ko,{a:e,b:s})}}),ze=U({sub_:function rC(n,t){let e=$(n,"a","sub"),s=$(t,"b","sub");return[e,s]=un(e,s),V.runKernel(Uo,{a:e,b:s})}});class Mx extends Xr{static get className(){return"Adam"}constructor(t,e,s,r=null){super(),this.learningRate=t,this.beta1=e,this.beta2=s,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Z(()=>{this.accBeta1=ut(e).variable(),this.accBeta2=ut(s).variable()}),null==r&&(this.epsilon=V.backend.epsilon())}applyGradients(t){const e=Array.isArray(t)?t.map(s=>s.name):Object.keys(t);Z(()=>{const s=ze(1,this.accBeta1),r=ze(1,this.accBeta2);e.forEach((i,a)=>{const o=V.registeredVariables[i],l=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${i}/m`,variable:Z(()=>Et(o).variable(l))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${i}/v`,variable:Z(()=>Et(o).variable(l))});const u=Array.isArray(t)?t[a].tensor:t[i];if(null==u)return;const c=this.accumulatedFirstMoment[a].variable,h=this.accumulatedSecondMoment[a].variable,d=me(L(c,this.beta1),L(u,1-this.beta1)),p=me(L(h,this.beta2),L(Kt(u),1-this.beta2)),f=je(d,s),g=je(p,r);c.assign(d),h.assign(p);const m=me(L(je(f,me(zn(g),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(L(this.accBeta1,this.beta1)),this.accBeta2.assign(L(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&xt(this.accumulatedFirstMoment.map(t=>t.variable)),null!=this.accumulatedSecondMoment&&xt(this.accumulatedSecondMoment.map(t=>t.variable))}getWeights(){var t=this;return(0,N.A)(function*(){const e=[...t.accumulatedFirstMoment,...t.accumulatedSecondMoment];return[yield t.saveIterations()].concat(e.map(s=>({name:s.originalName,tensor:s.variable})))})()}setWeights(t){var e=this;return(0,N.A)(function*(){t=yield e.extractIterations(t),Z(()=>{e.accBeta1.assign(Ri(e.beta1,e.iterations_+1)),e.accBeta2.assign(Ri(e.beta2,e.iterations_+1))});const s=t.length/2,r=!1;e.accumulatedFirstMoment=t.slice(0,s).map(i=>({originalName:i.name,variable:i.tensor.variable(r)})),e.accumulatedSecondMoment=t.slice(s,2*s).map(i=>({originalName:i.name,variable:i.tensor.variable(r)}))})()}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)}}const kn=U({abs_:function iC(n){const t=$(n,"x","abs");return V.runKernel("complex64"===t.dtype?eu:In,{x:t})}});function ga(n,t){const e=n.length,s=[];for(let r=0;r1&&1===(n[i]||1)&&s.unshift(i)}return s}function bn(n,t){const e=[];for(let s=0;s1)&&e.unshift(i)}return e}function ht(n,t){const e=Math.max(n.length,t.length),s=new Array(e);for(let r=0;r{this.iteration=ut(0).variable(),this.accBeta1=ut(e).variable()}),null==r&&(this.epsilon=V.backend.epsilon())}applyGradients(t){const e=Array.isArray(t)?t.map(s=>s.name):Object.keys(t);Z(()=>{const s=ze(1,this.accBeta1),r=je(-this.learningRate,me(L(this.iteration,this.decay),1));e.forEach((i,a)=>{const o=V.registeredVariables[i],l=!1;null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${i}/m`,variable:Et(o).variable(l)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${i}/v`,variable:Et(o).variable(l)});const u=Array.isArray(t)?t[a].tensor:t[i];if(null==u)return;const c=this.accumulatedFirstMoment[a].variable,h=this.accumulatedWeightedInfNorm[a].variable,d=me(L(c,this.beta1),L(u,1-this.beta1)),p=L(h,this.beta2),f=kn(u),g=Kr(p,f);c.assign(d),h.assign(g);const m=me(L(je(r,s),je(d,me(g,this.epsilon))),o);o.assign(m)}),this.iteration.assign(me(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&xt(this.accumulatedFirstMoment.map(t=>t.variable)),null!=this.accumulatedWeightedInfNorm&&xt(this.accumulatedWeightedInfNorm.map(t=>t.variable))}getWeights(){return(0,N.A)(function*(){throw new Error("getWeights() is not implemented for Adamax yet.")})()}setWeights(t){return(0,N.A)(function*(){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(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)}}class Tp extends Xr{static get className(){return"SGD"}constructor(t){super(),this.learningRate=t,this.setLearningRate(t)}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,r)=>{const i=Array.isArray(t)?t[r].tensor:t[s];if(null==i)return;const a=V.registeredVariables[s];Z(()=>{const o=me(L(this.c,i),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=nr(ut(-t))}dispose(){this.c.dispose()}getWeights(){var t=this;return(0,N.A)(function*(){return[yield t.saveIterations()]})()}setWeights(t){var e=this;return(0,N.A)(function*(){if(0!==(t=yield e.extractIterations(t)).length)throw new Error("SGD optimizer does not have settable weights.")})()}getConfig(){return{learningRate:this.learningRate}}static fromConfig(t,e){return new t(e.learningRate)}}class zx extends Tp{static get className(){return"Momentum"}constructor(t,e,s=!1){super(t),this.learningRate=t,this.momentum=e,this.useNesterov=s,this.accumulations=[],this.m=ut(this.momentum)}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,r)=>{const i=V.registeredVariables[s];null==this.accumulations[r]&&(this.accumulations[r]={originalName:`${s}/momentum`,variable:Z(()=>Et(i).variable(!1))});const a=this.accumulations[r].variable,o=Array.isArray(t)?t[r].tensor:t[s];null!=o&&Z(()=>{let l;const u=me(L(this.m,a),o);l=me(L(this.c,this.useNesterov?me(o,L(u,this.m)):u),i),a.assign(u),i.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&xt(this.accumulations.map(t=>t.variable))}setMomentum(t){this.momentum=t}getWeights(){var t=this;return(0,N.A)(function*(){return[yield t.saveIterations()].concat(t.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))})()}setWeights(t){var e=this;return(0,N.A)(function*(){t=yield e.extractIterations(t),e.accumulations=t.map(r=>({originalName:r.name,variable:r.tensor.variable(!1)}))})()}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)}}class Bx extends Xr{static get className(){return"RMSProp"}constructor(t,e=.9,s=0,r=null,i=!1){if(super(),this.learningRate=t,this.decay=e,this.momentum=s,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=i,null==r&&(this.epsilon=V.backend.epsilon()),null==t)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,r)=>{const i=V.registeredVariables[s],a=!1;null==this.accumulatedMeanSquares[r]&&(this.accumulatedMeanSquares[r]={originalName:`${s}/rms`,variable:Z(()=>Et(i).variable(a))}),null==this.accumulatedMoments[r]&&(this.accumulatedMoments[r]={originalName:`${s}/momentum`,variable:Z(()=>Et(i).variable(a))}),null==this.accumulatedMeanGrads[r]&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${s}/mg`,variable:Z(()=>Et(i).variable(a))});const o=Array.isArray(t)?t[r].tensor:t[s];if(null==o)return;const l=this.accumulatedMeanSquares[r].variable,u=this.accumulatedMoments[r].variable;Z(()=>{const c=me(L(l,this.decay),L(Kt(o),1-this.decay));if(this.centered){const h=this.accumulatedMeanGrads[r].variable,d=me(L(h,this.decay),L(o,1-this.decay)),p=je(L(o,this.learningRate),zn(ze(c,me(Kt(d),this.epsilon)))),f=me(L(u,this.momentum),p);l.assign(c),h.assign(d),u.assign(f);const g=ze(i,f);i.assign(g)}else{const h=me(L(l,this.decay),L(Kt(o),1-this.decay)),d=me(L(u,this.momentum),je(L(o,this.learningRate),zn(me(h,this.epsilon))));l.assign(h),u.assign(d);const p=ze(i,d);i.assign(p)}})}),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&xt(this.accumulatedMeanSquares.map(t=>t.variable)),null!=this.accumulatedMeanGrads&&this.centered&&xt(this.accumulatedMeanGrads.map(t=>t.variable)),null!=this.accumulatedMoments&&xt(this.accumulatedMoments.map(t=>t.variable))}getWeights(){var t=this;return(0,N.A)(function*(){const e=[...t.accumulatedMeanSquares,...t.accumulatedMoments];return t.centered&&e.push(...t.accumulatedMeanGrads),[yield t.saveIterations()].concat(e.map(s=>({name:s.originalName,tensor:s.variable})))})()}setWeights(t){var e=this;return(0,N.A)(function*(){t=yield e.extractIterations(t);const s=e.centered?t.length/3:t.length/2,r=!1;e.accumulatedMeanSquares=t.slice(0,s).map(i=>({originalName:i.name,variable:i.tensor.variable(r)})),e.accumulatedMoments=t.slice(s,2*s).map(i=>({originalName:i.name,variable:i.tensor.variable(r)})),e.centered&&(e.accumulatedMeanGrads=t.slice(2*s,3*s).map(i=>({originalName:i.name,variable:i.tensor.variable(r)})))})()}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)}}const oC=[Fx,Lx,Mx,Vx,zx,Bx,Tp];function Ux(n){return new Promise(t=>setTimeout(t)).then(n)}let Sp=(()=>{class n{constructor(e){if(!E().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(n.URL_SCHEME)&&(e=e.slice(n.URL_SCHEME.length)),(null==e||0===e.length)&&(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}save(e){var s=this;return(0,N.A)(function*(){if(typeof document>"u")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const r=er.join(e.weightData),i=window.URL.createObjectURL(new Blob([r],{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 o=Cx(e,[{paths:["./"+s.weightDataFileName],weights:e.weightSpecs}]),l=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),u=null==s.modelJsonAnchor?document.createElement("a"):s.modelJsonAnchor;if(u.download=s.modelJsonFileName,u.href=l,yield Ux(()=>u.dispatchEvent(new MouseEvent("click"))),null!=e.weightData){const c=null==s.weightDataAnchor?document.createElement("a"):s.weightDataAnchor;c.download=s.weightDataFileName,c.href=i,yield Ux(()=>c.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:nc(e)}}})()}}return n.URL_SCHEME="downloads://",n})();function Wx(n,t,e,s){(function a(l){T(null!=l&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")})(n),function o(l,u){T(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),T(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),T(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}(e=e??0,s=s??1);let r=0;return Promise.all(n.map(l=>(l.then(u=>{const c=e+ ++r/n.length*(s-e);return t(c),u}),l)))}function Gx(n,t){return Cp.apply(this,arguments)}function Cp(){return(Cp=(0,N.A)(function*(n,t){null==t&&(t={});const e=null==t.fetchFunc?E().platform.fetch:t.fetchFunc,s=n.map(h=>e(h,t.requestInit,{isBinary:!0})),o=(null==t.onProgress?yield Promise.all(s):yield Wx(s,t.onProgress,0,.5)).map(h=>h.arrayBuffer());return null==t.onProgress?yield Promise.all(o):yield Wx(o,t.onProgress,.5,1)})).apply(this,arguments)}sn.registerSaveRouter(n=>E().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(Sp.URL_SCHEME)?function fC(n="model"){return new Sp(n)}(n.slice(Sp.URL_SCHEME.length)):null);let Hx=(()=>{class n{constructor(e,s){if(this.DEFAULT_METHOD="POST",null==s&&(s={}),this.weightPathPrefix=s.weightPathPrefix,this.weightUrlConverter=s.weightUrlConverter,null!=s.fetchFunc?(T("function"==typeof s.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=s.fetchFunc):this.fetch=E().platform.fetch,T(null!=e&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&T(2===e.length,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,null!=s.requestInit&&null!=s.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=s.requestInit||{},this.loadOptions=s}save(e){var s=this;return(0,N.A)(function*(){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const r=Object.assign({method:s.DEFAULT_METHOD},s.requestInit);r.body=new FormData;const a=Cx(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(r.body.append("model.json",new Blob([JSON.stringify(a)],{type:"application/json"}),"model.json"),null!=e.weightData){const l=er.join(e.weightData);r.body.append("model.weights.bin",new Blob([l],{type:"application/octet-stream"}),"model.weights.bin")}const o=yield s.fetch(s.path,r);if(o.ok)return{modelArtifactsInfo:nc(e),responses:[o]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${o.status}.`)})()}loadModelJSON(){var e=this;return(0,N.A)(function*(){const s=yield e.fetch(e.path,e.requestInit);if(!s.ok)throw new Error(`Request to ${e.path} failed with status code ${s.status}. Please verify this URL points to the model JSON of the model to load.`);let r;try{r=yield s.json()}catch{let l=`Failed to parse model JSON of response from ${e.path}.`;throw e.path.endsWith(".pb")?l+=" 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.":l+=" Please make sure the server is serving valid JSON for this request.",new Error(l)}if(null==r.modelTopology&&null==r.weightsManifest)throw new Error(`The JSON from HTTP path ${e.path} contains neither model topology or manifest for weights.`);return r})()}load(){var e=this;return(0,N.A)(function*(){return e.loadOptions.streamWeights?e.loadStream():function Ix(n,t){return dp.apply(this,arguments)}(yield e.loadModelJSON(),r=>e.loadWeights(r))})()}loadStream(){var e=this;return(0,N.A)(function*(){const s=yield e.loadModelJSON(),r=yield e.getWeightUrls(s.weightsManifest),i=Ex(s.weightsManifest);return Object.assign(Object.assign({},s),{weightSpecs:i,getWeightStream:()=>function mC(n,t){var e;const s=null==t.fetchFunc?E().platform.fetch:t.fetchFunc;let i,r=0;return null===(e=t.onProgress)||void 0===e||e.call(t,0),new ReadableStream({pull:(a=(0,N.A)(function*(o){for(var l;rt?n.substring(e):""]}(r),o=s.weightPathPrefix||i,l=[],u=[];for(const c of e)for(const h of c.paths)null!=s.weightUrlConverter?u.push(s.weightUrlConverter(h)):l.push(o+h+a);return s.weightUrlConverter&&l.push(...yield Promise.all(u)),l})()}loadWeights(e){var s=this;return(0,N.A)(function*(){const r=yield s.getWeightUrls(e);return[Ex(e),yield Gx(r,s.loadOptions)]})()}}return n.URL_SCHEME_REGEX=/^https?:\/\//,n})();function jx(n){return null!=n.match(Hx.URL_SCHEME_REGEX)}const Xx=(n,t)=>{if(typeof fetch>"u"&&(null==t||null==t.fetchFunc))return null;{let e=!0;if(e=Array.isArray(n)?n.every(s=>jx(s)):jx(n),e)return function Kx(n,t){return new Hx(n,t)}(n,t)}return null};sn.registerSaveRouter(Xx),sn.registerLoadRouter(Xx);const Ap=-2,NC=-1;function Rp(n,t,e){const s=n.shape.length;T(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),T(s===e.length,()=>`Error in slice${s}D: Length of size ${e} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+e[r]}) would overflow input.shape[${r}] (${n.shape[r]})`)}function AC(n){const t=[];let e=0;for(;n>0;)1&n&&t.push(e),n/=2,e++;return t}function $p(n,t,e){const s=[];for(let r=0;r0){const p=t[0],f=e+1;c=ny(a,p,f,s,n),h=sy(o,p,f,r,n),d=Jx(i,p,f,n)}else for(let p=0;p-1)i[o]=0;else{const l=ey(t,e,o);let u=s[l];n&1<-1)i[o]=Number.MAX_SAFE_INTEGER;else{const l=ey(t,e,o);let u=s[l];n&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const l=s[r];return a<0&&(a+=l),a=G(0,a,l-1),a}function ay(n,t,e,s,r,i){let a=t[r];const o=e[r]||1;(n&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const l=s[r];return a<0&&(a+=l),a=o>0?G(0,a,l):G(-1,a,l-1),a}function Dp(n,t,e){let s=e.length;for(let r=0;r1){s=r;break}for(let r=s+1;r0||e[r]!==n[r])return!1;return!0}function Op(n,t){let e=n.length>0?n[n.length-1]:1;for(let s=0;s{T(-1!==a,()=>"slice() does not support negative begin indexing.")}),i=null==e?new Array(r).fill(-1):"number"==typeof e?[e,...new Array(r-1).fill(-1)]:e.lengtha>=0?a:(T(-1===a,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${o}.`),n.shape[o]-s[o])),[s,i]}function Pp(n,t,e,s,r,i,a,o,l){let u;if(null==s?(u=new Array(t.length),u.fill(1)):u=s,null!=a&&a&a-1)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:e.slice(),strides:u.slice(),beginMask:r,endMask:i,ellipsisMask:a,newAxisMask:o,shrinkAxisMask:l};for(let b=0;b0?0:-1,d.strides[b]>0?w:w-1];if(v&&d.strides[b]<=0)throw Error("only stride 1 allowed on non-range indexing.");g=g&&1===d.strides[b];const k=!!(d.beginMask&1<=w)throw Error(`slice index ${d.begin[b]} of dimension ${b} out of bounds.`)}else d.begin[b]=oy(d.begin[b],0,d.strides[b],w,S,I),d.end[b]=oy(d.end[b],1,d.strides[b],w,S,I);const B=1===d.strides[b]&&0===d.begin[b]&&d.end[b]===w;p=p&&B,f=f&&(0===b&&1===d.strides[b]||B)}else p=p&&1===d.strides[b]&&k,f=f&&(0===b&&1===d.strides[b]||k);let D,P=!1;if(d.beginValid&&d.endValid?(D=d.end[b]-d.begin[b],P=!0):v?(D=1,P=!0):k&&w>=0&&(D=d.strides[b]<0?-w:w,P=!0),P){let B;B=0===D||D<0!=d.strides[b]<0?0:Math.trunc(D/d.strides[b])+(D%d.strides[b]!=0?1:0),m.push(B)}else m.push(-1)}for(let b=0;b=0?x.push(m[v]):v===Ap&&x.push(1)}return{finalShapeSparse:x.filter((b,v)=>d.finalShapeGatherIndices[v]!==Ap),finalShape:x,isIdentity:p,sliceDim0:f,isSimpleSlice:g,begin:d.begin,end:d.end,strides:d.strides}}function oy(n,t,e,s,r,i){if(r[t])return e>0?i[t]:i[t+1&1];{const a=n<0?s+n:n;return ai[1]?i[1]:a}}const ly=U({all_:function OC(n,t=null,e=!1){const r={x:$(n,"x","all","bool")};return V.runKernel("All",r,{axis:t,keepDims:e})}}),Fp=U({any_:function PC(n,t=null,e=!1){const r={x:$(n,"x","any","bool")};return V.runKernel("Any",r,{axis:t,keepDims:e})}}),el=U({argMax_:function FC(n,t=0){const s={x:$(n,"x","argMax")};return V.runKernel(Kl,s,{axis:t})}});function tl(n,t,e,s,r="NHWC",i){return Nn(n,[...t,n[3]],e,i,s,null,null,Sr(r))}function ks(n,t,e,s,r,i,a="channelsLast"){const[o,l]=nl(t);let u;if("channelsLast"===a)u=[o,l,n[3],n[3]];else{if("channelsFirst"!==a)throw new Error(`Unknown dataFormat ${a}`);u=[o,l,n[1],n[1]]}return Nn(n,u,e,s,r,i,!1,a)}function Tr(n,t,e,s,r,i,a="NDHWC"){const[o,l,u]=Mp(t);let c,h;if("NDHWC"===a)h="channelsLast",c=[o,l,u,n[4],n[4]];else{if("NCDHW"!==a)throw new Error(`Unknown dataFormat ${a}`);h="channelsFirst",c=[o,l,u,n[1],n[1]]}return qr(n,c,e,s,r,!1,h,i)}function Nn(n,t,e,s,r,i,a=!1,o="channelsLast"){let[l,u,c,h]=[-1,-1,-1,-1];if("channelsLast"===o)[l,u,c,h]=n;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[l,h,u,c]=n}const[d,p,,f]=t,[g,m]=nl(e),[x,y]=nl(s),b=xa(d,x),v=xa(p,y),{padInfo:w,outHeight:S,outWidth:I}=function VC(n,t,e,s,r,i,a,o,l){let u,c,h;if("number"==typeof n){u={top:n,bottom:n,left:n,right:n,type:0===n?"VALID":"NUMBER"};const p=function LC(n,t,e,s,r){null==s&&(s=Lp(n,t,e));const a=n[1];return[sl((n[0]-t+2*s)/e+1,r),sl((a-t+2*s)/e+1,r)]}([t,e],i,s,n,o);c=p[0],h=p[1]}else if("same"===n){c=Math.ceil(t/s),h=Math.ceil(e/r);const d=Math.max(0,(c-1)*s+i-t),p=Math.max(0,(h-1)*r+a-e),f=Math.floor(d/2),g=d-f,m=Math.floor(p/2);u={top:f,bottom:g,left:m,right:p-m,type:"SAME"}}else if("valid"===n)u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-i+1)/s),h=Math.ceil((e-a+1)/r);else{if("object"!=typeof n)throw Error(`Unknown padding parameter: ${n}`);{const d="channelsLast"===l?n[1][0]:n[2][0],p="channelsLast"===l?n[1][1]:n[2][1],f="channelsLast"===l?n[2][0]:n[3][0],g="channelsLast"===l?n[2][1]:n[3][1];u={top:d,bottom:p,left:f,right:g,type:0===d&&0===p&&0===f&&0===g?"VALID":"EXPLICIT"},c=sl((t-i+d+p)/s+1,o),h=sl((e-a+f+g)/r+1,o)}}return{padInfo:u,outHeight:c,outWidth:h}}(r,u,c,g,m,b,v,i,o),k=a?f*h:f;let D;return"channelsFirst"===o?D=[l,k,S,I]:"channelsLast"===o&&(D=[l,S,I,k]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:c,inChannels:h,outHeight:S,outWidth:I,outChannels:k,padInfo:w,strideHeight:g,strideWidth:m,filterHeight:d,filterWidth:p,effectiveFilterHeight:b,effectiveFilterWidth:v,dilationHeight:x,dilationWidth:y,inShape:n,outShape:D,filterShape:t}}function qr(n,t,e,s,r,i=!1,a="channelsLast",o){let[l,u,c,h,d]=[-1,-1,-1,-1,-1];if("channelsLast"===a)[l,u,c,h,d]=n;else{if("channelsFirst"!==a)throw new Error(`Unknown dataFormat ${a}`);[l,d,u,c,h]=n}const[p,f,g,,m]=t,[x,y,b]=Mp(e),[v,w,S]=Mp(s),I=xa(p,v),k=xa(f,w),D=xa(g,S),{padInfo:P,outDepth:B,outHeight:Y,outWidth:Q}=function zC(n,t,e,s,r,i,a,o,l,u,c){let h,d,p,f;if("valid"===n&&(n=0),"number"==typeof n){h={top:n,bottom:n,left:n,right:n,front:n,back:n,type:0===n?"VALID":"NUMBER"};const m=function MC(n,t,e,s,r,i){null==r&&(r=Lp(n,t[0],s[0]));const a=[0,0,0,e];for(let o=0;o<3;o++)n[o]+2*r>=t[o]&&(a[o]=sl((n[o]-t[o]+2*r)/s[o]+1,i));return a}([t,e,s,1],[o,l,u],1,[r,i,a],n,c);d=m[0],p=m[1],f=m[2]}else{if("same"!==n)throw Error(`Unknown padding parameter: ${n}`);{d=Math.ceil(t/r),p=Math.ceil(e/i),f=Math.ceil(s/a);const g=(d-1)*r+o-t,m=(p-1)*i+l-e,x=(f-1)*a+u-s,y=Math.floor(g/2),b=g-y,v=Math.floor(m/2),w=m-v,S=Math.floor(x/2);h={top:v,bottom:w,left:S,right:x-S,front:y,back:b,type:"SAME"}}}return{padInfo:h,outDepth:d,outHeight:p,outWidth:f}}(r,u,c,h,x,y,b,I,k,D,o),ee=i?m*d:m;let J;return"channelsFirst"===a?J=[l,ee,B,Y,Q]:"channelsLast"===a&&(J=[l,B,Y,Q,ee]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:h,inChannels:d,outDepth:B,outHeight:Y,outWidth:Q,outChannels:ee,padInfo:P,strideDepth:x,strideHeight:y,strideWidth:b,filterDepth:p,filterHeight:f,filterWidth:g,effectiveFilterDepth:I,effectiveFilterHeight:k,effectiveFilterWidth:D,dilationDepth:v,dilationHeight:w,dilationWidth:S,inShape:n,outShape:J,filterShape:t}}function Lp(n,t,e,s=1){const r=xa(t,s);return Math.floor((n[0]*(e-1)-e+r)/2)}function nl(n){return"number"==typeof n?[n,n,n]:2===n.length?[n[0],n[1],1]:n}function Mp(n){return"number"==typeof n?[n,n,n]:n}function xa(n,t){return t<=1?n:n+(n-1)*(t-1)}function sl(n,t){if(!t)return Math.trunc(n);switch(t){case"round":return Math.round(n);case"ceil":return Math.ceil(n);case"floor":return Math.floor(n);default:throw new Error(`Unknown roundingMode ${t}`)}}function Zr(n){const[t,e,s]=nl(n);return 1===t&&1===e&&1===s}function Pn(n,t){return Zr(n)||Zr(t)}function Di(n){return nl(n).every(t=>t>0)}function Sr(n){if("NHWC"===n)return"channelsLast";if("NCHW"===n)return"channelsFirst";throw new Error(`Unknown dataFormat ${n}`)}function qn(n,t,e){if(null!=e){if("string"==typeof t)throw Error(`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);if("number"==typeof t)T(St(t),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);else{if("object"!=typeof t)throw Error(`Error in ${n}: Unknown padding parameter: ${t}`);t.forEach(s=>{s.forEach(r=>{T(St(r),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${r}.`)})})}}}const j=U({reshape_:function BC(n,t){const s={x:$(n,"x","reshape","string_or_numeric")};return V.runKernel(Ou,s,{shape:t})}}),Vp=U({avgPool_:function UC(n,t,e,s,r){const i=$(n,"x","avgPool","float32");T(Pn(e,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${e} and dilations '1'`);let o=i,l=!1;3===i.rank&&(l=!0,o=j(i,[1,i.shape[0],i.shape[1],i.shape[2]])),T(4===o.rank,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),qn("avgPool",s,r);let h=V.runKernel(Zl,{x:o},{filterSize:t,strides:e,pad:s,dimRoundingMode:r});return h=ke(h,i.dtype),l?j(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),GC=U({avgPool3d_:function WC(n,t,e,s,r,i="NDHWC"){const a=$(n,"x","avgPool3d","float32");let o=a,l=!1;4===a.rank&&(l=!0,o=j(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),T(5===o.rank,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),T("NDHWC"===i,()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),T("number"==typeof e&&e>0||Array.isArray(e)&&e[0]>0&&e[1]>0&&e[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${e}'`),qn("avgPool3d",s,r);let h=V.runKernel(Yl,{x:o},{filterSize:t,strides:e,pad:s,dimRoundingMode:r,dataFormat:i});return h=ke(h,o.dtype),l?j(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});function HC(n){let t;return t=0===n.rank||1===n.rank?j(n,[1,1,1,n.size]):2===n.rank?j(n,[1,1,n.shape[0],n.shape[1]]):3===n.rank?j(n,[1,n.shape[0],n.shape[1],n.shape[2]]):n,t}const oc=U({batchNorm_:function jC(n,t,e,s,r,i){null==i&&(i=.001);const a=$(n,"x","batchNorm"),o=$(t,"mean","batchNorm"),l=$(e,"variance","batchNorm");let u,c;null!=r&&(u=$(r,"scale","batchNorm")),null!=s&&(c=$(s,"offset","batchNorm")),T(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),T(null==c||o.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),T(null==u||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const d={x:HC(a),scale:u,offset:c,mean:o,variance:l},f=V.runKernel(cu,d,{varianceEpsilon:i});return j(f,a.shape)}}),KC=U({batchNorm2d_:function XC(n,t,e,s,r,i){const a=$(n,"x","batchNorm"),o=$(t,"mean","batchNorm"),l=$(e,"variance","batchNorm");let u,c;return null!=r&&(u=$(r,"scale","batchNorm")),null!=s&&(c=$(s,"offset","batchNorm")),T(2===a.rank,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),T(2===o.rank||1===o.rank,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),T(2===l.rank||1===l.rank,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),null!=u&&T(2===u.rank||1===u.rank,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),null!=c&&T(2===c.rank||1===c.rank,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),oc(a,o,l,c,u,i)}}),ZC=U({batchNorm3d_:function qC(n,t,e,s,r,i){const a=$(n,"x","batchNorm"),o=$(t,"mean","batchNorm"),l=$(e,"variance","batchNorm");let u,c;return null!=r&&(u=$(r,"scale","batchNorm")),null!=s&&(c=$(s,"offset","batchNorm")),T(3===a.rank,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),T(3===o.rank||1===o.rank,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),T(3===l.rank||1===l.rank,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),null!=u&&T(3===u.rank||1===u.rank,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),null!=c&&T(3===c.rank||1===c.rank,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),oc(a,o,l,c,u,i)}}),QC=U({batchNorm4d_:function YC(n,t,e,s,r,i){const a=$(n,"x","batchNorm"),o=$(t,"mean","batchNorm"),l=$(e,"variance","batchNorm");let u,c;return null!=r&&(u=$(r,"scale","batchNorm")),null!=s&&(c=$(s,"offset","batchNorm")),T(4===a.rank,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),T(4===o.rank||1===o.rank,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),T(4===l.rank||1===l.rank,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),null!=u&&T(4===u.rank||1===u.rank,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),null!=c&&T(4===c.rank||1===c.rank,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),oc(a,o,l,c,u,i)}}),rl=U({broadcastTo_:function JC(n,t){let e=$(n,"broadcastTo","x");const s=e.shape;if(Js(t),t.lengthe.rank){const u=e.shape.slice();for(;u.length=0;u--)if(r[u]===t[u])i[u]=1;else if(1!==e.shape[u])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);return 0===i.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length?Ai(e):V.runKernel(Ho,{x:e},{reps:i})}}),gs=U({clipByValue_:function eI(n,t,e){const s=$(n,"x","clipByValue");return T(t<=e,()=>`Error in clip: min (${t}) must be less than or equal to max (${e}).`),t===e?Jo(s.shape,t,s.dtype):V.runKernel(ao,{x:s},{clipValueMin:t,clipValueMax:e})}}),Bn=U({concat_:function tI(n,t=0){T(n.length>=1,()=>"Pass at least one tensor to concat");const e=xx(n,"tensors","concat","string_or_numeric");return"complex64"===e[0].dtype&&e.forEach(i=>{if("complex64"!==i.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${i.dtype}. `)}),1===e.length?Ai(e[0]):V.runKernel(tu,e,{axis:t})}}),sI=U({concat1d_:function nI(n){return Bn(n,0)}}),iI=U({concat2d_:function rI(n,t){return Bn(n,t)}}),oI=U({concat3d_:function aI(n,t){return Bn(n,t)}}),uI=U({concat4d_:function lI(n,t){return Bn(n,t)}}),Oi=U({conv2d_:function cI(n,t,e,s,r="NHWC",i=[1,1],a){const o=$(n,"x","conv2d","float32"),l=$(t,"filter","conv2d","float32");let u=o,c=!1;3===o.rank&&(c=!0,u=j(o,[1,o.shape[0],o.shape[1],o.shape[2]])),T(4===u.rank,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),T(4===l.rank,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),qn("conv2d",s,a);const h="NHWC"===r?u.shape[3]:u.shape[1];T(h===l.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`),T(Pn(e,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`),T(Di(i),()=>"Error in conv2D: Dilated rates should be larger than 0."),T(Di(e),()=>"Error in conv2D: Strides should be larger than 0.");const f=V.runKernel(nu,{x:u,filter:l},{strides:e,pad:s,dataFormat:r,dilations:i,dimRoundingMode:a});return c?j(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),uy=U({conv1d_:function hI(n,t,e,s,r="NWC",i=1,a){const o=$(n,"x","conv1d"),l=$(t,"filter","conv1d");let u=o,c=!1;2===o.rank&&(c=!0,u=j(o,[1,o.shape[0],o.shape[1]])),T(3===u.rank,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),T(3===l.rank,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),qn("conv1d",s,a),T(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),T(Pn(e,i),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${e} and dilation '${i}'`),T(Di(i),()=>"Error in conv1D: Dilated rates should be larger than 0."),T(Di(e),()=>"Error in conv1D: Stride should be larger than 0."),T("NWC"===r,()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);const h=j(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=j(u,[u.shape[0],1,u.shape[1],u.shape[2]]),m=Oi(d,h,[1,e],s,"NHWC",[1,i],a);return j(m,c?[m.shape[2],m.shape[3]]:[m.shape[0],m.shape[2],m.shape[3]])}}),zp=U({conv2DBackpropInput_:function dI(n,t,e,s,r,i="NHWC",a){T(n.length===t.rank,()=>`Length of inShape (${n.length}) and rank of dy (${t.rank}) must match`);let o=n,l=t,u=!1;3===t.rank&&(u=!0,l=j(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,n[0],n[1],n[2]]),T(4===o.length,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),T(4===l.rank,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),T(4===e.rank,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${e.rank}`);const c="NHWC"===i?o[3]:o[1],h="NHWC"===i?l.shape[3]:l.shape[1];T(c===e.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${e.shape[2]}.`),T(h===e.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${e.shape[3]}.`),qn("conv2dDerInput",r,a);const f=V.runKernel(su,{dy:l,filter:e},{strides:s,pad:r,dataFormat:i,dimRoundingMode:a,inputShape:o});return u?j(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),cy=U({conv2dTranspose_:function pI(n,t,e,s,r,i){const a=$(n,"x","conv2dTranspose"),o=$(t,"filter","conv2dTranspose");return zp(e,a,o,s,r,"NHWC",i)}}),mI=U({conv3d_:function fI(n,t,e,s,r="NDHWC",i=[1,1,1]){const a=$(n,"x","conv3d"),o=$(t,"filter","conv3d");let l=a,u=!1;4===a.rank&&(u=!0,l=j(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),T(5===l.rank,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),T(5===o.rank,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),T(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),T(Pn(e,i),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`),T("NDHWC"===r,()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`),T(Di(i),()=>"Error in conv3D: Dilated rates should be larger than 0."),T(Di(e),()=>"Error in conv3D: Strides should be larger than 0.");const d=V.runKernel(ru,{x:l,filter:o},{strides:e,pad:s,dataFormat:r,dilations:i});return u?j(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),hy=U({conv3DBackpropInput_:function gI(n,t,e,s,r){T(n.length===t.rank,()=>`Length of inShape (${n.length}) and rank of dy (${t.rank}) must match`);let i=n,a=t,o=!1;4===t.rank&&(o=!0,a=j(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),i=[1,n[0],n[1],n[2],n[3]]);const l=i[4],u=a.shape[4];T(5===i.length,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${i.length}.`),T(5===a.rank,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),T(5===e.rank,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${e.rank}`),T(l===e.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${e.shape[3]}.`),T(u===e.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${e.shape[4]}.`);const d=V.runKernel(cd,{dy:a,filter:e},{pad:r,strides:s,inputShape:i});return o?j(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),yI=U({conv3dTranspose_:function xI(n,t,e,s,r){const i=$(n,"x","conv3dTranspose"),a=$(t,"filter","conv3dTranspose");return hy(e,i,a,s,r)}}),dy=U({denseBincount_:function bI(n,t,e,s=!1){const r=$(n,"x","denseBincount"),i=$(t,"weights","denseBincount");return T("int32"===r.dtype,()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),T(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),T(e>=0,()=>`size must be non-negative, but got ${e}.`),T(i.size===r.size||0===i.size,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${i.shape}.`),V.runKernel(pd,{x:r,weights:i},{size:e,binaryOutput:s})}}),lc=U({depthwiseConv2d_:function vI(n,t,e,s,r="NHWC",i=[1,1],a){const o=$(n,"x","depthwiseConv2d","float32"),l=$(t,"filter","depthwiseConv2d","float32");let u=o,c=!1;3===o.rank&&(c=!0,u=j(o,[1,o.shape[0],o.shape[1],o.shape[2]])),T(4===u.rank,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),T(4===l.rank,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);const h="NHWC"===r?u.shape[3]:u.shape[1];T(h===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`),qn("depthwiseConv2d",s,a);const f=V.runKernel(au,{x:u,filter:l},{strides:e,pad:s,dataFormat:r,dilations:i,dimRoundingMode:a});return c?j(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),uc=U({elu_:function wI(n){const e={x:$(n,"x","elu","float32")};return V.runKernel(co,e)}}),rr=U({equal_:function _I(n,t){let e=$(n,"a","equal","string_or_numeric"),s=$(t,"b","equal","string_or_numeric");return[e,s]=un(e,s),ht(e.shape,s.shape),V.runKernel(lu,{a:e,b:s})}}),py=U({erf_:function TI(n){let t=$(n,"x","erf");return T("int32"===t.dtype||"float32"===t.dtype,()=>"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=ke(t,"float32")),V.runKernel(ho,{x:t})}}),xs=U({exp_:function SI(n){const e={x:$(n,"x","exp")};return V.runKernel(po,e)}}),Zn=U({expandDims_:function CI(n,t=0){const e=$(n,"x","expandDims","string_or_numeric");return T(t<=e.rank,()=>"Axis must be <= rank of the tensor"),V.runKernel(uu,{input:e},{dim:t})}}),Us=U({tile_:function II(n,t){const e=$(n,"x","tile","string_or_numeric");return T(e.rank===t.length,()=>`Error in transpose: rank of input ${e.rank} must match length of reps ${t}.`),V.runKernel(Ho,{x:e},{reps:t})}}),fy=U({eye_:function EI(n,t,e,s="float32"){null==t&&(t=n);const r=vt([n,t],s),i=n<=t?n:t;for(let o=0;o{const o=Ws(r,t,!0),l=ze(r,o),u=ze(ke(l,"float32"),Ns(Ge(xs(l),t,!0)));return i([u]),{value:u,gradFunc:(h,d)=>{const[p]=d,g=xs(p);return ze(h,L(Ge(h,t,!0),g))}}})(e)}});function Gp(n,t){for(let e=0;en[i])]}function hn(n,t){return gy(n,t.map(s=>1),t)}function Fn(n,t,e){T(Gp(t,e),()=>`${n} supports only inner-most axes for now. Got axes ${t} and rank-${e} input.`)}function rn(n,t){if(Gp(n,t))return null;const e=[];for(let s=0;se.push(s)),e}function Yr(n){return n.map((t,e)=>[e,t]).sort((t,e)=>t[1]-e[1]).map(t=>t[0])}function dn(n,t){const e=[];for(let s=t-n;s`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),T(Pn(e,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${e} and dilations '1'`),qn("maxPool",s,r);const h=V.runKernel(wu,{x:o},{filterSize:t,strides:e,pad:s,dimRoundingMode:r});return l?j(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),WI=U({maxPool3d_:function UI(n,t=[1,1,1],e,s,r,i="NDHWC"){const a=$(n,"x","maxPool3d");let o=a,l=!1;4===a.rank&&(l=!0,o=j(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),T(5===o.rank,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),T("NDHWC"===i,()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${i}`),qn("maxPool3d",s,r);const h=V.runKernel(_u,{x:o},{filterSize:t,strides:e,pad:s,dimRoundingMode:r,dataFormat:i});return l?j(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),pn=U({mean_:function GI(n,t=null,e=!1){const r={x:$(n,"x","mean")};return V.runKernel(Tu,r,{axis:t,keepDims:e})}}),hc=U({min_:function HI(n,t=null,e=!1){const r={x:$(n,"x","min")};return V.runKernel(Su,r,{axis:t,keepDims:e})}}),ya=U({minimum_:function jI(n,t){let e=$(n,"a","minimum"),s=$(t,"b","minimum");return[e,s]=un(e,s),"bool"===e.dtype&&(e=ke(e,"int32"),s=ke(s,"int32")),ht(e.shape,s.shape),V.runKernel(Co,{a:e,b:s})}}),Xp=U({moments_:function XI(n,t=null,e=!1){const s=pt(t,(n=$(n,"x","moments")).shape),r=pn(n,s,e);let i=r.shape;e||(i=hn(r.shape,s));const a=Kt(ze(ke(n,"float32"),j(r,i)));return{mean:r,variance:pn(a,s,e)}}}),Jt=U({neg_:function KI(n){const e={x:$(n,"x","neg")};return V.runKernel(Iu,e)}}),il=U({notEqual_:function qI(n,t){let e=$(n,"a","notEqual","string_or_numeric"),s=$(t,"b","notEqual","string_or_numeric");return[e,s]=un(e,s),ht(e.shape,s.shape),V.runKernel(Eu,{a:e,b:s})}}),xy=U({oneHot_:function ZI(n,t,e=1,s=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const a={indices:$(n,"indices","oneHot","int32")};return V.runKernel(Nu,a,{dtype:r,depth:t,onValue:e,offValue:s})}});function Rn(n,t="float32"){if(Js(n),"complex64"===t){const s=Rn(n,"float32"),r=Rn(n,"float32");return Ci(s,r)}const e=yn(K(n),t);return V.makeTensor(e,n,t)}function Ir(n,t="float32"){if(Js(n),"complex64"===t){const s=Ir(n,"float32"),r=Rn(n,"float32");return Ci(s,r)}const e=Vr(K(n),t);return V.makeTensor(e,n,t)}const As=U({onesLike_:function YI(n){const e={x:$(n,"x","onesLike")};return V.runKernel(ku,e)}}),Kp=U({pad_:function QI(n,t,e=0){const s=$(n,"x","pad");if(0===s.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");return V.runKernel(Ru,{x:s},{paddings:t,constantValue:e})}}),qp=U({prelu_:function JI(n,t){const e=$(n,"x","prelu"),s=$(t,"alpha","prelu");return V.runKernel($u,{x:e,alpha:s})}});var al=W(8814);class Zp{constructor(t,e,s,r,i){this.mean=t,this.stdDev=e,this.dtype=s,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const a=i||Math.random();this.random=al.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){const r=this.nextVal;return this.nextVal=NaN,r}let t,e,s=!1;for(;!s;){let r,i,a;do{r=2*this.random()-1,i=2*this.random()-1,a=r*r+i*i}while(a>=1||0===a);const o=Math.sqrt(-2*Math.log(a)/a);t=this.mean+this.stdDev*r*o,e=this.mean+this.stdDev*i*o,(!this.truncated||this.isValidTruncated(t))&&(s=!0)}return(!this.truncated||this.isValidTruncated(e))&&(this.nextVal=this.convertValue(e)),this.convertValue(t)}convertValue(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)}isValidTruncated(t){return t<=this.upper&&t>=this.lower}}class eE{constructor(t=0,e=1,s,r){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=t,this.range=e-t,this.dtype=s,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${t} - ${e} <= 1 and dtype is not float`);this.random=al.alea(r)}convertValue(t){return this.canReturnFloat()?t:Math.round(t)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const iE=U({randomNormal_:function rE(n,t=0,e=1,s,r){if(Js(n),null!=s&&"bool"===s)throw new Error(`Unsupported data type ${s}`);const i=new Zp(t,e,s,!1,r),a=vt(n,s);for(let o=0;o`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),T(4===l.rank,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),T(4===u.rank,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),T(1===u.shape[0],()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),T(1===u.shape[1],()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);const d=l.shape[2],p=l.shape[3];T(u.shape[2]===d*p,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*p}, but got ${u.shape[2]}.`);const f=lc(c,l,s,r,a,i),m=Oi(f,u,1,"valid",a);return h?j(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}),ba=U({sigmoid_:function hE(n){const e={x:$(n,"x","sigmoid","float32")};return V.runKernel(Mo,e)}}),Bt=U({slice_:function dE(n,t,e){const s=$(n,"x","slice","string_or_numeric");if(0===s.rank)throw new Error("Slicing scalar is not possible");return V.runKernel(Vu,{x:s},{begin:t,size:e})}}),Qp=U({slice1d_:function pE(n,t,e){const s=$(n,"x","slice1d");return T(1===s.rank,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),Bt(s,[t],[e])}}),vy=U({slice2d_:function fE(n,t,e){const s=$(n,"x","slice2d");return T(2===s.rank,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),Bt(s,t,e)}}),Jp=U({slice3d_:function mE(n,t,e){const s=$(n,"x","slice3d");return T(3===s.rank,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),Bt(s,t,e)}}),dc=U({slice4d_:function gE(n,t,e){const s=$(n,"x","slice4d");return T(4===s.rank,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),Bt(s,t,e)}}),ef=U({softmax_:function xE(n,t=-1){const e=$(n,"logits","softmax","float32");if(-1===t&&(t=e.rank-1),t!==e.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and dim was ${t}`);return V.runKernel(Wu,{logits:e},{dim:t})}}),ul=U({softplus_:function yE(n){const e={x:$(n,"x","softplus")};return V.runKernel(Vo,e)}}),bs=U({split_:function bE(n,t,e=0){const r={x:$(n,"x","split")};return V.runKernel(Uu,r,{numOrSizeSplits:t,axis:e})}}),cl=U({squeeze_:function vE(n,t){const e=$(n,"x","squeeze","string_or_numeric");return j(e,Qs(e.shape,t).newShape)}}),ir=U({stack_:function wE(n,t=0){const e=xx(n,"tensors","stack","string_or_numeric");return T(e.length>=1,()=>"Pass at least one tensor to tf.stack"),e.length>0&&T(t<=e[0].rank,()=>"Axis must be <= rank of the tensor"),V.runKernel(Au,e,{axis:t})}}),pc=U({tanh_:function _E(n){const e={x:$(n,"x","tanh","float32")};return V.runKernel(Go,e)}});function Un(n,t){Ye(n);const e=Yo(n,t);if(1!==e.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Qo(n,null,e,t)}function Qr(n,t,e){if(Ye(n),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const s=Yo(n,e);if(2!==s.length&&1!==s.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Qo(n,t,s,e)}const wy=U({truncatedNormal_:function TE(n,t=0,e=1,s,r){if(Js(n),null!=s&&"bool"===s)throw new Error("Unsupported data type $ { dtype }");const i=new Zp(t,e,s,!0,r),a=vt(n,s);for(let o=0;o=-e.shape.length&&t`Axis = ${t} is not in [-${e.shape.length}, ${e.shape.length})`),V.runKernel(Hu,{value:e},{axis:t})}}),Yn=U({where_:function IE(n,t,e){const s=$(t,"a","where"),r=$(e,"b","where"),i=$(n,"condition","where","bool"),a=ht(ht(i.shape,s.shape),r.shape),o=rl(i,a),l=rl(s,a),u=rl(r,a);return V.runKernel(Mu,{condition:o,t:l,e:u})}}),tf=U({imag_:function EE(n){const e={input:$(n,"input","imag")};return V.runKernel(Id,e)}}),fc=U({real_:function kE(n){const e={input:$(n,"input","real")};return V.runKernel(Od,e)}}),kt=U({transpose_:function NE(n,t,e){const s=$(n,"x","transpose");if(null==t&&(t=s.shape.map((a,o)=>o).reverse()),T(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`),t.forEach(a=>{T(a>=0&&a`All entries in 'perm' must be between 0 and ${s.rank-1} but got ${t}`)}),s.rank<=1)return s.clone();const r={x:s},i={perm:t};return"complex64"===s.dtype?Z(()=>{let a=fc(s),o=tf(s);return a=V.runKernel(la,{x:a},i),o=V.runKernel(la,{x:o},i),e&&(o=Jt(o)),Ci(a,o)}):V.runKernel(la,r,i)}}),$E=U({dropout_:function RE(n,t,e,s){const r=$(n,"x","dropout");if(T("float32"===r.dtype,()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),T(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),0===t)return n instanceof Qt?r.clone():r;const i=function AE(n,t){if(null==t)return n.shape.slice();if(rt(n.shape,t))return t;if(n.shape.length===t.length){const e=[];for(let s=0;s`The dtype for tf.spectral.fft() must be complex64 but got ${n.dtype}.`),V.runKernel("FFT",{input:n})}}),sf=U({rfft_:function OE(n,t){T("float32"===n.dtype,()=>`The dtype for rfft() must be real value but got ${n.dtype}`);let e=n.shape[n.shape.length-1];const s=n.size/e;let r;if(null!=t&&t0),g=n.shape.map(m=>m);g[n.shape.length-1]=t,r=Bt(n,f,g),e=t}else if(null!=t&&t>e){const f=n.shape.map(g=>g);f[n.shape.length-1]=t-e,r=Bn([n,Rn(f)],n.shape.length-1),e=t}else r=n;const i=Et(r),a=j(Ci(r,i),[s,e]),o=nf(a),l=Math.floor(e/2)+1,u=fc(o),c=tf(o),h=bs(u,[l,e-l],u.shape.length-1),d=bs(c,[l,e-l],c.shape.length-1),p=r.shape.slice();return p[r.shape.length-1]=l,j(Ci(h[0],d[0]),p)}}),mc=U({ifft_:function PE(n){return T("complex64"===n.dtype,()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${n.dtype}.`),V.runKernel(Cd,{input:n})}}),_y=U({irfft_:function FE(n){const t=n.shape[n.shape.length-1],e=n.size/t;let s;if(t<=2){const r=j(n,[e,t]);s=mc(r)}else{const r=[e,2*(t-1)],i=j(fc(n),[e,t]),a=j(tf(n),[e,t]),o=Fi(Bt(i,[0,1],[e,t-2]),1),l=L(Fi(Bt(a,[0,1],[e,t-2]),1),ut(-1)),u=Bn([i,o],1),c=Bn([a,l],1),h=j(Ci(u,c),[r[0],r[1]]);s=mc(h)}if(s=fc(s),3===n.rank&&0!==n.shape[0]){const r=s,i=n.shape[0];s=j(s,[i,s.shape[0]/i,s.shape[1]]),r.dispose()}return s}}),rf=U({conv2DBackpropFilter_:function LE(n,t,e,s,r,i="NHWC",a){let o=n;3===n.rank&&(o=j(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let l=t;3===l.rank&&(l=j(t,[1,t.shape[0],t.shape[1],t.shape[2]])),T(4===o.rank,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),T(4===l.rank,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),T(4===e.length,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${e}.`);const u="NHWC"===i?o.shape[3]:o.shape[1],c="NHWC"===i?l.shape[3]:l.shape[1];return T(u===e[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${e[2]}.`),T(c===e[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${e[3]}).`),qn("conv2dDerFilter",r,a),V.runKernel(ld,{x:o,dy:l},{strides:s,pad:r,dataFormat:i,dimRoundingMode:a,filterShape:e})}}),Ty=U({relu6_:function ME(n){const e={x:$(n,"x","relu6")};return V.runKernel(Ro,e)}}),hl=U({step_:function VE(n,t=0){const s={x:$(n,"x","step")};return V.runKernel(jo,s,{alpha:t})}});function gc(n,t,e){if(null==e||"linear"===e)return n;if("relu"===e)return L(n,hl(t));throw new Error(`Cannot compute gradient for fused activation ${e}.`)}function xc(n,t){let e=t;const s=bn(n.shape,t.shape);return s.length>0&&(e=Ge(e,s)),j(e,n.shape)}function yc(n,t,e,s){if("linear"===t)return n;if("relu"===t)return Er(n);if("elu"===t)return uc(n);if("relu6"===t)return Ty(n);if("prelu"===t)return qp(n,e);if("leakyrelu"===t)return Up(n,s);if("sigmoid"===t)return ba(n);throw new Error(`Unknown fused activation ${t}.`)}const bc=(n,t)=>!(n>0)||"linear"===t,BE=U({fusedConv2d_:function zE({x:n,filter:t,strides:e,pad:s,dataFormat:r="NHWC",dilations:i=[1,1],dimRoundingMode:a,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(!1===bc(V.state.gradientDepth,l=l||"linear")){T("NHWC"===r,()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let S=Oi(n,t,e,s,r,i,a);return null!=o&&(S=me(S,o)),yc(S,l,u,c)}const h=$(n,"x","conv2d","float32"),d=$(t,"filter","conv2d","float32");let p=h,f=!1;3===h.rank&&(f=!0,p=j(h,[1,h.shape[0],h.shape[1],h.shape[2]])),T(4===p.rank,()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`),T(4===d.rank,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),qn("fused conv2d",s,a);const g="NHWC"===r?p.shape[3]:p.shape[1];T(d.shape[2]===g,()=>`Error in conv2d: depth of input (${g}) must match input depth for filter ${d.shape[2]}.`),T(Pn(e,i),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`);const m=Nn(p.shape,d.shape,e,i,s,a);let x,y;if(null!=o&&(x=$(o,"bias","fused conv2d"),[x]=un(x,h),"NHWC"===r?ht(m.outShape,x.shape):(T(x.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${x.shape.length}.`),T(0===x.shape.length||x.shape[0]===m.outChannels||1===x.shape[0],()=>`Error in fused conv2d: bias shape (${x.shape}) is not compatible with the number of output channels (${m.outChannels})`))),null!=u){const S=u.shape;if(T(S.length<=1||3===S.length,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${S.length}.`),1===S.length)T(1===S[0]||S[0]===m.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${S}) is not compatible with the number of output channels (${m.outChannels}).`);else if(3===S.length)try{ht(S,m.outShape)}catch{throw Error(`Error in fused conv2d: PReLU activation weights (${S}) is not compatible with the output shape of the conv2d (${m.outShape}).`)}y=$(u,"prelu weights","fused conv2d")}const b=(S,I)=>{T("NHWC"===r,()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);const[k,D,P,B]=I,Y=gc(S,P,l);T(Zr(i),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`);const J=[zp(D.shape,Y,k,e,s),rf(D,Y,k.shape,e,s)];if(null!=B){const se=xc(B,Y);J.push(se)}return J},v={x:p,filter:d,bias:x,preluActivationWeights:y},w={strides:e,pad:s,dataFormat:r,dilations:i,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return null==o?_r((I,k,D)=>{let P=V.runKernel(qu,v,w);return D([k,I,P]),f&&(P=j(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:b}})(p,d):_r((I,k,D,P)=>{let B=V.runKernel(qu,v,w);return P([k,I,B,D]),f&&(B=j(B,[B.shape[1],B.shape[2],B.shape[3]])),{value:B,gradFunc:b}})(p,d,x)}}),Sy=U({depthwiseConv2dNativeBackpropFilter_:function UE(n,t,e,s,r,i=[1,1],a){let o=n;3===n.rank&&(o=j(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let l=t;return 3===l.rank&&(l=j(t,[1,t.shape[0],t.shape[1],t.shape[2]])),V.runKernel(md,{x:o,dy:l},{strides:s,pad:r,dimRoundingMode:a,dilations:i,filterShape:e})}}),Cy=U({depthwiseConv2dNativeBackpropInput_:function WE(n,t,e,s,r,i=[1,1],a){let o=t,l=!1;3===t.rank&&(l=!0,o=j(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const h=V.runKernel(gd,{dy:o,filter:e},{strides:s,pad:r,dimRoundingMode:a,dilations:i,inputShape:n});return l?j(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),Iy=U({fusedMatMul_:function HE({a:n,b:t,transposeA:e=!1,transposeB:s=!1,bias:r,activation:i="linear",preluActivationWeights:a,leakyreluAlpha:o=.2}){if(!1===bc(V.state.gradientDepth,i)){let B=Dt(n,t,e,s);return null!=r&&(B=me(B,r)),yc(B,i,a,o)}let l=$(n,"a","fused matMul"),u=$(t,"b","fused matMul");[l,u]=un(l,u);const c=e?l.shape[l.rank-2]:l.shape[l.rank-1],h=s?u.shape[u.rank-1]:u.shape[u.rank-2],d=e?l.shape[l.rank-1]:l.shape[l.rank-2],p=s?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),g=u.shape.slice(0,-2),m=K(f),x=K(g);T(c===h,()=>`Error in fused matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${e} and transposeB=${s} must match.`);const b=ht(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([d,p]),v=j(l,e?[m,c,d]:[m,d,c]),w=j(u,s?[x,p,h]:[x,h,p]);let S,I;null!=r&&(S=$(r,"bias","fused matMul"),[S]=un(S,l),ht(b,S.shape)),null!=a&&(I=$(a,"prelu weights","fused matMul"));const k=(B,Y)=>{const[Q,ee,J,se]=Y,ae=gc(j(B,J.shape),J,i);let te,le;return e||s?!e&&s?(te=Dt(ae,ee,!1,!1),le=Dt(ae,Q,!0,!1)):e&&!s?(te=Dt(ee,ae,!1,!0),le=Dt(Q,ae,!1,!1)):(te=Dt(ee,ae,!0,!0),le=Dt(ae,Q,!0,!0)):(te=Dt(ae,ee,!1,!0),le=Dt(Q,ae,!0,!1)),null!=r?[te,le,xc(se,ae)]:[te,le]},D={a:v,b:w,bias:S,preluActivationWeights:I},P={transposeA:e,transposeB:s,activation:i,leakyreluAlpha:o};return null==r?_r((Y,Q,ee)=>{const J=V.runKernel(Ku,D,P);return ee([Y,Q,J]),{value:j(J,b),gradFunc:k}})(v,w):_r((Y,Q,ee,J)=>{const se=V.runKernel(Ku,D,P);return J([Y,Q,se,ee]),{value:j(se,b),gradFunc:k}})(v,w,S)}}),ek=U({cropAndResize_:function JE(n,t,e,s,r="bilinear",i=0){const a=$(n,"image","cropAndResize"),o=$(t,"boxes","cropAndResize","float32"),l=$(e,"boxInd","cropAndResize","int32"),u=o.shape[0];return T(4===a.rank,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),T(2===o.rank&&4===o.shape[1],()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),T(1===l.rank&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),T(2===s.length,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),T(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),T("bilinear"===r||"nearest"===r,()=>`method must be bilinear or nearest, but was ${r}`),V.runKernel(dd,{image:a,boxes:o,boxInd:l},{method:r,extrapolationValue:i,cropSize:s})}}),nk=U({flipLeftRight_:function tk(n){const t=$(n,"image","flipLeftRight","float32");return T(4===t.rank,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`),V.runKernel(Sd,{image:t},{})}}),rk=U({grayscaleToRGB_:function sk(n){const t=$(n,"image","grayscaleToRGB"),e=t.rank-1,s=t.shape[e];T(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),T(1===s,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);const r=new Array(t.rank);return r.fill(1,0,e),r[e]=3,Us(t,r)}}),dl=U({einsum_:function ik(n,...t){const e=t.map((r,i)=>$(r,`tensors${i}`,"einsum"));return V.runKernel(vd,e,{equation:n})}}),ok=U({rgbToGrayscale_:function ak(n){const t=$(n,"image","RGBToGrayscale"),s=t.shape[t.rank-1];T(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),T(3===s,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${s}.`);const r=t.dtype,i=ke(t,"float32"),a=Un([.2989,.587,.114]);let o;switch(t.rank){case 2:o=dl("ij,j->i",i,a);break;case 3:o=dl("ijk,k->ij",i,a);break;case 4:o=dl("ijkl,l->ijk",i,a);break;case 5:o=dl("ijklm,m->ijkl",i,a);break;case 6:o=dl("ijklmn,n->ijklm",i,a);break;default:throw new Error("Not a valid tensor rank.")}return o=Zn(o,-1),ke(o,r)}}),uk=U({rotateWithOffset_:function lk(n,t,e=0,s=.5){const r=$(n,"image","rotateWithOffset","float32");return T(4===r.rank,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`),V.runKernel(Zd,{image:r},{radians:t,fillValue:e,center:s})}});function va(n,t,e,s,r,i){null==s&&(s=.5),null==r&&(r=Number.NEGATIVE_INFINITY),null==i&&(i=0);const a=n.shape[0];return e=Math.min(e,a),T(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),T(2===n.rank,()=>`boxes must be a 2D tensor, but was of rank '${n.rank}'`),T(4===n.shape[1],()=>`boxes must have 4 columns, but 2nd dimension was ${n.shape[1]}`),T(1===t.rank,()=>"scores must be a 1D tensor"),T(t.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`),T(0<=i&&i<=1,()=>`softNmsSigma must be in [0, 1], but was '${i}'`),{maxOutputSize:e,iouThreshold:s,scoreThreshold:r,softNmsSigma:i}}const hk=U({nonMaxSuppression_:function ck(n,t,e,s=.5,r=Number.NEGATIVE_INFINITY){const i=$(n,"boxes","nonMaxSuppression","float32"),a=$(t,"scores","nonMaxSuppression","float32"),o=va(i,a,e,s,r);return V.runKernel(Ad,{boxes:i,scores:a},{maxOutputSize:e=o.maxOutputSize,iouThreshold:s=o.iouThreshold,scoreThreshold:r=o.scoreThreshold})}});function dk(n,t,e){const s=function pk(n,t,e){return function mk(n,t,e){let s=0,r=n.length,i=0,a=!1;for(;s>>1);const o=e(t,n[i]);o>0?s=i+1:(r=i,a=!o)}return a?s:-s-1}(n,t,e||fk)}(n,t,e);n.splice(s<0?-(s+1):s,0,t)}function fk(n,t){return n>t?1:nr&&u.push({score:t[m],boxIndex:m,suppressBeginIndex:0});u.sort(Ay);const c=i>0?-.5/i:0,h=[],d=[];for(;h.length0;){const m=u.pop(),{score:x,boxIndex:y,suppressBeginIndex:b}=m;if(x=b;--w){const S=gk(n,y,h[w]);if(S>=s){v=!0;break}if(m.score=m.score*xk(s,c,S),m.score<=r)break}m.suppressBeginIndex=h.length,v||(m.score===x?(h.push(y),d.push(m.score)):m.score>r&&dk(u,m,Ay))}const p=h.length,f=e-p;o&&f>0&&(h.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));const g={selectedIndices:h};return a&&(g.selectedScores=d),l&&(g.validOutputs=p),g}function gk(n,t,e){const s=n.subarray(4*t,4*t+4),r=n.subarray(4*e,4*e+4),i=Math.min(s[0],s[2]),a=Math.min(s[1],s[3]),o=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),p=(o-i)*(l-a),f=(h-u)*(d-c);if(p<=0||f<=0)return 0;const g=Math.max(i,u),m=Math.max(a,c),x=Math.min(o,h),y=Math.min(l,d),b=Math.max(x-g,0)*Math.max(y-m,0);return b/(p+f-b)}function xk(n,t,e){const s=Math.exp(t*e*e);return e<=n?s:0}function Ay(n,t){return n.score-t.score||n.score===t.score&&t.boxIndex-n.boxIndex}function cf(){return(cf=(0,N.A)(function*(n,t,e,s=.5,r=Number.NEGATIVE_INFINITY){const i=$(n,"boxes","nonMaxSuppressionAsync"),a=$(t,"scores","nonMaxSuppressionAsync"),o=va(i,a,e,s,r);e=o.maxOutputSize,s=o.iouThreshold,r=o.scoreThreshold;const l=yield Promise.all([i.data(),a.data()]),u=l[0],c=l[1],{selectedIndices:h}=af(u,c,e,s,r);return i!==n&&i.dispose(),a!==t&&a.dispose(),Un(h,"int32")})).apply(this,arguments)}const wk=U({nonMaxSuppressionWithScore_:function vk(n,t,e,s=.5,r=Number.NEGATIVE_INFINITY,i=0){const a=$(n,"boxes","nonMaxSuppression"),o=$(t,"scores","nonMaxSuppression"),l=va(a,o,e,s,r,i),h=V.runKernel($d,{boxes:a,scores:o},{maxOutputSize:e=l.maxOutputSize,iouThreshold:s=l.iouThreshold,scoreThreshold:r=l.scoreThreshold,softNmsSigma:i=l.softNmsSigma});return{selectedIndices:h[0],selectedScores:h[1]}}});function hf(){return(hf=(0,N.A)(function*(n,t,e,s=.5,r=Number.NEGATIVE_INFINITY,i=0){const a=$(n,"boxes","nonMaxSuppressionAsync"),o=$(t,"scores","nonMaxSuppressionAsync"),l=va(a,o,e,s,r,i);e=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,i=l.softNmsSigma;const u=yield Promise.all([a.data(),o.data()]),c=u[0],h=u[1],{selectedIndices:d,selectedScores:p}=lf(c,h,e,s,r,i);return a!==n&&a.dispose(),o!==t&&o.dispose(),{selectedIndices:Un(d,"int32"),selectedScores:Un(p)}})).apply(this,arguments)}const Ck=U({nonMaxSuppressionPadded_:function Sk(n,t,e,s=.5,r=Number.NEGATIVE_INFINITY,i=!1){const a=$(n,"boxes","nonMaxSuppression"),o=$(t,"scores","nonMaxSuppression"),l=va(a,o,e,s,r,null),f=V.runKernel(Rd,{boxes:a,scores:o},{maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:i});return{selectedIndices:f[0],validOutputs:f[1]}}});function df(){return(df=(0,N.A)(function*(n,t,e,s=.5,r=Number.NEGATIVE_INFINITY,i=!1){const a=$(n,"boxes","nonMaxSuppressionAsync"),o=$(t,"scores","nonMaxSuppressionAsync"),l=va(a,o,e,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[d,p]=yield Promise.all([a.data(),o.data()]),{selectedIndices:f,validOutputs:g}=of(d,p,u,c,h,i);return a!==n&&a.dispose(),o!==t&&o.dispose(),{selectedIndices:Un(f,"int32"),validOutputs:ut(g,"int32")}})).apply(this,arguments)}const Ry=U({resizeBilinear_:function kk(n,t,e=!1,s=!1){const r=$(n,"images","resizeBilinear");T(3===r.rank||4===r.rank,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),T(2===t.length,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),T(!1===s||!1===e,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let i=r,a=!1;3===r.rank&&(a=!0,i=j(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,u=V.runKernel(Fu,{images:i},{alignCorners:e,halfPixelCenters:s,size:t});return a?j(u,[u.shape[1],u.shape[2],u.shape[3]]):u}}),$y=U({resizeNearestNeighbor_:function Nk(n,t,e=!1,s=!1){const r=$(n,"images","resizeNearestNeighbor");T(3===r.rank||4===r.rank,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),T(2===t.length,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),T("float32"===r.dtype||"int32"===r.dtype,()=>"`images` must have `int32` or `float32` as dtype"),T(!1===s||!1===e,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let i=r,a=!1;3===r.rank&&(a=!0,i=j(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,u=V.runKernel(Pu,{images:i},{alignCorners:e,halfPixelCenters:s,size:t});return a?j(u,[u.shape[1],u.shape[2],u.shape[3]]):u}}),Rk=U({bincount_:function Ak(n,t,e){const s=$(n,"x","bincount"),r=$(t,"weights","bincount");return T("int32"===s.dtype,()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),T(e>=0,()=>`size must be non-negative, but got ${e}.`),T(r.size===s.size||0===r.size,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`),V.runKernel(id,{x:s,weights:r},{size:e})}}),wa=U({lessEqual_:function $k(n,t){let e=$(n,"a","lessEqual","string_or_numeric"),s=$(t,"b","lessEqual","string_or_numeric");return[e,s]=un(e,s),ht(e.shape,s.shape),V.runKernel(mu,{a:e,b:s})}}),Dy=U({round_:function Dk(n){const e={x:$(n,"x","round")};return V.runKernel($o,e)}}),Fk=U({threshold_:function Ok(n,t="binary",e=!1,s=.5){const r=$(n,"image","threshold"),l=r.shape[0]*r.shape[1];let c,h,d,p,u=L(Un([s]),255);if(T(3===r.rank,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),T(3===r.shape[2]||1===r.shape[2],()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),T("int32"===r.dtype||"float32"===r.dtype,()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),T("otsu"===t||"binary"===t,()=>`Method must be binary or otsu, but was ${t}`),3===r.shape[2]){[c,h,d]=bs(r,[1,1,1],-1);const m=L(c,.2989),x=L(h,.587),y=L(d,.114);p=me(me(m,x),y)}else p=n;"otsu"===t&&(u=function Pk(n,t){let i,a,o,l,u,c,e=Un([-1]),s=Un([0]),r=Un([0]);for(let h=0;h`Error in transform: image must be rank 4,but got rank ${a.rank}.`),T(2===o.rank&&(o.shape[0]===a.shape[0]||1===o.shape[0])&&8===o.shape[1],()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),T(null==i||2===i.length,()=>`Error in transform: outputShape must be [height, width] or null, but got ${i}.`),V.runKernel(Xd,{image:a,transforms:o},{interpolation:e,fillMode:s,fillValue:r,outputShape:i})}}),vc=U({less_:function Vk(n,t){let e=$(n,"a","less","string_or_numeric"),s=$(t,"b","less","string_or_numeric");return[e,s]=un(e,s),ht(e.shape,s.shape),V.runKernel(fu,{a:e,b:s})}}),Bk=U({bandPart_:function zk(n,t,e){const s=$(n,"a","bandPart");T(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);const r=s.shape,[i,a]=s.shape.slice(-2);let o,l;"number"==typeof t?(T(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),T(t<=i,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${i}).`),o=$(t<0?i:t,"numLower","bandPart")):(T("int32"===t.dtype,()=>"bandPart(): numLower's dtype must be an int32."),o=Yn(vc(t,0),i,ya(t,i))),"number"==typeof e?(T(e%1==0,()=>`bandPart(): numUpper must be an integer, got ${e}.`),T(e<=a,()=>`bandPart(): numUpper (${e}) must not be greater than the number of columns (${a}).`),l=$(e<0?a:e,"numUpper","bandPart")):(T("int32"===e.dtype,()=>"bandPart(): numUpper's dtype must be an int32."),l=Yn(vc(e,0),a,ya(e,a)));const u=j(ll(0,i,1,"int32"),[-1,1]),c=ll(0,a,1,"int32"),h=ze(u,c),d=Cr(wa(h,o),Pi(h,Jt(l))),p=Rn([i,a],s.dtype);return j(ir(Li(j(s,[-1,i,a])).map(f=>Yn(d,f,p))),r)}});function Oy(n,t,e=null){if(0===n.rank)return kn(n);if(1!==n.rank&&null===e)return Oy(j(n,[-1]),t,e);if(1===n.rank||"number"==typeof e||Array.isArray(e)&&1===e.length){if(1===t)return Ge(kn(n),e);if(t===1/0)return Ws(kn(n),e);if(t===-1/0)return hc(kn(n),e);if("euclidean"===t||2===t)return zn(Ge(Ri(kn(n),ut(2,"int32")),e));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(e)&&2===e.length){if(1===t)return Ws(Ge(kn(n),e[0]),e[1]-1);if(t===1/0)return Ws(Ge(kn(n),e[1]),e[0]);if(t===-1/0)return hc(Ge(kn(n),e[1]),e[0]);if("fro"===t||"euclidean"===t)return zn(Ge(Kt(n),e));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${e}`)}const wc=U({norm_:function Uk(n,t="euclidean",e=null,s=!1){const r=Oy(n=$(n,"x","norm"),t,e);let i=r.shape;if(s){const a=pt(e,n.shape);i=hn(r.shape,a)}return j(r,i)}}),Gk=U({gramSchmidt_:function Wk(n){let t;if(Array.isArray(n)){t=!1,T(null!=n&&n.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const r=n[0].shape[0];for(let i=1;i`Gram-Schmidt: Non-unique lengths found in the input vectors: (${n[i].shape[0]} vs. ${r})`)}else t=!0,n=bs(n,n.shape[0],0).map(r=>cl(r,[0]));T(n.length<=n[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${n.length}) exceeds number of dimensions (${n[0].shape[0]}).`);const e=[],s=n;for(let r=0;r{let i=s[r];if(r>0)for(let a=0;a{T(2===n.shape.length,()=>`qr2d() requires a 2D Tensor, but got a ${n.shape.length}D Tensor.`);const e=n.shape[0],s=n.shape[1];let r=fy(e),i=Ai(n);const a=Qr([[1]],[1,1]);let o=Ai(a);const l=e>=s?s:e;for(let u=0;u{const p=Bt(i,[u,u],[e-u,1]),f=wc(p),g=Bt(i,[u,u],[1,1]),m=Yn(ys(g,0),Qr([[-1]]),Qr([[1]])),x=ze(g,L(m,f)),y=je(p,x);o=1===y.shape[0]?Ai(a):Bn([a,Bt(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);const b=Jt(je(Dt(m,x),f)),v=Bt(i,[u,0],[e-u,s]),w=L(b,o),S=kt(o);if(0===u)i=ze(v,Dt(w,Dt(S,v)));else{const D=ze(v,Dt(w,Dt(S,v)));i=Bn([Bt(i,[0,0],[u,s]),D],0)}const I=kt(w),k=Bt(r,[0,u],[e,r.shape[1]-u]);if(0===u)r=ze(k,Dt(Dt(k,o),I));else{const D=ze(k,Dt(Dt(k,o),I));r=Bn([Bt(r,[0,0],[e,u]),D],1)}return[o,i,r]}),xt([c,h,d])}return!t&&e>s&&(r=Bt(r,[0,0],[e,s]),i=Bt(i,[0,0],[s,s])),[r,i]})}const jk=U({qr_:function Hk(n,t=!1){if(T(n.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${n.rank}`),2===n.rank)return Py(n,t);{const e=n.shape.slice(0,n.shape.length-2).reduce((l,u)=>l*u),s=Li(j(n,[e,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),r=[],i=[];return s.forEach(l=>{const[u,c]=Py(l,t);r.push(u),i.push(c)}),[j(ir(r,0),n.shape),j(ir(i,0),n.shape)]}}}),Fy=U({squaredDifference_:function rN(n,t){let e=$(n,"a","squaredDifference"),s=$(t,"b","squaredDifference");return[e,s]=un(e,s),ht(e.shape,s.shape),V.runKernel(Bo,{a:e,b:s},{})}}),ar={flipLeftRight:nk,grayscaleToRGB:rk,resizeNearestNeighbor:$y,resizeBilinear:Ry,rgbToGrayscale:ok,rotateWithOffset:uk,cropAndResize:ek,nonMaxSuppression:hk,nonMaxSuppressionAsync:function yk(n,t,e){return cf.apply(this,arguments)},nonMaxSuppressionWithScore:wk,nonMaxSuppressionWithScoreAsync:function _k(n,t,e){return hf.apply(this,arguments)},nonMaxSuppressionPadded:Ck,nonMaxSuppressionPaddedAsync:function Ik(n,t,e){return df.apply(this,arguments)},threshold:Fk,transform:Mk},NN={bandPart:Bk,gramSchmidt:Gk,qr:jk},_a=class AN{static sgd(t){return new Tp(t)}static momentum(t,e,s=!1){return new zx(t,e,s)}static rmsprop(t,e=.9,s=0,r=null,i=!1){return new Bx(t,e,s,r,i)}static adam(t=.001,e=.9,s=.999,r=null){return new Mx(t,e,s,r)}static adadelta(t=.001,e=.95,s=null){return new Fx(t,e,s)}static adamax(t=.002,e=.9,s=.999,r=null,i=0){return new Vx(t,e,s,r,i)}static adagrad(t,e=.1){return new Lx(t,e)}},RN=typeof requestAnimationFrame<"u"?requestAnimationFrame:typeof setImmediate<"u"?setImmediate:n=>n();function Ly(){return new Promise(n=>RN(()=>n()))}function pf(n,t){const e=n[0].length;n.forEach((r,i)=>{T(r.length===e,()=>`Error in concat${e}D: rank of tensors[${i}] must be the same as the rank of the rest (${e})`)}),T(t>=0&&t`Error in concat${e}D: axis must be between 0 and ${e-1}.`);const s=n[0];n.forEach((r,i)=>{for(let a=0;a`Error in concat${e}D: Shape of tensors[${i}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${i}.`)})}function or(n,t){const e=n[0].slice();for(let s=1;s=0)if(o>=0){if(o!==i)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+n}] = ${i} but shape[${r+n}] = ${o}`)}else s[a]=i}return s}function Vy(n){const t={FIRST_DIM_SIZE:lr.FIRST_DIM_SIZE,VALUE_ROWIDS:lr.VALUE_ROWIDS,ROW_LENGTHS:lr.ROW_LENGTHS,ROW_SPLITS:lr.ROW_SPLITS,ROW_LIMITS:lr.ROW_LIMITS,ROW_STARTS:lr.ROW_STARTS},e=[];for(const s of n){if(!(s in t))break;e.push(t[s])}return e}function zy(n){return 0===n.length?0:n[0]===lr.FIRST_DIM_SIZE?n.length-1:n.length}function By(n,t){if(null==n||null==t)return;const e=n.length,s=t.length;if(e>=s)throw new Error(`defaultValue.shape=${n} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${e} must be less than ragged tensor input flatValues.rank = ${s})`);for(let r=0;r=0&&a>=0&&1!==i&&i!==a)throw new Error(`defaultValue.shape=${n}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-n.length}] = ${i} but ragged tensor input.flatValues.shape[${r-n.length}] = ${a}`)}}const ff=30;function _c(n){return n<=ff?n:vi(n,Math.floor(Math.sqrt(n)))}function mf(n,t,e){return[e*("number"==typeof n?n:n[0]),t*("number"==typeof n?n:n[1])]}function pl(n,t,e,s=!0){let r=[];if(s)r=r.concat(t.slice(0)),r.push(n[0]/e),r=r.concat(n.slice(1));else{r=r.concat(n[0]);const i=t.length;for(let a=0;a=2*t+1||a%2==1?i.push(a):r.push(a);s.push(...r),s.push(0),s.push(...i)}return s}function ml(n,t,e,s=!0){const r=[];r.push(s?n[0]/e:n[0]*e);for(let i=1;ie)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${e}`);if(0===K(n.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${n.shape}.`);const r=t.shape,i=r[r.length-1];let a=1;for(let h=0;hh/u),1].slice(0,i);return[l,a,u,c]}function Uy(n,t,e){const s=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,i=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${e.shape}, indices.shape: ${t.shape}, shape: ${n}, sliceDim: ${s}, and batchDim: ${r}.`;if(e.rank1?t.shape[s-1]:1,i=e.length;let a=1;for(let h=r;h/g,qy=",",Zy="...";function Ef(n,t){const e=((n=n.replace(/\s/g,"")).length-n.replace(DN,"").length)/If.length;if(e<1)throw new Error("Equations without an arrow are not supported.");if(e>1)throw new Error(`Equation must contain exactly one arrow ("${If}").`);const[s,r]=n.split(If);T(-1===s.indexOf(Zy),()=>`The ellipsis notation ("${Zy}") is not supported yet.`);const i=s.split(qy),a=i.length;if(t!==a)throw new Error(`Expected ${a} input tensors, received ${t}`);if(a>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const o=[];for(let d=0;d-1!==f.indexOf(p)))throw new Error(`Output subscripts contain the label ${p} not present in the input subscripts.`);-1===o.indexOf(p)&&o.push(p)}for(let d=0;d-1!==r),{permutationIndices:e,expandDims:s}}function Nf(n,t,e){const s=new Array(n);for(let r=0;r`Expected dimension ${s[t[r][a]]} at axis ${a} of input shaped ${JSON.stringify(i)}, but got dimension ${i[a]}`)}}function Af(n,t){const e=n,s=[];let r=0;0===n.length&&e.push(-1),r=n.length+1;for(let a=0;at===e)}function ON(n,t){const e=[];for(let s=0;s"Number of splits must evenly divide the axis."),s=new Array(t).fill(n.shape[e]/t);else{T(t.reduce((a,o)=>(-1===o&&(a+=1),a),0)<=1,()=>"There should be only one negative value in split array.");const i=t.indexOf(-1);if(-1!==i){const a=t.reduce((o,l)=>l>0?o+l:o);t[i]=n.shape[e]-a}T(n.shape[e]===t.reduce((a,o)=>a+o),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}function Yy(n){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${n}`}function Qy(n,t){return`indices(${n}, 0) is invalid: ${t} < 0`}function Jy(n,t,e){return`indices(${n}, 0) is invalid: ${t} >= ${e}`}function eb(n,t){return`only one output dimension may be -1, not both ${n} and ${t}`}function tb(n,t){return`size ${n} must be non-negative, not ${t}`}function nb(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function sb(n,t){return`Input to reshape is a SparseTensor with ${K(n)}\n dense values, but the requested shape requires a multiple of ${K(t)}. inputShape=${n} outputShape= ${t}`}function rb(n,t){return`Input to reshape is a tensor with ${K(n)} dense values, but the requested shape has ${K(t)}. inputShape=${n} outputShape=${t}`}function Df(){return"segment ids must be >= 0"}function ib(){return"segment ids are not increasing"}function ab(n,t){return`Segment id ${n} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function ob(n,t,e){return`Bad: indices[${n}] == ${t} out of range [0, ${e})`}function lb(n,t){let s,e=!1;for(n<=ff?(s=n,e=!0):s=vi(n,Math.floor(Math.sqrt(n)));!e;)s>t||s===n?e=!0:s=vi(n,s+1);return s}function ub(n,t,e){const s=[],r=n.length;for(let i=0;ir))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>i)throw new Error(`batchDims (${s}) must be less than rank(x) (\n ${i}).`);if(eWr(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function cb(n){return n.map(t=>Ur(t))}function hb(n,t){const e=[];for(let i=0;i{const[e]=t;return{x:()=>L(n,hl(ke(e,"float32"),-1))}}},PN={kernelName:jn,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=Kt(ke(e,"float32")),r=zn(ze(ut(1),s));return Jt(je(n,r))}}}},FN={kernelName:ps,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=zn(ze(Kt(ke(e,"float32")),1));return je(n,s)}}}},LN={kernelName:oa,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,r=ht(e.shape,s.shape);return{a:()=>{let o=n;const l=bn(e.shape,r);return l.length>0&&(o=Ge(o,l)),j(o,e.shape)},b:()=>{let o=n;const l=bn(s.shape,r);return l.length>0&&(o=Ge(o,l)),j(o,s.shape)}}}},MN={kernelName:ed,saveAllInputs:!0,gradFunc:(n,t)=>{const e={};return t.forEach((s,r)=>{e[r]=()=>n.clone()}),e}},VN={kernelName:Kl,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>Et(e)}}},zN={kernelName:ql,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>Et(e)}}},BN={kernelName:Qa,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>je(n,zn(ze(ut(1),Kt(ke(e,"float32")))))}}},UN={kernelName:Ja,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=zn(me(ut(1),Kt(ke(e,"float32"))));return je(n,s)}}}},WN={kernelName:no,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,r=ht(e.shape,s.shape);return{a:()=>{const o=me(Kt(e),Kt(s));let l=L(n,je(s,o));const u=bn(e.shape,r);return u.length>0&&(l=Ge(l,u)),j(l,e.shape)},b:()=>{const o=me(Kt(e),Kt(s));let l=Jt(L(n,je(e,o)));const u=bn(s.shape,r);return u.length>0&&(l=Ge(l,u)),j(l,s.shape)}}}},GN={kernelName:eo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>je(n,me(Kt(ke(e,"float32")),1))}}},HN={kernelName:to,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>je(n,ze(ut(1),Kt(ke(e,"float32"))))}}},XN=U({avgPool3dGrad_:function jN(n,t,e,s,r,i){const a=$(n,"dy","avgPool3dGrad"),o=$(t,"input","avgPool3dGrad");let l=a,u=o,c=!1;4===o.rank&&(c=!0,l=j(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),u=j(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),T(5===l.rank,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),T(5===u.rank,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),qn("avgPool3dGrad",r,i);const p=V.runKernel(rd,{dy:l,input:u},{filterSize:e,strides:s,pad:r,dimRoundingMode:i});return c?j(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),KN={kernelName:Yl,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:o}=e;return{x:()=>XN(n,s,r,i,a,o)}}},ZN=U({avgPoolGrad_:function qN(n,t,e,s,r){const i=$(n,"dy","avgPoolGrad"),a=$(t,"input","avgPoolGrad");T(a.rank===i.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${i.rank})`);let o=a,l=i,u=!1;3===a.rank&&(u=!0,o=j(a,[1,a.shape[0],a.shape[1],a.shape[2]]),l=j(i,[1,i.shape[0],i.shape[1],i.shape[2]])),T(4===l.rank,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),T(4===o.rank,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);const d=V.runKernel(sd,{dy:l,input:o},{filterSize:e,strides:s,pad:r});return u?j(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),YN={kernelName:Zl,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{filterSize:r,strides:i,pad:a}=e;return{x:()=>ZN(n,s,r,i,a)}}},QN={kernelName:Ql,inputsToSave:["a","b"],gradFunc:(n,t,e)=>{const[s,r]=t,{transposeA:i,transposeB:a}=e;return i||a?!i&&a?{a:()=>Dt(n,r,!1,!1),b:()=>Dt(n,s,!0,!1)}:i&&!a?{a:()=>Dt(r,n,!1,!0),b:()=>Dt(s,n,!1,!1)}:{a:()=>Dt(r,n,!0,!0),b:()=>Dt(n,s,!0,!0)}:{a:()=>Dt(n,r,!1,!0),b:()=>Dt(s,n,!0,!1)}}},Pf=U({spaceToBatchND_:function JN(n,t,e){const s=$(n,"x","spaceToBatchND");return T(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),T(e.length===t.length,()=>`paddings.shape[0] ${e.length} must be equal to [blockShape] ${t.length}`),T(s.shape.reduce((a,o,l)=>l>0&&l<=t.length?a&&(o+e[l-1][0]+e[l-1][1])%t[l-1]==0:a,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${e.toString()} must be divisible by blockShapes ${t.toString()}`),V.runKernel(Bu,{x:s},{blockShape:t,paddings:e})}}),e2={kernelName:Jl,gradFunc:(n,t,e)=>{const{blockShape:s,crops:r}=e;return{x:()=>Pf(n,s,r)}}},t2={kernelName:"BroadcastTo",gradFunc:(n,t,e)=>{const r=e.inputShape,i=e.shape,a=Array.from(i);for(let l=r.length-1;l>=0;l--)if(r[l]===i[l])a[l]=1;else if(1!==r[l])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${i}].`);const o=[];for(let l=0;l1&&o.push(l);return{x:()=>Ge(n,o,!0)}}},n2={kernelName:so,gradFunc:n=>({x:()=>n.clone()})},s2={kernelName:ro,gradFunc:n=>({x:()=>Et(n)})},r2={kernelName:ao,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{clipValueMin:r,clipValueMax:i}=e;return{x:()=>Yn(Cr(Pi(s,r),wa(s,i)),n,Et(n))}}},i2={kernelName:eu,inputsToSave:["x"],gradFunc:db.gradFunc},a2={kernelName:tu,saveAllInputs:!0,gradFunc:(n,t,e)=>{const s=t.map(l=>l.shape),{axis:r}=e,i=pt(r,t[0].shape)[0],a=s.map(l=>l[i]);return bs(n,a,i).map(l=>()=>l)}},o2={kernelName:nu,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const[s,r]=t,{dilations:i,strides:a,pad:o,dataFormat:l}=e;return T(Zr(i),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`),{x:()=>zp(s.shape,n,r,a,o,l),filter:()=>rf(s,n,r.shape,a,o,l)}}},l2={kernelName:su,inputsToSave:["dy","filter"],gradFunc:(n,t,e)=>{const[s,r]=t,{strides:i,pad:a,dataFormat:o,dimRoundingMode:l}=e;return{dy:()=>Oi(n,r,i,a,o,1,l),filter:()=>rf(n,s,r.shape,i,a,o,l)}}},c2=U({conv3DBackpropFilter_:function u2(n,t,e,s,r){let i=n;4===n.rank&&(i=j(n,[1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));let a=t;return 4===a.rank&&(a=j(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),T(5===i.rank,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${i.shape}.`),T(5===a.rank,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),T(5===e.length,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${e}.`),T(i.shape[4]===e[3],()=>`Error in conv3dDerFilter: depth of input ${i.shape[4]}) must match input depth in filter (${e[3]}.`),T(a.shape[4]===e[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${e[4]}).`),V.runKernel(ud,{x:i,dy:a},{strides:s,pad:r,filterShape:e})}}),h2={kernelName:ru,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const{dilations:s,strides:r,pad:i}=e;T(Zr(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const[a,o]=t;return{x:()=>hy(a.shape,n,o,r,i),filter:()=>c2(a,n,o.shape,r,i)}}},pb=U({sin_:function d2(n){const e={x:$(n,"x","sin","float32")};return V.runKernel(Po,e)}}),p2={kernelName:oo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(Jt(pb(ke(e,"float32"))),n)}}},fb=U({sinh_:function f2(n){const e={x:$(n,"x","sinh")};return V.runKernel(Fo,e)}}),m2={kernelName:lo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(fb(ke(e,"float32")),n)}}},mb=U({cumsum_:function g2(n,t=0,e=!1,s=!1){const i={x:$(n,"x","cumsum")};return V.runKernel(iu,i,{axis:t,exclusive:e,reverse:s})}}),x2={kernelName:iu,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:r,exclusive:i,reverse:a}=e;return{x:()=>{const o=rn([r],s.rank);let l=mb(n,r,i,!a);return null!=o&&(l=kt(l,o)),l}}}},y2={kernelName:au,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const{dilations:s,strides:r,pad:i,dimRoundingMode:a}=e,o=s??[1,1];T(Zr(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);const[l,u]=t;return T(4===l.rank,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),T(4===u.rank,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),T(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),T(Pn(r,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`),qn("depthwiseConv2d",i,a),{x:()=>Cy(l.shape,n,u,r,i,o,a),filter:()=>Sy(l,n,u.shape,r,i,o,a)}}},b2={kernelName:ou,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const[s,r]=t,i={x:s,filter:r,dy:n},a={x:s,filter:r,dy:n};return{x:()=>V.runKernel(xd,i,e),filter:()=>V.runKernel(yd,a,e)}}},v2={kernelName:co,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t,s={dy:n,y:e};return{x:()=>V.runKernel(wd,s)}}},w2={kernelName:ho,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t,s=L(xs(Jt(Kt(e))),2/Math.sqrt(Math.PI));return{x:()=>L(n,s)}}},_2={kernelName:po,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(n,e)}}},T2={kernelName:uu,inputsToSave:["input"],gradFunc:(n,t)=>{const[e]=t;return{input:()=>j(n,e.shape)}}},S2={kernelName:fo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(n,xs(e))}}},C2={kernelName:mo,gradFunc:n=>({x:()=>Et(n)})},I2={kernelName:go,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,r=ht(e.shape,s.shape);return{a:()=>{const o=je(n,ke(s,"float32")),l=bn(e.shape,r);return l.length>0?j(Ge(o,l),e.shape):o},b:()=>{let o=L(n,ke(e,"float32"));const l=bn(s.shape,r);l.length>0&&(o=j(Ge(o,l),s.shape));const u=Kt(s);return Jt(je(o,ke(u,"float32")))}}}},gb=U({rsqrt_:function E2(n){const e={x:$(n,"x","rsqrt","float32")};return V.runKernel(Do,e)}}),k2={kernelName:cu,inputsToSave:["x","mean","variance","scale"],gradFunc:(n,t,e)=>{const{varianceEpsilon:s}=e,[r,i,a,o]=t,l=o??ut(1),u=bn(i.shape,r.shape),c=[];if(1===i.rank){for(let v=0;vj(L(L(n,1===i.rank?Us(j(p,[1,1,1,i.shape[0]]),c):p),l),r.shape),mean:()=>{let v=L(L(p,ut(-1)),d);return 1===i.rank&&(v=Ge(v,u)),j(v,i.shape)},variance:()=>{let v=L(L(f,h),d);return 1===i.rank&&(v=Ge(v,u)),j(v,i.shape)},scale:()=>{const v=L(h,p);let w=L(n,v);return 1===i.rank&&(w=Ge(w,u)),j(w,i.shape)},offset:()=>{let v=n;return 1===i.rank&&(v=Ge(v,u)),j(v,i.shape)}}}},xb=U({unsortedSegmentSum_:function N2(n,t,e){const s=$(n,"x","unsortedSegmentSum"),r=$(t,"segmentIds","unsortedSegmentSum","int32");return T(St(e),()=>"numSegments must be of dtype int"),V.runKernel(ju,{x:s,segmentIds:r},{numSegments:e})}}),A2={kernelName:hu,inputsToSave:["x","indices"],gradFunc:(n,t,e)=>{const[s,r]=t,{axis:i,batchDims:a}=e,o=pt(i,s.shape)[0],l=(u,c,h)=>()=>{const d=u.shape,p=c.size,f=d.slice(0,o),g=f.length,m=d.slice(i,d.length).slice(1),x=m.length,y=yb(0,g),b=yb(g+1,g+1+x),v=bb([f,[p],m]),w=j(h,v),S=j(c,[p]),I=bb([[g],y,b]),k=kt(w,I);let D=xb(k,S,u.shape[o]);const P=Yr(I);return D=kt(D,P),D};if(1===a){const c=s.split(s.shape[0],0);return{x:()=>ir(c.map((p,f)=>l(p,r.slice(f,1),n.slice(f,1))())).reshape(s.shape),indices:()=>r}}return{x:l(s,r,n),indices:()=>r}}};function yb(n,t){const e=[];for(let s=n;s{const[e,s]=t;return{a:()=>Et(e),b:()=>Et(s)}}},$2={kernelName:yo,gradFunc:n=>({x:()=>ke(n,"float32")})},D2={kernelName:bo,gradFunc:n=>({x:()=>Et(n)})},O2={kernelName:vo,gradFunc:n=>({x:()=>Et(n)})},P2={kernelName:wo,gradFunc:n=>({x:()=>Et(n)})},F2={kernelName:pu,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{alpha:r}=e,i=ys(s,0);return{x:()=>Yn(i,n,L(n,r))}}},L2={kernelName:To,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>je(n,me(e,1))}}},M2={kernelName:_o,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>je(n,ke(e,"float32"))}}},V2={kernelName:"LogSoftmax",inputsToSave:[],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s]=t,{axis:r}=e;return{logits:()=>{const a=xs(s);return ze(n,L(Ge(n,r,!0),a))}}}},B2=U({localResponseNormalizationBackprop_:function z2(n,t,e,s=5,r=1,i=1,a=.5){return V.runKernel(Ed,{x:n,y:t,dy:e},{depthRadius:s,bias:r,alpha:i,beta:a})}}),U2={kernelName:bu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,r]=t,{depthRadius:i,bias:a,alpha:o,beta:l}=e;return{x:()=>B2(s,r,n,i,a,o,l)}}};function vb(n,t,e,s){return t.rankL(n,ke(rr(e,t),n.dtype))}}const wb={kernelName:vu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const s=e,{reductionIndices:r}=s,i=t[0],l=vb(n,t[1],i,pt(r,i.shape));return{x:()=>l.x()}}},W2={kernelName:So,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t;return{a:()=>L(n,ke(Pi(e,s),"float32")),b:()=>L(n,ke(vc(e,s),"float32"))}}},H2=U({maxPool3dGrad_:function G2(n,t,e,s,r,i,a){const o=$(n,"dy","maxPool3dGrad"),l=$(t,"input","maxPool3dGrad"),u=$(e,"output","maxPool3dGrad");let c=o,h=l,d=u,p=!1;4===l.rank&&(p=!0,c=j(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=j(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=j(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),T(5===c.rank,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),T(5===h.rank,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`),T(5===d.rank,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),qn("maxPool3dGrad",i,a);const m=V.runKernel(Nd,{dy:c,input:h,output:d},{filterSize:s,strides:r,pad:i,dimRoundingMode:a});return p?j(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}}),j2={kernelName:_u,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,r]=t,{filterSize:i,strides:a,pad:o,dimRoundingMode:l}=e;return{x:()=>H2(n,s,r,i,a,o,l)}}},K2=U({maxPoolGrad_:function X2(n,t,e,s,r,i,a){const o=$(n,"dy","maxPoolGrad"),l=$(t,"input","maxPoolGrad"),u=$(e,"output","maxPoolGrad");return T(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),T(4===o.rank,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),T(4===l.rank,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),qn("maxPoolGrad",i,a),V.runKernel(kd,{dy:o,input:l,output:u},{filterSize:s,strides:r,pad:i,dimRoundingMode:a})}}),q2={kernelName:wu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,r]=t,{filterSize:i,strides:a,pad:o}=e;return{x:()=>K2(n,s,r,i,a,o)}}},Z2={kernelName:Tu,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:r}=e,i=pt(r,s.shape),l=K(An(s.shape,i)[1]);return{x:()=>{const c=s.shape.slice();i.forEach(p=>{c[p]=1});const h=j(n,c);return je(L(h,Ir(s.shape,"float32")),l)}}}},Y2={kernelName:Su,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const s=e,{axis:r}=s,[i,a]=t,l=vb(n,a,i,pt(r,i.shape));return{x:()=>l.x()}}},Q2={kernelName:Co,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t;return{a:()=>L(n,ke(wa(e,s),"float32")),b:()=>L(n,ke(ys(e,s),"float32"))}}},J2={kernelName:Cu,inputsToSave:["x"],gradFunc:(n,t,e)=>{const s=t[0],{paddings:r}=e,i=r.map(a=>a[0]);return{x:()=>Bt(n,i,s.shape)}}},eA={kernelName:Io,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,r=ht(e.shape,s.shape);return{a:()=>{const o=bn(e.shape,r);return o.length>0?j(Ge(n,o),e.shape):n},b:()=>{const o=L(n,Jt(cc(je(e,s)))),l=bn(s.shape,r);return l.length>0?j(Ge(o,l),s.shape):o}}}},tA={kernelName:Eo,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,r=ht(e.shape,s.shape);return{a:()=>{const o=L(n,ke(s,"float32")),l=bn(e.shape,r);return l.length>0?j(Ge(o,l),e.shape):o},b:()=>{const o=L(n,ke(e,"float32")),l=bn(s.shape,r);return l.length>0?j(Ge(o,l),s.shape):o}}}},nA={kernelName:Iu,gradFunc:n=>({x:()=>Jt(n)})},sA={kernelName:Nu,inputsToSave:["indices"],gradFunc:(n,t)=>{const e=t[0];return{indices:()=>Rn(e.shape,"float32")}}},rA={kernelName:ku,gradFunc:n=>({x:()=>Et(n)})},iA={kernelName:Au,saveAllInputs:!0,gradFunc:(n,t,e)=>{const{axis:s}=e;return Li(n,s).map(i=>()=>i)}},_b={kernelName:Ru,inputsToSave:["x"],gradFunc:(n,t,e)=>{const s=t[0],{paddings:r}=e,i=r.map(a=>a[0]);return{x:()=>Bt(n,i,s.shape)}}},aA={kernelName:ko,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(n,t)=>{const[e,s,r]=t,i=e,a=s,o=ht(i.shape,a.shape);return{a:()=>{const c=ke(a,"float32");let h=L(n,L(c,Ri(i,ze(c,ut(1)))));const d=bn(i.shape,o);return d.length>0&&(h=Ge(h,d)),j(h,i.shape)},b:()=>{const c=ys(i,0),h=Yn(c,Ns(i),Et(i));let d=L(n,L(r,h));const p=bn(a.shape,o);return p.length>0&&(d=Ge(d,p)),j(d,a.shape)}}}},oA={kernelName:$u,inputsToSave:["x","alpha"],gradFunc:(n,t)=>{const[e,s]=t,r=ys(e,0);return{x:()=>Yn(r,n,L(n,s)),alpha:()=>{let i=Yn(r,Et(n),L(n,e));const a=bn(s.shape,n.shape);return a.length>0&&(i=Ge(i,a)),j(i,s.shape)}}}},Ff=U({cumprod_:function lA(n,t=0,e=!1,s=!1){const i={x:$(n,"x","cumprod")};return V.runKernel(hd,i,{axis:t,exclusive:e,reverse:s})}});const hA={kernelName:Du,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:r}=e;let i=[];return i=null==r?s.shape.map((a,o)=>o):"number"==typeof r?[r]:r,{x:()=>function cA(n,t,e){const s=n.shape.length,r=s-e.length,i=rn(e,s);let a=n;null!=i&&(a=kt(n,i));const o=a.shape.slice(),u=o.splice(s-e.length,e.length).reduce((d,p)=>d*p,1);o.push(u);let h=function uA(n,t,e){const s=n.shape.slice();s[e]=1;const r=j(t,s),i=Ff(n,e,!0,!1),a=Ff(n,e,!0,!0),o=L(i,a);return L(r,o)}(a.reshape(o),t,r);if(h=h.reshape(a.shape),null!=i){const d=Yr(i);h=kt(h,d)}return h}(s,n,i)}}},dA={kernelName:uo,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,r=ht(e.shape,s.shape);return{a:()=>{const o=je(n,ke(s,"float32")),l=bn(e.shape,r);return l.length>0?j(Ge(o,l),e.shape):o},b:()=>{let o=L(n,ke(e,"float32"));const l=bn(s.shape,r);l.length>0&&(o=j(Ge(o,l),s.shape));const u=Kt(s);return Jt(je(o,ke(u,"float32")))}}}},pA={kernelName:No,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>je(n,Jt(Kt(e)))}}},fA={kernelName:Ro,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t,s=L(wa(e,6),hl(e));return{x:()=>L(n,ke(s,"float32"))}}},mA={kernelName:Ao,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(n,ke(hl(e),"float32"))}}},gA={kernelName:Ou,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>j(n,e.shape)}}},xA={kernelName:Fu,inputsToSave:["images"],gradFunc:(n,t,e)=>{const[s]=t,r={dy:n,images:s};return{images:()=>V.runKernel(Fd,r,e)}}},yA={kernelName:Pu,inputsToSave:["images"],gradFunc:(n,t,e)=>{const[s]=t,r={dy:n,images:s};return{images:()=>V.runKernel(Pd,r,e)}}},bA={kernelName:Lu,gradFunc:(n,t,e)=>{const{dims:s}=e,r=pt(s,n.shape);return{x:()=>Fi(n,r)}}},vA={kernelName:$o,gradFunc:n=>({x:()=>Et(n)})},wA={kernelName:Do,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>Jt(je(n,L(Ri(e,1.5),2)))}}},Lf=U({logicalNot_:function _A(n){const e={x:$(n,"x","logicalNot","bool")};return V.runKernel(xu,e)}}),TA={kernelName:Mu,inputsToSave:["condition"],gradFunc:(n,t)=>{const[e]=t;return{condition:()=>ke(Et(e),"float32"),t:()=>L(n,ke(e,n.dtype)),e:()=>L(n,ke(Lf(e),n.dtype))}}},SA={kernelName:Oo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=ys(e,ut(0)),r=ut(Tc),i=ut(Sc),a=L(n,i),o=L(L(n,r),xs(ke(e,"float32")));return Yn(s,a,o)}}}},CA={kernelName:Mo,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(n,L(e,ze(ut(1),e)))}}},IA={kernelName:Lo,gradFunc:n=>({x:()=>Et(n)})},Mf=U({cos_:function EA(n){const e={x:$(n,"x","cos","float32")};return V.runKernel(oo,e)}}),kA={kernelName:Po,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(Mf(ke(e,"float32")),n)}}},Tb=U({cosh_:function NA(n){const e={x:$(n,"x","cosh","float32")};return V.runKernel(lo,e)}}),AA={kernelName:Fo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(Tb(ke(e,"float32")),n)}}},RA={kernelName:Vu,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{begin:r,size:i}=e,a=s.shape,[o,l]=ac(s,r,i),u=[];for(let c=0;cKp(n,u)}}},$A={kernelName:Wu,outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s]=t,{dim:r}=e,a=L(n,s);return{logits:()=>ze(a,L(Ge(a,[r],!0),s))}}},DA={kernelName:Vo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(n,ba(e))}}},Vf=U({batchToSpaceND_:function OA(n,t,e){const s=$(n,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);return T(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),T(e.length===t.length,()=>`crops.length is ${e.length} but should be equal to blockShape.length ${t.length}`),T(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`),V.runKernel(Jl,{x:s},{blockShape:t,crops:e})}}),Sb={kernelName:Bu,gradFunc:(n,t,e)=>{const{blockShape:s,paddings:r}=e;return{x:()=>Vf(n,s,r)}}},Cb={kernelName:Uu,gradFunc:(n,t,e)=>{const{axis:s}=e;return{x:()=>Bn(n,s)}}},qA=[db,PN,FN,LN,MN,VN,zN,BN,UN,WN,GN,HN,KN,YN,QN,e2,t2,n2,s2,r2,i2,a2,l2,o2,h2,p2,m2,x2,y2,b2,dA,v2,w2,_2,T2,S2,I2,C2,k2,A2,R2,$2,D2,O2,P2,F2,L2,M2,V2,U2,wb,wb,W2,j2,q2,Z2,Y2,Q2,J2,eA,tA,nA,sA,rA,iA,_b,_b,aA,oA,hA,pA,fA,mA,gA,xA,yA,bA,vA,wA,TA,SA,CA,IA,kA,AA,RA,$A,DA,Sb,Sb,Cb,Cb,{kernelName:zo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>je(n,L(zn(ke(e,"float32")),2))}}},{kernelName:Bo,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,r=ut(2);return{a:()=>L(n,L(r,ze(e,s))),b:()=>L(n,L(r,ze(s,e)))}}},{kernelName:Bd,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(n,L(ke(e,"float32"),2))}}},{kernelName:jo,gradFunc:n=>({x:()=>Et(n)})},{kernelName:Uo,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,r=ht(e.shape,s.shape);return{a:()=>{let o=n;const l=bn(e.shape,r);return l.length>0&&(o=Ge(o,l)),j(o,e.shape)},b:()=>{let o=n;const l=bn(s.shape,r);return l.length>0&&(o=Ge(o,l)),j(Jt(o),s.shape)}}}},{kernelName:zu,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,r=s.shape.slice(),{axis:i}=e;pt(i,s.shape).forEach(u=>{r[u]=1});const o=j(n,r),l=L(o,Ir(s.shape,"float32"));return{x:()=>l}}},{kernelName:Wo,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>je(n,Kt(Mf(e)))}}},{kernelName:Go,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>L(ze(ut(1),Kt(e)),n)}}},{kernelName:Ho,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{reps:r}=e;return{x:()=>{let a=Et(s);if(1===s.rank)for(let o=0;o{const s=e,{perm:r}=s,i=Yr(r);return{x:()=>kt(n,i)}}},{kernelName:Hu,gradFunc:(n,t,e)=>{const s=e,{axis:r}=s;return{value:()=>ir(n,r)}}},{kernelName:ju,inputsToSave:["segmentIds"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>function XA(n,t){const e=Kr(t,Et(t)),s=Bp(n,e);let r=Pi(t,ut(0,"int32"));const i=s.rank-r.rank;for(let o=0;o({x:()=>Et(n)})}];for(const n of qA)U1(n);ne().prototype.abs=function(){return this.throwIfDisposed(),kn(this)};const YA=U({acos_:function ZA(n){const e={x:$(n,"x","acos")};return V.runKernel(jn,e)}});ne().prototype.acos=function(){return this.throwIfDisposed(),YA(this)};const JA=U({acosh_:function QA(n){const e={x:$(n,"x","acosh")};return V.runKernel(ps,e)}});ne().prototype.acosh=function(){return this.throwIfDisposed(),JA(this)},ne().prototype.add=function(n){return this.throwIfDisposed(),me(this,n)},ne().prototype.all=function(n,t){return this.throwIfDisposed(),ly(this,n,t)},ne().prototype.any=function(n,t){return this.throwIfDisposed(),Fp(this,n,t)},ne().prototype.argMax=function(n){return this.throwIfDisposed(),el(this,n)};const tR=U({argMin_:function eR(n,t=0){const s={x:$(n,"x","argMin")};return V.runKernel(ql,s,{axis:t})}});ne().prototype.argMin=function(n){return this.throwIfDisposed(),tR(this,n)},ne().prototype.asScalar=function(){return this.throwIfDisposed(),T(1===this.size,()=>"The array must have only 1 element."),j(this,[])},ne().prototype.asType=function(n){return this.throwIfDisposed(),ke(this,n)},ne().prototype.as1D=function(){return this.throwIfDisposed(),j(this,[this.size])},ne().prototype.as2D=function(n,t){return this.throwIfDisposed(),j(this,[n,t])},ne().prototype.as3D=function(n,t,e){return this.throwIfDisposed(),j(this,[n,t,e])},ne().prototype.as4D=function(n,t,e,s){return this.throwIfDisposed(),j(this,[n,t,e,s])},ne().prototype.as5D=function(n,t,e,s,r){return this.throwIfDisposed(),j(this,[n,t,e,s,r])};const sR=U({asin_:function nR(n){const e={x:$(n,"x","asin")};return V.runKernel(Qa,e)}});ne().prototype.asin=function(){return this.throwIfDisposed(),sR(this)};const iR=U({asinh_:function rR(n){const e={x:$(n,"x","asinh")};return V.runKernel(Ja,e)}});ne().prototype.asinh=function(){return this.throwIfDisposed(),iR(this)};const oR=U({atan_:function aR(n){const e={x:$(n,"x","atan")};return V.runKernel(eo,e)}});ne().prototype.atan=function(){return this.throwIfDisposed(),oR(this)};const uR=U({atan2_:function lR(n,t){let e=$(n,"a","atan2"),s=$(t,"b","atan2");return[e,s]=un(e,s),V.runKernel(no,{a:e,b:s})}});ne().prototype.atan2=function(n){return this.throwIfDisposed(),uR(this,n)};const hR=U({atanh_:function cR(n){const e={x:$(n,"x","atanh")};return V.runKernel(to,e)}});ne().prototype.atanh=function(){return this.throwIfDisposed(),hR(this)},ne().prototype.avgPool=function(n,t,e,s){return this.throwIfDisposed(),Vp(this,n,t,e,s)},ne().prototype.batchToSpaceND=function(n,t){return this.throwIfDisposed(),Vf(this,n,t)},ne().prototype.batchNorm=function(n,t,e,s,r){return this.throwIfDisposed(),oc(this,n,t,e,s,r)},ne().prototype.broadcastTo=function(n){return this.throwIfDisposed(),rl(this,n)},ne().prototype.cast=function(n){return this.throwIfDisposed(),ke(this,n)};const pR=U({ceil_:function dR(n){const e={x:$(n,"x","ceil","float32")};return V.runKernel(ro,e)}});ne().prototype.ceil=function(){return this.throwIfDisposed(),pR(this)},ne().prototype.clipByValue=function(n,t){return this.throwIfDisposed(),gs(this,n,t)},ne().prototype.concat=function(n,t){return this.throwIfDisposed(),n instanceof Qt&&(n=[n]),Bn([this,...n],t)},ne().prototype.conv1d=function(n,t,e,s,r,i){return this.throwIfDisposed(),uy(this,n,t,e,s,r,i)},ne().prototype.conv2dTranspose=function(n,t,e,s,r){return this.throwIfDisposed(),cy(this,n,t,e,s,r)},ne().prototype.conv2d=function(n,t,e,s,r,i){return this.throwIfDisposed(),Oi(this,n,t,e,s,r,i)},ne().prototype.cos=function(){return this.throwIfDisposed(),Mf(this)},ne().prototype.cosh=function(){return this.throwIfDisposed(),Tb(this)},ne().prototype.cumprod=function(n,t,e){return this.throwIfDisposed(),Ff(this,n,t,e)},ne().prototype.cumsum=function(n,t,e){return this.throwIfDisposed(),mb(this,n,t,e)};const mR=U({depthToSpace_:function fR(n,t,e="NHWC"){const s=$(n,"x","depthToSpace","float32"),r="NHWC"===e?s.shape[1]:s.shape[2],i="NHWC"===e?s.shape[2]:s.shape[3],a="NHWC"===e?s.shape[3]:s.shape[1];return T(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),T(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${r} and ${t} for depthToSpace with input shape\n ${s.shape}`),T(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${i} and ${t} for depthToSpace with input shape\n ${s.shape}`),T(a%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${s.shape}`),V.runKernel(fd,{x:s},{blockSize:t,dataFormat:e})}});ne().prototype.depthToSpace=function(n,t){return this.throwIfDisposed(),mR(this,n,t)},ne().prototype.depthwiseConv2d=function(n,t,e,s,r,i){return this.throwIfDisposed(),lc(this,n,t,e,s,r,i)};const xR=U({dilation2d_:function gR(n,t,e,s,r=[1,1],i="NHWC"){const a=$(n,"x","dilation2d"),o=$(t,"filter","dilation2d");T(3===a.rank||4===a.rank,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),T(3===o.rank,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),T("NHWC"===i,()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${i}`);let l=a,u=!1;3===a.rank&&(l=j(a,[1,a.shape[0],a.shape[1],a.shape[2]]),u=!0),T(l.shape[3]===o.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${o.shape[2]}`);const d=V.runKernel(ou,{x:l,filter:o},{strides:e,pad:s,dilations:r});return u?j(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});ne().prototype.dilation2d=function(n,t,e,s,r){return this.throwIfDisposed(),xR(this,n,t,e,s,r)};const bR=U({divNoNan_:function yR(n,t){let e=$(n,"a","div"),s=$(t,"b","div");[e,s]=un(e,s);const r=je(e,s),i=Et(r),a=rr(s,i);return Yn(a,i,r)}});ne().prototype.divNoNan=function(n){return this.throwIfDisposed(),bR(this,n)},ne().prototype.div=function(n){return this.throwIfDisposed(),je(this,n)};const wR=U({dot_:function vR(n,t){const e=$(n,"t1","dot"),s=$(t,"t2","dot");T(!(1!==e.rank&&2!==e.rank||1!==s.rank&&2!==s.rank),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${e.rank} and ${s.rank}.`);const r=1===e.rank?e.size:e.shape[1],i=1===s.rank?s.size:s.shape[0];if(T(r===i,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${i}.`),1===e.rank&&1===s.rank){const a=j(e,[1,-1]),o=j(s,[-1,1]),l=Dt(a,o);return j(l,[])}if(1===e.rank&&2===s.rank){const a=j(e,[1,-1]),o=j(s,[s.shape[0],s.shape[1]]),l=Dt(a,o);return j(l,[l.size])}if(2===e.rank&&1===s.rank){const a=j(s,[-1,1]),o=Dt(e,a);return j(o,[o.size])}{const a=j(s,[s.shape[0],s.shape[1]]);return Dt(e,a)}}});ne().prototype.dot=function(n){return this.throwIfDisposed(),wR(this,n)},ne().prototype.elu=function(){return this.throwIfDisposed(),uc(this)},ne().prototype.equal=function(n){return this.throwIfDisposed(),rr(this,n)},ne().prototype.erf=function(){return this.throwIfDisposed(),py(this)};const TR=U({euclideanNorm_:function _R(n,t=null,e=!1){return wc(n,"euclidean",t,e)}});ne().prototype.euclideanNorm=function(n,t){return this.throwIfDisposed(),TR(this,n,t)},ne().prototype.exp=function(){return this.throwIfDisposed(),xs(this)},ne().prototype.expandDims=function(n){return this.throwIfDisposed(),Zn(this,n)};const CR=U({expm1_:function SR(n){const e={x:$(n,"x","expm1")};return V.runKernel(fo,e)}});ne().prototype.expm1=function(){return this.throwIfDisposed(),CR(this)},ne().prototype.fft=function(){return this.throwIfDisposed(),nf(this)},ne().prototype.flatten=function(){return this.throwIfDisposed(),j(this,[this.size])},ne().prototype.floor=function(){return this.throwIfDisposed(),cc(this)},ne().prototype.floorDiv=function(n){return this.throwIfDisposed(),Px(this,n)},ne().prototype.gather=function(n,t,e){return this.throwIfDisposed(),Bp(this,n,t,e)},ne().prototype.greaterEqual=function(n){return this.throwIfDisposed(),Pi(this,n)},ne().prototype.greater=function(n){return this.throwIfDisposed(),ys(this,n)},ne().prototype.ifft=function(){return this.throwIfDisposed(),mc(this)},ne().prototype.irfft=function(){return this.throwIfDisposed(),_y(this)};const ER=U({isFinite_:function IR(n){const e={x:$(n,"x","isFinite")};return V.runKernel(bo,e)}});ne().prototype.isFinite=function(){return this.throwIfDisposed(),ER(this)};const NR=U({isInf_:function kR(n){const e={x:$(n,"x","isInf")};return V.runKernel(vo,e)}});ne().prototype.isInf=function(){return this.throwIfDisposed(),NR(this)};const RR=U({isNaN_:function AR(n){const e={x:$(n,"x","isNaN")};return V.runKernel(wo,e)}});ne().prototype.isNaN=function(){return this.throwIfDisposed(),RR(this)},ne().prototype.leakyRelu=function(n){return this.throwIfDisposed(),Up(this,n)},ne().prototype.lessEqual=function(n){return this.throwIfDisposed(),wa(this,n)},ne().prototype.less=function(n){return this.throwIfDisposed(),vc(this,n)};const DR=U({localResponseNormalization_:function $R(n,t=5,e=1,s=1,r=.5){const i=$(n,"x","localResponseNormalization");T(4===i.rank||3===i.rank,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${i.rank}.`),T(St(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let a=i,o=!1;3===i.rank&&(o=!0,a=j(i,[1,i.shape[0],i.shape[1],i.shape[2]]));const c=V.runKernel(bu,{x:a},{depthRadius:t,bias:e,alpha:s,beta:r});return o?j(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});ne().prototype.localResponseNormalization=function(n,t,e,s){return this.throwIfDisposed(),DR(this,n,t,e,s)};const PR=U({logSigmoid_:function OR(n){const t=$(n,"x","logSigmoid");return _r(s=>({value:Jt(ul(Jt(s))),gradFunc:a=>L(a,ba(Jt(s)))}))(t)}});ne().prototype.logSigmoid=function(){return this.throwIfDisposed(),PR(this)},ne().prototype.logSoftmax=function(n){return this.throwIfDisposed(),my(this,n)},ne().prototype.logSumExp=function(n,t){return this.throwIfDisposed(),Hp(this,n,t)},ne().prototype.log=function(){return this.throwIfDisposed(),Ns(this)},ne().prototype.log1p=function(){return this.throwIfDisposed(),Wp(this)},ne().prototype.logicalAnd=function(n){return this.throwIfDisposed(),Cr(this,n)},ne().prototype.logicalNot=function(){return this.throwIfDisposed(),Lf(this)};const Ib=U({logicalOr_:function FR(n,t){const e=$(n,"a","logicalOr","bool"),s=$(t,"b","logicalOr","bool");return ht(e.shape,s.shape),V.runKernel(yu,{a:e,b:s})}});ne().prototype.logicalOr=function(n){return this.throwIfDisposed(),Ib(this,n)};const MR=U({logicalXor_:function LR(n,t){const e=$(n,"a","logicalXor","bool"),s=$(t,"b","logicalXor","bool");return ht(e.shape,s.shape),Cr(Ib(n,t),Lf(Cr(n,t)))}});ne().prototype.logicalXor=function(n){return this.throwIfDisposed(),MR(this,n)},ne().prototype.matMul=function(n,t,e){return this.throwIfDisposed(),Dt(this,n,t,e)},ne().prototype.maxPool=function(n,t,e,s){return this.throwIfDisposed(),jp(this,n,t,e,s)},ne().prototype.max=function(n,t){return this.throwIfDisposed(),Ws(this,n,t)},ne().prototype.maximum=function(n){return this.throwIfDisposed(),Kr(this,n)},ne().prototype.mean=function(n,t){return this.throwIfDisposed(),pn(this,n,t)},ne().prototype.min=function(n,t){return this.throwIfDisposed(),hc(this,n,t)},ne().prototype.minimum=function(n){return this.throwIfDisposed(),ya(this,n)};const zR=U({mirrorPad_:function VR(n,t,e){T("reflect"===e||"symmetric"===e,()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${e}.`);const s=$(n,"x","mirrorPad");if(0===s.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");T(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);const r="reflect"===e?1:0;for(let o=0;o"Invalid number of paddings. Must be length of 2 each."),T(t[o][0]>=0&&t[o][0]<=s.shape[o]-r&&t[o][1]>=0&&t[o][1]<=s.shape[o]-r,()=>`Padding in dimension ${o} cannot be greater than or equal to ${s.shape[o]-r} or less than 0 for input of shape ${s.shape}`);return V.runKernel(Cu,{x:s},{paddings:t,mode:e})}});ne().prototype.mirrorPad=function(n,t){return this.throwIfDisposed(),zR(this,n,t)};const UR=U({mod_:function BR(n,t){let e=$(n,"a","mod"),s=$(t,"b","mod");return[e,s]=un(e,s),V.runKernel(Io,{a:e,b:s})}});ne().prototype.mod=function(n){return this.throwIfDisposed(),UR(this,n)},ne().prototype.mul=function(n){return this.throwIfDisposed(),L(this,n)},ne().prototype.neg=function(){return this.throwIfDisposed(),Jt(this)},ne().prototype.norm=function(n,t,e){return this.throwIfDisposed(),wc(this,n,t,e)},ne().prototype.notEqual=function(n){return this.throwIfDisposed(),il(this,n)},ne().prototype.oneHot=function(n,t=1,e=0){return this.throwIfDisposed(),xy(this,n,t,e)},ne().prototype.onesLike=function(){return this.throwIfDisposed(),As(this)},ne().prototype.pad=function(n,t){return this.throwIfDisposed(),Kp(this,n,t)};const jR=U({pool_:function WR(n,t,e,s,r,i,a){null==r&&(r=[1,1]),null==i&&(i=1),0===s&&(s="valid");const o=$(n,"x","maxPool");let l=o,u=!1;3===o.rank&&(u=!0,l=j(o,[1,o.shape[0],o.shape[1],o.shape[2]])),T(Pn(i,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${i} and dilations '${r}'`);const c=ks(l.shape,t,i,r,s),h=[c.dilationHeight,c.dilationWidth];let d;d="same"===s?function HR(n,t){const s=n.map((a,o)=>a+(a-1)*(t[o]-1)).map(a=>a-1),r=s.map(a=>Math.floor(a/2)),i=s.map((a,o)=>a-r[o]);return s.map((a,o)=>[r[o],i[o]])}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];const p=1===h[0]&&1===h[1],[f,g]=function GR(n,t,e){const s=e.map(c=>c[0]),r=e.map(c=>c[1]),i=n.concat(s,r),a=t.map((c,h)=>(c-i[h]%c)%c),o=r.map((c,h)=>c+a[h]),l=t.map((c,h)=>[s[h],o[h]]),u=t.map((c,h)=>[0,a[h]]);return[l,u]}([c.inHeight,c.inWidth],h,d),m=p?s:"valid",x=p?l:Pf(l,h,f),b=("avg"===e?()=>Vp(x,t,i,m,a):()=>jp(x,t,i,m,a))(),v=p?b:Vf(b,h,g);return u?j(v,[v.shape[1],v.shape[2],v.shape[3]]):v}});ne().prototype.pool=function(n,t,e,s,r,i){return this.throwIfDisposed(),jR(this,n,t,e,s,r,i)},ne().prototype.pow=function(n){return this.throwIfDisposed(),Ri(this,n)},ne().prototype.prelu=function(n){return this.throwIfDisposed(),qp(this,n)};const KR=U({prod_:function XR(n,t=null,e=!1){let s=$(n,"x","prod");return"bool"===s.dtype&&(s=ke(s,"int32")),V.runKernel(Du,{x:s},{axis:t,keepDims:e})}});ne().prototype.prod=function(n,t){return this.throwIfDisposed(),KR(this,n,t)};const ZR=U({reciprocal_:function qR(n){const e={x:$(n,"x","reciprocal")};return V.runKernel(No,e)}});ne().prototype.reciprocal=function(){return this.throwIfDisposed(),ZR(this)},ne().prototype.relu=function(){return this.throwIfDisposed(),Er(this)},ne().prototype.relu6=function(){return this.throwIfDisposed(),Ty(this)},ne().prototype.reshapeAs=function(n){return this.throwIfDisposed(),j(this,n.shape)},ne().prototype.reshape=function(n){return this.throwIfDisposed(),j(this,n)},ne().prototype.resizeBilinear=function(n,t,e){return this.throwIfDisposed(),Ry(this,n,t,e)},ne().prototype.resizeNearestNeighbor=function(n,t,e){return this.throwIfDisposed(),$y(this,n,t,e)},ne().prototype.reverse=function(n){return this.throwIfDisposed(),Fi(this,n)},ne().prototype.rfft=function(){return this.throwIfDisposed(),sf(this)},ne().prototype.round=function(){return this.throwIfDisposed(),Dy(this)},ne().prototype.rsqrt=function(){return this.throwIfDisposed(),gb(this)},ne().prototype.selu=function(){return this.throwIfDisposed(),yy(this)},ne().prototype.separableConv2d=function(n,t,e,s,r,i){return this.throwIfDisposed(),by(this,n,t,e,s,r,i)},ne().prototype.sigmoid=function(){return this.throwIfDisposed(),ba(this)};const QR=U({sign_:function YR(n){const e={x:$(n,"x","sign")};return V.runKernel(Lo,e)}});ne().prototype.sign=function(){return this.throwIfDisposed(),QR(this)},ne().prototype.sin=function(){return this.throwIfDisposed(),pb(this)},ne().prototype.sinh=function(){return this.throwIfDisposed(),fb(this)},ne().prototype.slice=function(n,t){return this.throwIfDisposed(),Bt(this,n,t)},ne().prototype.softmax=function(n){return this.throwIfDisposed(),ef(this,n)},ne().prototype.softplus=function(){return this.throwIfDisposed(),ul(this)},ne().prototype.spaceToBatchND=function(n,t){return this.throwIfDisposed(),Pf(this,n,t)},ne().prototype.split=function(n,t){return this.throwIfDisposed(),bs(this,n,t)},ne().prototype.sqrt=function(){return this.throwIfDisposed(),zn(this)},ne().prototype.square=function(){return this.throwIfDisposed(),Kt(this)},ne().prototype.squaredDifference=function(n){return this.throwIfDisposed(),Fy(this,n)},ne().prototype.squeeze=function(n){return this.throwIfDisposed(),cl(this,n)},ne().prototype.stack=function(n,t){this.throwIfDisposed();const e=n instanceof Qt?[this,n]:[this,...n];return ir(e,t)},ne().prototype.step=function(n){return this.throwIfDisposed(),hl(this,n)};const e$=U({stridedSlice_:function JR(n,t,e,s,r=0,i=0,a=0,o=0,l=0){const c={x:$(n,"x","stridedSlice","string_or_numeric")};return V.runKernel(Ud,c,{begin:t,end:e,strides:s,beginMask:r,endMask:i,ellipsisMask:a,newAxisMask:o,shrinkAxisMask:l})}});ne().prototype.stridedSlice=function(n,t,e,s,r,i,a,o){return this.throwIfDisposed(),e$(this,n,t,e,s,r,i,a,o)},ne().prototype.sub=function(n){return this.throwIfDisposed(),ze(this,n)},ne().prototype.sum=function(n,t){return this.throwIfDisposed(),Ge(this,n,t)};const n$=U({tan_:function t$(n){const e={x:$(n,"x","tan","float32")};return V.runKernel(Wo,e)}});ne().prototype.tan=function(){return this.throwIfDisposed(),n$(this)},ne().prototype.tanh=function(){return this.throwIfDisposed(),pc(this)},ne().prototype.tile=function(n){return this.throwIfDisposed(),Us(this,n)},ne().prototype.toBool=function(){return this.throwIfDisposed(),ke(this,"bool")},ne().prototype.toFloat=function(){return this.throwIfDisposed(),ke(this,"float32")},ne().prototype.toInt=function(){return this.throwIfDisposed(),ke(this,"int32")};const r$=U({topk_:function s$(n,t=1,e=!0){const s=$(n,"x","topk");if(0===s.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);const i={x:s},a={k:t,sorted:e},[o,l]=V.runKernel(jd,i,a);return{values:o,indices:l}}});ne().prototype.topk=function(n,t){return this.throwIfDisposed(),r$(this,n,t)},ne().prototype.transpose=function(n){return this.throwIfDisposed(),kt(this,n)};const a$=U({unique_:function i$(n,t=0){const e=$(n,"x","unique","string_or_numeric");T(e.rank>0,()=>"The input tensor must be at least 1D");const s={x:e},r={axis:t},[i,a]=V.runKernel(Kd,s,r);return{values:i,indices:a}}});ne().prototype.unique=function(n){return this.throwIfDisposed(),a$(this,n)},ne().prototype.unsortedSegmentSum=function(n,t){return this.throwIfDisposed(),xb(this,n,t)},ne().prototype.unstack=function(n){return this.throwIfDisposed(),Li(this,n)},ne().prototype.where=function(n,t){return this.throwIfDisposed(),Yn(n,this,t)},ne().prototype.zerosLike=function(){return this.throwIfDisposed(),Et(this)};class ur extends Error{constructor(t){super(t),Object.setPrototypeOf(this,ur.prototype)}}class Rs extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Rs.prototype)}}class z extends Error{constructor(t){super(t),Object.setPrototypeOf(this,z.prototype)}}class dt extends Error{constructor(t){super(t),Object.setPrototypeOf(this,dt.prototype)}}class zf extends Error{constructor(t){super(t),Object.setPrototypeOf(this,zf.prototype)}}Error;class kb{constructor(t){this.maxEntries=t||100,this.cache=new Map}get(t){let e;return this.cache.has(t)&&(e=this.cache.get(t),this.cache.delete(t),this.cache.set(t,e)),e}put(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxEntries){const s=this.cache.keys().next().value;this.cache.delete(s)}this.cache.set(t,e)}getMaxEntries(){return this.maxEntries}setMaxEntries(t){if(t<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${t}.`);if(this.maxEntries>t)for(let e=0;ee.toUpperCase())}let $s={};function Bf(n){if(null==n)return null;const t={};return t.className=n.getClassName(),t.config=n.getConfig(),t}function Uf(n){if(null!=n&&"object"==typeof n)if(Array.isArray(n))n.forEach(t=>Uf(t));else{const t=Object.keys(n);for(const e of t){const s=n[e];null!=s&&"object"==typeof s&&(Array.isArray(s)||"ndarray"!==s.type||"number"!=typeof s.value?Uf(s):n[e]=s.value)}}}function gl(n,t={},e={},s="object",r=!1){if("string"==typeof n){let a;if(n in e)a=e[n];else if(n in $s)a=$s[n];else if(a=t[n],null==a)throw new z(`Unknown ${s}: ${n}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}{const i=n;if(null==i.className||null==i.config)throw new z(`${s}: Improper config format: ${JSON.stringify(i)}.\n'className' and 'config' must set.`);const a=i.className;let o,l;if(a in e?[o,l]=e[a]:a in $s?[o,l]=$s.className:a in t&&([o,l]=t[a]),null==o)throw new z(`Unknown ${s}: ${a}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=l){const u={};for(const p of Object.keys($s))u[p]=$s[p];for(const p of Object.keys(e))u[p]=e[p];i.config.customObjects=u;const h=Object.assign({},$s);for(const p of Object.keys(e))$s[p]=e[p];Uf(i.config);const d=l(o,i.config,e,r);return $s=Object.assign({},h),d}{const u=Object.assign({},$s);for(const h of Object.keys(e))$s[h]=e[h];const c=new o(i.config);return $s=Object.assign({},u),c}}}function Cc(n,t){return-1*function o$(n,t){return nt?1:0}(n,t)}function Jr(n){if(null==n)return n;const t=[];for(const e of n)-1===t.indexOf(e)&&t.push(e);return t}function l$(n){if(null==n)throw new z(`Invalid value in obj: ${JSON.stringify(n)}`);for(const t in n)if(n.hasOwnProperty(t))return!1;return!0}function Bi(n,t,e){if(null!=e&&n.indexOf(e)<0)throw new z(`${e} is not a valid ${t}. Valid values are ${n} or null/undefined.`)}function Wf(n,t,e=0,s=1/0){return vs(e>=0),vs(s>=e),Array.isArray(n)&&n.length>=e&&n.length<=s&&n.every(r=>typeof r===t)}function $n(n,t){Array.isArray(n)?(T(n.length>0,()=>`${t} is unexpectedly an empty array.`),n.forEach((e,s)=>$n(e,`element ${s+1} of ${t}`))):T(Number.isInteger(n)&&n>0,()=>`Expected ${t} to be a positive integer, but got ${Ab(n)}.`)}function Ab(n){return null===n?"null":Array.isArray(n)?"["+n.map(t=>Ab(t)).join(",")+"]":"string"==typeof n?`"${n}"`:`${n}`}function Rb(n){return"relu"===n?"relu":"linear"===n?"linear":"elu"===n?"elu":null}let c$=0;function $b(){return c$++}const Ic={};function Ec(n=""){return n in Ic||(Ic[n]=0),Ic[n]+=1,n+Ic[n].toString()}const h$=["channelsFirst","channelsLast"],d$=["nearest","bilinear"],p$=["valid","same","causal"],f$=["max","avg"],m$=["sum","mul","concat","ave"],Ta=new Map;function fn(n){Bi(h$,"DataFormat",n)}function ws(n){Bi(p$,"PaddingMode",n)}function Db(n){Bi(f$,"PoolMode",n)}const xl=[];function Ui(n,t){xl.push(n);try{const e=t();return xl.pop(),e}catch(e){throw xl.pop(),e}}function Pb(n){if(!Lb(n))throw new Error("Not a valid tensor name: '"+n+"'");return function x$(){return 0===xl.length?"":xl.join("/")+"/"}()+n}function Fb(n){if(!Lb(n))throw new Error("Not a valid tensor name: '"+n+"'");Ta.has(n)||Ta.set(n,0);const t=Ta.get(n);if(Ta.set(n,Ta.get(n)+1),t>0){const e=`${n}_${t}`;return Ta.set(e,1),e}return n}const y$=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Lb(n){return!!n.match(y$)}function b$(n){return n===parseInt(n.toString(),10)}function ei(n,t,e){null==t&&(t=0),null==e&&(e=n.length);let s=1;for(let r=t;rt&&(t=s)}return t}function Gs(n,t){if(t{switch(n.rank){case 1:return Qp(n,t,e);case 2:return vy(n,[t,0],[e,n.shape[1]]);case 3:return Jp(n,[t,0,0],[e,n.shape[1],n.shape[2]]);case 4:return dc(n,[t,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3]]);case 5:return Bt(n,[t,0,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3],n.shape[4]]);case 6:return Bt(n,[t,0,0,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3],n.shape[4],n.shape[5]]);default:throw new z(`sliceAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Gf(n,t,e){return Z(()=>{switch(n.rank){case 1:return Qp(n,t,e);case 2:return vy(n,[0,t],[n.shape[0],e]);case 3:return Jp(n,[0,0,t],[n.shape[0],n.shape[1],e]);case 4:return dc(n,[0,0,0,t],[n.shape[0],n.shape[1],n.shape[2],e]);default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Nc(n,t,e,s){return Z(()=>{switch(n.rank){case 1:return Qp(n,t,e);case 2:switch(s){case 1:return Wi(n,t,e);case 2:return Gf(n,t,e);default:throw new z(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return Wi(n,t,e);case 2:return Jp(n,[0,t,0],[n.shape[0],e,n.shape[2]]);case 3:return Gf(n,t,e);default:throw new z(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return Wi(n,t,e);case 2:return dc(n,[0,t,0,0],[n.shape[0],e,n.shape[2],n.shape[3]]);case 3:return dc(n,[0,0,t,0],[n.shape[0],n.shape[1],e,n.shape[3]]);case 4:return Gf(n,t,e);default:throw new z(`The axis is not within the rank of the tensor ${s}`)}default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Hf(n,t=-1){let e;return t<0&&(e=n[0].rank,t=0!==e?e:0),t===n[0].rank&&(t=-1),Bn(n,t)}function Vb(n,t){switch(n.rank){case 1:return sI([n,t]);case 2:return iI([n,t],0);case 3:return oI([n,t],0);case 4:return uI([n,t],0);default:throw new z(`concatAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}}function jf(n,t){if(Array.isArray(t)||(t=[t]),n.rank!==t.length)throw new z(`The length of input n (${t.length}) does not match the number of dimensions in input x (${n.rank})`);return Us(n,t)}function Ac(n,t=0,e=1,s,r){return iE(n,t,e,s,r)}function hr(n,t,e,s){if(n.rank<2||t.rank<2)throw new dt(`dot requires both inputs to be rank >= 2 but got x shape = ${n.shape} and y shape = ${t.shape}`);if(t.rank>=3&&n.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new dt(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${n.shape} and y shape = ${t.shape}`);if(2===n.rank&&2===t.rank)return Iy({a:n,b:t,transposeA:!1,transposeB:!1,bias:s?Xf(n.rank,s,"channelsLast"):null,activation:e});{const r=n.shape.slice(),i=r.pop();n=j(n,[-1,i]);const a=t.shape.slice(),o=a.pop(),l=a.pop(),u=[...a,o],c=Array.from({length:t.rank},(f,g)=>0===g?t.rank-2:g<=t.rank-2?g-1:g);t=j(kt(t,c),[l,-1]);const h=[...r,...u];return j(Iy({a:n,b:t,transposeA:!1,transposeB:!1,bias:s?Xf(n.rank,s,"channelsLast"):null,activation:e}),h)}}function zb(n,t,e){return Z(()=>(t=Array.isArray(t)?Un(t,"int32"):ke(t,"int32"),Bp(n,t,e)))}function bl(n){return L(n,n)}function Xf(n,t,e){const s=t.shape;if(1!==t.rank&&t.rank!==n)throw new z(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${n}`);if(5===n){if("channelsFirst"===e)return j(t,1===s.length?[1,s[0],1,1,1]:[1,s[3],s[0],s[1],s[2]]);if("channelsLast"===e)return j(t,1===s.length?[1,1,1,1,s[0]]:[1].concat(s))}else if(4===n){if("channelsFirst"===e)return j(t,1===s.length?[1,s[0],1,1]:[1,s[2],s[0],s[1]]);if("channelsLast"===e)return j(t,1===s.length?[1,1,1,s[0]]:[1].concat(s))}else if(3===n){if("channelsFirst"===e)return j(t,1===s.length?[1,s[0],1]:[1,s[1],s[0]]);if("channelsLast"===e)return j(t,1===s.length?[1,1,s[0]]:[1].concat(s))}else if(n<3)return t;throw new z(`Unsupported input rank by biasAdd: ${t.rank}`)}function js(n,t,e){return Z(()=>(null==e&&(e="channelsLast"),fn(e),me(n,Xf(n.rank,t,e))))}function Bb(n,t,e,s){return Z(()=>$E(n,t,e,s))}function vl(n,t,e=!1){return e?n():t()}const k$=["fanIn","fanOut","fanAvg"],N$=["normal","uniform","truncatedNormal"];class Ds extends ma{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}pe((()=>{class n extends Ds{apply(e,s){return Rn(e,s)}}return n.className="Zeros",n})());let Ub=(()=>{class n extends Ds{apply(e,s){return Ir(e,s)}}return n.className="Ones",n})();pe(Ub),pe((()=>{class n extends Ds{constructor(e){if(super(),"object"!=typeof e)throw new z(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new z(`config must have value set but got ${e}`);this.value=e.value}apply(e,s){return Z(()=>L(ut(this.value),Ir(e,s)))}getConfig(){return{value:this.value}}}return n.className="Constant",n})()),pe((()=>{class n extends Ds{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,s){return ol(e,this.minval,this.maxval,s,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}return n.className="RandomUniform",n})()),pe((()=>{class n extends Ds{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,s){if("float32"!==(s=s||"float32")&&"int32"!==s)throw new dt(`randomNormal does not support dType ${s}.`);return Ac(e,this.mean,this.stddev,s,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}return n.className="RandomNormal",n})()),pe((()=>{class n extends Ds{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,s){if("float32"!==(s=s||"float32")&&"int32"!==s)throw new dt(`truncatedNormal does not support dType ${s}.`);return wy(e,this.mean,this.stddev,s,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}return n.className="TruncatedNormal",n})()),pe((()=>{class n extends Ds{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,s){return Z(()=>{if(2!==e.length||e[0]!==e[1])throw new z("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,fy(e[0]))})}getConfig(){return{gain:this.gain}}}return n.className="Identity",n})());let _s=(()=>{class n extends Ds{constructor(e){if(super(),e.scale<0)throw new z(`scale must be a positive float. Got: ${e.scale}`);this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,function A$(n){Bi(k$,"FanMode",n)}(this.mode),this.distribution=null==e.distribution?"normal":e.distribution,function R$(n){Bi(N$,"Distribution",n)}(this.distribution),this.seed=e.seed}apply(e,s){const r=function $$(n,t="channelsLast"){let e,s;if(fn(t),2===n.length)e=n[0],s=n[1];else if(-1!==[3,4,5].indexOf(n.length)){if("channelsFirst"===t){const r=ei(n,2);e=n[1]*r,s=n[0]*r}else if("channelsLast"===t){const r=ei(n,0,n.length-2);e=n[n.length-2]*r,s=n[n.length-1]*r}}else{const r=ei(n);e=Math.sqrt(r),s=Math.sqrt(r)}return[e,s]}(e),i=r[0],a=r[1];let o=this.scale;if(o/="fanIn"===this.mode?Math.max(1,i):"fanOut"===this.mode?Math.max(1,a):Math.max(1,(i+a)/2),"normal"===this.distribution){const l=Math.sqrt(o);if("float32"!==(s=s||"float32")&&"int32"!==s)throw new dt(`${this.getClassName()} does not support dType ${s}.`);return wy(e,0,l,s,this.seed)}{const l=Math.sqrt(3*o);return ol(e,-l,l,s,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}return n.className="VarianceScaling",n})();pe(_s);let Wb=(()=>{class n extends _s{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return _s.className}}return n.className="GlorotUniform",n})();pe(Wb);let Gb=(()=>{class n extends _s{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return _s.className}}return n.className="GlorotNormal",n})();pe(Gb);let Hb=(()=>{class n extends _s{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return _s.className}}return n.className="HeNormal",n})();pe(Hb);let jb=(()=>{class n extends _s{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return _s.className}}return n.className="HeUniform",n})();pe(jb);let Xb=(()=>{class n extends _s{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return _s.className}}return n.className="LeCunNormal",n})();pe(Xb);let Kb=(()=>{class n extends _s{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return _s.className}}return n.className="LeCunUniform",n})();pe(Kb),pe((()=>{class n extends Ds{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,s){return Z(()=>{if(e.length<2)throw new dt("Shape must be at least 2D.");if("int32"!==s&&"float32"!==s&&void 0!==s)throw new TypeError(`Unsupported data type ${s}.`);const r=K(e.slice(0,-1)),i=e[e.length-1],a=r*i;a>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${a}) elements: Slowness may result.`);const l=Ac([Math.max(i,r),Math.min(i,r)],0,1,s,this.seed),u=NN.qr(l,!1);let c=u[0];const d=u[1].flatten().stridedSlice([0],[Math.min(i,r)*Math.min(i,r)],[Math.min(i,r)+1]);return c=L(c,d.sign()),rs*r);return t}const Yb="Variable";class dr{constructor(t,e="float32",s=Yb,r=!0,i=null){this.dtype=e??"float32",this.shape=t.shape,this.id=$b(),this.originalName=Pb(s=s??Yb),this.name=Fb(this.originalName),this.trainable_=r,this.constraint=i,this.val=function CE(n,t=!0,e,s){return V.makeVariable(n,t,e,s)}(t,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(t){return this.assertNotDisposed(),function D$(n,t){if(n.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(n.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,t),this.val.id!==t.id&&(this.val.assign(t),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(t){this.trainable_=t,this.val.trainable=t}}function qf(n){return n.map(t=>t.read())}function Zf(n){n.forEach(t=>{t[0].write(t[1])})}class wn{constructor(t){this.dtype=t.dtype,this.shape=t.shape,this.ndim=null!=t.shape?t.shape.length:t.ndim,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}}}class pr{constructor(t,e,s,r,i,a,o){this.dtype=t,this.shape=e,this.sourceLayer=s,this.inputs=r,this.callArgs=i,this.outputTensorIndex=o,this.id=$b(),null!=a&&(this.originalName=Pb(a),this.name=Fb(this.originalName)),this.rank=e.length}}let O$=0;class Dc{constructor(t,e){this.callArgs=e,this.id=O$++,this.outboundLayer=t.outboundLayer,this.inboundLayers=t.inboundLayers,this.nodeIndices=t.nodeIndices,this.tensorIndices=t.tensorIndices,this.inputTensors=t.inputTensors,this.outputTensors=t.outputTensors,this.inputMasks=t.inputMasks,this.outputMasks=t.outputMasks,this.inputShapes=t.inputShapes,this.outputShapes=t.outputShapes;for(const s of t.inboundLayers)s?.outboundNodes.push(this);t.outboundLayer.inboundNodes.push(this)}getConfig(){const t=[];for(const e of this.inboundLayers)t.push(null!=e?e.name:null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:t,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let P$=0;class wt extends ma{constructor(t={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=P$++,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 e=t.name;if(!e){const s=this.getClassName();e=Rr(s)+"_"+Ec(s)}if(this.name=e,this.trainable_=null==t.trainable||t.trainable,null!=t.inputShape||null!=t.batchInputShape){let s;if(null!=t.batchInputShape)s=t.batchInputShape;else if(null!=t.inputShape){let i=null;null!=t.batchSize&&(i=t.batchSize),s=[i].concat(t.inputShape)}this.batchInputShape=s;let r=t.dtype;null==r&&(r=t.inputDType),null==r&&(r="float32"),this.dtype=r}this.initialWeights=null!=t.weights?t.weights:null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(t,e){return t.name+"_ib-"+e.toString()}getNodeAtIndex(t,e){if(0===this.inboundNodes.length)throw new Rs(`The layer has never been called and thus has no defined ${e}.`);if(this.inboundNodes.length<=t)throw new z(`Asked to get ${e} at node ${t}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[t]}getInputAt(t){return ss(this.getNodeAtIndex(t,"input").inputTensors)}getOutputAt(t){return ss(this.getNodeAtIndex(t,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ur(`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 ur(`Layer ${this.name} is not connected, no input to return.`);return ss(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new ur(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ur(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return ss(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(t=>t())}get updates(){return this._updates}get built(){return this._built}set built(t){this._built=t}get trainable(){return this.trainable_}set trainable(t){this._trainableWeights.forEach(e=>e.trainable=t),this.trainable_=t}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(t=>t.trainable):[]}set trainableWeights(t){this._trainableWeights=t}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(t=>!t.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(t){this._nonTrainableWeights=t}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(t){const e=Ft(t);if(null==this.inputSpec||0===this.inputSpec.length)return;const s=Ft(this.inputSpec);if(e.length!==s.length)throw new z(`Layer ${this.name} expects ${s.length} inputs, but it received ${e.length} input tensors. Input received: ${t}`);for(let r=0;ra.maxNDim)throw new z(`Input ${r} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${o}`);if(null!=a.minNDim&&o=0?l[c]:l[l.length+c]))throw new z(`Input ${r} is incompatible with layer ${this.name}: expected axis ${c} of input shape to have value ${h} but got shape ${l}.`)}}if(null!=a.shape)for(let l=0;l{if(!this.built){this.assertInputCompatibility(t);const a=[];for(const o of Ft(t))a.push(o.shape);this.build(ss(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&i&&(this._refCount=1)}if(this.assertInputCompatibility(t),i){let a=this.call(t,e);this.supportsMasking&&this.setMaskMetadata(t,a);const o=Ft(a),l=[];for(let u of o)-1!==s.indexOf(u)&&(u=u.clone()),l.push(u);if(a=ss(l),null!=this.activityRegularizer)throw new dt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}{const a=function F$(n){n=Ft(n);const t=[];for(const e of n)t.push(e.shape);return ss(t)}(t),o=this.computeOutputShape(a);let l;const u="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(t)?a[0]:a),l=null!=o&&o.length>0&&Array.isArray(o[0])?o.map((c,h)=>new pr(u,c,this,Ft(t),e,this.name,h)):new pr(u,o,this,Ft(t),e,this.name),this.addInboundNode(t,l,null,null,a,o,e),this._refCount++,null!=this.activityRegularizer)throw new dt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return l}})}warnOnIncompatibleInputShape(t){if(null!=this.batchInputShape)if(t.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(t)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let e=!1;this.batchInputShape.forEach((s,r)=>{null!=s&&null!=t[r]&&t[r]!==s&&(e=!0)}),e&&console.warn(`The shape of the input tensor (${JSON.stringify(t)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new ur(`The layer ${this.name} has never been called and thus has no defined output shape.`);const t=[];for(const e of this.inboundNodes){const s=JSON.stringify(e.outputShapes);-1===t.indexOf(s)&&t.push(s)}if(1===t.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new ur(`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 Rs(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return $c(this.weights)}build(t){this.built=!0}getWeights(t=!1){return qf(t?this.trainableWeights:this.weights)}setWeights(t){Z(()=>{const e=this.weights;if(e.length!==t.length)throw new z(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${t.length}, but the layer was expecting ${e.length} weights. Provided weights: ${t}...`);if(0===e.length)return;const s=[],r=qf(e);for(let i=0;ii.apply(c.read())),null==a&&(a=!0),a?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(t){this.fastWeightInitDuringBuild=t}addLoss(t){null==t||Array.isArray(t)&&0===t.length||(t=Ft(t),null!=this._losses&&this.losses.push(...t))}computeOutputShape(t){return t}computeMask(t,e){if(!this.supportsMasking){if(null!=e){if(!Array.isArray(e))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);e.forEach(s=>{if(null!=s)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)})}return null}return e}setMaskMetadata(t,e,s){if(!this.supportsMasking)return;const r=this.computeMask(t,s),i=Ft(e),a=Ft(r);if(i.length!==a.length)throw new Error(`${this.name} outputs ${i.length} tensors but ${i.length} masks for those tensors`);for(let o=0;ot.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 t=0;return 0==--this._refCount&&(t=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:t}}}function Qb(n,t,e){if((null==t||null!=e&&e>0)&&(t=n.sourceLayer,e=n.nodeIndex),0===t.inboundNodes.length)return[n];{const s=t.inboundNodes[e];if(0===s.inboundLayers.length)return s.inputTensors;{const r=[];for(let i=0;i{class n extends wt{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:Ec("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 z("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let s=e.batchInputShape;if(null==s){if(null==e.inputShape)throw new z("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");s=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new z("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const r=e.dtype||"float32";this.batchInputShape=s,this.dtype=r,this.inputSpec=[{shape:s}];const i=new pr(this.dtype,this.batchInputShape,this,[],{},this.name);i.nodeIndex=0,i.tensorIndex=0,new Dc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[i],outputTensors:[i],inputMasks:[null],outputMasks:[null],inputShapes:[s],outputShapes:[s]})}apply(e,s){throw new z(`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}}}return n.className="InputLayer",n})();pe(wl);class ni{constructor(t){if(this.id2Value={},this.id2Mask={},this.name2Id={},t instanceof ni)for(const e in t.id2Value)this.id2Value[e]=t.id2Value[e],e in t.id2Mask&&(this.id2Mask[e]=t.id2Mask[e]);else{if(null==t)return;for(const e of t)this.add(e.key,e.value)}}add(t,e,s){if(null!=this.id2Value[t.id])throw new z(`Duplicate key: name=${t.name}, id=${t.id}`);return this.id2Value[t.id]=function z$(n,t){if(null==n.dtype||n.dtype===t.dtype)return t;try{return ke(t,n.dtype)}catch{throw new z(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${n.name}' (${n.dtype}).`)}}(t,e),this.name2Id[t.name]=t.id,null!=s&&(this.id2Mask[t.id]=s),this}addFeed(t){this.add(t.key,t.value)}hasKey(t){return null!=this.id2Value[t.id]}names(){return Object.keys(this.name2Id)}getValue(t){if(t instanceof pr){if(null==this.id2Value[t.id])throw new z(`Nonexistent key: ${t.name}`);return this.id2Value[t.id]}{const e=this.name2Id[t];if(null==e)throw new z(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Value[e]}}getMask(t){if(t instanceof pr){if(null==this.id2Value[t.id])throw new z(`Nonexistent key: ${t.name}`);return this.id2Mask[t.id]}{const e=this.name2Id[t];if(null==e)throw new z(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Mask[e]}}disposeMasks(){null!=this.id2Mask&&xt(this.id2Mask)}}const Oc=new kb,Pc=new kb;function _l(n,t,e,s){const r=null!=e&&e.training,i=Array.isArray(n),a=i?n:[n],o=a.map(f=>f.name),l=[],u=t.names();for(const f of o)-1!==u.indexOf(f)?l.push(t.getValue(f)):l.push(null);null!=s&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);const c=o.join(",")+"|"+t.names().sort().join(",");let d,h=Oc.get(c);if(null==h){const f=function U$(n,t){T(null!=n&&n.length>0,()=>"Expected at least one fetch, got none");let e=[],s={};if(1===n.length){const r=e0(n[0],t);e=r.sorted,s=r.recipientMap}else{const r=new Set;for(const i of n){const{sorted:a,recipientMap:o}=e0(i,t);for(const l of a)r.has(l.name)||(e.push(l),r.add(l.name));for(const l in o)null==s[l]&&(s[l]=new Set),o[l].forEach(u=>s[l].add(u))}}return{sorted:e,recipientCounts:W$(s)}}(a,t);h=f.sorted,d=f.recipientCounts,Oc.put(c,h),Pc.put(c,d)}d={},r||Object.assign(d,Pc.get(c));const p=new ni(t);for(let f=0;fs.maxNumTensors&&(s.maxNumTensors=D),D0;){const o=i[i.length-1];if(e.has(o.name)){i.pop();continue}const l=a[a.length-1]===i.length-1;if(0===o.inputs.length||l)i.pop(),s.push(o),e.add(o.name),l&&a.pop();else{a.push(i.length-1);for(const u of o.inputs)null==r[u.name]&&(r[u.name]=new Set),r[u.name].add(o.name),!e.has(u.name)&&i.push(u)}}return{sorted:s,recipientMap:r}}function G$(n){let t;if(1===n.sourceLayer.inboundNodes.length)t=n.sourceLayer.output;else{let e=null;for(let s=0;szn(Ge(L(n,n),t,!0)))}E().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,function B$(n){Oc?.setMaxEntries(n),Pc?.setMaxEntries(n)});class Tl extends ma{getConfig(){return{}}}pe((()=>{class n extends Tl{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 Z(()=>{const s=Yf(e,this.axis),r=gs(s,0,this.maxValue);return L(e,je(r,me(vn(),s)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}return n.className="MaxNorm",n})()),pe((()=>{class n extends Tl{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Z(()=>je(e,me(vn(),Yf(e,this.axis))))}getConfig(){return{axis:this.axis}}}return n.className="UnitNorm",n})()),pe((()=>{class n extends Tl{apply(e){return Er(e)}}return n.className="NonNeg",n})()),pe((()=>{class n extends Tl{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 Z(()=>{const s=Yf(e,this.axis),r=me(L(this.rate,gs(s,this.minValue,this.maxValue)),L(1-this.rate,s));return L(e,je(r,me(vn(),s)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}return n.className="MinMaxNorm",n})());const t0={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function _n(n){return Bf(n)}function n0(n,t={}){return gl(n,Es.getMap().classNameMap,t,"constraint")}function Tn(n){return null==n?null:"string"==typeof n?n0({className:n in t0?t0[n]:n,config:{}}):n instanceof Tl?n:n0(n)}function si(n){return Qf.apply(this,arguments)}function Qf(){return(Qf=(0,N.A)(function*(n){if(null==n)return;const t=[],e=[],s=[];for(const r in n){const i=n[r];if("number"!=typeof i){const a=i;t.push(a.data()),e.push(r),s.push(a)}}if(t.length>0){const r=yield Promise.all(t);for(let i=0;ime(s.totals[i],L(a,r)));s.totals[i]=l,o?.dispose()}}})()}onEpochEnd(t,e){var s=this;return(0,N.A)(function*(){if(null!=e)for(const r of s.params.metrics)null!=s.totals[r]&&("number"==typeof s.totals[r]?e[r]=s.totals[r]/s.seen:Z(()=>{const i=L(je(1,s.seen),s.totals[r]);e[r]=i,s.totals[r].dispose(),nr(e[r])}))})()}}class q$ extends Ca{onTrainBegin(t){var e=this;return(0,N.A)(function*(){e.epoch=[],e.history={}})()}onEpochEnd(t,e){var s=this;return(0,N.A)(function*(){null==e&&(e={}),s.epoch.push(t);for(const r in e)null==s.history[r]&&(s.history[r]=[]),s.history[r].push(e[r])})()}syncData(){var t=this;return(0,N.A)(function*(){const e=[],s=[],r=[];for(const a in t.history){const o=t.history[a];for(let l=0;l{const o=null!=e?e():Vn();return o-snew Z$(s,t))}let Y$=(()=>{class n{constructor(){}static registerCallbackConstructor(e,s){T(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),n.checkForDuplicate(s),null==n.constructors[e]&&(n.constructors[e]=[]),n.constructors[e].push(s)}static checkForDuplicate(e){for(const s in n.constructors)n.constructors[+s].forEach(i=>{if(i===e)throw new z("Duplicate callback constructor.")})}static clear(){n.constructors={}}static createCallbacks(e){const s=[];for(const r in n.constructors){const i=+r;e>=i&&s.push(...n.constructors[i])}return s.map(r=>new r)}}return n.constructors={},n})();function a0(n,t,e,s,r,i,a,o,l){const u=new q$,c=[new K$,...Y$.createCallbacks(t)];null!=n&&c.push(...n),c.push(u);const h=new X$(c);return h.setParams({epochs:e,initialEpoch:s,samples:r,steps:i,batchSize:a,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function $r(n,t={},e=!1){return gl(n,Es.getMap().classNameMap,t,"layer",e)}function Fc(n,t){return Z(()=>{"float32"!==n.dtype&&(n=ke(n,"float32"));const e=Ge(bl(n),t,!0),s=Jo(e.shape,vn()),r=zn(Kr(e,s));return je(n,r)})}function Lc(n,t){return Z(()=>pn(bl(ze(t,n)),-1))}function Jf(n,t){return Z(()=>pn(kn(ze(t,n)),-1))}function em(n,t){return Z(()=>{const e=ze(n,t),s=gs(kn(n),vn(),Number.MAX_VALUE),r=kn(je(e,s));return L(100,pn(r,-1))})}function Sl(n,t,e=!1){return Z(()=>{if(e)t=ef(t);else{const s=Ge(t,t.shape.length-1,!0);t=je(t,s)}return t=gs(t,vn(),1-vn()),Jt(Ge(L(ke(n,"float32"),Ns(t)),t.shape.length-1))})}function Mc(n,t,e=!1){return Z(()=>{const s=ke(cc(function T$(n){const t=[ei(n.shape)];return j(n,t)}(n)),"int32"),r=(t=gs(t,vn(),1-vn())).shape;return Sl(j(xy(s,r[r.length-1]),r),t,e)})}function Vc(n,t){return Z(()=>{let e;return e=gs(t,vn(),1-vn()),e=Ns(je(e,ze(1,e))),pn(function sD(n,t){if(!rt(n.shape,t.shape))throw new z(`logits and labels must have the same shape, but got shapes ${JSON.stringify(n.shape)} and ${JSON.stringify(t.shape)}`);return Z(()=>{const e=Er(t),s=Jt(kn(t));return me(ze(e,L(t,n)),Wp(xs(s)))})}(n,e),-1)})}function o0(n,t){return Z(()=>{const e=Fc(n,-1),s=Fc(t,-1),r=L(e,s);return Jt(Ge(r,-1))})}const zc={meanSquaredError:Lc,meanAbsoluteError:Jf,meanAbsolutePercentageError:em,meanSquaredLogarithmicError:function Q$(n,t){return Z(()=>{const e=gs(t,vn(),Number.MAX_VALUE),s=Ns(me(1,e)),r=gs(n,vn(),Number.MAX_VALUE),i=Ns(me(1,r));return pn(bl(ze(s,i)),-1)})},squaredHinge:function J$(n,t){return Z(()=>{const e=Kr(0,ze(1,L(n,t)));return pn(bl(e),-1)})},hinge:function eD(n,t){return Z(()=>{const e=Kr(0,ze(1,L(n,t)));return pn(e,-1)})},categoricalHinge:function tD(n,t){return Z(()=>{const e=Ge(L(n,t),-1),s=Ws(L(ze(1,n),t),-1);return Kr(0,me(1,ze(s,e)))})},logcosh:function nD(n,t){return Z(()=>{const e=Math.log(2),s=ze(t,n),r=ze(me(s,ul(L(-2,s))),e);return pn(r,-1)})},categoricalCrossentropy:Sl,sparseCategoricalCrossentropy:Mc,binaryCrossentropy:Vc,kullbackLeiblerDivergence:function rD(n,t){return Z(()=>{const e=gs(n,vn(),1),s=gs(t,vn(),1);return Ge(L(n,Ns(je(e,s))),-1)})},poisson:function iD(n,t){return Z(()=>{const e=Ns(me(vn(),t));return pn(ze(t,L(n,e)),-1)})},cosineProximity:o0};function tm(n){if("string"==typeof n){if(n in zc)return zc[n];let t=`Unknown loss ${n}`;throw n.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${n}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new z(t)}return n}function l0(n,t){return Z(()=>{const e=L(.5,As(t)),s=cr(ys(t,e),n.dtype);return pn(rr(n,s),-1)})}function u0(n,t){return Z(()=>cr(rr(el(n,-1),el(t,-1)),"float32"))}function uD(n,t){return Vc(n,t)}function cD(n,t){return n.rank===t.rank&&(n=cl(n,[n.rank-1])),(t=el(t,-1)).dtype!==n.dtype&&(t=ke(t,n.dtype)),ke(rr(n,t),"float32")}const h0=Sl,d0=Mc,Bc={binaryAccuracy:l0,categoricalAccuracy:u0,precision:function lD(n,t){return Z(()=>{const e=function c0(n,t){return Z(()=>ke(Ge(Cr(rr(n,1),rr(t,1))),"float32"))}(n,t),s=function oD(n,t){return Z(()=>ke(Ge(Cr(rr(n,0),rr(t,1))),"float32"))}(n,t),r=me(e,s);return ke(Yn(ys(r,0),je(e,r),0),"float32")})},categoricalCrossentropy:h0,sparseCategoricalCrossentropy:d0,mse:Lc,MSE:Lc,mae:Jf,MAE:Jf,mape:em,MAPE:em,cosine:o0};function yD(n){if("string"==typeof n&&n in Bc)return Bc[n];if("string"!=typeof n&&null!=n)return n;throw new z(`Unknown metric ${n}`)}function Uc(n){if(vs(null!==n,`Unknown LossOrMetricFn ${n}`),"string"==typeof n)return n;{let t;for(const e of Object.keys(zc))if(zc[e]===n){t=e;break}if(void 0!==t)return t;for(const e of Object.keys(Bc))if(Bc[e]===n){t=e;break}return void 0!==t?t:n.name}}function f0(n,t,e=!1){if(null==n||"object"!=typeof n||Object.getPrototypeOf(n)!==Object.prototype||!nm(n))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(e){const s=JSON.stringify(n);s.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function nm(n){if(null===n)return!0;if("object"==typeof n){if(Object.getPrototypeOf(n)===Object.prototype){const t=Object.keys(n);for(const e of t)if("string"!=typeof e||!nm(n[e]))return!1;return!0}if(Array.isArray(n)){for(const t of n)if(!nm(t))return!1;return!0}return!1}{const t=typeof n;return"string"===t||"number"===t||"boolean"===t}}function Wc(n,t,e=console.log){let s="";for(let r=0;r0&&(s=s.slice(0,s.length-1)+" "),s+=n[r],s=s.slice(0,t[r]),s+=" ".repeat(t[r]-s.length);e(s)}function TD(n,t,e){let s,r;try{r=n.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch{r="multiple"}try{s=JSON.stringify(n.outputShape)}catch{s="multiple"}Wc([`${n.name} (${n.getClassName()})`,r,s,n.countParams().toString()],t,e)}function SD(n,t,e,s){let r,i;try{i=n.inboundNodes.map(h=>JSON.stringify(h.inputShapes)).join(",")}catch{i="multiple"}try{r=JSON.stringify(n.outputShape)}catch{r="multiple"}const a=[];for(const h of n.inboundNodes)if(!(null!=e&&e.length>0&&-1===e.indexOf(h)))for(let d=0;dy.name)}`);Jr(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const y of this.outputs){const v=y.nodeIndex,w=y.tensorIndex;this.outputLayers.push(y.sourceLayer),this.outputLayersNodeIndices.push(v),this.outputLayersTensorIndices.push(w)}for(const y of this.inputs){const b=y.sourceLayer,v=y.nodeIndex,w=y.tensorIndex;vs(0===v,"input layer has >1 nodes"),vs(0===w,"input layer has >1 tensors"),this.inputLayers.push(b),this.inputLayersNodeIndices.push(v),this.inputLayersTensorIndices.push(w)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;yy.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);const e={},s={},r={},i={},a={},o=[],l=(y,b,v,w,S,I)=>{(null==w||null==S||null==I)&&(w=y.sourceLayer,S=y.nodeIndex,I=y.tensorIndex);const k=w.inboundNodes[S];if(-1!==v.indexOf(k))throw new Rs(`The tensor ${y.name} at layer "${w.name}" is part of a cycle.`);if(-1!==b.indexOf(k))return;this.containerNodes.add(Xs.nodeKey(w,S)),w.id in a||(a[w.id]=Object.keys(a).length),-1===v.indexOf(k)&&v.push(k);const D=k.inboundLayers.length;for(let P=0;P=0;)v.splice(v.indexOf(k),1);o.push(k)},u=[],c=[];for(const y of this.outputs)l(y,u,c);const h=o.slice().reverse();for(const y of h){s[y.id]=y,y.id in e||(e[y.id]=0);let b=e[y.id];b=Math.max(b,null==r[y.outboundLayer.id]?0:r[y.outboundLayer.id]),r[y.outboundLayer.id]=b,i[y.outboundLayer.id]=y.outboundLayer,e[y.id]=b;for(let w=0;wparseInt(y,10)).sort(Cc);this.layers=[];for(const y of f){const b=p[y];b.sort((v,w)=>{const S=a[v.id],I=a[w.id];return SI?1:0});for(const v of b)v instanceof Xs&&this.internalContainerRefs.push(v),this.layers.push(v)}this.layersByDepth=p,f=Object.keys(d).map(y=>parseInt(y,10)).sort(Cc);const g=this.inputs.slice(),m=[];for(const y of f)for(const b of d[y]){const v=b.outboundLayer;if(null!=v){for(const w of b.inputTensors)if(-1===g.indexOf(w))throw new Rs(`Graph disconnected: cannot obtain value for tensor ${w} at layer "${v.name}". The following previous layers were accessed without issue: ${m}`);for(const w of b.outputTensors)g.push(w);m.push(v.name)}}this.nodesByDepth=d;const x=this.layers.map(y=>y.name);for(const y of x){const b=x.filter(v=>v===y).length;if(1!==b)throw new Rs(`The name "${y}" is used ${b} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(x))}this.outboundNodes=[],this.inboundNodes=[],new Dc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.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 t={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const e of this.layers)t.numDisposedVariables+=e.dispose().numDisposedVariables;for(const e of this.internalContainerRefs)t.numDisposedVariables+=e.dispose().numDisposedVariables}return t.refCountAfterDispose=this._refCount,t}get trainable(){return this.trainable_}set trainable(t){this.layers.forEach(e=>{e._trainableWeights.forEach(s=>s.trainable=t)}),this.trainable_=t}get trainableWeights(){if(this._trainableWeights.length>0)throw new z("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 t=[];for(const e of this.layers)t=t.concat(e.trainableWeights);return t}get nonTrainableWeights(){const t=[];for(const e of this.layers)t.push(...e.nonTrainableWeights);if(!this.trainable){const e=[];for(const s of this.layers)e.push(...s.trainableWeights);return e.concat(t)}return t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(t,e=!0){const s={};let r=0;const i=(n=>{const t=Object.keys(n);if(0===t.length)return!1;const e=t[0].split("/");return!isNaN(parseInt(e[e.length-1],10))})(t);i&&this.parseWeights(t);for(const o of this.layers)for(const[l,u]of o.weights.entries()){const c=i?`${u.name.split("/").slice(0,-1).join("/")+"/"}${l}`:u.originalName;if(null!=s[c])throw new z(`Duplicate weight name: ${c}`);s[c]=u,r++}const a=[];for(const o in t){let l=o;if(null==s[o]){const u=o.split("/");l=u.slice(0,-2).concat([u[u.length-1]]).join("/")}if(null!=s[l])a.push([s[l],t[o]]);else if(e)throw new z(`Provided weight data has no target variable: ${o}`);delete s[l]}if(e){const o=[];for(const l in s)o.push(l);if(o.length>0)throw new z(`${o.length} of ${r} weights are not set: ${o}`)}Zf(a)}parseWeights(t){for(const e in Object.keys(t)){const s=e.split("/"),r=["vars","layer_checkpoint_dependencies"],i=s.map(a=>a.startsWith("_")?a.slice(1):a).filter(a=>!r.includes(a)).join("/");i!==e&&(t[i]=t[e],delete t[e])}}updatedConfig(){const t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion="tfjs-layers 4.22.0",e.backend="TensorFlow.js",e}toJSON(t,e=!0){const s=rm(this.updatedConfig());return e?JSON.stringify(s):s}call(t,e){return Z(()=>{t=Ft(t);const s=new ni;for(let r=0;r{let s;return t=Ft(t),s=null==e?Vi(null,t.length):Ft(e),this.runInternalGraph(t,s)[1]})}computeOutputShape(t){const e=Rc(t);if(e.length!==this.inputLayers.length)throw new z(`Invalid inputShape argument ${t}: model has ${this.inputLayers.length} tensor inputs.`);const s={};for(let o=0;oparseInt(o,10)).sort(Cc);if(r.length>1)for(const o of r){const l=this.nodesByDepth[o];for(const u of l){const c=u.outboundLayer;if(-1!==this.inputLayers.map(g=>g.id).indexOf(c.id))continue;const h=[];for(let g=0;gparseInt(l,10)).sort(Cc);for(const l of r){const u=this.nodesByDepth[l];for(const c of u){const h=c.outboundLayer,d=c.inputTensors,p=c.outputTensors,f=new Array;for(const g of d)g.id in s&&f.push(s[g.id]);if(f.length===d.length){let m,x,y,b,g={};if(null!=c.callArgs&&(g=c.callArgs),1===f.length){const[v,w]=f[0];null==g.mask&&(g.mask=w),y=Ft(h.call(v,g)),b=Ft(h.computeMask(v,w)),m=[v],x=[w]}else m=f.map(v=>v[0]),x=f.map(v=>v[1]),null==g.mask&&(g.mask=x),y=Ft(h.call(m,g)),b=Ft(h.computeMask(m,x));if(h.activityRegularizer)throw new dt("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let v=0;v{const t=[];for(const e of this.layers)for(let s=0;s0){const g=[];for(let m=0;m0&&m.apply(ss(y),b)}function u(m){const x=m.name,y=$r(m,null!=e.customObjects?e.customObjects:{});y.setFastWeightInitDuringBuild(r),i[x]=y,m.inboundNodes.forEach(v=>{if(!(v instanceof Array))throw new z(`Corrupted configuration, expected array for nodeData: ${v}`);o(y,v)})}const c=e.name,h=e.layers;for(const m of h)u(m);for(;!l$(a);)for(const m of h){const x=i[m.name];if(x.name in a){const y=a[x.name];delete a[x.name];for(const b of y)l(x,b)}}const d=[],p=[],f=e.inputLayers;for(const m of f){const x=m[0],y=m[1],b=m[2];vs(x in i),d.push(i[x].inboundNodes[y].outputTensors[b])}const g=e.outputLayers;for(const m of g){const x=m[0],y=m[1],b=m[2];vs(x in i),p.push(i[x].inboundNodes[y].outputTensors[b])}return new t({inputs:d,outputs:p,name:c})}get stateful(){if(this._stateful)throw new z("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 t of this.layers)if(t.stateful)return!0;return!1}resetStates(){Z(()=>{this.layers.forEach(t=>{t.stateful&&t.resetStates()})})}}function x0(n,t){return function g0(n,t,e){const s=t.length;if(null==n||Array.isArray(n)&&0===n.length)return t.map(r=>null);if(1===s)return Array.isArray(n)&&1===n.length?n:"object"==typeof n&&t[0]in n?[n[t[0]]]:[n];if(Array.isArray(n)){if(n.length!==s)throw new Error(`Provided ${e} is an array of ${n.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return n}if("object"==typeof n&&Object.keys(n).length>0&&"object"==typeof n[Object.keys(n)[0]]){const r=[];return t.forEach(i=>{r.push(i in n?n[i]:null)}),r}throw new Error(`The model has multiple (${s}) outputs, so ${e} must be either an array with ${s} elements or an object with ${t} keys. Provided ${e} not understood: ${JSON.stringify(n)}`)}(n,t,"classWeight")}function y0(n,t,e,s){return am.apply(this,arguments)}function am(){return(am=(0,N.A)(function*(n,t,e,s){if(null!=t||null!=s)throw new Error("Support sampleWeight is not implemented yet");if(null!=e){const r=Z(()=>{if(1===n.shape.length)return Ai(n);if(2===n.shape.length){if(n.shape[1]>1)return el(n,1);if(1===n.shape[1])return j(n,[n.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${n.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${n.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),i=Array.from(yield r.data());xt(r);const a=[];return i.forEach(o=>{if(null==e[o])throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);a.push(e[o])}),Un(a,"float32")}return null})).apply(this,arguments)}function ID(n,t){return L(n,t)}function b0(n,t){let e,s;e=t.xs,s=t.ys,T(null!=e&&null!=s,()=>`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 i=v0("input",n.inputNames,e),a=v0("output",n.outputNames,s),o=i[0].shape[0];T(i.length===n.inputs.length,()=>`LayersModel has ${n.inputs.length} inputs, but the dataset provides ${i.length} inputs. (Expected input keys: ${JSON.stringify(n.inputNames)})`),T(a.length===n.outputs.length,()=>`LayersModel has ${n.outputs.length} outputs, but the dataset provides ${a.length} outputs. (Expected output keys: ${JSON.stringify(n.outputNames)})`);for(let l=0;l`Batch size mismatch: input ${n.inputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${n.inputNames[0]}.`);for(let l=0;l`Batch size mismatch: output ${n.outputNames[l]} has ${a[l].shape[0]}; expected ${o} based on input ${n.inputNames[0]}.`);return{xs:i,ys:a}}function v0(n,t,e){if(e instanceof Qt)return[e];if(Array.isArray(e))return T(e.length===t.length,()=>`Received an array of ${e.length} Tensors, but expected ${t.length} to match the ${n} keys ${t}.`),e;{const s=[];for(const r of t){if(null==e[r])throw new z(`The feature data generated by the dataset lacks the required ${n} key '${r}'.`);s.push(e[r])}return s}}function om(){return(om=(0,N.A)(function*(n,t,e){const s=null!=e.batchesPerEpoch;if(T(null!=n.optimizer,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),T(null!=e,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),T(null!=e.epochs&&e.epochs>0&&Number.isInteger(e.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${e.epochs}`),T(!s||e.batchesPerEpoch>0&&Number.isInteger(e.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${e.batchesPerEpoch}`),T(null==e.validationSplit,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),n.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");n.isTraining=!0;try{const r=null!=e.validationData;let i,a;if(r)if(w0(e.validationData))T(null==e.validationBatches||e.validationBatches>0&&Number.isInteger(e.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${e.validationBatches}`);else{const m=function kD(n){if(3===n.length)throw new dt("Validation with sample weights is not implemented yet.");return{xs:n[0],ys:n[1]}}(e.validationData);i=m.xs,a=m.ys}const o=n.makeTrainFunction(),l=n.getDedupedMetricsNames();let u;u=r?l.slice().concat(l.map(m=>"val_"+m)):l.slice();const c=r0(e.callbacks,e.yieldEvery),h=null==e.verbose?1:e.verbose,{callbackList:d,history:p}=a0(c,h,e.epochs,null,null,function AD(n,t){let e=null;return null!=t.batchesPerEpoch?e=t.batchesPerEpoch:Number.isFinite(n.size)&&(e=n.size),e}(t,e),null,r,u);d.setModel(n),n.history=p,yield d.onTrainBegin(),n.stopTraining_=!1;let f=null==e.initialEpoch?0:e.initialEpoch,g=yield t.iterator();for(;f=e.batchesPerEpoch:b.done){if(r){let v;v=w0(e.validationData)?Ft(yield n.evaluateDataset(e.validationData,{batches:e.validationBatches})):Ft(n.evaluate(i,a,{batchSize:null==e.validationBatchSize?32:e.validationBatchSize,verbose:0}));for(let w=0;w0)throw new dt("Verbose mode is not implemented yet.");T(!s||e.batches>0&&Number.isInteger(e.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(e.batches)}`);const a=function RD(n){return"function"==typeof n.next}(t)?t:yield t.iterator();let o=0,l=0;for(;!s||l{if(u.value){const{xs:c,ys:h}=b0(n,u.value),d=c.concat(h),p=Z(()=>r(d));if(xt(d),0===l)for(let g=0;gme(i[g],L(f,m))),l>0&&xt(x)}xt(p),o+=f,++l}return i}),u.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${e.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let u=0;u0&&Number.isInteger(n),()=>`batchSize is required to be a positive integer, but got ${n}`)}function Cl(n,t,e){return null==n?[null]:Array.isArray(n)?n.map(s=>Wi(s,t,e-t)):Wi(n,t,e-t)}function cm(n,t){return Z(()=>null==n?null:Array.isArray(n)?n.map(e=>cm(e,t)):zb(n,"int32"===t.dtype?t:ke(t,"int32")))}function hm(n,t){const e=[];let s=0,r=null;for(;s=n&&(r=n),e.push([s,r]),s=r;return e}function _0(n){const t=[];n instanceof Qt&&(n=[n]);for(let e=0;ee.push(r.id));else if(null!=t)for(const r in t)e.push(t[r].id);const s=[];if(n instanceof Qt)-1===e.indexOf(n.id)&&s.push(n);else if(Array.isArray(n))n.forEach(r=>{-1===e.indexOf(r.id)&&s.push(r)});else if(null!=n)for(const r in n){const i=n[r];-1===e.indexOf(i.id)&&s.push(i)}s.forEach(r=>{r.isDisposed||r.dispose()})}function dm(n){return Array.isArray(n)}function T0(n){return!function DD(n){return n instanceof Qt}(n)&&!dm(n)}function S0(n,t,e,s=!0,r=""){if(null==t||0===t.length){if(null!=n){let a=!1;if(dm(n)&&n.length>0)a=!0;else if(T0(n)){for(const o in n)if(n.hasOwnProperty(o)){a=!0;break}}else a=!0;if(a)throw new z(`Error when checking model ${r} expected no data, but got ${n}`)}return[]}if(null==n)return t.map(a=>null);let i;if(T0(n)){i=[];for(const a of t){if(null==n[a])throw new z(`No data provided for "${a}". Need data for each key in: ${t}`);i.push(n[a])}}else if(dm(n)){if(n.length!==t.length)throw new z(`Error when checking model ${r}: 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): ${n}`);i=n}else{if(t.length>1)throw new z(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${n.shape}`);i=[n]}if(i=_0(i),null!=e)for(let a=0;a=0&&o.shape[l]!==c)throw new z(`${r} expected a batch of elements where each example has shape [${e[a].slice(1,e[a].length)}] (i.e.,tensor shape [*,${e[a].slice(1,e[a].length)}]) but the ${r} received an input with ${o.shape[0]} examples, each with shape [${o.shape.slice(1,o.shape.length)}] (tensor shape [${o.shape}])`)}}return i}function C0(n,t,e,s=!0,r=""){let i;if(Array.isArray(n)){if(n.length!==t.length)throw new z(`Error when checking model ${r}: 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 ${n.length} Tensors(s).`);i=n}else{if(t.length>1)throw new z(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(n.shape)}.`);i=[n]}if(null!=e)for(let a=0;a{class n extends Xs{constructor(e){super(e),this.isTraining=!1}summary(e,s,r=console.log){if(!this.built)throw new z("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).");!function vD(n,t,e,s=console.log){const r=function _D(n){let t=!0;const e=[],s=[];for(const r in n.nodesByDepth)e.push(n.nodesByDepth[r]);for(const r of e){if(r.length>1||1===r.length&&r[0].inboundLayers.length>1){t=!1;break}s.push(...r)}if(t)for(const r of n.layers){let i=!1;for(const a of r.inboundNodes)if(-1!==s.indexOf(a)){if(i){t=!1;break}i=!0}if(!t)break}return t}(n),i=["Layer (type)","Input Shape","Output shape","Param #"];let a;if(r?(t=t||90,e=e||[.32,.61,.89,1]):(t=t||115,e=e||[.24,.48,.7,.8,1]),e[e.length-1]<=1&&(e=e.map(c=>Math.floor(t*c))),!r){i.push("Receives inputs"),a=[];for(const c in n.nodesByDepth)a.push(...n.nodesByDepth[c])}s("_".repeat(t)),Wc(i,e,s),s("=".repeat(t));const o=n.layers;for(let c=0;c_a.adagrad(.01),Adadelta:()=>_a.adadelta(1,.95,vn()),Adam:()=>_a.adam(.001,.9,.999,vn()),Adamax:()=>_a.adamax(.002,.9,.999,vn(),0),RMSProp:()=>_a.rmsprop(.001,.9,0,vn()),SGD:()=>_a.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,n in t)return t[n]();throw new z(`Unknown Optimizer ${n}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Xr))throw new z("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let s=[];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 z(`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}.`);s=e.loss.map(l=>tm(l))}else{const o=tm(e.loss);this.outputs.forEach(l=>{s.push(o)})}else{e.loss=e.loss;for(const o in e.loss)if(-1===this.outputNames.indexOf(o))throw new z(`Unknown entry in loss dictionary: "${o}". Only expected the following keys: ${this.outputNames}`);for(const o of this.outputNames)null==e.loss[o]&&console.warn(`Output "${o}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${o} during training`),s.push(tm(e.loss[o]))}this.lossFunctions=s,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let o=0;o{for(let o=0;o1&&(this.metricsTensors.push([this.lossFunctions[o],o]),this.metricsNames.push(this.outputNames[o]+"_loss"))});const i=function FD(n,t){if(null==n||Array.isArray(n)&&0===n.length)return t.map(s=>[]);let e;if("string"==typeof n||"function"==typeof n)e=[n];else{if(!Array.isArray(n)&&"object"!=typeof n)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${n}`);e=n}if(Array.isArray(e))return t.map(s=>e);{const s=[];for(const r of t){let i=e.hasOwnProperty(r)?e[r]:[];Array.isArray(i)||(i=[i]),s.push(i)}return s}}(e.metrics,this.outputNames),a=(o,l,u)=>{this.outputNames.length>1&&(l=this.outputNames[o]+"_"+l),this.metricsNames.push(l),this.metricsTensors.push([u,o])};Ui("metric",()=>{for(let o=0;o{let d,p,f;for(const g of c){if("string"==typeof g&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(g)){const x=this.internalOutputShapes[o];let y;1===x[x.length-1]||this.lossFunctions[o]===Vc?-1!==["accuracy","acc"].indexOf(g)?p=l0:-1!==["crossentropy","ce"].indexOf(g)&&(p=uD):this.lossFunctions[o]===Mc?-1!==["accuracy","acc"].indexOf(g)?p=cD:-1!==["crossentropy","ce"].indexOf(g)&&(p=d0):-1!==["accuracy","acc"].indexOf(g)?p=u0:-1!==["crossentropy","ce"].indexOf(g)&&(p=h0),-1!==["accuracy","acc"].indexOf(g)?y="acc":-1!==["crossentropy","ce"].indexOf(g)&&(y="ce"),f=p,d=""+y}else f=yD(g),d=""+Uc(g);let m;Ui(d,()=>{m=f}),a(o,d,m)}})(i[o])}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,s,r={}){const i=null==r.batchSize?32:r.batchSize;um(i);const o=this.standardizeUserDataXY(e,s,!0,i);try{const l=o[0].concat(o[1]);return this.makeTestFunction(),ss(this.testLoop(this.testFunction,l,i,r.verbose,r.steps))}finally{Ks(o[0],e),Ks(o[1],s)}}evaluateDataset(e,s){var r=this;return(0,N.A)(function*(){return r.makeTestFunction(),function $D(n,t,e){return lm.apply(this,arguments)}(r,e,s)})()}checkNumSamples(e,s,r,i="steps"){let a;if(null!=r){if(a=null,null!=s)throw new z(`If ${i} is set, batchSize must be null or undefined.Got batchSize = ${s}`)}else{if(null==e)throw new z(`Either the input data should have a defined shape, or ${i} shoud be specified.`);a=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return a}execute(e,s){if(Array.isArray(s)&&0===s.length)throw new z("`outputs` is an empty Array, which is not allowed.");const r=Array.isArray(s),a=this.retrieveSymbolicTensors(r?s:[s]),o=new ni;if(e instanceof Qt&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new z(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let u=0;ul.name);for(let l=0;l0){const i=[];throw s.forEach((a,o)=>{null==a&&i.push(e[o])}),new z(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(i)}`)}return s}predictLoop(e,s=32,r=!1){return Z(()=>{const i=this.checkNumSamples(e);if(r)throw new dt("Verbose predictLoop() is not implemented yet.");const a=hm(i,s),o=this.outputs.map(l=>[]);for(let l=0;l{const d=Cl(e,a[l][0],a[l][1]),p=[];if(Array.isArray(d))for(let g=0;go[h].push(c));return ss(o.map(l=>Bn(l,0)))})}predict(e,s={}){const r=_0(e);C0(r,this.inputNames,this.feedInputShapes,!1);try{const i=null==s.batchSize?32:s.batchSize;return um(i),this.predictLoop(r,i)}finally{Ks(r,e)}}predictOnBatch(e){C0(e,this.inputNames,this.feedInputShapes,!0);const s=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,s)}standardizeUserDataXY(e,s,r=!0,i){if(null==this.optimizer_)throw new Rs("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const a=[];for(let o=0;oi.shape[0]));s.sort();const r=Jr(t.map(i=>i.shape[0]));if(r.sort(),s.length>1)throw new z(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(n.map(i=>i.shape))}`);if(r.length>1)throw new z(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(i=>i.shape))}`);if(s.length>0&&r.length>0&&!rt(s,r))throw new z(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}(e=S0(e,this.feedInputNames,this.feedInputShapes,!1,"input"),s=S0(s,this.feedOutputNames,a,!1,"target")),function PD(n,t,e){const s=[Lc,Vc,Sl];for(let r=0;r0&&e[0].shape[0]%i!=0)throw new z(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${i}. Found: ${e[0].shape[0]} sample(s).`);return[e,s]}standardizeUserData(e,s,r,i,a=!0,o){var l=this;return(0,N.A)(function*(){const[u,c]=l.standardizeUserDataXY(e,s,a,o);if(null!=r)throw new Error("sample weight is not supported yet.");let h=null;if(null!=i){const d=x0(i,l.outputNames);h=[];for(let p=0;p{const o=this.checkNumSamples(s,r,a,"steps"),l=[];if(i>0)throw new dt("Verbose mode is not implemented yet.");if(null!=a)throw new dt("steps mode in testLoop() is not implemented yet");{const u=hm(o,r),c=Un(Gs(0,o));for(let h=0;h1&&(a+=`_${Nb(e.slice(0,r),i)}`),s.push(a)}return s}makeTrainFunction(){return e=>{const s=[],r=e.slice(0,this.inputs.length),i=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),o=[],u=this.collectedTrainableWeights.map(d=>d.read());return[this.optimizer_.minimize(()=>{const d=[];for(let m=0;m1&&m{g=me(g,m)}),g},!0,u)].concat(o)}}makeTestFunction(){this.testFunction=e=>Z(()=>{const s=[];let r;const i=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),o=[];for(let c=0;c0){if(y=!0,2!==r.validationData.length)throw 3===r.validationData.length?new dt("validationData including sample weights is not supported yet."):new z(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${r.validationData} is invalid.`);c=r.validationData[0],h=r.validationData[1];const Y=yield i.standardizeUserData(c,h,null,null,!0,g);d=Y[0],p=Y[1],b=d.concat(p)}else if(null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1){y=!0;const B=Math.floor(a[0].shape[0]*(1-r.validationSplit)),Y=a[0].shape[0];d=Cl(a,B,Y),l=a,a=Cl(a,0,B),p=Cl(o,B,Y),u=o,o=Cl(o,0,B),b=d.concat(p)}else null!=r.validationSteps&&(y=!0);const v=a.concat(o).concat(f);i.checkTrainableWeightsConsistency();const w=i.makeTrainFunction(),S=i.getDedupedMetricsNames();let I,k;y?(i.makeTestFunction(),I=i.testFunction,k=S.slice().concat(S.map(B=>"val_"+B))):(I=null,b=[],k=S.slice());const D=r0(r.callbacks,r.yieldEvery);return yield i.fitLoop(w,v,S,g,r.epochs,r.verbose,D,I,b,r.shuffle,k,r.initialEpoch,null,null)}finally{i.isTraining=!1,Ks(a,e),Ks(o,s),Ks(l,e),Ks(u,s),Ks(d,c),Ks(p,h),null!=f&&xt(f)}})()}fitLoop(e,s,r,i,a,o,l,u,c,h,d,p,f,g){var m=this;return(0,N.A)(function*(){null==i&&(i=32),null==a&&(a=1),null==h&&(h=!0),null==p&&(p=0);let x=!1;if(null!=u&&null!=c&&(x=!0),null!=g&&(x=!0,null==f))throw new z("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const y=m.checkNumSamples(s,i,f,"steps_per_epoch");let b;null!=y&&(b=Gs(0,y)),null==o&&(o=1);const{callbackList:v,history:w}=a0(l,o,a,p,y,f,i,x,d);v.setModel(m),m.history=w,yield v.onTrainBegin(),m.stopTraining_=!1;for(let S=p;S{const Y=D[P][0],Q=D[P][1],ee=Wi(k,Y,Q-Y);B.batch=P,B.size=Q-Y;const J=cm(s,ee),se=e(J);for(let ae=0;aeRr(s))}else{const s=Object.keys(this.loss);e={};const r=this.loss;for(const i of s){if("string"!=typeof r[i])throw new Error("Serialization of non-string loss is not supported.");e[i]=Rr(r[i])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Rr(Uc(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Rr(Uc(e)));{const e={};for(const s in this.metrics)e[s]=Rr(Uc(this.metrics[s]));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 r=$r(sm(e.optimizer_config));let i,a;if("string"==typeof e.loss)i=zi(e.loss);else if(Array.isArray(e.loss))i=e.loss.map(o=>zi(o));else if(null!=e.loss){i={};for(const o in e.loss)i[o]=zi(e.loss[o])}if(Array.isArray(e.metrics))a=e.metrics.map(o=>zi(o));else if(null!=e.metrics){a={};for(const o in e.metrics)a[o]=zi(e.metrics[o])}this.compile({loss:i,metrics:a,optimizer:r})}save(e,s){var r=this;return(0,N.A)(function*(){if("string"==typeof e){const h=(n=>sn.getSaveHandlers(n))(e);if(0===h.length)throw new z(`Cannot find any save handlers for URL '${e}'`);if(h.length>1)throw new z(`Found more than one (${h.length}) save handlers for URL '${e}'`);e=h[0]}if(null==e.save)throw new z("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const i=yield vx(r.getNamedWeights(s)),u={modelTopology:r.toJSON(null,!1),format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.22.0",convertedBy:null};if(null!=s&&s.includeOptimizer&&null!=r.optimizer){u.trainingConfig=r.getTrainingConfig();const h="optimizer",{data:d,specs:p}=yield vx(yield r.optimizer.getWeights(),h);i.specs.push(...p),i.data=function CS(n){return er.join(n)}([i.data,d])}return null!=r.userDefinedMetadata&&(f0(r.userDefinedMetadata,r.name,!0),u.userDefinedMetadata=r.userDefinedMetadata),u.weightData=i.data,u.weightSpecs=i.specs,e.save(u)})()}setUserDefinedMetadata(e){f0(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}return n.className="Model",n})();pe(Ia),pe((()=>{class n extends Ia{}return n.className="Functional",n})());let I0=(()=>{class n extends Ia{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:Ec("sequential_"),null!=e.layers)for(const s of e.layers)this.add(s)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(r=>r<0))throw new z(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const s=e instanceof n||e instanceof Ia;let r;if(s){if(r=e,1!==r.outputs.length)throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==r.inputs.length)throw new z("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 z("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const i=function Jb(n){if(null==n.batchShape&&null==n.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!=n.batchShape&&null!=n.shape)throw new z("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=n.batchShape;null!=n.shape&&null==t&&(t=[null].concat(n.shape));let e=n.dtype;return null==e&&(e="float32"),new wl({batchInputShape:t,name:n.name,dtype:e,sparse:n.sparse}).inboundNodes[0].outputTensors[0]}({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(i)}if(s)this.outputs=r.outputs,this.inputs=r.inputs;else{if(1!==e.inboundNodes.length)throw new z(`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 z("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=Qb(this.outputs[0])}this.inboundNodes=[],new Dc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Vi(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(i=>i.shape),outputShapes:this.outputs[0].shape})}else{const i=e.apply(this.outputs[0]);if(Array.isArray(i))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=[i],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,s){return null==this.model&&this.build(),this.model.call(e,s)}build(e){if(At(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 Ia({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,s,r=console.log){this.built||this.build(),super.summary(e,s,r)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,s,r={}){if(!this.built)throw new Rs("The model needs to be compiled before being used.");return this.model.evaluate(e,s,r)}evaluateDataset(e,s){var r=this;return(0,N.A)(function*(){if(!r.built)throw new Rs("The model needs to be compiled before being used.");return r.model.evaluateDataset(e,s)})()}predict(e,s={}){return null==this.model&&this.build(),this.model.predict(e,s)}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}fit(e,s,r={}){var i=this;return(0,N.A)(function*(){if(!i.built)throw new Rs("The model needs to be compiled before being used.");return i.model.fit(e,s,r)})()}fitDataset(e,s){var r=this;return(0,N.A)(function*(){if(!r.built)throw new Rs("The model needs to be compiled before being used.");return r.model.fitDataset(e,s)})()}trainOnBatch(e,s){var r=this;return(0,N.A)(function*(){return r.model.trainOnBatch(e,s)})()}static fromConfig(e,s,r={},i=!1){let a,o={};if(s instanceof Array){if(null==s[0].className||"Merge"===s[0].className)throw new z("Legacy serialization format not supported yet.");a=s}else T(null!=s.layers,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),a=s.layers,delete s.layers,o=s;const l=new e(o);if(!(l instanceof n))throw new dt(`Sequential.fromConfig called on non-Sequential input: ${l}`);for(const u of a){const h=$r(u,void 0,i);i&&h.setFastWeightInitDuringBuild(!0),l.add(h)}return l}set stopTraining(e){if(null==this.model)throw new z("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 z("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const s of this.layers){const r={};r.className=s.getClassName(),r.config=s.getConfig(),e.push(r)}return{name:this.name,layers:e}}}return n.className="Sequential",n})();pe(I0);class Wn extends ma{getConfig(){return{}}}pe((()=>{class n extends Wn{apply(e,s=1){return function C$(n,t=1){if(1!==t)throw new dt(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return uc(n)}(e,s)}}return n.className="elu",n})()),pe((()=>{class n extends Wn{apply(e){return yy(e)}}return n.className="selu",n})()),pe((()=>{class n extends Wn{apply(e){return Er(e)}}return n.className="relu",n})()),pe((()=>{class n extends Wn{apply(e){return Z(()=>ya(6,Er(e)))}}return n.className="relu6",n})()),pe((()=>{class n extends Wn{apply(e){return e}}return n.className="linear",n})()),pe((()=>{class n extends Wn{apply(e){return ba(e)}}return n.className="sigmoid",n})()),pe((()=>{class n extends Wn{apply(e){return function E$(n){return Z(()=>{const t=me(.5,L(.2,n));return gs(t,0,1)})}(e)}}return n.className="hardSigmoid",n})()),pe((()=>{class n extends Wn{apply(e){return ul(e)}}return n.className="softplus",n})()),pe((()=>{class n extends Wn{apply(e){return function I$(n){return Z(()=>je(n,me(kn(n),1)))}(e)}}return n.className="softsign",n})()),pe((()=>{class n extends Wn{apply(e){return pc(e)}}return n.className="tanh",n})());let E0=(()=>{class n extends Wn{apply(e,s=-1){return ef(e,s)}}return n.className="softmax",n})();function ri(n){return n.getClassName()}function gm(n,t={}){return gl(n,Es.getMap().classNameMap,t,"activation")}function ii(n){if(null==n){return gm({className:"linear",config:{}})}if("string"==typeof n){const t={};return t.className=n,t.config={},gm(t)}return n instanceof Wn?n:gm(n)}pe(E0),pe((()=>{class n extends Wn{apply(e,s=-1){return my(e,s)}}return n.className="logSoftmax",n})()),pe((()=>{class n extends Wn{apply(e){return Z(()=>Z(()=>{const s=Math.sqrt(2),r=L(.5,me(1,py(je(e,s))));return L(e,r)}))}}return n.className="gelu",n})()),pe((()=>{class n extends Wn{apply(e){return Z(()=>L(.5,L(e,me(1,pc(L(zn(je(2,Math.PI)),me(e,L(.044715,Ri(e,3)))))))))}}return n.className="gelu_new",n})()),pe((()=>{class n extends Wn{apply(e){return Z(()=>L(e,pc(ul(e))))}}return n.className="mish",n})()),pe((()=>{class n extends Wn{apply(e,s=1){return Z(()=>L(ba(L(e,s)),e))}}return n.className="swish",n})());class k0 extends ma{}pe((()=>{class n extends k0{constructor(e){super(),function xm(n){if(null!=n&&"object"!=typeof n)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${n}`)}(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 Z(()=>{let s=Rn([1]);return this.hasL1&&(s=me(s,Ge(L(this.l1,kn(e))))),this.hasL2&&(s=me(s,Ge(L(this.l2,bl(e))))),j(s,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,s){return new e({l1:s.l1,l2:s.l2})}}return n.className="L1L2",n})());const N0={l1l2:"L1L2"};function Gt(n){return Bf(n)}function A0(n,t={}){return gl(n,Es.getMap().classNameMap,t,"regularizer")}function tn(n){return null==n?null:"string"==typeof n?A0({className:n in N0?N0[n]:n,config:{}}):n instanceof k0?n:A0(n)}function Ea(n,t,e){if("number"==typeof n)return Vi(n,t);if(n.length!==t)throw new z(`The ${e} argument must be an integer or tuple of ${t} integers. Received: ${n.length} elements.`);for(let s=0;s(fn(t),"channelsFirst"===t?kt(n,[0,2,3,1]):n))}function L0(n,t){return Z(()=>(fn(t),"channelsFirst"===t?kt(n,[0,2,3,4,1]):n))}function vm(n,t,e,s=[1,1],r="valid",i,a,o=null){return Z(()=>{if(null==i&&(i="channelsLast"),fn(i),3!==n.rank&&4!==n.rank)throw new z(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${n.rank}.`);if(3!==t.rank&&4!==t.rank)throw new z(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${n.rank}.`);let l=bm(n,i);if("causal"===r)throw new dt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=BE({x:l,filter:t,strides:s,pad:"same"===r?"same":"valid",dilations:a,dataFormat:"NHWC",bias:e,activation:o}),"channelsFirst"===i&&(l=kt(l,[0,3,1,2])),l})}pe((()=>{class n extends wt{constructor(e){super(e??{}),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,s){e=ot(e);let r=Er(e);return null!=this.maxValue&&(r=gs(r,0,this.maxValue)),r}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},s=super.getConfig();return Object.assign(e,s),e}}return n.className="ReLU",n})()),pe((()=>{class n extends wt{constructor(e){super(e??{}),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,s){const r=ot(e);return Up(r,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},s=super.getConfig();return Object.assign(e,s),e}}return n.className="LeakyReLU",n})()),pe((()=>{class n extends wt{constructor(e){if(super(e??{}),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=en(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=tn(e.alphaRegularizer),this.alphaConstraint=Tn(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 z(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const s=(e=At(e)).slice(1);if(null!=this.sharedAxes)for(const i of this.sharedAxes)s[i-1]=1;this.alpha=this.addWeight("alpha",s,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const r={};if(null!=this.sharedAxes)for(let i=1;i{class n extends wt{constructor(e){if(super(e??{}),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new dt(`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,s){const r=ot(e);return uc(r)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},s=super.getConfig();return Object.assign(e,s),e}}return n.className="ELU",n})()),pe((()=>{class n extends wt{constructor(e){super(e??{}),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,s){const r=ot(e);return L(r,ke(ys(r,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},s=super.getConfig();return Object.assign(e,s),e}}return n.className="ThresholdedReLU",n})()),pe((()=>{class n extends wt{constructor(e){super(e??{}),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new E0).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,s){return Z(()=>{let r=ot(e);const i=s.mask;if(null!=i){const a=L(ze(Ir(r.shape),ke(i,r.dtype)),ut(-1e9));r=me(r,a)}return this.axis instanceof Array?this.axis.length>1?xs(ze(r,Hp(r,this.axis,!0))):this.softmax(r,this.axis[0]):this.softmax(r,this.axis)})}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},s=super.getConfig();return Object.assign(e,s),e}}return n.className="Softmax",n})());class Gc extends wt{constructor(t,e){if(super(e),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Gc.verifyArgs(e),this.rank=t,$n(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new dt(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Ea(e.kernelSize,t,"kernelSize"),this.strides=Ea(null==e.strides?1:e.strides,t,"strides"),this.padding=null==e.padding?"valid":e.padding,ws(this.padding),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,fn(this.dataFormat),this.activation=ii(e.activation),this.useBias=null==e.useBias||e.useBias,this.biasInitializer=en(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Tn(e.biasConstraint),this.biasRegularizer=tn(e.biasRegularizer),this.activityRegularizer=tn(e.activityRegularizer),this.dilationRate=Ea(null==e.dilationRate?1:e.dilationRate,t,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new z(`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 z(`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 z(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(t){if(vs("kernelSize"in t,"required key 'kernelSize' not in config"),"number"!=typeof t.kernelSize&&!Wf(t.kernelSize,"number",1,3))throw new z(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(t.kernelSize)}.`)}getConfig(){const t={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:ri(this.activation),useBias:this.useBias,biasInitializer:an(this.biasInitializer),biasRegularizer:Gt(this.biasRegularizer),activityRegularizer:Gt(this.activityRegularizer),biasConstraint:_n(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}}class ka extends Gc{constructor(t,e){super(t,e),this.kernel=null,ka.verifyArgs(e),this.filters=e.filters,$n(this.filters,"filters"),this.kernelInitializer=en(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Tn(e.kernelConstraint),this.kernelRegularizer=tn(e.kernelRegularizer)}build(t){t=At(t);const e="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[e])throw new z(`The channel dimension of the input should be defined. Found ${t[e]}`);const s=t[e],r=this.kernelSize.concat([s,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:{[e]:s}}],this.built=!0}call(t,e){return Z(()=>{let s;t=ot(t);const r=null==this.bias?null:this.bias.read(),i=Rb(this.activation.getClassName());if(null!=i&&2===this.rank)s=vm(t,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(1===this.rank)s=function M0(n,t,e,s=1,r="valid",i,a=1){return Z(()=>{if(null==i&&(i="channelsLast"),fn(i),3!==n.shape.length)throw new z(`The input of a conv1dWithBias operation should be 3, but is ${n.shape.length} instead.`);if(3!==t.shape.length)throw new z(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=e&&1!==e.shape.length)throw new z(`The bias for a conv1dWithBias operation should be 1, but is ${e.shape.length} instead`);if("channelsFirst"===i&&(n=kt(n,[0,2,1])),"causal"===r)throw new dt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=uy(n,t,s,"same"===r?"same":"valid","NWC",a);return null!=e&&(o=js(o,e)),o})}(t,this.kernel.read(),r,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)s=vm(t,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new dt("convolutions greater than 3D are not implemented yet.");s=function V0(n,t,e,s=[1,1,1],r="valid",i,a){return Z(()=>{if(null==i&&(i="channelsLast"),fn(i),4!==n.rank&&5!==n.rank)throw new z(`conv3dWithBias expects input to be of rank 4 or 5, but received ${n.rank}.`);if(4!==t.rank&&5!==t.rank)throw new z(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${n.rank}.`);let o=L0(n,i);if("causal"===r)throw new dt("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=mI(o,t,s,"same"===r?"same":"valid","NDHWC",a),null!=e&&(o=js(o,e)),"channelsFirst"===i&&(o=kt(o,[0,4,1,2,3])),o})}(t,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(s=this.activation.apply(s))}return s})}computeOutputShape(t){t=At(t);const e=[],s="channelsLast"===this.dataFormat?t.slice(1,t.length-1):t.slice(2);for(let i=0;i 0 but got ${JSON.stringify(t.filters)}`)}}let wm=(()=>{class n extends ka{constructor(e){super(2,e),n.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!Wf(e.kernelSize,"number",1,2))throw new z(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}return n.className="Conv2D",n})();pe(wm);let _m=(()=>{class n extends ka{constructor(e){super(3,e),n.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 z(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}return n.className="Conv3D",n})();pe(_m),pe((()=>{class n extends wm{constructor(e){if(super(e),this.inputSpec=[new wn({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new z(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=At(e)).length)throw new z("Input should have rank 4; Received input shape: "+JSON.stringify(e));const s="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[s])throw new z("The channel dimension of the inputs should be defined. Found `None`.");const r=e[s],i=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",i,"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 wn({ndim:4,axes:{[s]:r}})],this.built=!0}call(e,s){return Z(()=>{let r=ot(e);if(4!==r.shape.length)throw new z(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);const i=r.shape;let o,l;"channelsFirst"===this.dataFormat?(o=2,l=3):(o=1,l=2);const c=i[l],d=this.kernelSize[1],f=this.strides[1],x=[i[0],fr(i[o],this.strides[0],this.kernelSize[0],this.padding),fr(c,f,d,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(r=kt(r,[0,2,3,1]));let y=cy(r,this.kernel.read(),x,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=kt(y,[0,3,1,2])),null!=this.bias&&(y=js(y,this.bias.read(),this.dataFormat)),null!=this.activation&&(y=this.activation.apply(y)),y})}computeOutputShape(e){const s=(e=At(e)).slice();let r,i,a;"channelsFirst"===this.dataFormat?(r=1,i=2,a=3):(r=3,i=1,a=2);const o=this.kernelSize[0],l=this.kernelSize[1],u=this.strides[0],c=this.strides[1];return s[r]=this.filters,s[i]=fr(s[i],u,o,this.padding),s[a]=fr(s[a],c,l,this.padding),s}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}return n.className="Conv2DTranspose",n})()),pe((()=>{class n extends _m{constructor(e){if(super(e),this.inputSpec=[new wn({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new z(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=At(e)).length)throw new z("Input should have rank 5; Received input shape: "+JSON.stringify(e));const s="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[s])throw new z("The channel dimension of the inputs should be defined. Found `None`.");const r=e[s],i=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",i,"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 wn({ndim:5,axes:{[s]:r}})],this.built=!0}call(e,s){return Z(()=>{let r=ot(e);if(5!==r.shape.length)throw new z(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);const i=r.shape;let o,l,u;"channelsFirst"===this.dataFormat?(u=2,o=3,l=4):(u=1,o=2,l=3);const h=i[o],d=i[l],f=this.kernelSize[1],g=this.kernelSize[2],x=this.strides[1],y=this.strides[2],S=[i[0],fr(i[u],this.strides[0],this.kernelSize[0],this.padding),fr(h,x,f,this.padding),fr(d,y,g,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(r=kt(r,[0,2,3,4,1]));let I=yI(r,this.kernel.read(),S,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(I=kt(I,[0,4,1,2,3])),null!==this.bias&&(I=js(I,this.bias.read(),this.dataFormat)),null!==this.activation&&(I=this.activation.apply(I)),I})}computeOutputShape(e){const s=(e=At(e)).slice();let r,i,a,o;"channelsFirst"===this.dataFormat?(r=1,i=2,a=3,o=4):(r=4,i=1,a=2,o=3);const l=this.kernelSize[0],u=this.kernelSize[1],c=this.kernelSize[2],h=this.strides[0],d=this.strides[1],p=this.strides[2];return s[r]=this.filters,s[i]=fr(s[i],h,l,this.padding),s[a]=fr(s[a],d,u,this.padding),s[o]=fr(s[o],p,c,this.padding),s}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}return n.className="Conv3DTranspose",n})());let BD=(()=>{class n extends ka{constructor(e,s){if(super(e,s),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==s.filters)throw new z("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=s.kernelInitializer||null!=s.kernelRegularizer||null!=s.kernelConstraint)throw new z("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=s.padding&&"same"!==s.padding&&"valid"!==s.padding)throw new z(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(s.padding)}`);this.depthMultiplier=null==s.depthMultiplier?1:s.depthMultiplier,this.depthwiseInitializer=en(s.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=tn(s.depthwiseRegularizer),this.depthwiseConstraint=Tn(s.depthwiseConstraint),this.pointwiseInitializer=en(s.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=tn(s.pointwiseRegularizer),this.pointwiseConstraint=Tn(s.pointwiseConstraint)}build(e){if((e=At(e)).length{let r;if(e=ot(e),1===this.rank)throw new dt("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=kt(e,[0,2,3,1])),r=by(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(r=js(r,this.bias.read(),this.dataFormat)),null!=this.activation&&(r=this.activation.apply(r)),"channelsFirst"===this.dataFormat&&(r=kt(r,[0,3,1,2])),r})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=an(this.depthwiseInitializer),e.pointwiseInitializer=an(this.pointwiseInitializer),e.depthwiseRegularizer=Gt(this.depthwiseRegularizer),e.pointwiseRegularizer=Gt(this.pointwiseRegularizer),e.depthwiseConstraint=_n(this.depthwiseConstraint),e.pointwiseConstraint=_n(this.pointwiseConstraint),e}}return n.className="SeparableConv",n})();function X0(n,t,e,s){if(Array.isArray(n)){if(null!=t||null!=e)throw new z("When inputs is an array, neither initialState or constants should be provided");null!=s&&(e=n.slice(n.length-s,n.length),n=n.slice(0,n.length-s)),n.length>1&&(t=n.slice(1,n.length)),n=n[0]}function r(i){return null==i||Array.isArray(i)?i:[i]}return{inputs:n,initialState:t=r(t),constants:e=r(e)}}function K0(n,t,e,s=!1,r,i,a=!1,o=!1){return Z(()=>{const l=t.shape.length;if(l<3)throw new z(`Input should be at least 3D, but is ${l}D.`);const u=[1,0].concat(Gs(2,l));if(t=kt(t,u),null!=i)throw new dt("The rnn() functoin of the deeplearn.js backend does not support constants yet.");a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=r&&((r=ke(ke(r,"bool"),"float32")).rank===l-1&&(r=Zn(r,-1)),r=kt(r,u)),s&&(t=Fi(t,0),null!=r&&(r=Fi(r,0)));const c=[];let h,d=e;const p=t.shape[0],f=Li(t);let g,m;null!=r&&(g=Li(r));for(let x=0;xn(y,d));if(null==r)h=b[0],d=b[1];else{const v=Z(()=>{const w=g[x],S=ze(As(w),w);return{output:me(L(b[0],w),L(d[0],S)),newStates:d.map((D,P)=>me(L(b[1][P],w),L(D,S)))}});h=v.output,d=v.newStates}o&&c.push(h)}return o&&(m=ir(c,1)),[h,m,d]})}pe((()=>{class n extends BD{constructor(e){super(2,e)}}return n.className="SeparableConv2D",n})()),pe((()=>{class n extends ka{constructor(e){super(1,e),n.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&&!Wf(e.kernelSize,"number",1,1))throw new z(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}return n.className="Conv1D",n})()),pe((()=>{class n extends wt{constructor(e){super(e),this.cropping="number"==typeof e.cropping?[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]: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,s){return Z(()=>{if(e=ot(e),"channelsLast"===this.dataFormat){const r=Nc(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Nc(r,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const r=Nc(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Nc(r,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},s=super.getConfig();return Object.assign(e,s),e}}return n.className="Cropping2D",n})()),pe((()=>{class n extends wt{constructor(e){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,fn(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,function g$(n){Bi(d$,"InterpolationFormat",n)}(this.interpolation)}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],null==e[2]?null:this.size[0]*e[2],null==e[3]?null:this.size[1]*e[3]]:[e[0],null==e[1]?null:this.size[0]*e[1],null==e[2]?null:this.size[1]*e[2],e[3]]}call(e,s){return Z(()=>{let r=ot(e);const i=r.shape;if("channelsFirst"===this.dataFormat){r=kt(r,[0,2,3,1]);const a=this.size[0]*i[2],o=this.size[1]*i[3],l="nearest"===this.interpolation?ar.resizeNearestNeighbor(r,[a,o]):ar.resizeBilinear(r,[a,o]);return kt(l,[0,3,1,2])}{const a=this.size[0]*i[1],o=this.size[1]*i[2];return"nearest"===this.interpolation?ar.resizeNearestNeighbor(r,[a,o]):ar.resizeBilinear(r,[a,o])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},s=super.getConfig();return Object.assign(e,s),e}}return n.className="UpSampling2D",n})()),pe((()=>{class n extends Gc{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=en(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Tn(e.depthwiseConstraint),this.depthwiseRegularizer=tn(e.depthwiseRegularizer)}build(e){if((e=At(e)).length<4)throw new z(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const s="channelsFirst"===this.dataFormat?1:3;if(null==e[s]||e[s]<0)throw new z(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[s]}).`);const r=e[s];this.depthwiseKernel=this.addWeight("depthwise_kernel",[this.kernelSize[0],this.kernelSize[1],r,this.depthMultiplier],null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.bias=this.useBias?this.addWeight("bias",[r*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.built=!0}call(e,s){return Z(()=>{let r=function UD(n,t,e=[1,1],s="valid",r,i){return Z(()=>{null==r&&(r="channelsLast"),fn(r);let a=bm(n,r);if(4!==n.rank)throw new z(`Input for depthwiseConv2d is required to be 4-D, but is instead ${n.rank}-D`);if(4!==t.rank)throw new z(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return a=lc(a,t,e,"same"===s?"same":"valid","NHWC",i),"channelsFirst"===r&&(a=kt(a,[0,3,1,2])),a})}(e=ot(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(r=js(r,this.bias.read(),this.dataFormat)),null!=this.activation&&(r=this.activation.apply(r)),r})}computeOutputShape(e){e=At(e);const r="channelsFirst"===this.dataFormat?e[3]:e[2],i="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=qs("channelsFirst"===this.dataFormat?e[2]:e[1],this.kernelSize[0],this.padding,this.strides[0]),o=qs(r,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],i,a,o]:[e[0],a,o,i]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=an(this.depthwiseInitializer),e.depthwiseRegularizer=Gt(this.depthwiseRegularizer),e.depthwiseConstraint=_n(this.depthwiseRegularizer),e}}return n.className="DepthwiseConv2D",n})());let Na=(()=>{class n extends wt{constructor(e){let s;if(super(e),null==e.cell)throw new z("cell property is missing for the constructor of RNN.");if(s=Array.isArray(e.cell)?new Cm({cells:e.cell}):e.cell,null==s.stateSize)throw new z("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=s,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 wn({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){return null==this.states_?Gs(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(s=>null):this.states_}setStates(e){this.states_=e}computeOutputShape(e){Kf(e)&&(e=e[0]);let s=this.cell.stateSize;Array.isArray(s)||(s=[s]);const r=s[0];let i;if(i=this.returnSequences?[e[0],e[1],r]:[e[0],r],this.returnState){const a=[];for(const o of s)a.push([e[0],o]);return[i].concat(a)}return i}computeMask(e,s){return Z(()=>{Array.isArray(s)&&(s=s[0]);const r=this.returnSequences?s:null;if(this.returnState){const i=this.states.map(a=>null);return[r].concat(i)}return r})}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,s=[];for(let r=0;rl.shape[l.shape.length-1]),o))throw new z(`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=o.map(l=>new wn({shape:[null,l]}));this.stateful&&this.resetStates()}resetStates(e,s=!1){Z(()=>{if(!this.stateful)throw new ur("Cannot call resetStates() on an RNN Layer that is not stateful.");const r=this.inputSpec[0].shape[0];if(null==r)throw new z("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_)this.states_=Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(i=>Rn([r,i])):[Rn([r,this.cell.stateSize])];else if(null==e)xt(this.states_),null!=this.keptStates&&(xt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(i=>Rn([r,i])):this.states_[0]=Rn([r,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===s?this.keptStates.push(this.states_.slice()):xt(this.states_);for(let i=0;inr(i.clone()))})}apply(e,s){let r=null==s?null:s.initialState,i=null==s?null:s.constants;null==s&&(s={});const a=X0(e,r,i,this.numConstants);e=a.inputs,r=a.initialState,i=a.constants;let o=[],l=[];if(null!=r){s.initialState=r,o=o.concat(r),this.stateSpec=[];for(const c of r)this.stateSpec.push(new wn({shape:c.shape}));l=l.concat(this.stateSpec)}if(null!=i&&(s.constants=i,o=o.concat(i),this.numConstants=i.length),o[0]instanceof pr){const c=[e].concat(o),h=this.inputSpec.concat(l),d=this.inputSpec;this.inputSpec=h;const p=super.apply(c,s);return this.inputSpec=d,p}return super.apply(e,s)}call(e,s){return Z(()=>{const r=null==s?null:s.mask,i=null==s?null:s.training;let a=null==s?null:s.initialState;e=ot(e),null==a&&(a=this.stateful?this.states_:this.getInitialState(e));const o=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==o)throw new z(`RNN Layer has ${o} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const l={training:i},c=K0((g,m)=>{const x=this.cell.call([g].concat(m),l);return[x[0],x.slice(1)]},e,a,this.goBackwards,r,null,this.unroll,this.returnSequences),h=c[0],d=c[1],p=c[2];this.stateful&&this.resetStates(p,i);const f=this.returnSequences?d:h;return this.returnState?[f].concat(p):f})}getInitialState(e){return Z(()=>{let s=Rn(e.shape);return s=Ge(s,[1,2]),s=yl(s),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(r=>r>1?jf(s,[1,r]):s):this.cell.stateSize>1?[jf(s,[1,this.cell.stateSize])]:[s]})}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(),s={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(s.numConstants=this.numConstants);const r=this.cell.getConfig();return this.getClassName()===n.className&&(s.cell={className:this.cell.getClassName(),config:r}),Object.assign(Object.assign(Object.assign({},r),e),s)}static fromConfig(e,s,r={}){const a=$r(s.cell,r);return new e(Object.assign(s,{cell:a}))}}return n.className="RNN",n})();pe(Na);class Hc extends wt{}let Tm=(()=>{class n extends Hc{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,$n(this.units,"units"),this.activation=ii(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=en(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=en(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=en(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=tn(e.kernelRegularizer),this.recurrentRegularizer=tn(e.recurrentRegularizer),this.biasRegularizer=tn(e.biasRegularizer),this.kernelConstraint=Tn(e.kernelConstraint),this.recurrentConstraint=Tn(e.recurrentConstraint),this.biasConstraint=Tn(e.biasConstraint),this.dropout=Sa([1,ti([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Sa([1,ti([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=At(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.bias=this.useBias?this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.built=!0}call(e,s){return Z(()=>{if(2!==e.length)throw new z(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let r=e[1];e=e[0];const i=null!=s.training&&s.training;let a;0As(e),rate:this.dropout,training:i,dropoutFunc:this.dropoutFunc})),0As(r),rate:this.recurrentDropout,training:i,dropoutFunc:this.dropoutFunc}));const o=this.dropoutMask,l=this.recurrentDropoutMask;a=hr(null!=o?L(e,o):e,this.kernel.read()),null!=this.bias&&(a=js(a,this.bias.read())),null!=l&&(r=L(r,l));let u=me(a,hr(r,this.recurrentKernel.read()));return null!=this.activation&&(u=this.activation.apply(u)),[u,u]})}getConfig(){const e=super.getConfig(),s={units:this.units,activation:ri(this.activation),useBias:this.useBias,kernelInitializer:an(this.kernelInitializer),recurrentInitializer:an(this.recurrentInitializer),biasInitializer:an(this.biasInitializer),kernelRegularizer:Gt(this.kernelRegularizer),recurrentRegularizer:Gt(this.recurrentRegularizer),biasRegularizer:Gt(this.biasRegularizer),activityRegularizer:Gt(this.activityRegularizer),kernelConstraint:_n(this.kernelConstraint),recurrentConstraint:_n(this.recurrentConstraint),biasConstraint:_n(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),s)}}return n.className="SimpleRNNCell",n})();pe(Tm),pe((()=>{class n extends Na{constructor(e){e.cell=new Tm(e),super(e)}call(e,s){return Z(()=>(null!=this.cell.dropoutMask&&(xt(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(xt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),super.call(e,{mask:null==s?null:s.mask,training:null==s?null:s.training,initialState:null==s?null:s.initialState})))}static fromConfig(e,s){return new e(s)}}return n.className="SimpleRNN",n})());let Sm=(()=>{class n extends Hc{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 z("GRUCell does not support reset_after parameter set to true.");this.units=e.units,$n(this.units,"units"),this.activation=ii(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ii(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=en(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=en(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=en(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=tn(e.kernelRegularizer),this.recurrentRegularizer=tn(e.recurrentRegularizer),this.biasRegularizer=tn(e.biasRegularizer),this.kernelConstraint=Tn(e.kernelConstraint),this.recurrentConstraint=Tn(e.recurrentConstraint),this.biasConstraint=Tn(e.biasConstraint),this.dropout=Sa([1,ti([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Sa([1,ti([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){e=At(e),this.kernel=this.addWeight("kernel",[e[e.length-1],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.bias=this.useBias?this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.built=!0}call(e,s){return Z(()=>{if(2!==e.length)throw new z(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const r=null!=s.training&&s.training;let i=e[1];e=e[0],0As(e),rate:this.dropout,training:r,count:3,dropoutFunc:this.dropoutFunc})),0As(i),rate:this.recurrentDropout,training:r,count:3,dropoutFunc:this.dropoutFunc}));const o=this.recurrentDropoutMask;let l,u,c;0{class n extends Na{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Sm(e),super(e)}call(e,s){return Z(()=>(null!=this.cell.dropoutMask&&(xt(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(xt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),super.call(e,{mask:null==s?null:s.mask,training:null==s?null:s.training,initialState:null==s?null:s.initialState})))}static fromConfig(e,s){return 0===s.implmentation&&(s.implementation=1),new e(s)}}return n.className="GRU",n})());let jc=(()=>{class n extends Hc{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,$n(this.units,"units"),this.activation=ii(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ii(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=en(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=en(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=en(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=tn(e.kernelRegularizer),this.recurrentRegularizer=tn(e.recurrentRegularizer),this.biasRegularizer=tn(e.biasRegularizer),this.kernelConstraint=Tn(e.kernelConstraint),this.recurrentConstraint=Tn(e.recurrentConstraint),this.biasConstraint=Tn(e.biasConstraint),this.dropout=Sa([1,ti([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Sa([1,ti([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 s;let i;if(e=At(e),this.kernel=this.addWeight("kernel",[e[e.length-1],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 a=this.biasInitializer,o=this.units;i=new((s=class extends Ds{apply(u,c){const h=a.apply([o]),d=(new Ub).apply([o]),p=a.apply([2*o]);return Vb(Vb(h,d),p)}}).className="CustomInit",s)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,i,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,s){return Z(()=>{const r=null!=s.training&&s.training;if(3!==e.length)throw new z(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let i=e[1];const a=e[2];e=e[0],0As(e),rate:this.dropout,training:r,count:4,dropoutFunc:this.dropoutFunc})),0As(i),rate:this.recurrentDropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));const l=this.recurrentDropoutMask;let u,c,h,d;0{class n extends Na{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new jc(e),super(e)}call(e,s){return Z(()=>(null!=this.cell.dropoutMask&&(xt(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(xt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),super.call(e,{mask:null==s?null:s.mask,training:null==s?null:s.training,initialState:null==s?null:s.initialState})))}static fromConfig(e,s){return 0===s.implmentation&&(s.implementation=1),new e(s)}}return n.className="LSTM",n})());let Cm=(()=>{class n extends Hc{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const s of this.cells.slice().reverse())Array.isArray(s.stateSize)?e.push(...s.stateSize):e.push(s.stateSize);return e}call(e,s){return Z(()=>{let r=e.slice(1);const i=[];for(const l of this.cells.slice().reverse())Array.isArray(l.stateSize)?i.push(r.splice(0,l.stateSize.length)):i.push(r.splice(0,1));i.reverse();const a=[];let o;for(let l=0;l{Ui(`RNNCell_${i}`,()=>{r.build(e),s=Array.isArray(r.stateSize)?r.stateSize[0]:r.stateSize,e=[e[0],s]})}),this.built=!0}getConfig(){const e=super.getConfig(),i={cells:this.cells.map(a=>({className:a.getClassName(),config:a.getConfig()}))};return Object.assign(Object.assign({},e),i)}static fromConfig(e,s,r={}){const i=[];for(const a of s.cells)i.push($r(a,r));return new e({cells:i})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const s of this.cells)e.push(...s.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const s of this.cells)e.push(...s.nonTrainableWeights);if(!this.trainable){const s=[];for(const r of this.cells)s.push(...r.trainableWeights);return s.concat(e)}return e}getWeights(){const e=[];for(const s of this.cells)e.push(...s.weights);return qf(e)}setWeights(e){const s=[];for(const r of this.cells){const a=e.splice(r.weights.length);for(let o=0;onull!=i?i(t(),e):Bb(t(),e),o=()=>vl(a,t,s);return!r||r<=1?nr(o().clone()):Array(r).fill(void 0).map(o).map(u=>nr(u.clone()))}pe(Cm);let GD=(()=>{class n extends Na{constructor(e){if(e.unroll)throw new dt("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new dt("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new wn({ndim:5})]}call(e,s){return Z(()=>{if(null!=this.cell.dropoutMask&&(xt(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(xt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),s&&s.constants)throw new z("ConvRNN2D cell does not support constants");return super.call(e,{mask:null==s?null:s.mask,training:null==s?null:s.training,initialState:null==s?null:s.initialState})})}computeOutputShape(e){let s=this.computeSingleOutputShape(e);return this.returnSequences||(s=[s[0],...s.slice(2)]),this.returnState&&(s=[s,...Array(2).fill([e[0],...s.slice(-3)])]),s}getInitialState(e){return Z(()=>{const{stateSize:s}=this.cell,i=this.computeSingleOutputShape(e.shape),o=Rn([i[0],...i.slice(2)]);return Array.isArray(s)?Array(s.length).fill(o):[o]})}resetStates(e,s=!1){Z(()=>{if(!this.stateful)throw new ur("Cannot call resetStates() on an RNN Layer that is not stateful.");const r=this.inputSpec[0].shape,i=this.computeSingleOutputShape(r),a=[i[0],...i.slice(2)];if(null==r[0])throw new z("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())this.states_=Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(()=>Rn(a)):[Rn(a)];else if(null==e)xt(this.states_),null!=this.keptStates&&(xt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Rn(a)):this.states_[0]=Rn(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);s?this.keptStates.push(this.states_.slice()):xt(this.states_);for(let l=0;lnr(l.clone()))})}computeSingleOutputShape(e){const{dataFormat:s,filters:r,kernelSize:i,padding:a,strides:o,dilationRate:l}=this.cell,u="channelsFirst"===s,h=e[u?4:3],d=qs(e[u?3:2],i[0],a,o[0],l[0]),p=qs(h,i[1],a,o[1],l[1]);return[...e.slice(0,2),...u?[r,d,p]:[d,p,r]]}}return n.className="ConvRNN2D",n})(),Im=(()=>{class n extends jc{constructor(e){const{filters:s,kernelSize:r,strides:i,padding:a,dataFormat:o,dilationRate:l}=e;super(Object.assign(Object.assign({},e),{units:s})),this.filters=s,$n(this.filters,"filters"),this.kernelSize=Ea(r,2,"kernelSize"),this.kernelSize.forEach(u=>$n(u,"kernelSize")),this.strides=Ea(i||1,2,"strides"),this.strides.forEach(u=>$n(u,"strides")),this.padding=a||"valid",ws(this.padding),this.dataFormat=o||"channelsLast",fn(this.dataFormat),this.dilationRate=Ea(l||1,2,"dilationRate"),this.dilationRate.forEach(u=>$n(u,"dilationRate"))}build(e){var s;e=At(e);const r="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[r])throw new z(`The channel dimension of the input should be defined. Found ${e[r]}`);const o=this.kernelSize.concat([e[r],4*this.filters]);this.kernel=this.addWeight("kernel",o,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const l=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",l,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let u;if(this.unitForgetBias){const c=this.biasInitializer,h=this.filters;u=new((s=class extends Ds{apply(p,f){return Hf([c.apply([h]),Ir([h]),c.apply([2*h])])}}).className="CustomInit",s)}else u=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,u,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,s){return Z(()=>{if(3!==e.length)throw new z(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const r=s.training||!1,i=e[0],a=e[1],o=e[2];0As(i),rate:this.dropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));const u=this.dropoutMask,c=(xe,Se,be)=>Se&&Se[be]?L(Se[be],xe):xe;let h=c(i,u,0),d=c(i,u,1),p=c(i,u,2),f=c(i,u,3);0As(a),rate:this.recurrentDropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));const g=this.recurrentDropoutMask;let m=c(a,g,0),x=c(a,g,1),y=c(a,g,2),b=c(a,g,3);const[w,S,I,k]=bs(this.kernel.read(),4,3),[D,P,B,Y]=this.useBias?bs(this.bias.read(),4):[null,null,null,null];h=this.inputConv(h,w,D,this.padding),d=this.inputConv(d,S,P,this.padding),p=this.inputConv(p,I,B,this.padding),f=this.inputConv(f,k,Y,this.padding);const[Q,ee,J,se]=bs(this.recurrentKernel.read(),4,3);m=this.recurrentConv(m,Q),x=this.recurrentConv(x,ee),y=this.recurrentConv(y,J),b=this.recurrentConv(b,se);const ae=this.recurrentActivation.apply(me(h,m)),te=this.recurrentActivation.apply(me(d,x)),le=me(L(te,o),L(ae,this.activation.apply(me(p,y)))),ge=L(this.recurrentActivation.apply(me(f,b)),this.activation.apply(le));return[ge,ge,le]})}getConfig(){const r=function(n,t){var e={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(null!=n&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(n);r{class n extends GD{constructor(e){const s=new Im(e);super(Object.assign(Object.assign({},e),{cell:s}))}static fromConfig(e,s){return new e(s)}}return n.className="ConvLSTM2D",n})());let Em=(()=>{class n extends wt{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 s=e.shape,r=[];for(let i=0;i{this.invokeCallHook(e,s);const r=ot(e);if(0Bb(r,this.rate,a,this.seed),()=>r,i)}return e})}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},s=super.getConfig();return Object.assign(e,s),e}dispose(){return super.dispose()}}return n.className="Dropout",n})();pe(Em),pe((()=>{class n extends Em{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const s=e.shape;return[s[0],1,s[2]]}}return n.className="SpatialDropout1D",n})());let ev=(()=>{class n extends wt{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 s=null;null!=e.batchSize&&(s=e.batchSize),this.batchInputShape=[s,e.inputDim]}this.units=e.units,$n(this.units,"units"),this.activation=ii(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=en(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=en(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Tn(e.kernelConstraint),this.biasConstraint=Tn(e.biasConstraint),this.kernelRegularizer=tn(e.kernelRegularizer),this.biasRegularizer=tn(e.biasRegularizer),this.activityRegularizer=tn(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const s=(e=At(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[s,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]:s}}],this.built=!0}computeOutputShape(e){const s=(e=At(e)).slice();return s[s.length-1]=this.units,s}call(e,s){return Z(()=>{this.invokeCallHook(e,s);const r=ot(e),i=Rb(this.activation.getClassName());let a;return null!=i?a=hr(r,this.kernel.read(),i,this.bias?this.bias.read():null):(a=hr(r,this.kernel.read()),null!=this.bias&&(a=js(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a})}getConfig(){const e={units:this.units,activation:ri(this.activation),useBias:this.useBias,kernelInitializer:an(this.kernelInitializer),biasInitializer:an(this.biasInitializer),kernelRegularizer:Gt(this.kernelRegularizer),biasRegularizer:Gt(this.biasRegularizer),activityRegularizer:Gt(this.activityRegularizer),kernelConstraint:_n(this.kernelConstraint),biasConstraint:_n(this.biasConstraint)},s=super.getConfig();return Object.assign(e,s),e}}return n.className="Dense",n})();pe(ev),pe((()=>{class n extends wt{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=At(e);for(const s of e.slice(1))if(null==s)throw new z(`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],ei(e,1)]}call(e,s){return Z(()=>{this.invokeCallHook(e,s);let r=ot(e);if("channelsFirst"===this.dataFormat&&r.rank>1){const i=[0];for(let a=2;a{class n extends wt{constructor(e){super(e),this.supportsMasking=!0,this.activation=ii(e.activation)}call(e,s){return Z(()=>{this.invokeCallHook(e,s);const r=ot(e);return this.activation.apply(r)})}getConfig(){const e={activation:ri(this.activation)},s=super.getConfig();return Object.assign(e,s),e}}return n.className="Activation",n})()),pe((()=>{class n extends wt{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,s){return Z(()=>function _$(n,t){return Z(()=>{if(2!==n.shape.length)throw new z(`repeat() expects a rank-2 tensor, but received a rank-${n.shape.length} tensor.`);return jf(yl(n,1),[1,t,1])})}(e=ot(e),this.n))}getConfig(){const e={n:this.n},s=super.getConfig();return Object.assign(e,s),e}}return n.className="RepeatVector",n})()),pe((()=>{class n extends wt{constructor(e){super(e),this.targetShape=e.targetShape;for(let s=0;s{this.invokeCallHook(e,s);const r=ot(e),i=r.shape,a=i.slice(0,1).concat(this.fixUnknownDimension(i.slice(1),this.targetShape));return j(r,a)})}getConfig(){const e={targetShape:this.targetShape},s=super.getConfig();return Object.assign(e,s),e}}return n.className="Reshape",n})()),pe((()=>{class n extends wt{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 s=Gs(1,e.dims.length+1);if(!rt(e.dims.slice().sort(),s))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 wn({ndim:this.dims.length+1})]}computeOutputShape(e){const s=(e=At(e)).slice();return this.dims.forEach((r,i)=>{s[i+1]=e[r]}),s}call(e,s){return kt(ot(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},s=super.getConfig();return Object.assign(e,s),e}}return n.className="Permute",n})()),pe((()=>{class n extends wt{constructor(e){super(e??{}),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),s={maskValue:this.maskValue};return Object.assign(s,e),s}computeMask(e,s){const r=ot(e);return Fp(il(r,this.maskValue),-1)}call(e,s){return Z(()=>{this.invokeCallHook(e,s);const r=ot(e),o=Fp(il(r,this.maskValue),-1,!0);return L(r,ke(o,r.dtype))})}}return n.className="Masking",n})()),pe((()=>{class n extends wt{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let s=null;null!=e.batchSize&&(s=e.batchSize),this.batchInputShape=null==e.inputLength?[s,null]:[s].concat(Ft(e.inputLength))}this.inputDim=e.inputDim,$n(this.inputDim,"inputDim"),this.outputDim=e.outputDim,$n(this.outputDim,"outputDim"),this.embeddingsInitializer=en(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=tn(e.embeddingsRegularizer),this.activityRegularizer=tn(e.activityRegularizer),this.embeddingsConstraint=Tn(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,s){return Z(()=>this.maskZero?(e=ot(e),il(e,Et(e))):null)}computeOutputShape(e){if(e=At(e),null==this.inputLength)return[...e,this.outputDim];const s=Ft(this.inputLength);if(s.length!==e.length-1)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let r=0;for(let i=0;i{this.invokeCallHook(e,s);let r=ot(e);"int32"!==r.dtype&&(r=cr(r,"int32"));const i=zb(this.embeddings.read(),j(r,[r.size]));return j(i,At(this.computeOutputShape(r.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:an(this.embeddingsInitializer),embeddingsRegularizer:Gt(this.embeddingsRegularizer),activityRegularizer:Gt(this.activityRegularizer),embeddingsConstraint:_n(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},s=super.getConfig();return Object.assign(e,s),e}}return n.className="Embedding",n})());class Gi extends wt{constructor(t){super(t||{}),this.supportsMasking=!0}mergeFunction(t){throw new dt}computeElementwiseOpOutputShape(t,e){if(null==t||null==e)return null;if(t.length1)throw new z(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(t)}.`);let s=null==t[0]?null:t[0].slice(1);for(let i=1;ii.length);this.reshapeRequired=-1!==t.indexOf(null)||1!==Jr(r).length}call(t,e){return Z(()=>{if(this.reshapeRequired){const s=[],r=t.map(i=>i.rank);if(-1===r.indexOf(null)){const i=ti(r);for(let a of t){const o=a.rank;for(let l=0;l1){const c=Gs(1,u).concat([0]);s.push(kt(l,c)),i=!0}else s.push(l)}let a=this.mergeFunction(s);const o=a.rank;if(i)if(null==o){const l=a.shape,c=l[l.length-1],h=[c].concat(l.slice(0,l.length-1));a=j(kt(j(a,[-1,c]),[1,0]),h)}else if(o>1){const l=[o-1].concat(Gs(0,o-1));a=kt(a,l)}return a}}return this.mergeFunction(t)})}computeOutputShape(t){let e;e=null==t[0]?null:t[0].slice(1);for(let r=1;r{if(null==e)return null;if(!Array.isArray(e))throw new z("`mask` should be an Array");if(!Array.isArray(t))throw new z("`inputs` should be an Array");if(e.length!==t.length)throw new z(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${t.length} vs ${e.length})`);if(e.every(r=>null==r))return null;let s=(e=e.map(r=>null==r?r:Zn(r,0)))[0];for(let r=1;r{let a;fn(r),Db(i),ws(s),null==e&&(e=[1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==i&&(i="max"),n=bm(n,r);const o="same"===s?"same":"valid";return a="max"===i?jp(n,t,e,o):Vp(n,t,e,o),"channelsFirst"===r&&(a=kt(a,[0,3,1,2])),a})}function mv(n,t,e,s,r,i){return Z(()=>{let a;fn(r),Db(i),ws(s),null==e&&(e=[1,1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==i&&(i="max"),n=L0(n,r);const o="same"===s?"same":"valid";return a="max"===i?WI(n,t,e,o):GC(n,t,e,o),"channelsFirst"===r&&(a=kt(a,[0,4,1,2,3])),a})}pe((()=>{class n extends Gi{constructor(e){super(e)}mergeFunction(e){return Z(()=>{let s=e[0].clone();for(let r=1;r{class n extends Gi{constructor(e){super(e)}mergeFunction(e){return Z(()=>{let s=e[0].clone();for(let r=1;r{class n extends Gi{constructor(e){super(e)}mergeFunction(e){return Z(()=>{let s=e[0].clone();for(let r=1;r{class n extends Gi{constructor(e){super(e)}mergeFunction(e){return Z(()=>{let s=e[0];for(let r=1;r{class n extends Gi{constructor(e){super(e)}mergeFunction(e){return Z(()=>{let s=e[0];for(let r=1;r{class n extends Gi{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 z("A `Concatenate` layer should be called on a list of at least 2 inputs");let s=!0;for(const i of e)if(null!=i){s=!1;break}if(s)return;const r=[];for(let i=0;i1)throw new z("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Z(()=>Hf(e,this.axis))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new z("A `Concatenate` layer should be called on a list of inputs.");const s=e,r=s[0].slice(),i=this.axis<0?r.length+this.axis:this.axis;for(const a of s.slice(1)){if(null==r[i]||null==a[i]){r[i]=null;break}r[i]+=a[i]}return r}computeMask(e,s){if(null==s)return null;if(!Array.isArray(s))throw new z("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new z("`inputs` should be an array for Concatenate");if(s.length!==e.length)throw new z(`Mismatch in the length of mask (${s.length}) and the legnth of inputs (${e.length})`);return Z(()=>{let r=!0;if(s.forEach(o=>{null==o||(r=!1)}),r)return null;const i=[];for(let o=0;o{class n extends Gi{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){T(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 s=e[0],r=e[1];if(s.length>3||r.length>3)throw new dt("Dot layer does not support tensors of 4D or higher rank yet.");const i=this.interpretAxes(s,r);if(s[i[0]]!==r[i[1]])throw new z(`Dimension incompatibility: ${s[i[0]]} !== ${r[i[1]]}`)}mergeFunction(e){if(2!==e.length)throw new z(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let i,s=e[0],r=e[1];return i=Array.isArray(this.axes)?this.axes.map((a,o)=>Il(a,e[o].shape.length)):[Il(this.axes,s.shape.length),Il(this.axes,r.shape.length)],this.normalize&&(s=Fc(s,i[0]),r=Fc(r,i[1])),function HD(n,t,e){if(n.shape.length>3||t.shape.length>3)throw new dt("batchDot is not implemented for tensors of 4D or higher rank yet");if(T(n.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${n.shape.length}`),T(n.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),"number"==typeof e&&(e=[e,e]),"complex64"===n.dtype||"complex64"===t.dtype)throw new dt("batchDot is not implemented for complex64-type Tensors yet.");const s=n.shape.length,r=t.shape.length;null==e&&(e=[s-1,r-2]);const i=e;return Z(()=>{let a,o;if(s>r){a=s-r;const l=[];for(let u=0;us){a=r-s;const l=[];for(let u=0;u0){let l;l=s>r?s+r-3:s-1;const u=[];for(let c=l;c"A `Dot` layer should be called on a list of exactly 2 inputs.");const s=e[0].slice(),r=e[1].slice();if(s.length>3||r.length>3)throw new dt("Dot layer does not support tensors of 4D or higher rank yet.");const i=this.interpretAxes(s,r);s.splice(i[0],1),r.splice(i[1],1),r.splice(0,1);const a=s.concat(r);return 1===a.length&&a.push(1),a}computeMask(e,s){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},s=super.getConfig();return Object.assign(e,s),e}}return n.className="Dot",n})()),pe((()=>{class n extends wt{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),s={stddev:this.stddev};return Object.assign(s,e),s}call(e,s){return Z(()=>{this.invokeCallHook(e,s);const r=ot(e);return vl(()=>me(Ac(r.shape,0,this.stddev),r),()=>r,s.training||!1)})}}return n.className="GaussianNoise",n})()),pe((()=>{class n extends wt{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),s={rate:this.rate};return Object.assign(s,e),s}call(e,s){return Z(()=>{this.invokeCallHook(e,s);const r=ot(e);return this.rate>0&&this.rate<1?vl(()=>{const a=Math.sqrt(this.rate/(1-this.rate));return L(r,Ac(r.shape,1,a))},()=>r,s.training||!1):r})}}return n.className="GaussianDropout",n})()),pe((()=>{class n extends wt{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||ot(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),s={rate:this.rate};return Object.assign(s,e),s}call(e,s){return Z(()=>{if(this.rate<1&&this.rate>0){const r=this._getNoiseShape(e);return vl(()=>{const a=ot(e),u=-1.7580993408473766;let c=Pi(ol(r),this.rate);c=cr(c,"float32");const h=((1-this.rate)*(1+this.rate*u**2))**-.5,d=-h*u*this.rate,p=me(L(a,c),L(me(c,-1),u));return me(L(p,h),d)},()=>ot(e),s.training||!1)}return e})}}return n.className="AlphaDropout",n})()),pe((()=>{class n extends wt{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=en(e.betaInitializer||"zeros"),this.gammaInitializer=en(e.gammaInitializer||"ones"),this.movingMeanInitializer=en(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=en(e.movingVarianceInitializer||"ones"),this.betaConstraint=Tn(e.betaConstraint),this.gammaConstraint=Tn(e.gammaConstraint),this.betaRegularizer=tn(e.betaRegularizer),this.gammaRegularizer=tn(e.gammaRegularizer)}build(e){e=At(e);const s=this.axis>=0?this.axis:this.axis+e.length,r=e[s];if(null==r)throw new z(`Axis ${s} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new wn({ndim:e.length,axes:{[s]:r}})];const i=[r];this.scale&&(this.gamma=this.addWeight("gamma",i,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",i,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",i,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",i,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,s){return Z(()=>{const r=null!=s.training&&s.training,i=ot(e),a=i.shape,o=a.length,l=Gs(0,o),u=this.axis>=0?this.axis:this.axis+o;l.splice(u,1);const c=Vi(1,o);c[u]=a[u];const h=l.slice();h.sort();const d=!rt(h,Gs(0,o).slice(0,o-1));if(!r)return(()=>{if(d){const b=j(this.movingMean.read(),c),v=j(this.movingVariance.read(),c),w=this.center?j(this.beta.read(),c):null,S=this.scale?j(this.gamma.read(),c):null;return El(i,b,v,w,S,this.epsilon)}return El(i,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[f,g,m]=function KD(n,t,e,s,r=.001){return rt(s.slice().sort(),Gs(0,n.rank-1))?function jD(n,t,e,s,r=.001){return Z(()=>{const i=Xp(n,s),a=i.mean,o=i.variance;return[El(n,a,o,e,t,r),a,o]})}(n,t,e,s,r):function XD(n,t,e,s,r=.001){return Z(()=>{const i=Xp(n,s),a=i.mean,o=i.variance,l=[];for(const f of Gs(0,n.rank))-1!==s.indexOf(f)?l.push(1):l.push(n.shape[f]);const u=j(a,l),c=j(o,l),h=null==t?null:j(t,l),d=null==e?null:j(e,l);return[El(n,u,c,d,h,r),a,o]})}(n,t,e,s,r)}(i,this.gamma.read(),this.beta.read(),l,this.epsilon),x=(b,v,w)=>{Z(()=>{const S=1-w,I=b.read(),k=L(ze(I,v),S);b.write(ze(I,k))})};return(()=>{x(this.movingMean,g,this.momentum),x(this.movingVariance,m,this.momentum)})(),f})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:an(this.betaInitializer),gammaInitializer:an(this.gammaInitializer),movingMeanInitializer:an(this.movingMeanInitializer),movingVarianceInitializer:an(this.movingVarianceInitializer),betaRegularizer:Gt(this.betaRegularizer),gammaRegularizer:Gt(this.gammaRegularizer),betaConstraint:_n(this.betaConstraint),gammaConstraint:_n(this.gammaConstraint)},s=super.getConfig();return Object.assign(e,s),e}}return n.className="BatchNormalization",n})()),pe((()=>{class n extends wt{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 s of this.axis)if(!Number.isInteger(s))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=en(e.betaInitializer||"zeros"),this.gammaInitializer=en(e.gammaInitializer||"ones"),this.betaRegularizer=tn(e.betaRegularizer),this.gammaRegularizer=tn(e.gammaRegularizer),this.supportsMasking=!0}build(e){const s=(e=At(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let a=0;a=s)throw new Error(`Invalid axis: ${a}`);if(this.axis.length!==Jr(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const r=this.axis.map(a=>e[a]),i=!0;this.gamma=this.scale?this.addWeight("gamma",r,"float32",this.gammaInitializer,this.gammaRegularizer,i):null,this.beta=this.center?this.addWeight("beta",r,"float32",this.betaInitializer,this.betaRegularizer,i):null,this.built=!0}call(e,s){const r=ot(e),i=r.shape,a=i.length;return Z(()=>{let{mean:l,variance:u}=Xp(r,this.axis,!0);const c=Vi(1,a);for(const m of this.axis)c[m]=i[m];const h=m=>null!=m&&m.shape.length!==a?j(m,c):m;let d=this.scale?h(this.gamma.read()):null,p=this.center?h(this.beta.read()):null;const f=[],g=[];for(let m=0;m{class n extends wt{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 z(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let s,r;if("number"==typeof e.padding[0])s=[e.padding[0],e.padding[0]],r=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new z(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(s=e.padding[0],2!==e.padding[1].length)throw new z(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);r=e.padding[1]}this.padding=[s,r]}this.inputSpec=[new wn({ndim:4})]}computeOutputShape(e){let s,r;return e=At(e),"channelsFirst"===this.dataFormat?(s=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,r=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],s,r]):(s=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,r=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],s,r,e[3]])}call(e,s){return Z(()=>function qD(n,t,e){return Z(()=>{if(4!==n.rank)throw new z(`temporalPadding expects input tensor to be 4-D, but received a ${n.rank}-D tensor.`);if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new z("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==e&&(e="channelsLast"),"channelsLast"!==e&&"channelsFirst"!==e)throw new z(`Unknown data format: ${e}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return s="channelsFirst"===e?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],Kp(n,s)})}(ot(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},s=super.getConfig();return Object.assign(e,s),e}}return n.className="ZeroPadding2D",n})());class gv extends wt{constructor(t){if(null==t.poolSize&&(t.poolSize=2),super(t),"number"==typeof t.poolSize)this.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new z(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.poolSize)}`);this.poolSize=t.poolSize}if($n(this.poolSize,"poolSize"),null==t.strides)this.strides=this.poolSize;else if("number"==typeof t.strides)this.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new z(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.strides)}`);this.strides=t.strides}$n(this.strides,"strides"),this.padding=null==t.padding?"valid":t.padding,ws(this.padding),this.inputSpec=[new wn({ndim:3})]}computeOutputShape(t){const e=qs((t=At(t))[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]}call(t,e){return Z(()=>{this.invokeCallHook(t,e),t=yl(ot(t),2);const s=this.poolingFunction(ot(t),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return cl(s,[2])})}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},e=super.getConfig();return Object.assign(t,e),t}}pe((()=>{class n extends gv{constructor(e){super(e)}poolingFunction(e,s,r,i,a){return fn(a),ws(i),Jc(e,s,r,i,a,"max")}}return n.className="MaxPooling1D",n})()),pe((()=>{class n extends gv{constructor(e){super(e)}poolingFunction(e,s,r,i,a){return fn(a),ws(i),Jc(e,s,r,i,a,"avg")}}return n.className="AveragePooling1D",n})());class bv extends wt{constructor(t){if(null==t.poolSize&&(t.poolSize=[2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new z(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides];$n(this.poolSize,"poolSize"),$n(this.strides,"strides"),this.padding=null==t.padding?"valid":t.padding,this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,fn(this.dataFormat),ws(this.padding),this.inputSpec=[new wn({ndim:4})]}computeOutputShape(t){t=At(t);let e="channelsFirst"===this.dataFormat?t[2]:t[1],s="channelsFirst"===this.dataFormat?t[3]:t[2];return e=qs(e,this.poolSize[0],this.padding,this.strides[0]),s=qs(s,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,s]:[t[0],e,s,t[3]]}call(t,e){return Z(()=>(this.invokeCallHook(t,e),this.poolingFunction(ot(t),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}pe((()=>{class n extends bv{constructor(e){super(e)}poolingFunction(e,s,r,i,a){return fn(a),ws(i),Jc(e,s,r,i,a,"max")}}return n.className="MaxPooling2D",n})()),pe((()=>{class n extends bv{constructor(e){super(e)}poolingFunction(e,s,r,i,a){return fn(a),ws(i),Jc(e,s,r,i,a,"avg")}}return n.className="AveragePooling2D",n})());class _v extends wt{constructor(t){if(null==t.poolSize&&(t.poolSize=[2,2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize,t.poolSize],null==t.strides)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(3!==t.strides.length)throw new z(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides,t.strides];$n(this.poolSize,"poolSize"),$n(this.strides,"strides"),this.padding=null==t.padding?"valid":t.padding,this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,fn(this.dataFormat),ws(this.padding),this.inputSpec=[new wn({ndim:5})]}computeOutputShape(t){t=At(t);let e="channelsFirst"===this.dataFormat?t[2]:t[1],s="channelsFirst"===this.dataFormat?t[3]:t[2],r="channelsFirst"===this.dataFormat?t[4]:t[3];return e=qs(e,this.poolSize[0],this.padding,this.strides[0]),s=qs(s,this.poolSize[1],this.padding,this.strides[1]),r=qs(r,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,s,r]:[t[0],e,s,r,t[4]]}call(t,e){return Z(()=>(this.invokeCallHook(t,e),this.poolingFunction(ot(t),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}pe((()=>{class n extends _v{constructor(e){super(e)}poolingFunction(e,s,r,i,a){return fn(a),ws(i),mv(e,s,r,i,a,"max")}}return n.className="MaxPooling3D",n})()),pe((()=>{class n extends _v{constructor(e){super(e)}poolingFunction(e,s,r,i,a){return fn(a),ws(i),mv(e,s,r,i,a,"avg")}}return n.className="AveragePooling3D",n})());class Cv extends wt{constructor(t){super(t),this.inputSpec=[new wn({ndim:3})]}computeOutputShape(t){return[t[0],t[2]]}call(t,e){throw new dt}}pe((()=>{class n extends Cv{constructor(e){super(e||{})}call(e,s){return Z(()=>{const r=ot(e);return pn(r,1)})}}return n.className="GlobalAveragePooling1D",n})()),pe((()=>{class n extends Cv{constructor(e){super(e||{})}call(e,s){return Z(()=>{const r=ot(e);return Ws(r,1)})}}return n.className="GlobalMaxPooling1D",n})());class kv extends wt{constructor(t){super(t),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,fn(this.dataFormat),this.inputSpec=[new wn({ndim:4})]}computeOutputShape(t){return"channelsLast"===this.dataFormat?[t[0],t[3]]:[t[0],t[1]]}call(t,e){throw new dt}getConfig(){const t={dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}pe((()=>{class n extends kv{call(e,s){return Z(()=>{const r=ot(e);return pn(r,"channelsLast"===this.dataFormat?[1,2]:[2,3])})}}return n.className="GlobalAveragePooling2D",n})()),pe((()=>{class n extends kv{call(e,s){return Z(()=>{const r=ot(e);return Ws(r,"channelsLast"===this.dataFormat?[1,2]:[2,3])})}}return n.className="GlobalMaxPooling2D",n})());class Rv extends wt{constructor(t){super(t),this.layer=t.layer}build(t){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(t){null!=this.layer&&(this.layer.trainable=t)}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(t){this.layer.setWeights(t)}getConfig(){const t={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},e=super.getConfig();return Object.assign(t,e),t}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(t)}static fromConfig(t,e,s={}){const i=$r(e.layer,s);delete e.layer;const a={layer:i};return Object.assign(a,e),new t(a)}}pe((()=>{class n extends Rv{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=At(e)).length<3)throw new z(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const s=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(s),this.layer.built=!0),super.build(e)}computeOutputShape(e){const s=[(e=At(e))[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(s);return[r[0],e[1]].concat(r.slice(1))}call(e,s){return Z(()=>K0((o,l)=>[ot(this.layer.call(o,s)),[]],e=ot(e),[],!1,null,null,!1,!0)[1])}}return n.className="TimeDistributed",n})()),pe((()=>{class n extends Rv{constructor(e){super(e);const s=e.layer.getConfig(),r={};r.className=e.layer.getClassName(),r.config=s,this.forwardLayer=$r(r),s.goBackwards=!0!==s.goBackwards;const i={};if(i.className=e.layer.getClassName(),i.config=s,this.backwardLayer=$r(i),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,function ZD(n){Bi(m$,"BidirectionalMergeMode",n)}(this.mergeMode),e.weights)throw new dt("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 r=Math.floor(e.length/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))}computeOutputShape(e){let r,i,a,s=this.forwardLayer.computeOutputShape(e);return Array.isArray(s)&&Array.isArray(s[0])||(s=[s]),this.returnState&&(a=s.slice(1)),r=s[0],"concat"===this.mergeMode?(r[r.length-1]*=2,i=[r]):i=null==this.mergeMode?[r,r.slice()]:[r],this.returnState?null==this.mergeMode?i.concat(a).concat(a.slice()):[r].concat(a).concat(a.slice()):ss(i)}apply(e,s){let r=null==s?null:s.initialState,i=null==s?null:s.constants;null==s&&(s={});const a=X0(e,r,i,this.numConstants);if(e=a.inputs,r=a.initialState,i=a.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(null==r||0===r.length)&&null==i)return super.apply(e,s);const o=[],l=[];if(null!=r){const c=r.length;if(c%2>0)throw new z("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");s.initialState=r,o.push(...r);const h=r.map(d=>new wn({shape:d.shape}));this.forwardLayer.stateSpec=h.slice(0,c/2),this.backwardLayer.stateSpec=h.slice(c/2),l.push(...h)}if(null!=i)throw new dt("Support for constants in Bidirectional layers is not implemented yet.");const u=o[0]instanceof pr;for(const c of o)if(c instanceof pr!==u)throw new z("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(u){const c=[e].concat(o),h=this.inputSpec.concat(l),d=this.inputSpec;this.inputSpec=h;const p=super.apply(c,s);return this.inputSpec=d,p}return super.apply(e,s)}call(e,s){return Z(()=>{const r=s.initialState;let i,a,o,l;if(null==r)i=this.forwardLayer.call(e,s),a=this.backwardLayer.call(e,s);else{const u=r.slice(0,r.length/2),c=r.slice(r.length/2);i=this.forwardLayer.call(e,Object.assign(s,{initialState:u})),a=this.backwardLayer.call(e,Object.assign(s,{initialState:c}))}return this.returnState&&(Array.isArray(i)&&(o=i.slice(1).concat(a.slice(1))),i=i[0],a=a[0]),this.returnSequences&&(a=Fi(a,1)),"concat"===this.mergeMode?l=Hf([i,a]):"sum"===this.mergeMode?l=me(i,a):"ave"===this.mergeMode?l=L(.5,me(i,a)):"mul"===this.mergeMode?l=L(i,a):null==this.mergeMode&&(l=[i,a]),this.returnState?null==this.mergeMode?l.concat(o):[l].concat(o):l})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Ui(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Ui(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,s){let r;if(Array.isArray(s)&&(s=s[0]),r=this.returnSequences?null==this.mergeMode?[s,s]:s:null==this.mergeMode?[null,null]:null,this.returnState){const a=this.forwardLayer.states.map(o=>null);return Array.isArray(r)?r.concat(a).concat(a):[r].concat(a).concat(a)}return r}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},s=super.getConfig();return Object.assign(e,s),e}static fromConfig(e,s){const r=$r(s.layer);if(delete s.layer,null!=s.numConstants)throw new dt("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const i=s;return i.layer=r,new e(i)}}return n.className="Bidirectional",n})()),pe((()=>{class n extends wt{constructor(e){super(e),this.scale=e.scale,this.offset=e.offset?e.offset:0}getConfig(){const e={scale:this.scale,offset:this.offset},s=super.getConfig();return Object.assign(e,s),e}call(e,s){return Z(()=>("float32"!==(e=ot(e)).dtype&&(e=cr(e,"float32")),me(L(e,this.scale),this.offset)))}}return n.className="Rescaling",n})());const{resizeBilinear:QD,cropAndResize:JD}=ar;pe((()=>{class n extends wt{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,s,r,i,a,o,l,u){return Z(()=>{let c,h=!1;const m=[s/o,r/l,(i+s)/o,(a+r)/l],x=[];3===e.rank?(h=!0,c=ir([e])):c=e;for(let S=0;Scr(QD(e,[s,r]),i))}call(e,s){return Z(()=>{const r=ot(e),i=r.dtype,a=r.shape,o=a[a.length-3],l=a[a.length-2];let u=0;o!==this.height&&(u=Math.floor((o-this.height)/2));let c=0;return l!==this.width&&(c=Math.floor((l-this.width)/2),0===c&&(c=1)),u>=0&&c>=0?this.centerCrop(r,u,c,this.height,this.width,o,l,i):this.upsize(e,this.height,this.width,i)})}getConfig(){const e={height:this.height,width:this.width},s=super.getConfig();return Object.assign(e,s),e}computeOutputShape(e){const r=(e=At(e)).length-2;return e[e.length-3]=this.height,e[r]=this.width,e}}return n.className="CenterCrop",n})()),pe((()=>{class n extends wt{constructor(e){super(e),this.numTokens=e.numTokens,this.outputMode=e.outputMode?e.outputMode:"multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},s=super.getConfig();return Object.assign(e,s),e}computeOutputShape(e){return null==(e=At(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,s){return Z(()=>{let r;if("int32"!==(e=ot(e)).dtype&&(e=cr(e,"int32")),typeof s.countWeights<"u"){if("count"!==this.outputMode)throw new z(`countWeights is not used when outputMode !== count.\n Received countWeights=${s.countWeights}`);r=ot(s.countWeights)}const i=Ws(e),a=hc(e),o=ys(this.numTokens,i).bufferSync().get(0),l=Pi(a,0).bufferSync().get(0);if(!o||!l)throw new z(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return function eO(n,t,e,s){let r=ot(n);if("int32"!==r.dtype&&(r=cr(r,"int32")),"int"===t)return r;const i=r.shape;if(0===r.rank&&(r=Zn(r,-1)),"oneHot"===t&&1!==r.shape[r.shape.length-1]&&(r=Zn(r,-1)),r.rank>2)throw new z(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${i} which would result in output rank ${r.rank}.`);const a=["multiHot","oneHot"].includes(t);let l;if(l=dy(r,typeof s<"u"&&"count"===t?s:[],e,a),"tfIdf"!==t)return l;if(s)return L(l,s);throw new z("When outputMode is 'tfIdf', weights must be provided.")}(e,this.outputMode,this.numTokens,r)})}}return n.className="CategoryEncoding",n})());const Lv=new Set(["bilinear","nearest"]);pe((()=>{class n extends wt{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation){if(!Lv.has(e.interpolation))throw new z(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);this.interpolation=e.interpolation}else this.interpolation="bilinear";this.cropToAspectRatio=!!e.cropToAspectRatio}computeOutputShape(e){return e=At(e),[this.height,this.width,e[2]]}getConfig(){const e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},s=super.getConfig();return Object.assign(e,s),e}call(e,s){return Z(()=>{const r=[this.height,this.width];if("bilinear"===this.interpolation)return ar.resizeBilinear(e,r,!this.cropToAspectRatio);if("nearest"===this.interpolation)return ar.resizeNearestNeighbor(e,r,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...Lv]} are supported`)})}}return n.className="Resizing",n})());let nO=(()=>{class n{constructor(e){this.seed=e}next(){if(void 0!==this.seed)return this.seed++}}return n.className="RandomSeed",n})(),sO=(()=>{class n extends wt{constructor(e){super(e),this.randomGenerator=new nO(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},s=super.getConfig();return Object.assign(e,s),e}}return n.className="BaseRandomLayer",n})();const Vv=new Set(["bilinear","nearest"]);function Bv(n){return new ev(n)}var jv;function We(n,t){Array.isArray(n)||(n=[n]),n.forEach(e=>{null!=e&&T("complex64"!==e.dtype,()=>`${t} does not support complex64 tensors in the CPU backend.`)})}pe((()=>{class n extends sO{constructor(e){super(e);const{factor:s,interpolation:r="bilinear"}=e;if(this.factor=s,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 z(`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 z(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper{const r=ot(e);this.imgHeight=r.shape[r.shape.length-3];const i=r.shape[r.shape.length-2];this.widthFactor=ol([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let a=this.widthFactor.dataSync()[0]*i;a=Math.round(a);const o=[this.imgHeight,a];switch(this.interpolation){case"bilinear":return ar.resizeBilinear(e,o);case"nearest":return ar.resizeNearestNeighbor(e,o);default:throw new Error(`Interpolation is ${this.interpolation}\n but only ${[...Vv]} are supported`)}})}}return n.className="RandomWidth",n})()),E().registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,n=>{n&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")}),function(n){let t;var e;(e=t=n.CheckpointFormatVersion||(n.CheckpointFormatVersion={}))[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(jv||(jv={})),Error,Symbol("out"),Symbol("field"),Symbol("quote"),Symbol("quoteafterquote"),Symbol("quoteinquote");const rP=hb;let iP=(()=>{class n extends Fe{nextDataId(){return n.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new we(this,tr())}write(e,s,r){this.firstUse&&(this.firstUse=!1,E().get("IS_NODE")&&fs("\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 i={id:this.nextDataId()};return this.data.set(i,{values:e,dtype:r,refCount:1}),i}makeTensorInfo(e,s,r){let i;if("string"===s&&null!=r&&r.length>0&&os(r[0])){const a=r.map(o=>Ur(o));i=this.write(a,e,s)}else i=this.write(r,e,s);return{dataId:i,shape:e,dtype:s}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){this.data.get(e).refCount++}decRef(e){this.data.has(e)&&this.data.get(e).refCount--}move(e,s,r,i,a){this.data.set(e,{values:s,dtype:i,refCount:a})}numDataIds(){return this.data.numDataIds()}read(e){var s=this;return(0,N.A)(function*(){return s.readSync(e)})()}readSync(e){const{dtype:s,complexTensorInfos:r}=this.data.get(e);return"complex64"===s?Nr(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):function Xl(n,t){if(Array.isArray(n))return n;if("float32"===t)return n instanceof Float32Array?n:new Float32Array(n);if("int32"===t)return n instanceof Int32Array?n:new Int32Array(n);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(n));throw new Error(`Unknown dtype ${t}`)}(this.data.get(e).values,s)}bufferSync(e){const s=this.readSync(e.dataId);if("string"===e.dtype)try{const r=s.map(i=>Wr(i));return vt(e.shape,e.dtype,r)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return vt(e.shape,e.dtype,s)}makeOutput(e,s,r){return tr().makeTensorFromTensorInfo(this.makeTensorInfo(s,r,e),this)}disposeData(e,s=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!s&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:r}=this.data.get(e);null!=r&&(this.disposeData(r.real.dataId,!0),this.disposeData(r.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}time(e){return(0,N.A)(function*(){const s=Vn();return e(),{kernelMs:Vn()-s}})()}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){We([e],"where");const s=this.readSync(e.dataId);return rP(e.shape,s)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}return n.nextDataId=0,n})();function mr(n){return(t,e,s)=>{const r=$t(e,t.length);for(let i=0;i{const{x:a}=s;We(a,n);const o=i,l=o.data.get(a.dataId).values;let u;if("string"===a.dtype){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");u=Ar(l)}else u=l;const c=e||a.dtype,h=t(u,c,r);return o.makeTensorInfo(a.shape,c,h)}}yx("cpu",()=>new iP,1);const Nw=Mt(co,n=>n>=0?n:Math.exp(n)-1),oP={kernelName:co,backendName:"cpu",kernelFunc:Nw};function gr(n){const{inputs:t,backend:e}=n,{x:s}=t;return e.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const lP={kernelName:yo,backendName:"cpu",kernelFunc:gr};function Aw(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{alpha:i}=s;We([r],"leakyRelu");const a=K(r.shape),o=e.data.get(r.dataId).values,l=Cn("float32",a);for(let u=0;u{const a=ht(t,e),o=a.length,l=Ue(a),c=Cn(i,K(a)),h=t.length,d=e.length,p=Ue(t),f=Ue(e),g=ga(t,a),m=ga(e,a);if(g.length+m.length===0)for(let x=0;xb[I]=0);const v=Is(b,h,p),w=y.slice(-d);m.forEach(I=>w[I]=0);const S=Is(w,d,f);c[x]=n(s[v],r[S])}return[c,a]}}const cP=mn((n,t)=>n<0?t*n:n);function Rw(n){const{inputs:t,backend:e}=n,{x:s,alpha:r}=t;We([s,r],"prelu");const i=e.data.get(s.dataId).values,a=e.data.get(r.dataId).values,[o,l]=cP(s.shape,r.shape,i,a,"float32");return e.makeTensorInfo(l,"float32",o)}const hP={kernelName:$u,backendName:"cpu",kernelFunc:Rw},$w=Mt(Ao,n=>Math.max(0,n)),dP={kernelName:Ao,backendName:"cpu",kernelFunc:$w},Dw=Mt(Ro,n=>Math.min(Math.max(0,n),6)),pP={kernelName:Ro,backendName:"cpu",kernelFunc:Dw},fP=mr(n=>1/(1+Math.exp(-n))),Ow=Mt(Mo,n=>1/(1+Math.exp(-n))),mP={kernelName:Mo,backendName:"cpu",kernelFunc:Ow};function lh(n,t,e,s,r){if("linear"===e)return gr({inputs:{x:t},backend:n});if("relu"===e)return $w({inputs:{x:t},backend:n});if("elu"===e)return Nw({inputs:{x:t},backend:n});if("relu6"===e)return Dw({inputs:{x:t},backend:n});if("prelu"===e)return Rw({inputs:{x:t,alpha:s},backend:n});if("leakyrelu"===e)return Aw({inputs:{x:t},backend:n,attrs:{alpha:r}});if("sigmoid"===e)return Ow({inputs:{x:t},backend:n});throw new Error(`Activation ${e} has not been implemented for the CPU backend.`)}function cs(n){const{inputs:t,backend:e}=n,{real:s,imag:r}=t,i=e.data.get(s.dataId).values,a=e.data.get(r.dataId).values,o=e.makeTensorInfo(s.shape,"complex64");return e.data.get(o.dataId).complexTensorInfos={real:e.makeTensorInfo(s.shape,"float32",i),imag:e.makeTensorInfo(r.shape,"float32",a)},o}const gP={kernelName:od,backendName:"cpu",kernelFunc:cs};function uh(n,t,e="float32"){if("complex64"===e)return cs({inputs:{real:uh(n,t,"float32"),imag:uh(n,t,"float32")},backend:n});const s=yn(K(t),e);return n.makeTensorInfo(t,e,s)}function ji(n){const{inputs:t,backend:e}=n,{input:s}=t,r=e.data.get(s.dataId).complexTensorInfos.real,i=e.data.get(r.dataId).values;return e.makeTensorInfo(r.shape,r.dtype,i)}const xP={kernelName:Od,backendName:"cpu",kernelFunc:ji};function Pw(n,t,e,s){if("int32"===s)return[t,"int32",Int32Array.from(n)];if("bool"===s){const r=Ti([0],e),[i,a]=mn((o,l)=>o!==l?1:0)(t,[],n,r,"bool");return[a,"bool",i]}throw new Error(`Error in Cast: failed to cast ${e} to ${s}`)}function li(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{dtype:i}=s;if("complex64"===i){if("complex64"===r.dtype)return gr({inputs:{x:r},backend:e});const c=uh(e,r.shape,r.dtype),h=li({inputs:{x:r},backend:e,attrs:{dtype:"float32"}}),d=cs({inputs:{real:h,imag:c},backend:e});return e.disposeIntermediateTensorInfo(c),e.disposeIntermediateTensorInfo(h),d}if("complex64"===r.dtype){const c=ji({inputs:{input:r},backend:e}),h=li({inputs:{x:c},backend:e,attrs:{dtype:i}});return e.disposeIntermediateTensorInfo(c),h}if(!Ve(r.dtype,i)){const c=gr({inputs:{x:r},backend:e});return{dataId:c.dataId,shape:c.shape,dtype:i}}const a=e.data.get(r.dataId).values,[o,l,u]=Pw(a,r.shape,r.dtype,i);return e.makeTensorInfo(o,l,u)}const yP={kernelName:so,backendName:"cpu",kernelFunc:li};function Sn(n,t,e,s){return null==e?({inputs:r,backend:i})=>{const{a,b:o}=r,l=i;We([a,o],n);const u=l.data.get(a.dataId).values,c=l.data.get(o.dataId).values,h="string"===a.dtype?Ar(u):u,d="string"===a.dtype?Ar(c):c,p=s||a.dtype,[f,g]=t(a.shape,o.shape,h,d,p);return l.makeTensorInfo(g,p,f)}:({inputs:r,backend:i})=>{const{a,b:o}=r,l=i;if("complex64"===a.dtype||"complex64"===o.dtype){const u=li({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),c=l.data.get(u.dataId),d=c.complexTensorInfos.imag,p=l.data.get(c.complexTensorInfos.real.dataId).values,f=l.data.get(d.dataId).values,g=li({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),m=l.data.get(g.dataId),y=m.complexTensorInfos.imag,b=l.data.get(m.complexTensorInfos.real.dataId).values,v=l.data.get(y.dataId).values,[w,S,I]=e(a.shape,o.shape,p,f,b,v),k=l.makeTensorInfo(I,"float32",w),D=l.makeTensorInfo(I,"float32",S),P=cs({inputs:{real:k,imag:D},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(g),l.disposeIntermediateTensorInfo(k),l.disposeIntermediateTensorInfo(D),P}{const u=l.data.get(a.dataId).values,c=l.data.get(o.dataId).values,h=s||a.dtype,[d,p]=t(a.shape,o.shape,u,c,h);return l.makeTensorInfo(p,h,d)}}}function Vm(n){return(t,e,s,r,i,a)=>{const o=ht(t,e),l=K(o),u=o.length,c=Ue(o),h=Cn("float32",l),d=Cn("float32",l),p=ga(t,o),f=ga(e,o),g=Nr(s,r),m=Nr(i,a),x=t.length,y=Ue(t),b=e.length,v=Ue(e);if(p.length+f.length===0)for(let w=0;wI[Y]=0);const k=Is(I,x,y),D=S.slice(-b);f.forEach(Y=>D[Y]=0);const P=Is(D,b,v),B=n(g[2*k],g[2*k+1],m[2*P],m[2*P+1]);h[w]=B.real,d[w]=B.imag}return[h,d,o]}}const Fw=mn((n,t)=>n+t),bP=Vm((n,t,e,s)=>({real:n+e,imag:t+s})),Ra=Sn(oa,Fw,bP),vP={kernelName:oa,backendName:"cpu",kernelFunc:Ra};function qt(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{shape:i}=s,a=K(r.shape),o=It(i,a),l=K(o);T(a===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${r.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),e.incRef(r.dataId);const u=e.data.get(r.dataId);if(null!=u.complexTensorInfos){const h=u.complexTensorInfos.imag;u.complexTensorInfos.real.shape=o,h.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}const wP={kernelName:Ou,backendName:"cpu",kernelFunc:qt};function Lw(n){const{inputs:t,backend:e,attrs:s}=n,{a:r,b:i}=t,{transposeA:a,transposeB:o}=s;We([r,i],"matMul");const l=r.shape.length,u=i.shape.length,c=a?r.shape[l-2]:r.shape[l-1],h=o?i.shape[u-1]:i.shape[u-2],d=a?r.shape[l-1]:r.shape[l-2],p=o?i.shape[u-2]:i.shape[u-1],f=r.shape.slice(0,-2),g=i.shape.slice(0,-2),m=K(f),x=K(g),b=ht(r.shape.slice(0,-2),i.shape.slice(0,-2)).concat([d,p]);T(c===h,()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${r.shape} and ${i.shape} and transposeA=${a} and transposeB=${o} must match.`);const w=o?[x,p,h]:[x,h,p],S=qt({inputs:{x:r},backend:e,attrs:{shape:a?[m,c,d]:[m,d,c]}}),I=qt({inputs:{x:i},backend:e,attrs:{shape:w}}),k=a?S.shape[1]:S.shape[2],D=a?S.shape[2]:S.shape[1],P=o?I.shape[1]:I.shape[2],B=Math.max(m,x),Y=e.data.get(S.dataId).values,Q=e.data.get(I.dataId).values,ee=Ue(S.shape),J=Ue(I.shape),[se,ae,te]=a?[ee[0],1,ee[1]]:[ee[0],ee[1],1],[le,ge,xe]=o?[1,J[1],J[0]]:[J[1],1,J[0]],Se=D*P,be=vt([B,D,P],S.dtype),De=be.values,Ie=e.blockSize;for(let Le=0;Le{const{x:t}=n.inputs,e=n.backend;We(t,"abs");let s=new Float32Array(K(t.shape));return s=Mw(e.data.get(t.dataId).values),e.makeOutput(s,t.shape,t.dtype)}},IP=Mt(jn,n=>Math.acos(n)),EP={kernelName:jn,backendName:"cpu",kernelFunc:IP},kP=Mt(ps,n=>Math.acosh(n)),NP={kernelName:ps,backendName:"cpu",kernelFunc:kP},RP={kernelName:ed,backendName:"cpu",kernelFunc:function AP(n){const{inputs:t,backend:e}=n,s=t;We(t,"addN");const r=s.map(o=>e.data.get(o.dataId).values),i=vt(s[0].shape,s[0].dtype),a=i.values;for(let o=0;oy&&(y=w,b=v)}p[m]=b}return u.forEach(m=>e.disposeIntermediateTensorInfo(m)),e.makeTensorInfo(c,"int32",p)}},zP={kernelName:ql,backendName:"cpu",kernelFunc:function VP(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i}=s;We(r,"argMin");let a=pt(i,r.shape);const o=rn(a,r.shape.length);let l=r;const u=[];null!=o&&(l=rs({inputs:{x:r},backend:e,attrs:{perm:o}}),u.push(l),a=dn(a.length,l.shape.length)),a=[a[0]],Fn("argMin",a,l.shape.length);const[c,h]=An(l.shape,a),p=yn(K(c),"int32"),f=K(h),g=e.data.get(l.dataId).values;for(let m=0;me.disposeIntermediateTensorInfo(m)),e.makeTensorInfo(c,"int32",p)}},BP=Mt(Qa,n=>Math.asin(n)),UP={kernelName:Qa,backendName:"cpu",kernelFunc:BP},WP=Mt(Ja,n=>Math.asinh(n)),GP={kernelName:Ja,backendName:"cpu",kernelFunc:WP},HP=Mt(eo,n=>Math.atan(n)),jP={kernelName:eo,backendName:"cpu",kernelFunc:HP},XP=mn((n,t)=>Math.atan2(n,t)),KP=Sn(no,XP),qP={kernelName:no,backendName:"cpu",kernelFunc:KP},ZP=Mt(to,n=>Math.atanh(n)),YP={kernelName:to,backendName:"cpu",kernelFunc:ZP};function Bm(n,t,e,s,r,i){const a=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,h=r.effectiveFilterWidth,d=r.padInfo.top,p=r.padInfo.left,f="max"===i?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=vt(r.outShape,e),m=g.values,x=r.outShape[1]*r.outShape[2]*r.outShape[3],y=r.outShape[2]*r.outShape[3],b=r.outShape[3];for(let v=0;vae?ae=Ie:"avg"===i&&(te+=Ie,le++)}if(isNaN(ae))break}m[Y+Q*b+I]="avg"===i?te/le:ae}}}return g}function Vw(n,t,e,s,r=!1,i=!1){const a=vt(s.outShape,"int32"),o=s.strideHeight,l=s.strideWidth,u=s.dilationHeight,c=s.dilationWidth,h=s.effectiveFilterHeight,d=s.effectiveFilterWidth,p=s.padInfo.top,f=s.padInfo.left,g=vt(t,e,n);for(let m=0;mP&&(P=se,B=r?i?((m*s.inHeight+Y)*s.inWidth+ee)*s.inChannels+x:(Y*s.inWidth+ee)*s.inChannels+x:Q*d+J)}}a.set(B,m,y,S,x)}}return a}function zw(n,t,e,s,r,i){const a=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,h=r.dilationWidth,d=r.effectiveFilterDepth,p=r.effectiveFilterHeight,f=r.effectiveFilterWidth,g=r.padInfo.front,m=r.padInfo.top,x=r.padInfo.left,y="max"===i?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,b=vt(r.outShape,e),v=b.values,w=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],S=r.outShape[2]*r.outShape[3]*r.outShape[4],I=r.outShape[3]*r.outShape[4],k=r.outShape[4];for(let D=0;Dit?it=nn:"avg"===i&&(tt+=nn,mt++),isNaN(it))break}if(isNaN(it))break}if(isNaN(it))break}v[Ze+Y]="avg"===i?tt/Math.max(mt,1):it}}}}return b}const eF={kernelName:Zl,backendName:"cpu",kernelFunc:function JP(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t;We(r,"avgPool");const{filterSize:i,strides:a,pad:o,dimRoundingMode:l}=s;T(Pn(a,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '1'`);const c=ks(r.shape,i,a,1,o,l);let h;if(1===c.filterWidth&&1===c.filterHeight&&rt(c.inShape,c.outShape))h=gr({inputs:{x:r},backend:e});else{const d=e.data.get(r.dataId).values,p=Ue(r.shape),f=Bm(d,0,r.dtype,p,c,"avg");h=e.makeTensorInfo(c.outShape,r.dtype,f.values)}return h}},nF={kernelName:Yl,backendName:"cpu",kernelFunc:function tF(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{filterSize:i,strides:a,pad:o,dimRoundingMode:l,dataFormat:u}=s;We(r,"avgPool3d");const c=Tr(r.shape,i,a,1,o,l,u),d=zw(e.data.get(r.dataId).values,0,r.dtype,Ue(r.shape),c,"avg");return e.makeTensorInfo(d.shape,"float32",d.values)}},rF={kernelName:rd,backendName:"cpu",kernelFunc:function sF(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,input:i}=t,{filterSize:a,strides:o,pad:l,dimRoundingMode:u}=s;We([r,i],"avgPool3DGrad");const c=Tr(i.shape,a,o,1,l,u),h=c.strideDepth,d=c.strideHeight,p=c.strideWidth,f=c.filterDepth,g=c.filterHeight,m=c.filterWidth,x=c.dilationDepth,y=c.dilationHeight,b=c.dilationWidth,v=c.effectiveFilterDepth,w=c.effectiveFilterHeight,S=c.effectiveFilterWidth,I=v-1-c.padInfo.front,k=S-1-c.padInfo.left,D=w-1-c.padInfo.top,P=vt(i.shape,"float32"),B=1/(f*g*m),Y=e.bufferSync(r);for(let Q=0;Q=c.outDepth||Math.floor(be)!==be))for(let De=0;De=c.outHeight||Math.floor(Ie)!==Ie))for(let Le=0;Le=c.outWidth||Math.floor(Ze)!==Ze||(xe+=Y.get(Q,be,Ie,Ze,ee))}}}P.set(xe*B,Q,J,se,ae,ee)}return e.makeTensorInfo(P.shape,P.dtype,P.values)}},aF={kernelName:sd,backendName:"cpu",kernelFunc:function iF(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,input:i}=t,a=i;We([r,i],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=ks(a.shape,o,l,1,u),h=c.strideHeight,d=c.strideWidth,p=c.filterHeight,f=c.filterWidth,g=c.dilationHeight,m=c.dilationWidth,x=c.effectiveFilterHeight,y=c.effectiveFilterWidth,b=y-1-c.padInfo.left,v=x-1-c.padInfo.top,w=vt(a.shape,"float32"),S=1/(p*f),I=e.data.get(r.dataId).values,k=vt(r.shape,"float32",I);for(let D=0;D=c.outHeight||Math.floor(ae)!==ae))for(let te=0;te=c.outWidth||Math.floor(le)!==le||(J+=k.get(D,ae,le,P))}}w.set(J*S,D,B,Y,P)}return e.makeTensorInfo(w.shape,w.dtype,w.values)}},lF={kernelName:cu,backendName:"cpu",kernelFunc:function oF(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,scale:i,offset:a,mean:o,variance:l}=t;T(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),T(null==a||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),T(null==i||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),We([r,o,l,i,a],"batchNorm");let{varianceEpsilon:u}=s;null==u&&(u=.001);const c=e.data.get(r.dataId).values,h=e.data.get(o.dataId).values,d=e.data.get(l.dataId).values,p=i?e.data.get(i.dataId).values:new Float32Array([1]),f=a?e.data.get(a.dataId).values:new Float32Array([0]),g=new Float32Array(c.length),m=f.length,x=p.length,y=d.length,b=h.length;let v=0,w=0,S=0,I=0;for(let k=0;k=m&&(v=0),w>=b&&(w=0),S>=x&&(S=0),I>=y&&(I=0);return e.makeTensorInfo(r.shape,r.dtype,g)}};function Bw(n,t,e,s,r){const i=Dp(s,t,e),a=K(e),o=Ue(s);if(i){const h=Op(t,o);return"string"===r?n.slice(h,h+a):n.subarray(h,h+a)}const u=vt(s,r,"string"===r?Ar(n):n),c=vt(e,r);for(let h=0;hf+t[g]);c.set(u.get(...p),...d)}return"string"===r?cb(c.values):c.values}function Xi(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{begin:i,size:a}=s;We(r,"slice");const[o,l]=ac(r,i,a);Rp(r,o,l);const c=Bw(e.data.get(r.dataId).values,o,l,r.shape,r.dtype);return e.makeTensorInfo(l,r.dtype,c)}const uF={kernelName:Vu,backendName:"cpu",kernelFunc:Xi},hF={kernelName:Jl,backendName:"cpu",kernelFunc:function cF(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{blockShape:i,crops:a}=s;We([r],"batchToSpaceND");const o=i.reduce((x,y)=>x*y),l=pl(r.shape,i,o),u=fl(l.length,i.length),c=ml(r.shape,i,o),h=gf(a,i.length),d=xf(c,a,i.length),p=qt({inputs:{x:r},backend:e,attrs:{shape:l}}),f=rs({inputs:{x:p},backend:e,attrs:{perm:u}}),g=qt({inputs:{x:f},backend:e,attrs:{shape:c}}),m=Xi({inputs:{x:g},backend:e,attrs:{begin:h,size:d}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(g),m}};function Um(n,t,e,s,r){const i=K(s),a=yn(r,e);for(let o=0;o=r||(a[l]+=i>0?t[o]:1)}return a}function Uw(n,t,e,s=!1){const r=n.shape[0],i=n.shape[1],a=vt([r,e],t.dtype);for(let o=0;o=e||a.set(s?1:t.size>0?a.get(o,u)+t.get(o,l):a.get(o,u)+1,o,u)}return a}const pF={kernelName:id,backendName:"cpu",kernelFunc:function dF(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,weights:i}=t,{size:a}=s,u=Um(e.data.get(r.dataId).values,e.data.get(i.dataId).values,i.dtype,i.shape,a);return e.makeTensorInfo([a],i.dtype,u)}},Ww=mn((n,t)=>n&t),mF={kernelName:ad,backendName:"cpu",kernelFunc:Sn(ad,Ww)},xF={kernelName:Fg,backendName:"cpu",kernelFunc:function gF(n){const{inputs:t,backend:e}=n,{s0:s,s1:r}=t,i=e.data.get(s.dataId).values,a=e.data.get(r.dataId).values,o=ht(Array.from(i),Array.from(a));return e.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},Gw=mr(n=>Math.ceil(n)),yF=oi(ro,Gw),bF={kernelName:ro,backendName:"cpu",kernelFunc:yF},vF=Mt(ao,(n,t)=>n>t.clipValueMax?t.clipValueMax:n{const{x:t}=n.inputs,e=n.backend,s=new Float32Array(K(t.shape)),r=e.data.get(t.dataId),a=r.complexTensorInfos.imag,o=e.data.get(r.complexTensorInfos.real.dataId).values,l=e.data.get(a.dataId).values;for(let u=0;u{const o=K(a.shape);r.set(a.vals,i),i+=o})}else{let i=0;n.forEach(a=>{const o="string"===e?Ar(a.vals):a.vals;let l=0;for(let u=0;ug.shape),i);let o=or(t.map(g=>g.shape),i);if(0===K(o))return e.makeTensorInfo(o,t[0].dtype,[]);const l=t.filter(g=>K(g.shape)>0);if(1===l.length)return gr({inputs:{x:l[0]},backend:e});if("complex64"===l[0].dtype){const g=l.map(v=>ji({inputs:{input:v},backend:e})),m=l.map(v=>$a({inputs:{input:v},backend:e})),x=Da({inputs:g,backend:e,attrs:{axis:i}}),y=Da({inputs:m,backend:e,attrs:{axis:i}}),b=cs({inputs:{real:x,imag:y},backend:e});return g.forEach(v=>e.disposeIntermediateTensorInfo(v)),m.forEach(v=>e.disposeIntermediateTensorInfo(v)),e.disposeIntermediateTensorInfo(x),e.disposeIntermediateTensorInfo(y),b}const u=l.map(g=>{const x=[-1,K(g.shape.slice(i))];return qt({inputs:{x:g},backend:e,attrs:{shape:x}})}),c=u.map(g=>({vals:e.data.get(g.dataId).values,shape:g.shape}));o=or(u.map(g=>g.shape),1);const d=Hw(c,o,t[0].dtype,1===u[0].shape[0]),p=or(l.map(g=>g.shape),i),f=e.makeTensorInfo(p,t[0].dtype,d);return u.forEach(g=>e.disposeIntermediateTensorInfo(g)),f}const SF={kernelName:tu,backendName:"cpu",kernelFunc:Da};function jw(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,filter:i}=t,{strides:a,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s;We([r,i],"conv2d");const h=Sr(l),d=Nn(r.shape,i.shape,a,u,o,c,!1,h),p=d.filterHeight,f=d.filterWidth,g=d.dilationHeight,m=d.dilationWidth,x=d.padInfo.left,y=d.padInfo.top,b="channelsLast"===d.dataFormat,v=new On(d.outShape,r.dtype),w=Ue(r.shape),S=Ue(i.shape),I=w[0],k=b?w[1]:w[2],D=b?w[2]:1,P=b?1:w[1],B=v.strides[0],Y=b?v.strides[1]:v.strides[2],Q=b?v.strides[2]:1,ee=b?1:v.strides[1],J=e.data.get(r.dataId).values,se=e.data.get(i.dataId).values,ae=v.values;for(let te=0;te=d.inHeight)continue;const Le=De*S[0],Ze=le+Ie*k;for(let it=0;it=d.inWidth)continue;const cn=Ze+Vt*D;let Yt=Le+yt*S[1];for(let Wt=0;Wt=u.inDepth)continue;const te=se*D[0],le=B+ae*k[1];for(let ge=0;ge=u.inHeight)continue;const Ie=te+be*D[1],Le=le+De*k[2];for(let Ze=0;Ze=u.inWidth)continue;const Zt=Le+yt*u.inChannels;let cn=Ie+mt*D[2];for(let Yt=0;YtMath.cos(n)),LF={kernelName:oo,backendName:"cpu",kernelFunc:FF},MF=Mt(lo,n=>Math.cosh(n)),VF={kernelName:lo,backendName:"cpu",kernelFunc:MF},BF={kernelName:dd,backendName:"cpu",kernelFunc:function zF(n){const{inputs:t,backend:e,attrs:s}=n,{image:r,boxes:i,boxInd:a}=t,{cropSize:o,method:l,extrapolationValue:u}=s,[c,h,d,p]=r.shape,f=i.shape[0],[g,m]=o,x=vt([f,g,m,p],"float32"),y=e.data.get(i.dataId).values,b=e.data.get(a.dataId).values,v=e.data.get(r.dataId).values,w=Ue(r.shape),S=Ue(x.shape);for(let I=0;I=c)continue;const ee=g>1?(B-D)*(h-1)/(g-1):0,J=m>1?(Y-P)*(d-1)/(m-1):0;for(let se=0;se1?D*(h-1)+se*ee:.5*(D+B)*(h-1);if(ae<0||ae>h-1)for(let te=0;te1?P*(d-1)+xe*J:.5*(P+Y)*(d-1);if(Se<0||Se>d-1){for(let Le=0;Le1?P*(d-1)+te*J:.5*(P+Y)*(d-1);if(le<0||le>d-1){for(let Se=0;Sex+f-y-1:(x,y)=>x+y;for(let x=0;xx+f-y-1:(x,y)=>x+y;for(let x=0;x`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${a}`);const o=r.shape[0],l=r.shape[1],u=r.shape[2],c=r.shape[3],h=l*i,d=u*i,p=c/(i*i),f=e.data.get(r.dataId).values,g=new Float32Array(o*h*d*p);let m=0;for(let x=0;x`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const p=Nn(r.shape,i.shape,a,d,o,u,!0),{filterHeight:f,filterWidth:g,dilationHeight:m,dilationWidth:x,padInfo:y}=p,b=y.left,v=y.top,w=p.outChannels/p.inChannels,S=new On(p.outShape,r.dtype),I=e.data.get(r.dataId).values,k=e.data.get(i.dataId).values,D=S.values;for(let P=0;P=p.inHeight)continue;const te=se*h[0],le=B+ae*c[1];for(let ge=0;ge=p.inWidth)continue;const Le=le+De*p.inChannels;let Ze=xe,it=te+be*h[1];for(let tt=0;tt{const{x:s,filter:r}=n,{strides:i,pad:a,dilations:o}=e,l=t,u=l.data.get(s.dataId).values,c=s.shape.length,h=l.data.get(r.dataId).values,d=r.shape.length,{batchSize:p,inHeight:f,inWidth:g,inChannels:m,outHeight:x,outWidth:y,padInfo:b,strideHeight:v,strideWidth:w,filterHeight:S,filterWidth:I,dilationHeight:k,dilationWidth:D,outShape:P}=tl(s.shape,r.shape,i,a,"NHWC",o),B=K(P),Y=P.length,Q=$t(s.dtype,B);for(let J=0;J=0&&De=0&&Lexe&&(xe=tt)}}}Q[Is([J,se,te,ge],Y,Ue(P))]=xe}}}return{dataId:l.write(Ti(Q,s.dtype),P,s.dtype),shape:P,dtype:s.dtype}}},rL={kernelName:yd,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,filter:r,dy:i}=n,{strides:a,pad:o,dilations:l}=e,u=t,c=ds(s.shape,u.data.get(s.dataId).values),h=ds(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:g,outHeight:m,outWidth:x,padInfo:y,strideHeight:b,strideWidth:v,filterHeight:w,filterWidth:S,dilationHeight:I,dilationWidth:k,outShape:D}=tl(s.shape,r.shape,a,o,"NHWC",l);T(i.rank===D.length,()=>`Error in ${yd}, dy must have the same rank as output ${D.length}, but got ${i.rank}`);const P=ds(D,u.data.get(i.dataId).values),B=Jh(r.shape,r.dtype);for(let Q=0;Q=0&&be=0&&Iele&&(le=Le,ge=Se,xe=De)}}}B[ge][xe][te]+=P[Q][ee][se][te]}}}return{dataId:u.write(Ti(B,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},iL={kernelName:xd,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,filter:r,dy:i}=n,{strides:a,pad:o,dilations:l}=e,u=t,c=ds(s.shape,u.data.get(s.dataId).values),h=ds(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:p,inWidth:f,inChannels:g,outHeight:m,outWidth:x,padInfo:y,strideHeight:b,strideWidth:v,filterHeight:w,filterWidth:S,dilationHeight:I,dilationWidth:k,outShape:D}=tl(s.shape,r.shape,a,o,"NHWC",l);T(i.rank===D.length,()=>`Error in ${xd}, dy must have the same rank as output ${D.length}, but got ${i.rank}`);const P=ds(D,u.data.get(i.dataId).values),B=Jh(s.shape,s.dtype);for(let Q=0;Q=0&&be=0&&Iele&&(le=Le,ge=be,xe=Ie)}}}B[Q][ge][xe][te]+=P[Q][ee][se][te]}}}return{dataId:u.write(Ti(B,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},oL={kernelName:"Draw",backendName:"cpu",kernelFunc:function aL(n){const{inputs:t,backend:e,attrs:s}=n,{image:r}=t,{canvas:i,options:a}=s,{contextOptions:o,imageOptions:l}=a||{},u=l?.alpha||1,c=o?.contextType||"2d";if("2d"!==c)throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);const h=i.getContext(c,o?.contextAttributes||{});if(null==h)throw new Error(`Could not get the context with ${c} type.`);const[d,p]=r.shape.slice(0,2),f=2===r.shape.length?1:r.shape[2],g=e.data.get(r.dataId).values,m="float32"===r.dtype?255:1,x=new Uint8ClampedArray(p*d*4);for(let b=0;b1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${I}.`)}else if("int32"===r.dtype&&(I<0||I>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${I}.`);1===f?(v[0]=I*m,v[1]=I*m,v[2]=I*m):v[S]=I*m}const w=4*b;x[w+0]=Math.round(v[0]),x[w+1]=Math.round(v[1]),x[w+2]=Math.round(v[2]),x[w+3]=Math.round(v[3])}i.width=p,i.height=d;const y=new ImageData(x,p,d);return h.putImageData(y,0,0),r}},Wm=mn((n,t)=>n*t),lL=Vm((n,t,e,s)=>({real:n*e-t*s,imag:n*s+t*e})),ch=Sn(Eo,Wm,lL),uL={kernelName:Eo,backendName:"cpu",kernelFunc:ch};function Nl(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i,keepDims:a}=s;let o;We(r,"sum"),o="bool"===r.dtype?li({inputs:{x:r},backend:e,attrs:{dtype:"int32"}}):gr({inputs:{x:r},backend:e});const l=o.shape.length,u=pt(i,o.shape),c=rn(u,l);let h=u,d=o;null!=c&&(d=rs({inputs:{x:o},backend:e,attrs:{perm:c}}),h=dn(h.length,l)),Fn("sum",h,d.shape.length);const[p,f]=An(d.shape,h);let m=uh(e,p,ls(d.dtype,"int32"));const x=K(f),y=e.data.get(m.dataId).values,b=e.data.get(d.dataId).values;for(let v=0;v=0&&(d=Nl({inputs:{x:d},backend:e,attrs:{axis:u[g]-(a.length-p),keepDims:!1}}),f.push(d)),p--)}for(const g of f)g!==d&&e.disposeIntermediateTensorInfo(g);return d}},fL={kernelName:wd,backendName:"cpu",kernelFunc:function pL(n){const{inputs:t,backend:e}=n,{dy:s,y:r}=t;We([s,r],"eluGrad");const i=new Float32Array(K(r.shape)),a=e.data.get(r.dataId).values,o=e.data.get(s.dataId).values;for(let l=0;l=0?o[l]:o[l]*(u+1)}return e.makeTensorInfo(r.shape,"float32",i)}},Kw=mn((n,t)=>n===t?1:0),qw=Sn(lu,Kw,null,"bool"),mL={kernelName:lu,backendName:"cpu",kernelFunc:qw},gL=bf,xL=vf,yL=wf,bL=_f,vL=Tf,wL=Sf,_L=Mt(ho,n=>{const t=Math.sign(n),e=Math.abs(n),s=1/(1+gL*e);return t*(1-((((wL*s+vL)*s+bL)*s+yL)*s+xL)*s*Math.exp(-e*e))}),TL={kernelName:ho,backendName:"cpu",kernelFunc:_L},Zw=mr(n=>Math.exp(n)),Yw=oi(po,Zw,"float32"),SL={kernelName:po,backendName:"cpu",kernelFunc:Yw};function hh(n){const{inputs:t,backend:e,attrs:s}=n,{input:r}=t,{dim:i}=s,a=r.shape.length,o=r.shape.slice();let l=i;return i<0&&(T(-(a+1)<=i,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+i+1),o.splice(l,0,1),qt({inputs:{x:r},backend:e,attrs:{shape:o}})}const CL={kernelName:uu,backendName:"cpu",kernelFunc:hh},Qw=mr(n=>Math.expm1(n)),IL=oi(fo,Qw),EL={kernelName:fo,backendName:"cpu",kernelFunc:IL},kL=mn((n,t)=>n/t),Gm=Sn(uo,kL),Hm={kernelName:uo,backendName:"cpu",kernelFunc:Gm},Jw=mn((n,t)=>n-t),NL=Vm((n,t,e,s)=>({real:n-e,imag:t-s})),jm=Sn(Uo,Jw,NL),AL={kernelName:Uo,backendName:"cpu",kernelFunc:jm};function e_(n,t,e){const s=n.shape,r=s[0],i=s[1],a=e.data.get(n.dataId),o=a.complexTensorInfos.real,l=a.complexTensorInfos.imag,u=[r,i],c=K(u),h=Cn("float32",c),d=Cn("float32",c);for(let m=0;m{const{image:s}=n,r=e,i=Cn(s.dtype,K(s.shape)),[a,o,l,u]=s.shape,c=r.data.get(s.dataId).values;for(let d=0;d=0&&bMath.floor(n)),VL=oi(mo,t_),zL={kernelName:mo,backendName:"cpu",kernelFunc:VL},BL=mn((n,t)=>Math.floor(n/t)),UL=Sn(go,BL,null,"int32"),WL={kernelName:go,backendName:"cpu",kernelFunc:UL},HL={kernelName:qu,backendName:"cpu",kernelFunc:function GL(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,filter:i,bias:a,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s;let g=jw({inputs:{x:r,filter:i},backend:e,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d}});if(a){const m=g;if("NCHW"===c&&1===a.shape.length&&1!==a.shape[0]){const x=qt({inputs:{x:a},backend:e,attrs:{shape:[a.shape[0],1,1]}});g=Ra({inputs:{a:g,b:x},backend:e}),e.disposeIntermediateTensorInfo(x)}else g=Ra({inputs:{a:g,b:a},backend:e});e.disposeIntermediateTensorInfo(m)}if(p){const m=g;if("NCHW"===c&&"prelu"===p&&1===o.shape.length&&1!==o.shape[0]){const x=qt({inputs:{x:o},backend:e,attrs:{shape:[o.shape[0],1,1]}});g=lh(e,g,p,x,f),e.disposeIntermediateTensorInfo(x)}else g=lh(e,g,p,o,f);e.disposeIntermediateTensorInfo(m)}return g}},XL={kernelName:Zu,backendName:"cpu",kernelFunc:function jL(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,filter:i,bias:a,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s;let g=Xw({inputs:{x:r,filter:i},backend:e,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d}});if(a){const m=g;g=Ra({inputs:{a:g,b:a},backend:e}),e.disposeIntermediateTensorInfo(m)}if(p){const m=g;g=lh(e,g,p,o,f),e.disposeIntermediateTensorInfo(m)}return g}};function n_(n,t,e,s,r,i,a,o,l){const u=vt([s,i],e);for(let c=0;c=l/i)throw new Error(`Invalid indices: ${h} does not index into ${o}`);for(let p=0;p=0,()=>`GatherV2: the index value ${w} is not in [0, ${c-1}]`)}let h=o;null==o&&(h=0);const d=K(i.shape),p=Of(r,i,l,h),f=qt({inputs:{x:r},backend:e,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),g=qt({inputs:{x:i},backend:e,attrs:{shape:[p.batchSize,d/p.batchSize]}}),m=[p.batchSize,p.outerSize,d/p.batchSize,p.sliceSize],x=e.bufferSync(g),b=s_(e.bufferSync(f),x,m);return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(g),e.makeTensorInfo(p.outputShape,b.dtype,b.values)}},r_=mn((n,t)=>n>t?1:0),QL=Sn(du,r_,null,"bool"),JL={kernelName:du,backendName:"cpu",kernelFunc:QL},i_=mn((n,t)=>n>=t?1:0),eM=Sn(xo,i_,null,"bool"),tM={kernelName:xo,backendName:"cpu",kernelFunc:eM},sM={kernelName:Cd,backendName:"cpu",kernelFunc:function nM(n){const{inputs:t,backend:e}=n,{input:s}=t,r=K(s.shape),i=s.shape[s.shape.length-1],o=qt({inputs:{x:s},backend:e,attrs:{shape:[r/i,i]}}),l=e_(o,!0,e),u=qt({inputs:{x:l},backend:e,attrs:{shape:s.shape}});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(l),u}},rM=Mt(bo,n=>Number.isFinite(n)?1:0,"bool"),iM={kernelName:bo,backendName:"cpu",kernelFunc:rM},aM=Mt(vo,n=>Math.abs(n)===1/0?1:0,"bool"),oM={kernelName:vo,backendName:"cpu",kernelFunc:aM},lM=Mt(wo,n=>Number.isNaN(n)?1:0,"bool"),uM={kernelName:wo,backendName:"cpu",kernelFunc:lM},a_=mn((n,t)=>nn<=t?1:0),dM=Sn(mu,o_,null,"bool"),pM={kernelName:mu,backendName:"cpu",kernelFunc:dM};function l_(n,t,e){const s=(t-n)/(e-1),r=yn(e,"float32");r[0]=n;for(let i=1;iMath.log(n)),gM=oi(_o,u_),xM={kernelName:_o,backendName:"cpu",kernelFunc:gM},yM=Mt(To,n=>Math.log1p(n)),bM={kernelName:To,backendName:"cpu",kernelFunc:yM},vM=mn((n,t)=>n&&t),wM=Sn(gu,vM,null,"bool"),_M={kernelName:gu,backendName:"cpu",kernelFunc:wM},TM=Mt(xu,n=>n?0:1,"bool"),SM={kernelName:xu,backendName:"cpu",kernelFunc:TM},CM=mn((n,t)=>n||t),IM=Sn(yu,CM,null,"bool"),EM={kernelName:yu,backendName:"cpu",kernelFunc:IM},NM={kernelName:bu,backendName:"cpu",kernelFunc:function kM(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{depthRadius:i,bias:a,alpha:o,beta:l}=s;We(r,"LRN");const u=r.shape[3],c=u-1,h=e.data.get(r.dataId).values,d=K(r.shape),p=new Float32Array(d);function f(g){const m=g%u;let x=g-m+Math.max(0,m-i);const y=g-m+Math.min(m+i,c);let b=0;for(;x<=y;x++){const v=h[x];b+=v*v}return b}for(let g=0;go)&&(o=u)}r[i]=o}return r}function h_(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{reductionIndices:i,keepDims:a}=s,o=e;let l=r.shape;const u=l.length,c=pt(i,l);let h=c;const d=rn(h,u);let p=o.data.get(r.dataId).values;if(null!=d){const v=new Array(u);for(let w=0;wMath.max(n,t)),DM=Sn(So,d_),OM={kernelName:So,backendName:"cpu",kernelFunc:DM},FM={kernelName:wu,backendName:"cpu",kernelFunc:function PM(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t;We(r,"maxPool");const{filterSize:i,strides:a,pad:o,dimRoundingMode:l}=s;T(Pn(a,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '1'`);const c=ks(r.shape,i,a,1,o,l);let h;if(1===c.filterWidth&&1===c.filterHeight&&rt(c.inShape,c.outShape))h=gr({inputs:{x:r},backend:e});else{const d=e.data.get(r.dataId).values,p=Ue(r.shape),f=Bm(d,0,r.dtype,p,c,"max");h=e.makeTensorInfo(c.outShape,r.dtype,f.values)}return h}},MM={kernelName:_u,backendName:"cpu",kernelFunc:function LM(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{filterSize:i,strides:a,pad:o,dimRoundingMode:l,dataFormat:u}=s;We(r,"maxPool3d");const c=Tr(r.shape,i,a,1,o,l,u),d=zw(e.data.get(r.dataId).values,0,r.dtype,Ue(r.shape),c,"max");return e.makeTensorInfo(d.shape,"float32",d.values)}},zM={kernelName:Nd,backendName:"cpu",kernelFunc:function VM(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,input:i}=t,{filterSize:a,strides:o,pad:l,dimRoundingMode:u}=s;We([r,i],"maxPool3DGrad");const c=Tr(i.shape,a,o,1,l,u),d=function QP(n,t){const e=vt(t.outShape,"int32"),s=t.strideDepth,r=t.strideHeight,i=t.strideWidth,a=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,c=t.effectiveFilterHeight,h=t.effectiveFilterWidth,d=t.padInfo.front,p=t.padInfo.top,f=t.padInfo.left;for(let g=0;g=Q&&(Q=xe,ee=se*c*h+te*c+ge)}}}e.set(ee,g,x,w,D,m)}}}return e}(e.bufferSync(i),c),p=c.strideDepth,f=c.strideHeight,g=c.strideWidth,m=c.dilationDepth,x=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,v=c.effectiveFilterHeight,w=c.effectiveFilterWidth,S=b-1-c.padInfo.front,I=w-1-c.padInfo.left,k=v-1-c.padInfo.top,D=vt(i.shape,"float32"),P=e.bufferSync(r);for(let B=0;B=c.outDepth||Math.floor(xe)!==xe))for(let Se=0;Se=c.outHeight||Math.floor(be)!==be))for(let De=0;De=c.outWidth||Math.floor(Ie)!==Ie)continue;const it=b*v*w-1-d.get(B,xe,be,Ie,Y)===ge*v*w+Se*w+De?1:0;0!==it&&(le+=P.get(B,xe,be,Ie,Y)*it)}}}D.set(le,B,Q,ee,J,Y)}return e.makeTensorInfo(D.shape,D.dtype,D.values)}},UM={kernelName:kd,backendName:"cpu",kernelFunc:function BM(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,input:i,output:a}=t,o=i;We([i,a],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,d=ks(o.shape,l,u,1,c,h),p=e.data.get(o.dataId).values,f=vt(d.outShape,o.dtype,Vw(p,o.shape,o.dtype,d).values),g=d.strideHeight,m=d.strideWidth,x=d.dilationHeight,y=d.dilationWidth,b=d.effectiveFilterHeight,v=d.effectiveFilterWidth,w=v-1-d.padInfo.left,S=b-1-d.padInfo.top,I=vt(o.shape,"float32"),k=e.data.get(r.dataId).values,D=vt(r.shape,"float32",k);for(let P=0;P=d.outHeight||Math.floor(te)!==te))for(let le=0;le=d.outWidth||Math.floor(ge)!==ge)continue;const be=b*v-1-f.get(P,te,ge,B)===ae*v+le?1:0;0!==be&&(se+=D.get(P,te,ge,B)*be)}}I.set(se,P,Y,Q,B)}return e.makeTensorInfo(I.shape,I.dtype,I.values)}},GM={kernelName:zg,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{filterSize:r,strides:i,pad:a,includeBatchInIndex:o}=t,l=e;We(s,"MaxPoolWithArgmax");const u=l.data.get(s.dataId).values,c=ks(s.shape,r,i,[1,1],a),[h,d]=function WM(n,t,e,s,r){const a=Bm(n,0,e,Ue(t),r,"max"),o=Vw(n,t,e,r,!0,s);return[a.values,o.values]}(u,s.shape,s.dtype,o,c),p=l.write(h,c.outShape,s.dtype),f=l.write(d,c.outShape,s.dtype);return[{dataId:p,shape:c.outShape,dtype:s.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}},jM={kernelName:Tu,backendName:"cpu",kernelFunc:function HM(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i,keepDims:a}=s,o=pt(i,r.shape),c=K(An(r.shape,o)[1]),h=[],d=e.makeTensorInfo([],"float32",new Float32Array([c]));h.push(d);const p=li({inputs:{x:r},backend:e,attrs:{dtype:"float32"}});h.push(p);const f=Gm({inputs:{a:p,b:d},backend:e});h.push(f);const g=Nl({inputs:{x:f},backend:e,attrs:{axis:i,keepDims:a}});return h.forEach(m=>e.disposeIntermediateTensorInfo(m)),g}},KM={kernelName:Su,backendName:"cpu",kernelFunc:function XM(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i,keepDims:a}=s;We(r,"min");const o=pt(i,r.shape);let l=o;const u=rn(l,r.shape.length);let c=r;null!=u&&(c=rs({inputs:{x:r},backend:e,attrs:{perm:u}}),l=dn(l.length,r.shape.length)),Fn("min",l,c.shape.length);const[h,d]=An(c.shape,l),p=K(d),f=yn(K(h),c.dtype),g=e.data.get(c.dataId).values;for(let x=0;xMath.min(n,t)),qM=Sn(Co,p_),ZM={kernelName:Co,backendName:"cpu",kernelFunc:qM},QM={kernelName:Cu,backendName:"cpu",kernelFunc:function YM(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{paddings:i,mode:a}=s;We(r,"mirrorPad");const o=i.map((b,v)=>b[0]+r.shape[v]+b[1]),l=i.map(b=>b[0]),u=i.map((b,v)=>b[0]+r.shape[v]),c="reflect"===a?0:1,h=e.data.get(r.dataId).values,d=r.shape.length,p=Ue(r.shape),f=K(o),g=o.length,m=Ue(o),x=Cn(r.dtype,f);for(let b=0;b=u[S]&&(v[S]=2*(u[S]-1)-v[S]+c);v=v.map((S,I)=>S-l[I]);const w=Is(v,d,p);x[b]=h[w]}return{dataId:e.write(x,o,r.dtype),shape:o,dtype:r.dtype}}},JM=mn((n,t)=>{const e=n%t;return n<0&&t<0||n>=0&&t>=0?e:(e+t)%t}),eV=Sn(Io,JM),tV={kernelName:Io,backendName:"cpu",kernelFunc:eV};function f_(n){const{inputs:t,backend:e,attrs:s}=n,{logits:r}=t,{dim:i}=s,a=r.shape.length;let o=i;if(-1===o&&(o=a-1),o!==a-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${a} and dim was ${o}`);const l=pt([o],r.shape),u=h_({inputs:{x:r},backend:e,attrs:{reductionIndices:l,keepDims:!1}}),c=hn(u.shape,l),h=qt({inputs:{x:u},backend:e,attrs:{shape:c}}),d=jm({inputs:{a:r,b:h},backend:e}),p=Yw({inputs:{x:d},backend:e}),f=Nl({inputs:{x:p},backend:e,attrs:{axis:l,keepDims:!1}}),g=qt({inputs:{x:f},backend:e,attrs:{shape:c}}),m=Gm({inputs:{a:p,b:g},backend:e});return e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(g),m}const nV={kernelName:Wu,backendName:"cpu",kernelFunc:f_},rV={kernelName:Bg,backendName:"cpu",kernelFunc:function sV(n){const{inputs:t,backend:e,attrs:s}=n,{logits:r}=t,{numSamples:i,seed:a,normalized:o}=s;We(r,"multinomial");const l=o?r:f_({inputs:{logits:r},backend:e,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],h=e.data.get(l.dataId).values,d=[u,i],p=yn(K(d),"int32");for(let f=0;fn!==t?1:0),gV=Sn(Eu,g_,null,"bool"),xV={kernelName:Eu,backendName:"cpu",kernelFunc:gV},bV={kernelName:Nu,backendName:"cpu",kernelFunc:function yV(n){const{inputs:t,backend:e,attrs:s}=n,{indices:r}=t,{dtype:i,depth:a,onValue:o,offValue:l}=s;We(r,"oneHot");const u=K(r.shape),c=new Float32Array(u*a);c.fill(l);const h=e.data.get(r.dataId).values;for(let d=0;d=0&&h[d]{Me(i,c.shape,"All tensors passed to stack must have matching shapes"),T(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=[],u=Da({inputs:t.map(c=>{const h=hh({inputs:{input:c},backend:e,attrs:{dim:r}});return o.push(h),h}),backend:e,attrs:{axis:r}});return o.forEach(c=>e.disposeIntermediateTensorInfo(c)),u}const _V={kernelName:Au,backendName:"cpu",kernelFunc:y_},b_={kernelName:Ru,backendName:"cpu",kernelFunc:function TV(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{paddings:i,constantValue:a}=s;We(r,"pad");const o=i.map((y,b)=>y[0]+r.shape[b]+y[1]),l=i.map(y=>y[0]),u=e.data.get(r.dataId).values,c=K(r.shape),h=r.shape.length,d=Ue(r.shape),p=K(o),f=o.length,g=Ue(o),m=Cn(r.dtype,p);0!==a&&m.fill(a);for(let y=0;yS+l[I]),f,g)]=u[y];return{dataId:e.write(m,o,r.dtype),shape:o,dtype:r.dtype}}},SV=mn((n,t)=>Math.pow(n,t)),CV=Sn(ko,SV),IV={kernelName:ko,backendName:"cpu",kernelFunc:CV};function v_(n,t,e,s){const[r,i]=An(n,s),a=ls(t,"int32"),o=yn(K(r),a),l=K(i);for(let u=0;ue.disposeIntermediateTensorInfo(y)),e.makeTensorInfo(x,m,f)}};function w_(n,t){const e=n.slice(0,t);for(;e.length{if(s<0||s>=e){const i=wr(r,t.length,Ue(t)).join(",");throw new Error(`indices[${i}] = ${s} is not in [0, ${e})`)}})}(i,a,t[0][0]-1),0===s.length)throw new Error("params.rank must be nonzero");const u=s[0],{outSplits:c,valueSlices:h,numValues:d}=function RV(n,t,e,s){const r=[];let i=0;const o=new Array(t.length-1+e.length).fill(null).map(()=>[0]);!function AV(n,t){for(let e=0;er)throw new Error("Ragged splits must not point past values");for(let i=1;is[i])throw new Error("Ragged splits must be sorted in ascending order")}}(e,s);let l=1;for(let u=0;u=0){const g=o[f],m=g[g.length-1]-p[c];for(let x=c;xr[a]=i)}return t}(c),f=function OV(n,t,e,s,r){const i=t.slice();i[0]=r;const a=$t(e,K(i)),o=n.length;return function DV(n,t,e,s,r,i){const a=w_(t,2)[1],o=w_(i,2)[1];let l=0;for(const u of e)for(let c=u[0];ce.data.get(x.dataId).values),u=r.map(x=>x.shape),c=e.data.get(i.dataId).values,h=e.data.get(a.dataId).values,[d,p,f]=__(l,u,c,i.shape,i.dtype,h,a.shape),g=d.map(x=>e.makeTensorInfo([x.length],"int32",x)),m=e.makeTensorInfo(f,i.dtype,p);return g.concat([m])}},T_=2147483647;function S_(n,t,e,s,r,i,a){if(t.length>1)throw new Error("starts must be a scalar or vector");if(r.length>1)throw new Error("limits must be a scalar or vector");if(a.length>1)throw new Error("deltas must be a scalar or vector");const o=0===t.length,l=0===r.length,u=0===a.length,c=[];o||c.push(t[0]),l||c.push(r[0]),u||c.push(a[0]);for(let m=1;m0&&yx)v=0;else if(v=Math.ceil(Math.abs((y-x)/b)),v>T_)throw new Error(`Requires ((limit - start) / delta) <= ${T_}`);d[m+1]=d[m]+v}const f=$t(e,d[h]);let g=0;for(let m=0;ms&&(s=i)}return s}static getMaxWidthValueRowID(t){const e=t.length;if(0===e)return 0;let s=0,r=t[0],i=0;for(let a=1;a"Final length of result must be equal to firstDimension."),i}calculateOutputIndexRowSplit(t,e,s,r){const i=t.length,a=[];for(let o=0;o0&&a.length!==t[i-1])throw new Error("Invalid row split size.");return a}calculateOutputIndexValueRowID(t,e,s,r){const i=t.length,a=[];if(0===i)return[];let o=0,l=t[0];if(l>=e.length)throw new Error(`Got currentValueRowId=${l}, which is not less than ${e.length}`);let u=e[l];a.push(u);for(let c=1;c=0&&(++o,o=e.length)throw new Error(`Got nextValueRowId=${h} which is not less than ${e.length}`);u=e[h]}a.push(u)}if(a.length!==t.length)throw new Error("Invalid row ids.");return a}calculateOutputIndex(t,e,s,r){const i=this.getRowPartitionTensor(t),a=this.getRowPartitionTypeByDimension(t);switch(a){case Ps.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(i,e,s,r);case Ps.ROW_SPLITS:if(i.length-1>e.length)throw new Error(`Row partition size is greater than output size: ${i.length-1} > ${e.length}`);return this.calculateOutputIndexRowSplit(i,e,s,r);default:throw new Error(`Unsupported partition type: ${Ps[a]}`)}}getFirstDimensionSize(){const t=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const e=this.rowPartitionTypes[0];switch(e){case Ps.FIRST_DIM_SIZE:return t[0];case Ps.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case Ps.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${Ps[e]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),s=this.calculateOutputSize(e),r=new Array(this.raggedRank+1);r[r.length-1]=1;for(let l=r.length-2;l>=0;--l)r[l]=r[l+1]*s[l+1];const i=I_(s,!1),a=$t(this.valuesDType,K(i));if(r[0]*s[0]>0){let l=this.calculateFirstParentOutputIndex(e,r[0],s[0]);for(let u=1;u<=this.raggedRank;++u)l=this.calculateOutputIndex(u-1,l,r[u],s[u]);this.setOutput(this.raggedRank,l,a,i)}return[i,a]}setOutput(t,e,s,r){if(0===s.length)return;const i=this.values,a=s;let o=r.slice();o=o.slice(t+1);const l=K(o),u=e.length;let c=this.defaultValue;if(c.length!==l&&1!==c.length){const f=this.defaultValueShape;Z(()=>{const g=j(c,f);c=rl(g,o).dataSync()})}let h=0,d=0,p=0;for(let f=0;f<=u;++f){let g=f=u&&(g=Math.floor(s.length/l)),g>p)if(1===this.defaultValue.length)a.subarray(p*l,g*l).fill(this.defaultValue[0]),p=g;else for(;g>p;)C_(a.slice(p*l),c,l),++p;g<0?(h=f+1,d=p):(h=f,d=p,p=d+1)}else++p}}}function C_(n,t,e){for(let s=0;s= 0`);if(s<-1)throw new Error(`Dimension ${s} must be >= -1`);s=-1}e.push(s)}return e}function E_(n,t,e,s,r,i,a,o,l,u){return new ph(n,t,e,s,r,i,a,o,l,u).compute()}const zV={kernelName:Gg,backendName:"cpu",kernelFunc:function VV(n){const{inputs:t,backend:e,attrs:s}=n,{shape:r,values:i,defaultValue:a,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=s,u=e.data.get(r.dataId).values,c=e.data.get(i.dataId).values,h=e.data.get(a.dataId).values,d=o.map(m=>e.data.get(m.dataId).values),p=o.map(m=>m.shape),[f,g]=E_(u,r.shape,c,i.shape,i.dtype,h,a.shape,d,p,l);return e.makeTensorInfo(f,i.dtype,g)}};function k_(n,t,e,s){if(n===t||n1)return yn(0,s);const l=yn(Math.abs(Math.ceil((t-n)/e)),s);t1/n),GV={kernelName:No,backendName:"cpu",kernelFunc:WV},jV={kernelName:Fu,backendName:"cpu",kernelFunc:function HV(n){const{inputs:t,backend:e,attrs:s}=n,{images:r}=t,{alignCorners:i,halfPixelCenters:a,size:o}=s;We(r,"resizeBilinear");const l=Ue(r.shape),[u,c]=o,[h,d,p,f]=r.shape,g=e.data.get(r.dataId).values,m=new Float32Array(K([h,u,c,f])),x=[i&&u>1?d-1:d,i&&c>1?p-1:p],y=[i&&u>1?u-1:u,i&&c>1?c-1:c];let b=0;const v=x[0]/y[0],w=x[1]/y[1];for(let S=0;S1?u-1:u,a&&p>1?c-1:c],m=[a&&d>1?d-1:d,a&&p>1?p-1:p],x=g[0]/m[0],y=g[1]/m[1],b=e.data.get(i.dataId).values;let v=0;for(let w=0;w1?d-1:d,i&&c>1?p-1:p],y=[i&&u>1?u-1:u,i&&c>1?c-1:c],b=x[0]/y[0],v=x[1]/y[1];let w=0;for(let S=0;S1?c-1:c,a&&f>1?h-1:h],y=[a&&p>1?p-1:p,a&&f>1?f-1:f],b=x[0]/y[0],v=x[1]/y[1],w=1/b,S=1/v,I=2*Math.ceil(w)+2,k=2*Math.ceil(S)+2;for(let D=0;D=p)continue;const be=P+Se*l[1],De=Se*b;if(B===Math.min(c-1,a?Math.round(De):Math.floor(De)))for(let Le=0;Le=f)continue;const it=be+Ze*l[2],tt=Ze*v;J===Math.min(h-1,a?Math.round(tt):Math.floor(tt))&&(ge+=m[it+le])}}g[se+le]=ge}}}}return e.makeTensorInfo(r.shape,r.dtype,g)}},e3={kernelName:Lu,backendName:"cpu",kernelFunc:function JV(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{dims:i}=s;We(r,"reverse");const a=r.shape.length,o=pt(i,r.shape);if(0===a)return gr({inputs:{x:r},backend:e});const l=new On(r.shape,r.dtype),u=e.bufferSync(r);for(let c=0;cd[p]=r.shape[p]-1-d[p]),l.set(u.get(...d),...h)}return e.makeTensorInfo(l.shape,l.dtype,l.values)}},t3={kernelName:Zd,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{image:s}=n,{radians:r,fillValue:i,center:a}=t,o=e,l=Cn(s.dtype,K(s.shape)),[u,c,h,d]=s.shape,[p,f]=mf(a,c,h),m=Math.sin(r),x=Math.cos(r),y=o.data.get(s.dataId).values;for(let v=0;v=0&&ee=0&&J{const t=Math.floor(n);return n-t<.5?Math.floor(n):n-t>.5?Math.ceil(n):t%2==0?t:t+1}),s3={kernelName:$o,backendName:"cpu",kernelFunc:n3},N_=mr(n=>1/Math.sqrt(n)),r3=oi(Do,N_),i3={kernelName:Do,backendName:"cpu",kernelFunc:r3};function Ki(n,t,e,s,r,i,a,o,l,u){const c=[s/r,r],h=n.values,d=t.values;if(0===s)return vt(e,t.dtype);const p=l instanceof On?l:vt(c,t.dtype);"string"==typeof l||"number"==typeof l?p.values.fill(l):"boolean"==typeof l&&p.values.fill(+l);for(let f=0;f=s/r)throw new Error(`Invalid indices: ${g} does not index into ${e}`);for(let x=0;x1||1===r.shape.length?1:K(r.shape.slice(1));for(let f=0;fn>=0?g3*n:m3*(Math.exp(n)-1)),y3={kernelName:Oo,backendName:"cpu",kernelFunc:x3},b3=Mt(Lo,n=>n<0?-1:n>0?1:0),v3={kernelName:Lo,backendName:"cpu",kernelFunc:b3},w3=Mt(Po,n=>Math.sin(n)),_3={kernelName:Po,backendName:"cpu",kernelFunc:w3},T3=Mt(Fo,n=>Math.sinh(n)),S3={kernelName:Fo,backendName:"cpu",kernelFunc:T3},A_=Math.log(1.1920928955078125e-7)+2,C3=Mt(Vo,n=>{const t=n>-A_,e=n=l)throw new Error(Jy(m,x,l));++f[x],d=d&&x>=p,p=x}let g=!0;for(let m=0;m0&&(f[m]+=f[m-1])}if(g&&d){const m=n,x=s;for(let y=0;yNumber(m)))),e.makeTensorInfo([g.length],s.dtype,new Int32Array(g))]}};function $_(n,t,e,s,r){const i=K(s),a=t[0],o=r.length,l=[];let u=1,c=-1;for(let m=0;m0){p[d-1]=1;for(let m=d-2;m>=0;--m)p[m]=p[m+1]*s[m+1]}const f=[];if(o>0){f[o-1]=1;for(let m=o-2;m>=0;--m)f[m]=f[m+1]*l[m+1]}const g=$t(e,a*o);for(let m=0;m0?r[o-1]+1:0;if(h<0)throw new Error("segment ids must be >= 0");const d=t.slice();d[0]=h;const f=$t(e,d.reduce((b,v)=>b*v,1));if(0===o)return h>0&&f.fill(a),[f,d];if(h<=0)throw new Error("segment ids must be >= 0");let g=0,m=1,x=0,y=r[g];for(;;){let b=0;if(m=b)throw new Error("segment ids are not increasing")}if(y<0||y>=h)throw new Error(ab(y,h));y>x&&f.fill(a,x*u,y*u);for(let v=g;v=l[0])throw new Error(ob(v,s[v],l[0]));for(let S=0;So)break}return x{const d=[...c];d[o]=h;const p=Xi({inputs:{x:r},backend:e,attrs:{begin:u,size:d}});return u[o]+=h,p})}},B3=mr(n=>Math.sqrt(n)),U3=Mt(zo,n=>Math.sqrt(n)),W3={kernelName:zo,backendName:"cpu",kernelFunc:U3},G3={kernelName:Bd,backendName:"cpu",kernelFunc:({inputs:n,backend:t})=>{const{x:e}=n,s=t;We(e,"square");const r=s.data.get(e.dataId).values,i=new Float32Array(r.length);for(let o=0;o{const e=n-t;return e*e}),j3=Sn(Bo,H3),X3={kernelName:Bo,backendName:"cpu",kernelFunc:j3},D_=mr((n,t)=>{const{pattern:e,replaceGlobal:s,rewrite:r}=t;return n.replace(new RegExp(e,s?"g":""),r)}),q3={kernelName:Gu,backendName:"cpu",kernelFunc:oi(Gu,D_)},Z3=Mt(jo,(n,t)=>{const e=t;return isNaN(n)?NaN:n>0?1:e.alpha}),Y3={kernelName:jo,backendName:"cpu",kernelFunc:Z3};function O_(n,t,e,s){const r=vt(n,t.dtype);for(let i=0;i=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);const S=$p(y,b,v),I=Xi({inputs:{x:r},backend:e,attrs:{begin:y,size:S}});w=qt({inputs:{x:I},backend:e,attrs:{shape:f}}),e.disposeIntermediateTensorInfo(I)}else{const I=O_(p,e.bufferSync(r),v,y);w=e.makeTensorInfo(f,I.dtype,I.values)}return w}};class ez{constructor(t,e,s,r,i,a){this.separator=Ur(t),this.nGramWidths=e,this.leftPad=Ur(s),this.rightPad=Ur(r),this.padWidth=i,this.preserveShort=a}getPadWidth(t){return Math.min(this.padWidth<0?t-1:this.padWidth,t-1)}getNumNGrams(t,e){const s=this.getPadWidth(e);return Math.max(0,t+2*s-e+1)}createNGrams(t,e,s,r,i,a){for(let o=0;o0?0:o-l);let p=0;p+=u*this.leftPad.length;for(let y=0;yy.forEach(b=>g[m++]=b);for(let y=0;y0){x(t[d+h-1]);for(let y=0;y0){let l=e[0];if(0!==l)throw new Error(`First split value must be 0, got ${l}`);for(let u=1;u=l;if(c=c&&e[u]<=s,!c)throw new Error(`Invalid split value ${e[u]}, must be in [${l}, ${s}]`);l=e[u]}if(l!==s)throw new Error(`Last split value must be data size. Expected ${s}, got ${l}`)}const i=r-1,a=$t("int32",r);if(0===s||0===r){const l=new Array(s);for(let u=0;u<=i;++u)a[u]=0;return[l,a]}a[0]=0;for(let l=1;l<=i;++l){const u=e[l]-e[l-1];let c=0;this.nGramWidths.forEach(h=>{c+=this.getNumNGrams(u,h)}),this.preserveShort&&u>0&&0===c&&(c=1),a[l]=a[l-1]+c}const o=new Array(a[i]);for(let l=0;l{const p=this.getNumNGrams(e[l+1]-e[l],h);this.createNGrams(t,u,o,c,p,h),c+=p}),this.preserveShort&&c===a[l]){const h=e[l+1]-e[l];if(0===h)continue;this.createNGrams(t,u,o,c,1,h+2*this.padWidth)}}return[o,a]}}function P_(n,t,e,s,r,i,a,o){return new ez(e,s,r,i,a,o).compute(n,t)}const nz={kernelName:Wd,backendName:"cpu",kernelFunc:function tz(n){const{inputs:t,backend:e,attrs:s}=n,{separator:r,nGramWidths:i,leftPad:a,rightPad:o,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=t,d=e.data.get(c.dataId).values,p=e.data.get(h.dataId).values,[f,g]=P_(d,p,r,i,a,o,l,u);return[e.makeTensorInfo([f.length],"string",f),e.makeTensorInfo(h.shape,"int32",g)]}};function sz(n,t,e,s){if(!n.length)return;if(0===t.length){for(let i=0;iMath.tan(n)),uz={kernelName:Wo,backendName:"cpu",kernelFunc:lz},cz=Mt(Go,n=>Math.tanh(n));function M_(n,t){const e=new Array(n.rank);for(let r=0;r{const e=t.value-n.value;return 0===e?n.index-t.index:e};function V_(n,t,e=0,s=n.length-1){for(;s>e;){if(s-e>600){const o=s-e+1,l=t-e+1,u=Math.log(o),c=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*c*(o-c)/o)*Math.sign(l-o/2);V_(n,t,Math.max(e,Math.floor(t-l*c/o+h)),Math.min(s,Math.floor(t+(o-l)*c/o+h)))}const r=n[t];let i=e,a=s;for(M(n,e,t),Al(n[s],r)>0&&M(n,e,s);i0;)a-=1}0===Al(n[e],r)?M(n,e,a):(a+=1,M(n,a,s)),a<=t&&(e=a+1),t<=a&&(s=a-1)}}function z_(n,t,e,s,r){const i=t[t.length-1],[a,o]=[n.length/i,i],l=Cn(e,a*s),u=Cn("int32",a*s);for(let h=0;hf[b]={value:y,index:b}),st-1)if(t<=1)e=0;else{const s=2*t;e-=s*Math.trunc(e/s),e>=t&&(e=s-e-1)}return G(0,e,t-1)}(n,t);case"wrap":return function wz(n,t){let e=n;return e<0?t<=1?e=0:e+=t*(Math.trunc(-e/(t-1))+1):e>t-1&&(t<=1?e=0:e-=t*Math.trunc(e/(t-1))),G(0,e,t-1)}(n,t);case"nearest":return function Tz(n,t){return G(0,n,t-1)}(n,t);default:return function _z(n){return n}(n)}}function Rl(n,t,e,s,r,i,a,o,l,u,c){return 0<=o&&o{for(let m=0;me.disposeIntermediateTensorInfo(f)),p}},vV];for(const n of $z)Qd(n);const ui={},fh={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Zs(n,t){if(!(n in ui)||null!=t){const s=function Pz(n,t){if(1!==n&&2!==n)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const e=t??function Oz(n){if(!E().getBool("IS_SAFARI")&&typeof OffscreenCanvas<"u"&&2===n)return new OffscreenCanvas(300,150);if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(n);return e.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete ui[n]},!1),E().getBool("SOFTWARE_WEBGL_ENABLED")&&(fh.failIfMajorPerformanceCaveat=!1),1===n?e.getContext("webgl",fh)||e.getContext("experimental-webgl",fh):e.getContext("webgl2",fh)}(n,t);if(null===s)return console.log("Could not get context for WebGL version",n),null;ui[n]=s}const e=ui[n];return null==e||e.isContextLost()?(delete ui[n],Zs(n)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),ui[n])}var mh=function(n){return n[n.DENSE=0]="DENSE",n[n.SHARED_BATCH=1]="SHARED_BATCH",n}(mh||{}),Fs=function(n){return n[n.RENDER=0]="RENDER",n[n.UPLOAD=1]="UPLOAD",n[n.PIXELS=2]="PIXELS",n[n.DOWNLOAD=3]="DOWNLOAD",n}(Fs||{}),Gn=function(n){return n[n.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",n[n.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",n[n.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",n[n.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",n[n.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16",n}(Gn||{});function $l(n,t){return[t,n]}function gh(n){const t=K(n);return Vs(Math.ceil(t/4))}function Oa(n,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(n/2))]}function Zm(n,t){const e=n;let s,r,i,a,o,l,u,c,h,d;return 2===E().getNumber("WEBGL_VERSION")?(s=e.R32F,r=e.R16F,i=e.RGBA16F,a=e.RGBA32F,o=e.RED,u=4,c=1,h=e.HALF_FLOAT,d=e.FLOAT,l=e.RGBA8):(s=n.RGBA,r=n.RGBA,i=n.RGBA,a=e.RGBA,o=n.RGBA,u=4,c=4,h=null!=t?t.HALF_FLOAT_OES:null,d=n.FLOAT,l=n.RGBA),{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:a,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:d}}function Ae(n,t){const e=t();return E().getBool("DEBUG")&&function Mz(n){const t=n.getError();if(t!==n.NO_ERROR)throw new Error("WebGL Error: "+function Uz(n,t){switch(t){case n.NO_ERROR:return"NO_ERROR";case n.INVALID_ENUM:return"INVALID_ENUM";case n.INVALID_VALUE:return"INVALID_VALUE";case n.INVALID_OPERATION:return"INVALID_OPERATION";case n.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case n.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case n.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}(n,t))}(n),e}function Bz(n){return!!(E().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===n||5.96e-8n.getExtension(t),'Extension "'+t+'" not supported on this browser.')}const Hz=/ERROR: [0-9]+:([0-9]+):/g;function W_(n,t){const e=Hz.exec(t);if(null==e)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(n);const s=+e[1],r=n.split("\n"),i=r.length.toString().length+2,a=r.map((h,d)=>zs((d+1).toString(),i)+h);let o=0;for(let h=0;hn.validateProgram(t)),!1===n.getProgramParameter(t,n.VALIDATE_STATUS))throw console.log(n.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function G_(n,t,e,s,r,i,a){const o=n.getAttribLocation(t,e);return-1!==o&&(Ae(n,()=>n.bindBuffer(n.ARRAY_BUFFER,s)),Ae(n,()=>n.vertexAttribPointer(o,r,n.FLOAT,!1,i,a)),Ae(n,()=>n.enableVertexAttribArray(o)),!0)}function nB(n,t,e,s){Ae(n,()=>function Jz(n,t,e){(function j_(n,t){const e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+n.TEXTURE0;if(se)throw new Error(`textureUnit must be in [gl.TEXTURE0, gl.TEXTURE${e}].`)})(n,e),Ae(n,()=>n.activeTexture(n.TEXTURE0+e)),Ae(n,()=>n.bindTexture(n.TEXTURE_2D,t))}(n,t,s)),Ae(n,()=>n.uniform1i(e,s))}function Qm(n,t,e){Ae(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,e)),Ae(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0))}function H_(n,t){Ae(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,t)),Ae(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0))}function yh(n){const t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function sB(n,t){switch(t){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}(n,t))}function Dr(n,t,e){const s=Ae(n,()=>t());if(null==s)throw new Error(e);return s}function Pa(n,t=2){return K(n.slice(0,n.length-t))}function Fa(n){if(0===n.length)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function bh(n){let t=[1,1,1];return 0===n.length||1===n.length&&1===n[0]||(t=[Pa(n),...Fa(n)]),t}function vh(n){return n%2==0}function wh(n,t){if(rt(n=n.slice(-2),t=t.slice(-2))||!n.length||!t.length||0===n[0]||0===n[1]||0===t[0]||0===t[1])return!0;if(n.length!==t.length){const e=n[n.length-1],s=t[t.length-1];if(e===s||vh(e)&&vh(s)&&(1===n[0]||1===t[0]))return!0}return n[1]===t[1]&&vh(n[0])&&vh(t[0])}let _h,Th;function Ls(n,t){return null!=n.getExtension(t)}function X_(n){try{if(null!=Zs(n))return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function Jm(n){const t=Zm(n),e=n.createTexture();n.bindTexture(n.TEXTURE_2D,e),n.texImage2D(n.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const i=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,i),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0);const a=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(e),n.deleteFramebuffer(i),a}function Dl(n,t){Array.isArray(n)||(n=[n]),n.forEach(e=>{null!=e&&T("complex64"!==e.dtype,()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const He=E();function Qn(){let n,t,e,s,r,i,a,o,l,u;return 2===E().getNumber("WEBGL_VERSION")?(n="#version 300 es",t="in",e="out",s="in",r="texture",i="outputColor",a="out vec4 outputColor;",o=E().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 ":"",l="",u="\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 "):(n="",t="attribute",e="varying",s="varying",r="texture2D",i="gl_FragColor",a="",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 ",l="\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 ",u="\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:n,attribute:t,varyingVs:e,varyingFs:s,texture2D:r,output:i,defineOutput:a,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function qi(n,t,e="index"){const s=Ue(t);return s.map((r,i)=>`int ${n[i]} = ${e} / ${r}; ${i===s.length-1?`int ${n[i+1]} = ${e} - ${n[i]} * ${r}`:`index -= ${n[i]} * ${r}`};`).join("")}function Sh(n,t,e="index"){const s=Ue(t);return s.map((r,i)=>`int ${n[i]} = ${e} / outShapeStrides[${i}]; ${i===s.length-1?`int ${n[i+1]} = ${e} - ${n[i]} * outShapeStrides[${i}]`:`index -= ${n[i]} * outShapeStrides[${i}]`};`).join("")}function eg(n){const t=Ue(n).map(e=>e.toString());return`\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n }\n`}He.registerFlag("HAS_WEBGL",()=>He.getNumber("WEBGL_VERSION")>0),He.registerFlag("WEBGL_VERSION",()=>X_(2)?2:X_(1)?1:0),He.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),He.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>2===He.get("WEBGL_VERSION")),He.registerFlag("WEBGL_CPU_FORWARD",()=>!0),He.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),He.registerFlag("WEBGL_PACK",()=>He.getBool("HAS_WEBGL")),He.registerFlag("WEBGL_PACK_NORMALIZATION",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_PACK_CLIP",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_PACK_REDUCE",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_LAZILY_UNPACK",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_CONV_IM2COL",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>He.getBool("WEBGL_PACK")),He.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>function iB(n){if(null==_h){const t=Zs(n);_h=t.getParameter(t.MAX_TEXTURE_SIZE)}return _h}(He.getNumber("WEBGL_VERSION"))),He.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>function aB(n){if(null==Th){const t=Zs(n);Th=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Th)}(He.getNumber("WEBGL_VERSION"))),He.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const n=He.getNumber("WEBGL_VERSION");return 0===n?0:function oB(n){if(0===n)return 0;let t;const e=Zs(n);return t=Ls(e,"EXT_disjoint_timer_query_webgl2")&&2===n?2:Ls(e,"EXT_disjoint_timer_query")?1:0,t}(n)}),He.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>He.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!px()),He.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>function lB(n){if(0===n)return!1;const t=Zs(n);if(1===n){if(!Ls(t,"OES_texture_float"))return!1}else if(!Ls(t,"EXT_color_buffer_float"))return!1;return Jm(t)}(He.getNumber("WEBGL_VERSION"))),He.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>!He.getBool("WEBGL_FORCE_F16_TEXTURES")&&He.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),He.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>function uB(n){if(0===n)return!1;const t=Zs(n);if(1!==n){if(Ls(t,"EXT_color_buffer_float"))return Jm(t);const s="EXT_color_buffer_half_float";if(Ls(t,s)){const r=t.getExtension(s);return function cB(n,t){const e=Zm(n,t),s=n.createTexture();n.bindTexture(n.TEXTURE_2D,s),n.texImage2D(n.TEXTURE_2D,0,e.internalFormatHalfFloat,1,1,0,e.textureFormatFloat,e.textureTypeHalfFloat,null);const a=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,s,0);const o=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(s),n.deleteFramebuffer(a),o}(t,r)}return!1}return!(!Ls(t,"OES_texture_float")||!Ls(t,"WEBGL_color_buffer_float"))&&Jm(t)}(He.getNumber("WEBGL_VERSION"))),He.registerFlag("WEBGL_FENCE_API_ENABLED",()=>function hB(n){return 2===n&&null!=Zs(n).fenceSync}(He.getNumber("WEBGL_VERSION"))),He.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>He.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0),He.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,n=>{if("number"!=typeof n)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${n}.`);if(n<0&&-1!==n)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${n}.`)}),He.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>px()?1:-1,n=>{if("number"!=typeof n)throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${n}.`);if(n<0&&-1!==n)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${n}.`)}),He.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128),He.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1),He.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5),He.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128),He.registerFlag("WEBGL_EXP_CONV",()=>!1),He.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>He.getBool("IS_TEST")),He.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0),He.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1),He.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1),He.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);const K_="\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:q_}=Ke;function fB(n,t,e){const s=[];if(n.forEach(p=>{const f=K(p.shapeInfo.logicalShape);if(p.shapeInfo.isUniform?s.push(`uniform float ${p.name}${f>1?`[${f}]`:""};`):(s.push(`uniform sampler2D ${p.name};`),s.push(`uniform int offset${p.name};`)),e.enableShapeUniforms){const{uniformShape:g}=ng(e.packedInputs,p.shapeInfo.logicalShape,p.shapeInfo.texShape);switch(g.length){case 1:s.push(`uniform int ${p.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${p.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${p.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${p.name}Shape;`)}s.push(`uniform ivec2 ${p.name}TexShape;`)}}),e.enableShapeUniforms){switch(t.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;")}s.push("uniform ivec2 outTexShape;")}e.customUniforms&&e.customUniforms.forEach(p=>{s.push(`uniform ${p.type} ${p.name}${p.arrayIndex?`[${p.arrayIndex}]`:""};`)});const r=s.join("\n"),i=n.map(p=>function mB(n,t,e=!1,s){let r="";r+=e?Z_(n,s):La(n,s);return n.shapeInfo.logicalShape.length<=t.logicalShape.length&&(r+=e?function KB(n,t){const e=n.name,s=e.charAt(0).toUpperCase()+e.slice(1),r="get"+s+"AtOutCoords",i=n.shapeInfo.logicalShape.length,a=t.logicalShape.length,o=q_(n.shapeInfo.logicalShape,t.logicalShape),l=Ut(a),u=a-i;let c;const h=["x","y","z","w","u","v"];c=0===i?"":a<2&&o.length>=1?"coords = 0;":o.map(y=>`coords.${h[y+u]} = 0;`).join("\n");let d="";d=a<2&&i>0?"coords":n.shapeInfo.logicalShape.map((y,b)=>`coords.${h[b+u]}`).join(", ");let p="return outputValue;";const g=1===K(n.shapeInfo.logicalShape),x=1===K(t.logicalShape);if(1!==i||g||x){if(g&&!x)p=1===a?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(o.length){const y=i-2,b=i-1;o.indexOf(y)>-1&&o.indexOf(b)>-1?p="return vec4(outputValue.x);":o.indexOf(y)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(b)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}}else p="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${r}() {\n ${l} coords = getOutputCoords();\n ${c}\n vec4 outputValue = get${s}(${d});\n ${p}\n }\n `}(n,t):function qB(n,t){const e=n.name,s=e.charAt(0).toUpperCase()+e.slice(1),r="get"+s+"AtOutCoords",o=n.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!n.shapeInfo.isUniform&&o===l&&null==n.shapeInfo.flatOffset&&rt(n.shapeInfo.texShape,t.texShape))return`\n float ${r}() {\n return sampleTexture(${e}, resultUV);\n }\n `;const u=Ut(l),c=q_(n.shapeInfo.logicalShape,t.logicalShape),h=l-o;let d;const p=["x","y","z","w","u","v"];d=0===o?"":l<2&&c.length>=1?"coords = 0;":c.map(g=>`coords.${p[g+h]} = 0;`).join("\n");let f="";return f=l<2&&o>0?"coords":n.shapeInfo.logicalShape.map((g,m)=>`coords.${p[m+h]}`).join(", "),`\n float ${r}() {\n ${u} coords = getOutputCoords();\n ${d}\n return get${s}(${f});\n }\n `}(n,t)),r}(p,t,e.packedInputs,e.enableShapeUniforms)).join("\n"),a=t.texShape,o=Qn(),l=function yB(n){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${n.texture2D}(textureSampler, uv).r;\n }\n `}(o);let u,c,h=function wB(n){return`${n.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${n.varyingFs} vec2 resultUV;\n ${n.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 ${n.defineSpecialNaN}\n ${n.defineSpecialInf}\n ${n.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 ${_B}\n ${TB}\n ${SB}\n `}(o);return t.isPacked?(u=function gB(n,t,e){switch(n.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function IB(n,t,e){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===s[0]?e?"\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 * ${s[1]}.0);\n }\n `:1===s[1]?e?"\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 * ${s[0]}.0);\n }\n `:e?"\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 ":`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);\n }\n `}(0,t,e);case 2:return function OB(n,t,e){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(rt(n,t))return e?"\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(${s[0]}, ${s[1]}));\n }\n `;const r=Math.ceil(n[1]/2);return e?"\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 ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n\n int index = resTexRC.x * ${s[1]} + resTexRC.y;\n int r = 2 * (index / ${r});\n int c = imod(index, ${r}) * 2;\n\n return ivec2(r, c);\n }\n `}(n,t,e);case 3:return function kB(n,t,e){if(e)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 s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[2]/2),i=r*Math.ceil(n[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${s[0]}, ${s[1]}));\n int index = resTexRC.x * ${s[1]} + resTexRC.y;\n\n int b = index / ${i};\n index -= b * ${i};\n\n int r = 2 * (index / ${r});\n int c = imod(index, ${r}) * 2;\n\n return ivec3(b, r, c);\n }\n `}(n,t,e);default:return function AB(n,t,e){if(e)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 s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[n.length-1]/2),i=r*Math.ceil(n[n.length-2]/2);let a=i,o="",l="b, r, c";for(let u=2;u1&&!rt(t,e)&&s.lengthn[e]).join(", ")}function Q_(n,t,e){const s=[],r=[];let i,a,o,l=null,u=null;u=n.getUniformLocation(e,"NAN",!1),1===E().getNumber("WEBGL_VERSION")&&(l=n.getUniformLocation(e,"INFINITY",!1));const c=!1;for(const h of t.variableNames){const d={name:h,uniform:n.getUniformLocation(e,h,c),offset:n.getUniformLocation(e,`offset${h}`,c)};t.enableShapeUniforms&&(d.shape=n.getUniformLocation(e,`${h}Shape`,c),d.texShape=n.getUniformLocation(e,`${h}TexShape`,c)),s.push(d)}if(t.enableShapeUniforms&&(i=n.getUniformLocation(e,"outShape",c),o=n.getUniformLocation(e,"outShapeStrides",c),a=n.getUniformLocation(e,"outTexShape",c)),t.customUniforms)for(const h of t.customUniforms)r.push(n.getUniformLocation(e,h.name,c));return{variablesLocations:s,customUniformLocations:r,infLoc:l,nanLoc:u,outShapeLocation:i,outShapeStridesLocation:o,outTexShapeLocation:a}}function J_(n,t){if(n.length!==t.length)throw Error(`Binary was compiled with ${n.length} inputs, but was executed with ${t.length} inputs`);n.forEach((e,s)=>{const r=e.logicalShape,i=t[s],a=i.shape;if(!rt(r,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${a} must match`);if(e.isUniform&&i.isUniform)return;const o=e.texShape,l=i.isUniform?null:i.texData.texShape;if(!rt(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function Hn(n){return E().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&n<=4}class JB{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=mh.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const e=Qn();this.outputShape=t,this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Sh(["r","c","d"],t):qi(["r","c","d"],t)}\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 ${e.output} = result;\n }\n `}}class eU{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=mh.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const e=Qn();this.outputShape=t,this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Sh(["r","c","d"],t):qi(["r","c","d"],t)}\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 ${e.output} = result;\n }\n `}}class tU{constructor(t){this.variableNames=["A"],this.outTexUsage=Fs.DOWNLOAD;const e=Qn();this.outputShape=t,this.userCode=`\n ${K_}\n\n void main() {\n float x = getAAtOutCoords();\n ${e.output} = encode_float(x);\n }\n `}}class nU{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Fs.DOWNLOAD;const e=Qn();this.outputShape=t,this.userCode=`\n ${K_}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${e.output} = encode_float(x);\n }\n `}}const sU={R:0,G:1,B:2,A:3};class eT{constructor(t,e=!1,s="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=Qn();this.outputShape=t,this.enableShapeUniforms=Hn(this.outputShape.length);let i="result";e&&(i="floor(result * 255. + 0.5)");let a="";for(let o=0;oe||t>e)throw new Error(`Requested texture size [${n}x${t}] greater than WebGL maximum on this browser / GPU [${e}x${e}].`)}(t,e);const a=function Zz(n){return Dr(n,()=>n.createTexture(),"Unable to create WebGLTexture.")}(n),o=n.TEXTURE_2D;return Ae(n,()=>n.bindTexture(o,a)),Ae(n,()=>n.texParameteri(o,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)),Ae(n,()=>n.texParameteri(o,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),Ae(n,()=>n.texParameteri(o,n.TEXTURE_MIN_FILTER,n.NEAREST)),Ae(n,()=>n.texParameteri(o,n.TEXTURE_MAG_FILTER,n.NEAREST)),1===E().getNumber("WEBGL_VERSION")?Ae(n,()=>n.texImage2D(o,0,s,t,e,0,r,i,null)):Ae(n,()=>n.texStorage2D(o,1,s,t,e)),Ae(n,()=>n.bindTexture(n.TEXTURE_2D,null)),{texture:a,texShape:[e,t]}}function tT(n){return n.internalFormatFloat}function nT(n){return n.internalFormatHalfFloat}function sT(n){return n.downloadTextureFormat}function rT(n){return n.internalFormatPackedFloat}function iT(n){return n.internalFormatPackedHalfFloat}class sg{constructor(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const e=E().getNumber("WEBGL_VERSION");if(null!=t?(this.gl=t,function Dz(n,t){ui[n]=t}(e,t)):this.gl=Zs(e),t=this.gl,2===E().getNumber("WEBGL_VERSION")){const i=t;this.createVertexArray=()=>Ae(i,()=>i.createVertexArray()),this.bindVertexArray=a=>Ae(i,()=>i.bindVertexArray(a)),this.deleteVertexArray=a=>Ae(i,()=>i.deleteVertexArray(a)),this.getVertexArray=()=>Ae(i,()=>i.getParameter(i.VERTEX_ARRAY_BINDING))}else if(null!=t){const i=t.getExtension("OES_vertex_array_object");if(null==i)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>Ae(t,()=>i.createVertexArrayOES()),this.bindVertexArray=a=>Ae(t,()=>i.bindVertexArrayOES(a)),this.deleteVertexArray=a=>Ae(t,()=>i.deleteVertexArrayOES(a)),this.getVertexArray=()=>Ae(t,()=>t.getParameter(i.VERTEX_ARRAY_BINDING_OES))}let s="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===E().getNumber("WEBGL_VERSION")){const a="OES_texture_half_float";if(this.textureFloatExtension=xh(this.gl,"OES_texture_float"),Ls(this.gl,a))this.textureHalfFloatExtension=xh(this.gl,a);else if(E().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(s),Ls(this.gl,r))this.colorBufferHalfFloatExtension=xh(this.gl,r);else if(E().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(s="EXT_color_buffer_float",Ls(this.gl,s))this.colorBufferFloatExtension=this.gl.getExtension(s);else{if(!Ls(this.gl,r))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}this.vertexBuffer=function aU(n){return function Kz(n,t){const e=Dr(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return Ae(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),Ae(n,()=>n.bufferData(n.ARRAY_BUFFER,t,n.STATIC_DRAW)),e}(n,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}(this.gl),this.indexBuffer=function oU(n){return function qz(n,t){const e=Dr(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return Ae(n,()=>n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e)),Ae(n,()=>n.bufferData(n.ELEMENT_ARRAY_BUFFER,t,n.STATIC_DRAW)),e}(n,new Uint16Array([0,1,2,2,1,3]))}(this.gl),this.framebuffer=function Qz(n){return Dr(n,()=>n.createFramebuffer(),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=Zm(this.gl,this.textureHalfFloatExtension)}get debug(){return E().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const t=this.gl;Ae(t,()=>t.finish()),Ae(t,()=>t.bindFramebuffer(t.FRAMEBUFFER,null)),Ae(t,()=>t.deleteFramebuffer(this.framebuffer)),Ae(t,()=>t.bindBuffer(t.ARRAY_BUFFER,null)),Ae(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),Ae(t,()=>t.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(t,e){return this.throwIfDisposed(),function lU(n,t,e,s){const[r,i]=$l(t,e);return Ol(n,r,i,tT(s),s.textureFormatFloat,n.FLOAT)}(this.gl,t,e,this.textureConfig)}createFloat16MatrixTexture(t,e){return this.throwIfDisposed(),function uU(n,t,e,s){const[r,i]=$l(t,e);return Ol(n,r,i,nT(s),s.textureFormatFloat,s.textureTypeHalfFloat)}(this.gl,t,e,this.textureConfig)}createUnsignedBytesMatrixTexture(t,e){return this.throwIfDisposed(),function cU(n,t,e,s){const[r,i]=$l(t,e);return Ol(n,r,i,sT(s),n.RGBA,n.UNSIGNED_BYTE)}(this.gl,t,e,this.textureConfig)}uploadPixelDataToTexture(t,e){this.throwIfDisposed(),function mU(n,t,e){Ae(n,()=>n.bindTexture(n.TEXTURE_2D,t)),e.data instanceof Uint8Array?2===E().getNumber("WEBGL_VERSION")?Ae(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,e.width,e.height,n.RGBA,n.UNSIGNED_BYTE,e.data)):Ae(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)):2===E().getNumber("WEBGL_VERSION")?Ae(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,e)):Ae(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)),Ae(n,()=>n.bindTexture(n.TEXTURE_2D,null))}(this.gl,t,e)}uploadDenseMatrixToTexture(t,e,s,r){this.throwIfDisposed(),function fU(n,t,e,s,r,i){let a,o,l;Ae(n,()=>n.bindTexture(n.TEXTURE_2D,t)),r instanceof Uint8Array?(a=new Uint8Array(e*s*4),o=n.UNSIGNED_BYTE,l=n.RGBA):(a=new Float32Array(e*s*4),o=n.FLOAT,l=i.internalFormatPackedFloat),a.set(r),2===E().getNumber("WEBGL_VERSION")?Ae(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,s,n.RGBA,o,a)):Ae(n,()=>n.texImage2D(n.TEXTURE_2D,0,l,e,s,0,n.RGBA,o,a)),Ae(n,()=>n.bindTexture(n.TEXTURE_2D,null))}(this.gl,t,e,s,r,this.textureConfig)}createFloat16PackedMatrixTexture(t,e){return this.throwIfDisposed(),function dU(n,t,e,s){const[r,i]=Oa(t,e);return Ol(n,r,i,iT(s),n.RGBA,s.textureTypeHalfFloat)}(this.gl,t,e,this.textureConfig)}createPackedMatrixTexture(t,e){return this.throwIfDisposed(),function hU(n,t,e,s){const[r,i]=Oa(t,e);return Ol(n,r,i,rT(s),n.RGBA,n.FLOAT)}(this.gl,t,e,this.textureConfig)}deleteMatrixTexture(t){this.throwIfDisposed(),this.outputTexture===t&&(H_(this.gl,this.framebuffer),this.outputTexture=null),Ae(this.gl,()=>this.gl.deleteTexture(t))}downloadByteEncodedFloatMatrixFromOutputTexture(t,e,s){return this.downloadMatrixDriver(t,()=>function yU(n,t,e,s){const[r,i]=$l(t,e),o=new Uint8Array(function Fz(n,t){return n*t}(t*e,4));return Ae(n,()=>n.readPixels(0,0,r,i,s.downloadTextureFormat,n.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}(this.gl,e,s,this.textureConfig))}downloadPackedMatrixFromBuffer(t,e,s,r,i,a){return function bU(n,t,e,s,r,i,a,o){const l=n,u=new Float32Array(function Lz(n,t){const[e,s]=Oa(n,t);return e*s*4}(i,a));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}(this.gl,t,0,0,0,i,a)}downloadFloat32MatrixFromBuffer(t,e){return function xU(n,t,e){const s=n,r=new Float32Array(e);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,r),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),r}(this.gl,t,e)}createBufferFromTexture(t,e,s){this.bindTextureToFrameBuffer(t);const r=function gU(n,t,e){const r=n.createBuffer();Ae(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,r));const o=16*t*e;return Ae(n,()=>n.bufferData(n.PIXEL_PACK_BUFFER,o,n.STREAM_READ)),Ae(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)),Ae(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,null)),r}(this.gl,e,s);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e,s;if(E().getBool("WEBGL_FENCE_API_ENABLED")){const r=t,i=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),s=()=>{const a=r.clientWaitSync(i,0,0);return a===r.ALREADY_SIGNALED||a===r.CONDITION_SATISFIED},e=i}else E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),s=()=>this.isQueryAvailable(e,E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):s=()=>!0;return{query:e,isFencePassed:s}}downloadMatrixFromPackedTexture(t,e,s){return this.downloadMatrixDriver(t,()=>function vU(n,t,e){const s=new Float32Array(t*e*4);return Ae(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,s)),s}(this.gl,e,s))}createProgram(t){this.throwIfDisposed();const e=this.gl;null==this.vertexShader&&(this.vertexShader=function iU(n){const t=Qn();return function Wz(n,t){const e=Dr(n,()=>n.createShader(n.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ae(n,()=>n.shaderSource(e,t)),Ae(n,()=>n.compileShader(e)),!1===n.getShaderParameter(e,n.COMPILE_STATUS))throw console.log(n.getShaderInfoLog(e)),new Error("Failed to compile vertex shader.");return e}(n,`${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 }`)}(e));const s=function jz(n){return Dr(n,()=>n.createProgram(),"Unable to create WebGLProgram.")}(e);Ae(e,()=>e.attachShader(s,this.vertexShader)),Ae(e,()=>e.attachShader(s,t)),function Xz(n,t){if(Ae(n,()=>n.linkProgram(t)),!E().get("ENGINE_COMPILE_ONLY")&&!1===n.getProgramParameter(t,n.LINK_STATUS))throw console.log(n.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}(e,s);const r=Object.assign(s,{vao:this.createVertexArray()});return this.debug&&Ym(e,r),r}buildVao(t){this.setProgram(t),this.bindVertexArray(t.vao);const e=this.gl;Ae(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),function pU(n,t,e){Ae(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),G_(n,t,"clipSpacePos",e,3,20,0)&&G_(n,t,"uv",e,2,20,12)}(e,t,this.vertexBuffer)}deleteProgram(t){this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&(Ae(this.gl,()=>this.gl.deleteProgram(t)),this.deleteVertexArray(t.vao))}setProgram(t){this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&Ym(this.gl,this.program),Ae(this.gl,()=>this.gl.useProgram(t))}getUniformLocation(t,e,s=!0){return this.throwIfDisposed(),s?function eB(n,t,e){return Dr(n,()=>n.getUniformLocation(t,e),'uniform "'+e+'" not present in program.')}(this.gl,t,e):function tB(n,t,e){return n.getUniformLocation(t,e)}(this.gl,t,e)}getAttributeLocation(t,e){return this.throwIfDisposed(),Ae(this.gl,()=>this.gl.getAttribLocation(t,e))}getUniformLocationNoThrow(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)}setInputMatrixTexture(t,e,s){this.throwIfDisposed(),this.throwIfNoProgram(),nB(this.gl,t,e,s)}setOutputMatrixTexture(t,e,s){this.setOutputMatrixTextureDriver(t,s,e)}setOutputPackedMatrixTexture(t,e,s){this.throwIfDisposed();const[r,i]=Oa(e,s);this.setOutputMatrixTextureDriver(t,r,i)}setOutputMatrixWriteRegion(t,e,s,r){this.setOutputMatrixWriteRegionDriver(s,t,r,e)}setOutputPackedMatrixWriteRegion(t,e,s,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&Ym(this.gl,this.program),yh(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const t=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}Ae(t,()=>t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ae(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=xh(this.gl,2===E().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===E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const s=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=s.createQuery();return s.beginQuery(r.TIME_ELAPSED_EXT,i),i}const t=this.getQueryTimerExtensionWebGL1(),e=t.createQueryEXT();return t.beginQueryEXT(t.TIME_ELAPSED_EXT,e),e}endQuery(){if(2===E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,s=this.getQueryTimerExtensionWebGL2();return void e.endQuery(s.TIME_ELAPSED_EXT)}const t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}waitForQueryAndGetTime(t){var e=this;return(0,N.A)(function*(){return yield Ct(()=>e.disposed||e.isQueryAvailable(t,E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),e.getQueryTime(t,E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})()}getQueryTime(t,e){if(0===e)return null;if(2===e){const s=this.gl;return s.getQueryParameter(t,s.QUERY_RESULT)/1e6}{const s=this.getQueryTimerExtensionWebGL1();return s.getQueryObjectEXT(t,s.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(t,e){if(0===e)return!0;if(2===e){const s=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=s.getQueryParameter(t,s.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}{const s=this.getQueryTimerExtensionWebGL1(),r=s.getQueryObjectEXT(t,s.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),r&&!this.disjoint}}pollFence(t){return new Promise(e=>{this.addItemToPoll(()=>t.isFencePassed(),()=>e())})}pollItems(){const t=function wU(n){let t=0;for(;te.isDoneFn));for(let e=0;e<=t;++e){const{resolveFn:s}=this.itemsToPoll[e];s()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}addItemToPoll(t,e){if(this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1)return;let s;"setTimeoutCustom"in E().platform&&(s=E().platform.setTimeoutCustom.bind(E().platform)),Ct(()=>(this.pollItems(),0===this.itemsToPoll.length),()=>0,null,s)}bindTextureToFrameBuffer(t){this.throwIfDisposed(),Qm(this.gl,t,this.framebuffer),this.debug&&yh(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(Qm(this.gl,this.outputTexture,this.framebuffer),this.debug&&yh(this.gl)):H_(this.gl,this.framebuffer)}downloadMatrixDriver(t,e){this.bindTextureToFrameBuffer(t);const s=e();return this.unbindTextureToFrameBuffer(),s}setOutputMatrixTextureDriver(t,e,s){this.throwIfDisposed();const r=this.gl;Qm(r,t,this.framebuffer),this.debug&&yh(r),this.outputTexture=t,Ae(r,()=>r.viewport(0,0,e,s)),Ae(r,()=>r.scissor(0,0,e,s))}setOutputMatrixWriteRegionDriver(t,e,s,r){this.throwIfDisposed(),Ae(this.gl,()=>this.gl.scissor(t,e,s,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{mx:_U,XI:aT,Nk:TU,f6:SU,ct:CU,YG:IU,hH:EU,z3:kU,sG:NU,uM:AU,vS:RU,qB:$U,GG:DU,rq:OU,lg:PU,WR:FU,cu:LU,GE:MU,px:VU,jC:zU,He:BU,hE:UU,BF:WU,Dk:GU,cl:HU,_B:jU,ub:XU,_f:KU,Ku:qU,qy:ZU,Zy:YU,bu:QU,zv:JU,dH:oT,HS:eW,yH:tW,l3:nW,z9:lT,x6:sW,_m:rW,eW:iW,GK:aW,SP:oW,yr:lW,dl:uW,Dw:cW,xT:hW,_X:rg,wz:dW}=Tt;function uT(n,t){return["x","y","z","w","u","v"].slice(0,t).map(e=>`${n}.${e}`)}function Jn(n,t){return 1===t?[n]:uT(n,t)}class fW{constructor(t){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t,this.rank=t.length,this.enableShapeUniforms=Hn(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=Jn("rc",this.rank),s=Ut(this.rank),r=this.getOutOfBoundsCondition(e),i=this.getSetup(e),a=this.getOutput(e);this.userCode=`\n void main() {\n ${s} rc = getOutputCoords();\n\n if(${r}) {\n setOutput(vec4(0));\n } else {\n ${i}\n\n setOutput(vec4(${a}));\n }\n }\n `}}getSourceCoordsArr(t){const e=[];for(let s=0;s<=1;s++)for(let r=0;r<=1;r++){let i=`${0===s?"r":"rp1"}, ${0===r?"c":"cp1"}`;for(let a=2;a ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let e="";for(let s=this.rank-2;s= ${this.enableShapeUniforms?`outShape[${s}]`:this.outputShape[s]}`,s= ${this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1]};\n bool rEdge = rp1 >= ${this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2]};\n `}getOutput(t){const e=this.getSourceCoordsArr(t);return 1===this.rank?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${e[0]}),\n cEdge ? 0. : getA(${e[1]}),\n rEdge ? 0. : getA(${e[2]}),\n rEdge || cEdge ? 0. : getA(${e[3]})`}}class cT{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=t,this.enableShapeUniforms=Hn(this.outputShape.length);let s="";for(let r=0;r<4;r++){let i="thisRC = rc;";r%2==1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),s+=`\n ${i}\n ${r>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${r}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${r>0?"}":""}\n `}this.userCode=`\n ${function mW(n,t){return`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${t?function pB(n,t,e="index"){const r=function dB(n,t){const e=n.length,s=n.map(i=>`${t}[${i}]`),r=new Array(e-1);r[e-2]=s[e-1];for(let i=e-3;i>=0;--i)r[i]=`(${r[i+1]} * ${s[i+1]})`;return r}(n.map((i,a)=>a),t);return r.map((i,a)=>`int ${n[a]} = ${e} / ${r[a]}; ${a===r.length-1?`int ${n[a+1]} = ${e} - ${n[a]} * ${r[a]}`:`index -= ${n[a]} * ${r[a]}`};`).join("")}(["r","c","d"],"inputShape"):qi(["r","c","d"],n)}\n return ivec3(r, c, d);\n }\n `}(e,this.enableShapeUniforms)}\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":eg(t)}\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]":t[1]};\n int cols = ${this.enableShapeUniforms?"outShape[2]":t[2]};\n\n ${s}\n\n setOutput(result);\n }\n `}}class gW{constructor(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(t,e,s){const r=dT(e,s),i=pT(t,r,s);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const a=hT(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,s);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();const l=this.freeTextures[i].pop();return this.usedTextures[i].push(l),l}let o;return r===Gn.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):r===Gn.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):r===Gn.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):r===Gn.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):r===Gn.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[i].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(t,e,s,r){if(null==this.freeTextures)return;const i=dT(s,r),a=pT(e,i,r);a in this.freeTextures||(this.freeTextures[a]=[]);const o=hT(e,i,this.gpgpu.gl,this.gpgpu.textureConfig,r),l=E().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==l&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(t.texture),this._numBytesAllocated-=o):(this.freeTextures[a].push(t),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const u=this.usedTextures[a],c=u&&u.indexOf(t);if(null==c||c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u[c]=u[u.length-1],u.pop(),this.log()}log(){if(!this.logEnabled)return;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${this.numFreeTextures+this.numUsedTextures})`);const e=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*e)}%)`)}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 t in this.freeTextures)this.freeTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});for(const t in this.usedTextures)this.usedTextures[t].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 hT(n,t,e,s,r){const i=function yW(n,t){switch(n){case Gn.PACKED_2X2_FLOAT32:return rT(t);case Gn.PACKED_2X2_FLOAT16:return iT(t);case Gn.UNPACKED_FLOAT32:return tT(t);case Gn.UNPACKED_FLOAT16:return nT(t);case Gn.PACKED_4X1_UNSIGNED_BYTE:return sT(t);default:throw new Error(`Unknown physical texture type ${n}`)}}(t,s);let a;if(r){const[l,u]=Oa(n[0],n[1]);a=l*u}else{const[l,u]=$l(n[0],n[1]);a=l*u}const o=function xW(n,t){if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===n.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(e,i);return a*o}function dT(n,t){if(n===Fs.UPLOAD)return Gn.PACKED_2X2_FLOAT32;if(n===Fs.RENDER||null==n)return function bW(n){return E().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?Gn.PACKED_2X2_FLOAT32:Gn.UNPACKED_FLOAT32:n?Gn.PACKED_2X2_FLOAT16:Gn.UNPACKED_FLOAT16}(t);if(n===Fs.DOWNLOAD||n===Fs.PIXELS)return Gn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${n}`)}function pT(n,t,e){return`${n[0]}_${n[1]}_${t}_${e}`}class xr{constructor(t,e){this.variableNames=["A"],this.outputShape=t,this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode=`\n float unaryOperation(float x) {\n ${e}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}const Ts="if (isnan(x)) return x;",fT="return abs(x);",_W=Ts+"\n return (x < 0.0) ? 0.0 : x;\n",TW=Ts+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",ci="return x;";class hi{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode=`\n vec4 unaryOperation(vec4 x) {\n ${e}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}class AW{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t,this.enableShapeUniforms=Hn(this.outputShape.length);const e=t.length,s=Jn("rc",e),r=Ut(e),i=function pW(n,t){if(1===n)return"rc";let e="";for(let s=0;s{class n extends Fe{nextDataId(){return n.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,!E().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let s;if(null!=e){if(e instanceof sg)s=e;else{const r=Zs(E().getNumber("WEBGL_VERSION"),e);s=new sg(r)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const r=Zs(E().getNumber("WEBGL_VERSION"));s=new sg(r),this.binaryCache=function OW(n){return n in Ih||(Ih[n]={}),Ih[n]}(E().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=s,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new gW(this.gpgpu),this.numMBBeforeWarning=function LW(){return null==E().global.screen?1024:E().global.screen.height*E().global.screen.width*window.devicePixelRatio*600/1024/1024}(),this.texData=new we(this,tr())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,s,r,i,a,o){const l=this.makeTensorInfo(s,r),u=this.texData.get(l.dataId);u.isPacked=!1,u.texture={texture:e,texShape:[i,a]},u.texShape=[i,a];const c=bh(s),h=new eT(c,!1,o),d=this.runWebGLProgram(h,[l],r,[[i,a]]);return d.shape=s,u.texture=null,this.disposeIntermediateTensorInfo(l),d.dataId}write(e,s,r){if((E().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||E().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===r&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const i={id:this.nextDataId()};return this.texData.set(i,{shape:s,dtype:r,values:e,usage:Fs.UPLOAD,refCount:1}),i}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){this.texData.get(e).refCount++}decRef(e){this.texData.has(e)&&this.texData.get(e).refCount--}move(e,s,r,i,a){if(E().getBool("DEBUG")&&this.checkNumericalProblems(s),"complex64"===i)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:r,dtype:i,values:s,usage:Fs.UPLOAD,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const s=this.texData.get(e),{values:r,dtype:i,complexTensorInfos:a,slice:o,shape:l,isPacked:u}=s;if(null!=o){let p;p=u?new hi(l,ci):new xr(l,ci);const f=this.runWebGLProgram(p,[{dataId:e,shape:l,dtype:i}],i),g=this.readSync(f.dataId);return this.disposeIntermediateTensorInfo(f),g}if(null!=r)return this.convertAndCacheOnCPU(e);if("string"===i)return r;const c=null!=this.activeTimers;let h,d;return c&&(h=Vn()),d="complex64"===i?Nr(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.getValuesFromTexture(e),c&&(this.downloadWaitMs+=Vn()-h),this.convertAndCacheOnCPU(e,d)}read(e){var s=this;return(0,N.A)(function*(){if(s.pendingRead.has(e)){const m=s.pendingRead.get(e);return new Promise(x=>m.push(x))}const r=s.texData.get(e),{values:i,shape:a,slice:o,dtype:l,complexTensorInfos:u,isPacked:c}=r;if(null!=o){let m;m=c?new hi(a,ci):new xr(a,ci);const x=s.runWebGLProgram(m,[{dataId:e,shape:a,dtype:l}],l),y=s.read(x.dataId);return s.disposeIntermediateTensorInfo(x),y}if(null!=i)return s.convertAndCacheOnCPU(e);if(E().getBool("DEBUG")&&!E().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===E().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let d,p,h=null;if("complex64"!==l&&E().get("WEBGL_BUFFER_SUPPORTED")){d=s.decode(e);const m=s.texData.get(d.dataId);h=s.gpgpu.createBufferFromTexture(m.texture.texture,...gh(a))}if(s.pendingRead.set(e,[]),"complex64"!==l&&(yield s.gpgpu.createAndWaitForFence()),"complex64"===l){const m=yield Promise.all([s.read(u.real.dataId),s.read(u.imag.dataId)]);p=Nr(m[0],m[1])}else if(null==h)p=s.getValuesFromTexture(e);else{const m=K(a);p=s.gpgpu.downloadFloat32MatrixFromBuffer(h,m)}if(null!=d&&s.disposeIntermediateTensorInfo(d),null!=h){const m=s.gpgpu.gl;Ae(m,()=>m.deleteBuffer(h))}const f=s.convertAndCacheOnCPU(e,p),g=s.pendingRead.get(e);return s.pendingRead.delete(e),g.forEach(m=>m(f)),s.pendingDisposal.has(e)&&(s.pendingDisposal.delete(e),s.disposeData(e)&&tr().removeDataId(e,s),s.pendingDeletes--),f})()}readToGPU(e,s={}){const r=this.texData.get(e),{values:i,shape:a,slice:o,dtype:l,isPacked:u,texture:c}=r;if("complex64"===l)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=o){let f;f=u?new hi(a,ci):new xr(a,ci);const g=this.runWebGLProgram(f,[{dataId:e,shape:a,dtype:l}],l),m=this.readToGPU(g,s);return this.disposeIntermediateTensorInfo(g),m}if(null==c)throw null!=i?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const h=this.decode(e,s.customTexShape),d=tr().makeTensorFromTensorInfo(h),p=this.texData.get(h.dataId);return Object.assign({tensorRef:d},p.texture)}bufferSync(e){const s=this.readSync(e.dataId);if("string"===e.dtype)try{const r=s.map(i=>Wr(i));return vt(e.shape,e.dtype,r)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return vt(e.shape,e.dtype,s)}checkNumericalProblems(e){if(null!=e)for(let s=0;s0}time(e){var s=this;const r=this.activeTimers,i=[];let a=!1;null==this.programTimersStack?(this.programTimersStack=i,a=!0):this.activeTimers.push(i),this.activeTimers=i,e();const o=Si(this.activeTimers.map(c=>c.query)).filter(c=>null!=c),l=Si(this.activeTimers.map(c=>c.name)).filter(c=>null!=c);this.activeTimers=r,a&&(this.programTimersStack=null);const u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(0,N.A)(function*(){if(E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const c=yield Promise.all(o);u.kernelMs=function X(n){let t=0;for(let e=0;ec.map((h,d)=>({name:l[d],ms:h})).map(h=>`${h.name}: ${h.ms}`).join(", ")}else u.kernelMs={error:"WebGL query timers are not supported in this environment."};return s.uploadWaitMs=0,s.downloadWaitMs=0,u})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Vn(),endMs:null}}endTimer(e){return E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Vn(),e)}getQueryTime(e){var s=this;return(0,N.A)(function*(){return E().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?s.gpgpu.waitForQueryAndGetTime(e):e.endMs-e.startMs})()}disposeData(e,s=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(s?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!s&&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:r}=this.texData.get(e);return null!=r&&(this.disposeData(r.real.dataId,s),this.disposeData(r.imag.dataId,s)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:s,dtype:r,texShape:i,usage:a,isPacked:o,slice:l}=this.texData.get(e),u=l&&l.origDataId||e,c=this.dataRefCount.get(u);c>1?this.dataRefCount.set(u,c-1):(this.dataRefCount.delete(u),null!=s&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(s,i,a,o)));const h=this.texData.get(e);h.texture=null,h.texShape=null,h.isPacked=!1,h.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,s=PW){return E().getBool("WEBGL_CPU_FORWARD")&&e.every(r=>null==this.texData.get(r.dataId).texture&&K(r.shape)0&&os(r[0])){const a=r.map(o=>Ur(o));i=this.write(a,e,s)}else i=this.write(r,e,s);return this.texData.get(i).usage=null,{dataId:i,shape:e,dtype:s}}makeOutput(e,s,r){return tr().makeTensorFromTensorInfo(this.makeTensorInfo(e,s,r),this)}unpackTensor(e){const s=new AW(e.shape);return this.runWebGLProgram(s,[e],e.dtype)}packTensor(e){const s=new fW(e.shape);return this.runWebGLProgram(s,[e],e.dtype,null,!0)}packedReshape(e,s){const r=[Pa(e.shape),...Fa(e.shape)],i={dtype:e.dtype,shape:r,dataId:e.dataId},a=[Pa(s),...Fa(s)],o=new cT(a,r),c=this.runWebGLProgram(o,[i],e.dtype,[r],!0);return{dataId:c.dataId,shape:s,dtype:c.dtype}}decode(e,s){const r=this.texData.get(e),{isPacked:i,shape:a,dtype:o}=r;null!=s&&T(K(a)<=s[0]*s[1]*4,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.");const l=bh(a);let u;u=i?new eU(l):new JB(l);const h=[s??gh(l)];return{dtype:o,shape:a,dataId:this.runWebGLProgram(u,[{shape:l,dtype:o,dataId:e}],o,h,!0,s).dataId}}runWebGLProgram(e,s,r,i,a=!1,o){const l=this.makeTensorInfo(e.outputShape,r),u=this.texData.get(l.dataId);if(e.packedOutput&&(u.isPacked=!0),e.outPackingScheme===mh.DENSE){const y=o??gh(e.outputShape);u.texShape=y.map(b=>2*b)}if(null!=e.outTexUsage&&(u.usage=e.outTexUsage),0===K(l.shape))return u.values=Cn(l.dtype,0),l;const c=[],h=s.map(y=>{if("complex64"===y.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let b=this.texData.get(y.dataId);if(null==b.texture){if(!e.packedInputs&&K(y.shape)<=E().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:y.shape,texData:null,isUniform:!0,uniformValues:b.values};e.packedInputs&&(b.isPacked=!0,b.shape=y.shape)}if(this.uploadToGPU(y.dataId),!!b.isPacked!=!!e.packedInputs)y=b.isPacked?this.unpackTensor(y):this.packTensor(y),c.push(y),b=this.texData.get(y.dataId);else if(b.isPacked&&!wh(b.shape,y.shape)){const v=y,w=y.shape;y.shape=b.shape,y=this.packedReshape(y,w),c.push(y),b=this.texData.get(y.dataId),v.shape=w}return{shape:y.shape,texData:b,isUniform:!1}});this.uploadToGPU(l.dataId);const d={shape:l.shape,texData:u,isUniform:!1},p=function QB(n,t,e){let s="";t.concat(e).forEach(a=>{const o=null!=a.texData&&null!=a.texData.slice&&a.texData.slice.flatOffset>0;if(n.enableShapeUniforms&&!a.isUniform){const l=a.texData.texShape,{useSqueezeShape:u,uniformShape:c,keptDims:h}=ng(n.packedInputs,a.shape,l);let d="",p="",f="";if(1===c.length&&n.packedInputs){const w=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];d=`${w[0]>1}_${w[1]>1}`}else if(2!==c.length||n.packedInputs){if(c.length>2&&!n.packedInputs){const w=Ue(c);f=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}}else p=`${c[0]>1}_${c[1]>1}`;const g=a.shape.length,m=2===c.length&&rt(a.shape,l),x=1===K(a.shape),y=ga(a.shape,e.shape),b=!n.packedInputs&&g===e.shape.length&&rt(l,e.texData.texShape);s+=`${g}_${b}_${u?h:""}_${c.length}_${x}_${y}_${m}_${d}_${p}_${f}_${n.packedInputs||c.length>2?"":`${l[0]>1}_${l[1]>1}`}_${o}`}else s+=`${a.shape}_${a.isUniform?"uniform":a.texData.texShape}_${o}`});let i=n.constructor.name;return i+="_"+s+"_"+n.userCode+`${E().getNumber("WEBGL_VERSION")}`,i}(e,h,d),f=this.getAndSaveBinary(p,()=>function ZB(n,t,e,s){const r=e.map((c,h)=>{const d={logicalShape:c.shape,texShape:c.isUniform?null:c.texData.texShape,isUniform:c.isUniform,isPacked:!c.isUniform&&c.texData.isPacked,flatOffset:null};return null!=c.texData&&null!=c.texData.slice&&c.texData.slice.flatOffset>0&&(d.flatOffset=c.texData.slice.flatOffset),{name:t.variableNames[h],shapeInfo:d}}),i=r.map(c=>c.shapeInfo),a={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},o=fB(r,a,t),l=function Gz(n,t){const e=Dr(n,()=>n.createShader(n.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ae(n,()=>n.shaderSource(e,t)),Ae(n,()=>n.compileShader(e)),E().get("ENGINE_COMPILE_ONLY"))return e;if(!1===n.getShaderParameter(e,n.COMPILE_STATUS))throw W_(t,n.getShaderInfoLog(e)),new Error("Failed to compile fragment shader.");return e}(n.gl,o),u=n.createProgram(l);return E().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:i,outShapeInfo:a,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(n.buildVao(u),Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:i,outShapeInfo:a},Q_(n,t,u)))}(this.gpgpu,e,h,d)),g=null!=this.activeTimers;let m;g&&(m=this.startTimer()),E().get("ENGINE_COMPILE_ONLY")||function YB(n,t,e,s,r){t.program.enableShapeUniforms||(J_(t.inShapeInfos,e),J_([t.outShapeInfo],[s]));const i=s.texData.texture,a=s.texData.texShape;s.texData.isPacked?n.setOutputPackedMatrixTexture(i.texture,a[0],a[1]):n.setOutputMatrixTexture(i.texture,a[0],a[1]),n.setProgram(t.webGLProgram),n.bindVertexArray(t.webGLProgram.vao),1===E().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&n.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&n.gl.uniform1f(t.nanLoc,NaN);for(let l=0;lthis.disposeIntermediateTensorInfo(y)),g&&(m=this.endTimer(m),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(m)}));const x=E().getNumber("WEBGL_FLUSH_THRESHOLD");if(x>0){const y=Vn();y-this.lastGlFlushTime>x&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=y)}if(!E().getBool("WEBGL_LAZILY_UNPACK")&&u.isPacked&&!1===a){const y=this.unpackTensor(l);return this.disposeIntermediateTensorInfo(l),y}return l}compileAndRun(e,s,r,i,a=!1){return this.runWebGLProgram(e,s,r=r||s[0].dtype,i,a)}getAndSaveBinary(e,s){return e in this.binaryCache||(this.binaryCache[e]=s()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(E().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(s=>{this.gpgpu.deleteProgram(this.binaryCache[s].webGLProgram),delete this.binaryCache[s]}),this.textureManager.dispose(),null!=this.canvas&&typeof HTMLCanvasElement<"u"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Z(()=>{if(!E().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=E().getBool("DEBUG");E().set("DEBUG",!1);const s=this.abs(ut(1e-8)).dataSync()[0];if(E().set("DEBUG",e),s>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const s=this.texData.get(e),{shape:r,dtype:i,values:a,texture:o,usage:l,isPacked:u}=s;if(null!=o)return;const c=null!=this.activeTimers;let h;c&&(h=Vn());let d=s.texShape;if(null==d&&(d=function rB(n,t=!1){let e=E().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=E().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");s===1/0&&E().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=e/2),t&&(e*=2,s*=2,1===(n=n.map((o,l)=>l>=n.length-2?C(n[l]):n[l])).length&&(n=[2,n[0]])),2!==n.length&&(n=Qs(n).newShape);let r=K(n),i=null;n.length<=1&&r<=e?i=[1,r]:2===n.length&&n[0]<=e&&n[1]<=e?i=n:3===n.length&&n[0]*n[1]<=e&&n[2]<=e?i=[n[0]*n[1],n[2]]:3===n.length&&n[0]<=e&&n[1]*n[2]<=e?i=[n[0],n[1]*n[2]]:4===n.length&&n[0]*n[1]*n[2]<=e&&n[3]<=e?i=[n[0]*n[1]*n[2],n[3]]:4===n.length&&n[0]<=e&&n[1]*n[2]*n[3]<=e&&(i=[n[0],n[1]*n[2]*n[3]]);const a=null!=i&&Math.max(...i)>s&&Math.min(...i)<=(t?2:1)&&Math.min(...i)>0;if(null==i||a)if(t){const o=Pa(n);let l=2,u=2;n.length&&([l,u]=Fa(n)),r=o*(l/2)*(u/2),i=Vs(r).map(c=>2*c)}else i=Vs(r);return i}(r,u),s.texShape=d),null!=a){const p=bh(r);let f,g=d[1],m=d[0];const x=a instanceof Uint8Array||a instanceof Uint8ClampedArray;(u||!x)&&([g,m]=Oa(d[0],d[1])),f=u?new rU(p,x):new eT(p,x);const y=x?[m,g]:d,b=this.makeTensorInfo(y,i),v=this.texData.get(b.dataId);v.usage=x?Fs.PIXELS:Fs.UPLOAD,v.texShape=y,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId),g,m,a);const I=this.runWebGLProgram(f,[b],i,[[m,g]],!0),k=this.texData.get(I.dataId);s.texShape=k.texShape,s.isPacked=k.isPacked,s.usage=k.usage,E().get("ENGINE_COMPILE_ONLY")?this.disposeData(I.dataId):(s.texture=k.texture,s.values=null,this.texData.delete(I.dataId)),this.disposeIntermediateTensorInfo(b),c&&(this.uploadWaitMs+=Vn()-h)}else{const p=this.acquireTexture(d,l,i,u);s.texture=p}}convertAndCacheOnCPU(e,s){const r=this.texData.get(e),{dtype:i}=r;return null!=s&&(r.values=function VW(n,t){if("float32"===t||"complex64"===t)return n;if("int32"===t||"bool"===t){const e="int32"===t?new Int32Array(n.length):new Uint8Array(n.length);for(let s=0;s1024*this.numMBBeforeWarning*1024){const a=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${a} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,s,i)}computeBytes(e,s){return e[0]*e[1]*ra(s)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}checkCompileCompletionAsync(){var e=this;return(0,N.A)(function*(){const s=[];if(e.gpgpu.parallelCompilationExtension){for(const[,r]of Object.entries(e.binaryCache))s.push(e.checkCompletionAsync_(r));return Promise.all(s)}for(const[,r]of Object.entries(e.binaryCache)){const i=new Promise(a=>{try{e.checkCompletion_(r),a(!0)}catch(o){throw o}});s.push(i)}return Promise.all(s)})()}checkCompletionAsync_(e){var s=this;return(0,N.A)(function*(){return s.gpgpu.gl.getProgramParameter(e.webGLProgram,s.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?s.checkCompletion_(e):(yield Ly(),s.checkCompletionAsync_(e))})()}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS))throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)?(W_(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):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:s,customUniformLocations:r,infLoc:i,nanLoc:a,outShapeLocation:o,outShapeStridesLocation:l,outTexShapeLocation:u}=Q_(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=s,e.customUniformLocations=r,e.infLoc=i,e.nanLoc=a,e.outShapeLocation=o,e.outShapeStridesLocation=l,e.outTexShapeLocation=u}}createTensorFromGPUData(e,s,r){e.channels=e.channels||"RGBA";const{texture:i,height:a,width:o,channels:l}=e,u=tr().backend;if(!u.gpgpu.gl.isTexture(i))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 c=u.writeTexture(i,s,r,a,o,l);return tr().makeTensorFromDataId(c,s,r,u)}}return n.nextDataId=0,n})();fx()&&yx("webgl",()=>new MW,2);const ig="\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n";class Yi{constructor(t,e,s){this.variableNames=["A","B"],this.outputShape=ht(e,s),this.enableShapeUniforms=Hn(this.outputShape.length),this.userCode=`\n float binaryOperation(float a, float b) {\n ${t}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `}}const Qi="\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 Ba{constructor(t,e,s,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=ht(e,s);const i=this.outputShape.length;this.enableShapeUniforms=Hn(i);let a="";if(r)if(0===i||1===K(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a=`\n ${Ut(i)} coords = getOutputCoords();\n `,1===i)a+=this.enableShapeUniforms?"\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ":`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const l=Jn("coords",i);a+=this.enableShapeUniforms?`\n bool nextRowOutOfBounds =\n (${l[i-2]} + 1) >= outShape[${i} - 2];\n bool nextColOutOfBounds =\n (${l[i-1]} + 1) >= outShape[${i} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `:`\n bool nextRowOutOfBounds =\n (${l[i-2]} + 1) >= ${this.outputShape[i-2]};\n bool nextColOutOfBounds =\n (${l[i-1]} + 1) >= ${this.outputShape[i-1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `}this.userCode=`\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${t}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${a}\n\n setOutput(result);\n }\n `}}function hs(n){const{inputs:t,backend:e}=n,{x:s}=t;return e.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const UW={kernelName:yo,backendName:"webgl",kernelFunc:hs};function di(n){const{inputs:t,backend:e}=n,{real:s,imag:r}=t,i=e.makeTensorInfo(s.shape,"complex64"),a=e.texData.get(i.dataId),o=hs({inputs:{x:s},backend:e}),l=hs({inputs:{x:r},backend:e});return a.complexTensorInfos={real:o,imag:l},i}const WW={kernelName:od,backendName:"webgl",kernelFunc:di},mT="return (a < 0.) ? b * a : a;",gT="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",HW={kernelName:pu,backendName:"webgl",kernelFunc:function GW(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{alpha:i}=s,a=e.makeTensorInfo([],"float32",Br(i,"float32")),o=E().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ba(gT,r.shape,a.shape):new Yi(mT,r.shape,a.shape),l=e.runWebGLProgram(o,[r,a],"float32");return e.disposeIntermediateTensorInfo(a),l}},xT="return (a < 0.) ? b * a : a;",yT="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",XW={kernelName:$u,backendName:"webgl",kernelFunc:function jW(n){const{inputs:t,backend:e}=n,{x:s,alpha:r}=t,i=E().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ba(yT,s.shape,r.shape):new Yi(xT,s.shape,r.shape);return e.runWebGLProgram(i,[s,r],"float32")}},Ua="if (isnan(x)) return x;";function Nt({opSnippet:n,packedOpSnippet:t,cpuKernelImpl:e,dtype:s}){return({inputs:r,backend:i})=>{const{x:a}=r,o=i,l=s||a.dtype;if(o.shouldExecuteOnCPU([a])&&null!=e){const h=o.texData.get(a.dataId),d=e(h.values,l);return o.makeTensorInfo(a.shape,l,d)}let c;return c=E().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new hi(a.shape,t):new xr(a.shape,n),o.runWebGLProgram(c,[a],l)}}function Ln({opSnippet:n,packedOpSnippet:t,checkOutOfBounds:e=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:i}){return({inputs:a,backend:o})=>{const{a:l,b:u}=a,c=o;if(s&&"complex64"===l.dtype){const f=c.texData.get(l.dataId),g=c.texData.get(u.dataId),[m,x]=[[f.complexTensorInfos.real,g.complexTensorInfos.real],[f.complexTensorInfos.imag,g.complexTensorInfos.imag]].map(b=>{const[v,w]=b,S={dataId:v.dataId,dtype:v.dtype,shape:l.shape},I={dataId:w.dataId,dtype:w.dtype,shape:u.shape},k=new Yi(n,l.shape,u.shape);return c.runWebGLProgram(k,[S,I],ls(v.dtype,w.dtype))}),y=di({inputs:{real:m,imag:x},backend:c});return c.disposeIntermediateTensorInfo(m),c.disposeIntermediateTensorInfo(x),y}const h=i||ls(l.dtype,u.dtype);if(("string"===l.dtype||"string"===u.dtype||c.shouldExecuteOnCPU([l,u]))&&null!=r){const f=c.texData.get(l.dataId).values,g=c.texData.get(u.dataId).values,m="string"===l.dtype?Ar(f):f,x="string"===l.dtype?Ar(g):g,[y,b]=r(l.shape,u.shape,m,x,h),v=c.makeTensorInfo(b,h);return c.texData.get(v.dataId).values=y,v}let p;return p=E().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new Ba(t,l.shape,u.shape,e):new Yi(n,l.shape,u.shape),c.runWebGLProgram(p,[l,u],h)}}function Pl(n,t=!1){if("linear"===n)return"return x;";if("relu"===n)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":_W;if("elu"===n)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"===n)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":TW;if("prelu"===n)return t?yT:xT;if("leakyrelu"===n)return t?gT:mT;if("sigmoid"===n)return"return 1.0 / (1.0 + exp(-1.0 * x));";throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`)}class bT{constructor(t,e,s,r=!1,i=!1,a=!1,o=null,l=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s,this.enableShapeUniforms=Hn(this.outputShape.length);const h=Math.ceil((r?t[1]:t[2])/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=i?"rc.z, i * 2":"i * 2, rc.z",f=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],g=i?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",x="";o&&(m=l?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${o}\n }`:u?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${o}\n }`:`vec4 activation(vec4 x) {\n ${o}\n }`,x="result = activation(result);");const y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let b="rc.x",v="rc.x";t[0]`The new shape (${l}) has ${u} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);const c=a.texData.get(r.dataId);return!c.isPacked||wh(r.shape,l)||null!==c.texture&&wh(c.shape,l)?(a.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype}):function qW(n,t,e){const s=[Pa(n.shape),...Fa(n.shape)],r={dtype:n.dtype,shape:s,dataId:n.dataId},i=[Pa(t),...Fa(t)],a=new cT(i,s),u=e.runWebGLProgram(a,[r],n.dtype,[s],!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}}(r,l,a)}const ZW={kernelName:Ou,backendName:"webgl",kernelFunc:Ne};class TT{constructor(t,e){this.variableNames=["x"];const{windowSize:s,batchSize:r,inSize:i,outSize:a}=t;this.outputShape=[r,a];const o=4*Math.floor(s/4),l=s%4;let u="sumValue += dot(values, ones);";if(null!=e){const h=1/e;u=`sumValue += dot(values * ${St(h)?h.toPrecision(2):h}, ones);`}let c="";i%s>0&&(c=`\n if (inIdx < 0 || inIdx >= ${i}) {\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 ${c}\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 * ${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 ${u}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===l}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${u}\n } else if (${2===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${u}\n } else if (${3===l}) {\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 YW{constructor(t,e){this.variableNames=["x"];const{windowSize:s,batchSize:r,inSize:i,outSize:a}=t;this.outputShape=[r,a];let o="0.0",l="";"prod"===e?o="1.0":"min"===e?(o="1.0 / 1e-20",l="min"):"max"===e&&(o="-1.0 / 1e-20",l="max");let u=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");const c=4*Math.floor(s/4),h=s%4;let d=`\n if (${"sum"===e}) {\n sumValue += dot(values, ones);\n } else if (${"prod"===e}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${l}(values, minMaxValue);\n if (${"min"===e} || ${"max"===e}) {\n minMaxValue = ${l}(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"===e?(o="1.0",d="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===e&&(o="0.0",d="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");let f="";i%s>0&&(f=`\n if (inIdx < 0 || inIdx >= ${i}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${o};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${f}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${s};\n\n vec4 minMaxValue = vec4(${o});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${c}; 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 + ${c};\n if (${1===h}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${d}\n } else if (${2===h}) {\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===h}) {\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(n,t,e,s){const r=function QW(n){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const e=t.length?t[t.length-1].outSize:n[1],s=_c(e);t.push({inSize:e,windowSize:s,outSize:Math.ceil(e/s)})}return t}(n.shape);let i=n;for(let a=0;a6)throw Error(`Transpose for rank ${t} is not yet supported`);const e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let r=0;r6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=Ut(this.rank),i=uT("rc",this.rank),a=new Array(this.rank);for(let c=0;c`Error in matMul: inner shapes (${h}) and (${d}) of Tensors with shapes ${n.shape} and ${t.shape} and transposeA=${e} and transposeB=${s} must match.`);const w=e?[x,h,p]:[x,p,h],S=s?[y,f,d]:[y,d,f],I=Ne({inputs:{x:n},backend:r,attrs:{shape:w}}),k=Ne({inputs:{x:t},backend:r,attrs:{shape:S}}),D=[I,k],P=Math.max(x,y),B=e?I.shape[1]:I.shape[2],Y=null!=i,Q=null!=a,ee="leakyrelu"===l,J=null!=l?Pl(l,!0):null;let ae;if((1===p||1===f)&&B>1e3&&!1===(Y||Q||ee||null!=J)){let le=I,ge=k;e&&(le=es({inputs:{x:I},backend:r,attrs:{perm:[0,2,1]}}),D.push(le)),s&&(ge=es({inputs:{x:k},backend:r,attrs:{perm:[0,2,1]}}),D.push(ge));const Se=1===f;let be=le;1!==f&&(be=Ne({inputs:{x:le},backend:r,attrs:{shape:[P,B,1]}}),D.push(be));const De=1===f?2:1;let Ie=ge;Se&&(Ie=Ne({inputs:{x:ge},backend:r,attrs:{shape:[P,1,B]}}),D.push(Ie));const Le=ag({inputs:{a:be,b:Ie},backend:r});ae=kh({inputs:{x:Le},backend:r,attrs:{axis:De,keepDims:!0}}),D.push(Le)}else{const le=ls(n.dtype,t.dtype),ge=new bT(w,S,[P,p,f],e,s,Y,J,Q,ee),xe=[I,k];if(null!=i&&xe.push(i),Q&&xe.push(a),ee){const Se=r.makeTensorInfo([],"float32",Br(o,"float32"));xe.push(Se),D.push(Se)}ae=r.runWebGLProgram(ge,xe,le)}const te=Ne({inputs:{x:ae},backend:r,attrs:{shape:v}});D.push(ae);for(const le of D)r.disposeIntermediateTensorInfo(le);return te}const a4={kernelName:Ku,backendName:"webgl",kernelFunc:function i4(n){const{inputs:t,backend:e,attrs:s}=n,{a:r,b:i,bias:a,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=s;return Nh({a:r,b:i,transposeA:l,transposeB:u,backend:e,bias:a,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},CT="return abs(x);",l4={kernelName:In,backendName:"webgl",kernelFunc:function o4(n){const{inputs:t,backend:e}=n,{x:s}=t;if(e.shouldExecuteOnCPU([s])&&"complex64"!==s.dtype){const i=e.texData.get(s.dataId),a=oT(i.values);return e.makeTensorInfo(s.shape,s.dtype,a)}let r;return r=E().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new hi(s.shape,CT):new xr(s.shape,CT),e.runWebGLProgram(r,[s],s.dtype)}},c4=Nt({opSnippet:Ts+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),h4={kernelName:jn,backendName:"webgl",kernelFunc:c4},p4=Nt({opSnippet:Ts+"\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),f4={kernelName:ps,backendName:"webgl",kernelFunc:p4},IT="return a + b;",m4=Ln({opSnippet:IT,packedOpSnippet:IT,supportsComplex:!0,cpuKernelImpl:_U}),g4={kernelName:oa,backendName:"webgl",kernelFunc:m4};class x4{constructor(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map((i,a)=>`T${a}`);const s=[];this.variableNames.forEach(i=>{s.push(`float v${i} = get${i}AtOutCoords();`)});const r=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`\n void main() {\n ${s.join("\n ")}\n\n float result = ${r};\n setOutput(result);\n }\n `}}class y4{constructor(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((i,a)=>`T${a}`);const s=[];this.variableNames.forEach(i=>{s.push(`vec4 v${i} = get${i}AtOutCoords();`)});const r=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`\n void main() {\n ${s.join("\n ")}\n\n vec4 result = ${r};\n setOutput(result);\n }\n `}}const b4={kernelName:ed,backendName:"webgl",kernelFunc:function Ah(n){const{inputs:t,backend:e}=n,s=t;if(1===s.length)return hs({inputs:{x:s[0]},backend:e});if(s.length>E().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const l=Math.floor(s.length/2),u=Ah({inputs:s.slice(0,l),backend:e}),c=Ah({inputs:s.slice(l),backend:e});return Ah({inputs:[u,c],backend:e})}const r=s.map(l=>l.dtype).reduce((l,u)=>ls(l,u)),i=s.map(l=>l.shape),o=E().getBool("WEBGL_PACK")?new y4(s[0].shape,i):new x4(s[0].shape,i);return e.runWebGLProgram(o,s,r)}},w4={kernelName:"All",backendName:"webgl",kernelFunc:function v4(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i,keepDims:a}=s,o=r.shape.length,l=pt(i,r.shape);let u=l;const c=rn(u,o);let h=r;null!=c&&(h=es({inputs:{x:r},backend:e,attrs:{perm:c}}),u=dn(u.length,o)),Fn("all",u,o);const[d,p]=An(h.shape,u),g=Ne({inputs:{x:h},backend:e,attrs:{shape:[-1,K(p)]}}),m=Ji(g,g.dtype,"all",e);let x;return x=Ne(a?{inputs:{x:m},backend:e,attrs:{shape:hn(d,l)}}:{inputs:{x:m},backend:e,attrs:{shape:d}}),e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(m),null!=c&&e.disposeIntermediateTensorInfo(h),x}},T4={kernelName:"Any",backendName:"webgl",kernelFunc:function _4(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i,keepDims:a}=s,o=r.shape.length,l=pt(i,r.shape);let u=l;const c=rn(u,o);let h=r;null!=c&&(h=es({inputs:{x:r},backend:e,attrs:{perm:c}}),u=dn(u.length,o)),Fn("any",u,o);const[d,p]=An(h.shape,u),g=Ne({inputs:{x:h},backend:e,attrs:{shape:[-1,K(p)]}}),m=Ji(g,g.dtype,"any",e);let x;return x=Ne(a?{inputs:{x:m},backend:e,attrs:{shape:hn(d,l)}}:{inputs:{x:m},backend:e,attrs:{shape:d}}),e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(m),null!=c&&e.disposeIntermediateTensorInfo(h),x}};class S4{constructor(t,e,s){this.variableNames=["A"];const{windowSize:r,batchSize:i,outSize:a}=t;s||this.variableNames.push("bestIndicesA"),this.outputShape=[i,a],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 = ${s?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));"};\n float candidate = getA(batch, inIdx);\n if (candidate ${"max"===e?">":"<"} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}}class C4{constructor(t,e,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,T(t.length>2,()=>`Packed arg${s.charAt(0).toUpperCase()+s.slice(1)} supports only inputs with rank above 2.`);const a=Math.ceil(t[t.length-1]/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");const o=this.outputShape,l=o.length,u=Ut(l),c=Jn("coords",l);let h,d;if(1===a){d=l+1;const k=Ut(d);h=`\n ${k} sourceLocR = ${k}(${c.join()}, 0);\n ++${c[l-1]};\n ${k} sourceLocG = ${k}(${c.join()}, 0);\n ++${c[l-2]};\n ${k} sourceLocA = ${k}(${c.join()}, 0);\n --${c[l-1]};\n ${k} sourceLocB = ${k}(${c.join()}, 0);\n --${c[l-2]};`}else d=l,h=`\n ${u} sourceLocR = coords;\n ++${c[l-1]};\n ${u} sourceLocG = coords;\n ++${c[l-2]};\n ${u} sourceLocA = coords;\n --${c[l-1]};\n ${u} sourceLocB = coords;\n --${c[l-2]};`;const p=["x","y","z","w","u","v"].slice(0,d),f="."+p[d-1],g=p.map(k=>"int "+k),m=Jn("sourceLocR",d-1).concat("inIdx.r"),x=Jn("sourceLocG",d-1).concat("inIdx.g"),y=Jn("sourceLocB",d-1).concat("inIdx.b"),b=Jn("sourceLocA",d-1).concat("inIdx.a"),v="max"===s?"greaterThan":"lessThan",w=r?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\n getBestIndicesAChannel(${x.join()}),\n getBestIndicesAChannel(${y.join()}),\n getBestIndicesAChannel(${b.join()})));`,S=`vec4(\n getAChannel(${m.join()}),\n hasNextCol ? getAChannel(${x.join()}) : 0.,\n hasNextRow ? getAChannel(${y.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,I=r?"":`\n float getBestIndicesAChannel(${g.join()}) {\n return getChannel(getBestIndicesA(${p.join()}),\n vec2(${p.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${g.join()}) {\n return getChannel(getA(${p.join()}),\n vec2(${p.slice(-2).join()}));\n }\n ${I}\n void main() {\n ${u} coords = getOutputCoords();\n bool hasNextCol = ${c[l-1]} < ${o[l-1]-1};\n bool hasNextRow = ${c[l-2]} < ${o[l-2]-1};\n ${h}\n ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},\n sourceLocB${f}, sourceLocA${f}) * ${e};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${S};\n\n for (int i = 0; i < ${e}; i++) {\n inIdx = srcIdx;\n ${w}\n vec4 candidate = ${S};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${v}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `}}function ET(n,t,e,s=null){let r=t.shape[0],i=t.shape[1];null!=s&&(r=s.shape[0],i=s.shape[1]);const a=_c(i),o={windowSize:a,inSize:i,batchSize:r,outSize:Math.ceil(i/a)},l=new S4(o,e,null==s),u=[t];null!=s&&u.push(s);const c=n.runWebGLProgram(l,u,"int32");if(1===c.shape[1])return c;const h=ET(n,t,e,c);return n.disposeIntermediateTensorInfo(c),h}function kT(n,t,e,s=null){const r=null!=s?s.shape:t.shape,a=_c(r[r.length-1]),o=new C4(r,a,e,null==s),u=n.runWebGLProgram(o,null==s?[t]:[t,s],"int32");if(u.shape.length===t.shape.length){const c=kT(n,t,e,u);return n.disposeIntermediateTensorInfo(u),c}return u}function NT(n,t,e,s){const r=[e];if(Fn("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,t.shape.length),!E().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const i=[],a=n.texData.get(t.dataId);let l=t;null!==a&&a.isPacked&&(l=n.unpackTensor(t),i.push(l));const[u,c]=An(l.shape,r),h=K(c),d=Ne({inputs:{x:l},backend:n,attrs:{shape:[-1,h]}});i.push(d);const p=ET(n,d,s);i.push(p);const f=Ne({inputs:{x:p},backend:n,attrs:{shape:u}});return i.forEach(g=>n.disposeIntermediateTensorInfo(g)),f}return kT(n,t,s)}const E4={kernelName:Kl,backendName:"webgl",kernelFunc:function I4(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i}=s;let a=pt(i,r.shape);const o=rn(a,r.shape.length);let l=r;const u=[];null!=o&&(l=es({inputs:{x:r},backend:e,attrs:{perm:o}}),u.push(l),a=dn(a.length,l.shape.length)),Fn("argMax",[a[0]],l.shape.length);const c=NT(e,l,a[0],"max");return u.forEach(h=>e.disposeIntermediateTensorInfo(h)),c}},N4={kernelName:ql,backendName:"webgl",kernelFunc:function k4(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i}=s;let a=pt(i,r.shape);const o=rn(a,r.shape.length);let l=r;const u=[];null!=o&&(l=es({inputs:{x:r},backend:e,attrs:{perm:o}}),u.push(l),a=dn(a.length,l.shape.length)),Fn("argMin",[a[0]],l.shape.length);const c=NT(e,l,a[0],"min");return u.forEach(h=>e.disposeIntermediateTensorInfo(h)),c}},R4=Nt({opSnippet:Ts+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),$4={kernelName:Qa,backendName:"webgl",kernelFunc:R4},O4=Nt({opSnippet:Ts+"return log(x + sqrt(x * x + 1.0));"}),P4={kernelName:Ja,backendName:"webgl",kernelFunc:O4},L4=Nt({opSnippet:Ts+"\n return atan(x);\n"}),M4={kernelName:eo,backendName:"webgl",kernelFunc:L4},B4=Ln({opSnippet:ig+"\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 "+Qi+"\n return result;\n"}),U4={kernelName:no,backendName:"webgl",kernelFunc:B4},G4=Nt({opSnippet:Ts+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),H4={kernelName:to,backendName:"webgl",kernelFunc:G4};class Fl{constructor(t,e,s,r=!1,i=!1){if(this.variableNames=["x"],"avg"===e&&s)throw new Error("Cannot compute positions for average pool.");const a=t.filterWidth,o=t.strideHeight,l=t.strideWidth,u=t.dilationHeight,c=t.dilationWidth,h=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.top,f=t.padInfo.left;this.outputShape=t.outShape;const g="avg"===e;let y="0.0";if(g||(y="-1.0 / 1e-20"),s)return void(this.userCode=`\n const ivec2 strides = ivec2(${o}, ${l});\n const ivec2 pads = ivec2(${p}, ${f});\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 < ${h};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${t.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${d};\n wC += ${c}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${t.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?i?`((batch * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + d`:`(xR * ${t.inWidth} + xC) * ${t.inChannels} + d`:`wR * ${d} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `);let v=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===e&&(v="avgValue / max(count, 1.0)");const w=4*Math.floor(a/4),S=a%4,I=`\n if (${g}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${o}, ${l});\n const ivec2 pads = ivec2(${p}, ${f});\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 >= ${t.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${y});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${h};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${t.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${w}; wC += 4) {\n int xC = xCCorner + wC * ${c};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${c}, d),\n getValue(batch, xR, xC + 2 * ${c}, d),\n getValue(batch, xR, xC + 3 * ${c}, d)\n );\n\n ${I}\n }\n\n int xC = xCCorner + ${w};\n if (${1===S}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${2===S}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${c}, d),\n initializationValue,\n initializationValue\n );\n\n ${I}\n } else if (${3===S}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${c}, d),\n getValue(batch, xR, xC + 2 * ${c}, d),\n initializationValue\n );\n\n ${I}\n }\n }\n setOutput(${v});\n }\n `}}class og{constructor(t,e,s,r=!1,i=!1){if(this.variableNames=["x"],"avg"===e&&s)throw new Error("Cannot compute positions for average pool.");const a=t.filterWidth,o=t.strideDepth,l=t.strideHeight,u=t.strideWidth,c=t.dilationDepth,h=t.dilationHeight,d=t.dilationWidth,p=t.effectiveFilterDepth,f=t.effectiveFilterHeight,g=t.effectiveFilterWidth,m=t.padInfo.front,x=t.padInfo.top,y=t.padInfo.left;this.outputShape=t.outShape;const b="avg"===e;let v="0.0";if(b||(v="-1.0 / 1e-20"),s)return void(this.userCode=`\n const ivec3 strides =\n ivec3(${o}, ${l}, ${u});\n const ivec3 pads = ivec3(${m}, ${x}, ${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 += ${c}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${t.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${f};\n wR += ${h}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${t.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${g};\n wC += ${d}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${t.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?i?`(((batch * ${t.inDepth} + xD) * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`((xD * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`wD * ${f} * ${g} +\n wR * ${g} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `);let S=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===e&&(S="avgValue / max(count, 1.0)");const I=4*Math.floor(a/4),k=a%4,D=`\n if (${b}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec3 strides =\n ivec3(${o}, ${l}, ${u});\n const ivec3 pads = ivec3(${m}, ${x}, ${y});\n const float initializationValue = ${v};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= ${t.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4(${v});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${p};\n wD += ${c}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${t.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${f};\n wR += ${h}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${t.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${I}; 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 ${D}\n }\n\n int xC = xCCorner + ${I};\n if (${1===k}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${D}\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 ${D}\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 ${D}\n }\n }\n }\n setOutput(${S});\n }\n `}}const X4={kernelName:Zl,backendName:"webgl",kernelFunc:function j4(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t;Dl(r,"avgPool");const{filterSize:i,strides:a,pad:o,dimRoundingMode:l}=s;T(Pn(a,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '1'`);const c=ks(r.shape,i,a,1,o,l);if(1===c.filterWidth&&1===c.filterHeight&&rt(c.inShape,c.outShape))return hs({inputs:{x:r},backend:e});const h=new Fl(c,"avg",!1);return e.runWebGLProgram(h,[r],"float32")}},q4={kernelName:Yl,backendName:"webgl",kernelFunc:function K4(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{filterSize:i,strides:a,pad:o,dimRoundingMode:l,dataFormat:u}=s,h=Tr(r.shape,i,a,[1,1,1],o,l,u),d=new og(h,"avg",!1);return e.runWebGLProgram(d,[r],"float32")}};class Z4{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;const l=t.effectiveFilterHeight,u=t.effectiveFilterWidth;this.userCode=`\n const ivec2 pads = ivec2(${l-1-t.padInfo.top}, ${u-1-t.padInfo.left});\n const float avgMultiplier = float(${1/(t.filterHeight*t.filterWidth)});\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 < ${l};\n wR += ${t.dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${t.strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${u};\n wC+= ${t.dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${t.strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `}}class Y4{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;const h=t.effectiveFilterDepth,d=t.effectiveFilterHeight,p=t.effectiveFilterWidth;this.userCode=`\n const ivec3 pads = ivec3(${h-1-t.padInfo.front}, ${d-1-t.padInfo.top}, ${p-1-t.padInfo.left});\n const float avgMultiplier = float(${1/(t.filterDepth*t.filterHeight*t.filterWidth)});\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 < ${h};\n wD += ${t.dilationDepth}) {\n float dyD = float(dyDCorner + wD) / ${t.strideDepth}.0;\n\n if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${d};\n wR += ${t.dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${t.strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${p};\n wC += ${t.dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${t.strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const J4={kernelName:rd,backendName:"webgl",kernelFunc:function Q4(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,input:i}=t,a=i,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,d=Tr(a.shape,o,l,[1,1,1],u,c),p=new Y4(d);return e.runWebGLProgram(p,[r],a.dtype)}},tG={kernelName:sd,backendName:"webgl",kernelFunc:function eG(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,input:i}=t,a=i;Dl([r,i],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=ks(a.shape,o,l,1,u),h=new Z4(c);return e.runWebGLProgram(h,[r],a.dtype)}},sG={kernelName:Ql,backendName:"webgl",kernelFunc:function nG(n){const{inputs:t,backend:e,attrs:s}=n,{a:r,b:i}=t,{transposeA:a,transposeB:o}=s;return Nh({a:r,b:i,transposeA:a,transposeB:o,backend:e})}};class rG{constructor(t,e,s,r,i,a){this.outputShape=[],this.variableNames=["x","mean","variance"],ht(t,e),ht(t,s);let o="0.0";null!=r&&(ht(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let l="1.0";null!=i&&(ht(t,i),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${o};\n float scale = ${l};\n float inv = scale * inversesqrt(variance + float(${a}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `}}class iG{constructor(t,e,s,r,i,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],ht(t,e),ht(t,s);let o="vec4(0.0)";null!=r&&(ht(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let l="vec4(1.0)";null!=i&&(ht(t,i),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`\n void main() {\n vec4 offset = ${o};\n vec4 scale = ${l};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${a}));\n\n setOutput((x - mean) * inv + offset);\n }\n `}}const aG={kernelName:cu,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,mean:r,variance:i,offset:a,scale:o}=n;T(r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),T(null==a||r.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),T(null==o||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=e;null==l&&(l=.001);const u=[s,r,i];let c=null;null!=a&&(c=a.shape,u.push(a));let h=null;null!=o&&(h=o.shape,u.push(o));const d=E().getBool("WEBGL_PACK_NORMALIZATION")?new iG(s.shape,r.shape,i.shape,c,h,l):new rG(s.shape,r.shape,i.shape,c,h,l);return t.runWebGLProgram(d,u,u[0].dtype)}};class oG{constructor(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;const e=Ut(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const s=function lG(n){if(1===n)return"sourceLoc";if(n<=6)return lg.slice(0,n).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}(this.rank);let r;r=`\n ${e} sourceLoc;\n ${e} coords = getOutputCoords();\n ${t.map((a,o)=>`sourceLoc.${lg[o]} = start[${o}] + coords.${lg[o]};`).join("\n")}\n `,this.userCode=`\n void main() {\n ${r}\n setOutput(getSource(${s}));\n }\n `}}const lg=["x","y","z","w","u","v"];class uG{constructor(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const e=Ut(this.rank),s=Jn("coords",this.rank),r=Jn("sourceLoc",this.rank),i=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${i})`,o=`\n result.x = ${a};\n if (++${s[this.rank-1]} < ${t[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.y = ${a};\n --${r[this.rank-1]};\n }\n `,l=1===this.rank?"":`\n --${s[this.rank-1]};\n if (++${s[this.rank-2]} < ${t[this.rank-2]}) {\n ++${r[this.rank-2]};\n result.z = ${a};\n if (++${s[this.rank-1]} < ${t[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.w = ${a};\n }\n }\n `,u=this.rank<=4?`sourceLoc = coords +\n ${e}(${t.map((c,h)=>`start[${h}]`).join()});`:t.map((c,h)=>`${r[h]} = ${s[h]} + start[${h}];`).join("\n");this.userCode=`\n void main() {\n ${e} coords = getOutputCoords();\n ${e} sourceLoc;\n ${u}\n vec4 result = vec4(0.);\n ${o}\n ${l}\n setOutput(result);\n }\n `}}function Wa(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{begin:i,size:a}=s,[o,l]=ac(r,i,a);if(Rp(r,o,l),0===K(l))return e.makeTensorInfo(l,r.dtype,[]);if(e.shouldExecuteOnCPU([r])||"string"===r.dtype){const h=e.texData.get(r.dataId),d=eW(h.values,o,l,r.shape,r.dtype);return e.makeTensorInfo(l,r.dtype,d)}const{isPacked:u}=e.texData.get(r.dataId),c=Dp(r.shape,o,l);if(u||!c){const h=E().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new uG(l):new oG(l);return e.runWebGLProgram(h,[r],r.dtype,[o])}return e.uploadToGPU(r.dataId),function cG(n,t,e,s){const r=s.texData.get(n.dataId),i=s.makeTensorInfo(e,n.dtype),a=s.texData.get(i.dataId);Object.assign(a,r),a.refCount=1,a.shape=e,a.dtype=n.dtype;let o=Op(t,Ue(n.shape));r.slice&&(o+=r.slice.flatOffset),a.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||n.dataId};const l=s.dataRefCount.get(a.slice.origDataId)||1;return s.dataRefCount.set(a.slice.origDataId,l+1),i}(r,o,l,e)}const hG={kernelName:Vu,backendName:"webgl",kernelFunc:Wa},dG={kernelName:Jl,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{blockShape:i,crops:a}=s;T(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const o=i.reduce((y,b)=>y*b),l=pl(r.shape,i,o),u=fl(l.length,i.length),c=ml(r.shape,i,o),h=gf(a,i.length),d=xf(c,a,i.length),p=[],f=Ne({inputs:{x:r},backend:e,attrs:{shape:l}}),g=es({inputs:{x:f},backend:e,attrs:{perm:u}}),m=Ne({inputs:{x:g},backend:e,attrs:{shape:c}}),x=Wa({inputs:{x:m},backend:e,attrs:{begin:h,size:d}});return p.push(f),p.push(g),p.push(m),p.forEach(y=>e.disposeIntermediateTensorInfo(y)),x}},fG={kernelName:id,backendName:"webgl",kernelFunc:function pG(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,weights:i}=t,{size:a}=s,o=e.readSync(r.dataId),l=e.readSync(i.dataId),u=aT(o,l,i.dtype,i.shape,a);return e.makeTensorInfo([a],i.dtype,u)}},yG={kernelName:ad,backendName:"webgl",kernelFunc:function xG(n){const{inputs:t,backend:e}=n,{a:s,b:r}=t,i=E().getBool("WEBGL_PACK_BINARY_OPERATIONS"),a=E().getNumber("WEBGL_VERSION");if(e.shouldExecuteOnCPU([s,r])||1===a){const l=e.texData.get(s.dataId).values,u=e.texData.get(r.dataId).values,[c,h]=SU(s.shape,r.shape,l,u,s.dtype),d=e.makeTensorInfo(h,s.dtype);return e.texData.get(d.dataId).values=c,d}let o;return o=i?new Ba("\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",s.shape,r.shape,!1):new Yi("\n return float(int(a.r) & int(b.r));\n",s.shape,r.shape),e.runWebGLProgram(o,[s,r],s.dtype)}},vG={kernelName:Fg,backendName:"webgl",kernelFunc:function bG(n){const{inputs:t,backend:e}=n,{s0:s,s1:r}=t,i=e.readSync(s.dataId),a=e.readSync(r.dataId),o=ht(Array.from(i),Array.from(a));return e.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},AT=Ln({opSnippet:"return float(a != b);",cpuKernelImpl:HU,dtype:"bool"}),wG={kernelName:Eu,backendName:"webgl",kernelFunc:AT};function Ll(n){const{inputs:t,backend:e}=n,{input:s}=t;return hs({inputs:{x:e.texData.get(s.dataId).complexTensorInfos.real},backend:e})}const _G={kernelName:Od,backendName:"webgl",kernelFunc:Ll},CG={kernelName:so,backendName:"webgl",kernelFunc:function ug(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{dtype:i}=s;if("complex64"===i){if("complex64"===r.dtype)return hs({inputs:{x:r},backend:e});const a=Rn(r.shape),o=ug({inputs:{x:r},backend:e,attrs:{dtype:"float32"}}),l=di({inputs:{real:o,imag:a},backend:e});return a.dispose(),e.disposeIntermediateTensorInfo(o),l}if("complex64"===r.dtype){const a=Ll({inputs:{input:r},backend:e}),o=ug({inputs:{x:a},backend:e,attrs:{dtype:i}});return e.disposeIntermediateTensorInfo(a),o}if(!Ve(r.dtype,i)){const a=hs({inputs:{x:r},backend:e});return{dataId:a.dataId,shape:a.shape,dtype:i}}if(e.shouldExecuteOnCPU([r])){const a=e.texData.get(r.dataId).values,[o,l,u]=CU(a,r.shape,r.dtype,i);return e.makeTensorInfo(o,l,u)}if("int32"===i)return function SG(n,t){const e=new xr(n.shape,"return float(int(x));"),s=t.runWebGLProgram(e,[n],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}(r,e);if("bool"===i){const a=e.makeTensorInfo([],"bool",Cn("bool",1)),l=AT({inputs:{a:r,b:a},backend:e});return e.disposeIntermediateTensorInfo(a),l}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${i}`)}},RT="return ceil(x);",IG=Nt({opSnippet:RT,packedOpSnippet:RT,cpuKernelImpl:IU}),EG={kernelName:ro,backendName:"webgl",kernelFunc:IG};class kG{constructor(t){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,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 NG{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,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 RG={kernelName:ao,backendName:"webgl",kernelFunc:function AG(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{clipValueMin:i,clipValueMax:a}=s;let o;return o=E().getBool("WEBGL_PACK_CLIP")?new NG(r.shape):new kG(r.shape),e.runWebGLProgram(o,[r],r.dtype,[[i],[a]])}};class $G{constructor(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "}}function $T(n,t){return{dataId:t.dataId,dtype:t.dtype,shape:n.shape}}const OG={kernelName:eu,backendName:"webgl",kernelFunc:function DG(n){const{inputs:t,backend:e}=n,{x:s}=t,r=e.texData.get(s.dataId),i=new $G(s.shape),a=[$T(s,r.complexTensorInfos.real),$T(s,r.complexTensorInfos.imag)];return e.runWebGLProgram(i,a,a[0].dtype)}};class PG{constructor(t){this.outputShape=[],this.outputShape=or(t,1),this.variableNames=t.map((a,o)=>`T${o}`);const e=new Array(t.length-1);e[0]=t[0][1];for(let a=1;a`T${m}`);const l=new Array(t.length-1);l[0]=t[0][e];for(let g=1;g= ${l[g-1]}) {\n return getChannel(\n getT${g}(${Rh(o,u,m)}),\n vec2(${Rh(c,u,m)}));\n }`}const f=l[l.length-1];d+=`\n return getChannel(\n getT${l.length}(${Rh(o,u,f)}),\n vec2(${Rh(c,u,f)}));`,this.userCode=`\n float getValue(${o.map(g=>"int "+g)}) {\n ${d}\n }\n\n void main() {\n ${i} coords = getOutputCoords();\n vec4 result = vec4(getValue(${a}), 0., 0., 0.);\n\n ${a[r-1]} = ${a[r-1]} + 1;\n if (${a[r-1]} < ${s[r-1]}) {\n result.g = getValue(${a});\n }\n\n ${a[r-2]} = ${a[r-2]} + 1;\n if (${a[r-2]} < ${s[r-2]}) {\n result.a = getValue(${a});\n }\n\n ${a[r-1]} = ${a[r-1]} - 1;\n if (${a[r-2]} < ${s[r-2]} &&\n ${a[r-1]} < ${s[r-1]}) {\n result.b = getValue(${a});\n }\n setOutput(result);\n }\n `}}function Rh(n,t,e){const s=n.indexOf(t);return n.map((i,a)=>a===s?`${i} - ${e}`:i).join()}function $h(n){const{inputs:t,backend:e}=n,{input:s}=t;return hs({inputs:{x:e.texData.get(s.dataId).complexTensorInfos.imag},backend:e})}const LG={kernelName:Id,backendName:"webgl",kernelFunc:$h};function Ml(n,t,e){const s=n[0].dtype;if("complex64"===s){const p=n.map(y=>Ll({inputs:{input:y},backend:e})),f=n.map(y=>$h({inputs:{input:y},backend:e})),g=Ml(p,t,e),m=Ml(f,t,e),x=di({inputs:{real:g,imag:m},backend:e});return p.forEach(y=>e.disposeIntermediateTensorInfo(y)),f.forEach(y=>e.disposeIntermediateTensorInfo(y)),e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(m),x}let r=e.shouldExecuteOnCPU(n);if("string"===s&&(r=!0),r){const p=n.map(v=>{const S=[-1,K(v.shape.slice(t))];return Ne({inputs:{x:v},backend:e,attrs:{shape:S}})}),f=p.map(v=>({vals:e.readSync(v.dataId),shape:v.shape})),g=or(p.map(v=>v.shape),1),x=EU(f,g,s,1===p[0].shape[0]),y=or(n.map(v=>v.shape),t),b=e.makeTensorInfo(y,s,x);return p.forEach(v=>e.disposeIntermediateTensorInfo(v)),b}const i=n.filter(p=>K(p.shape)>0),a=E().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&i[0].shape.length>1;if(1===i.length){const p=a?new xr(n[0].shape,ci):new hi(n[0].shape,ci);return e.runWebGLProgram(p,n,s)}const o=E().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(i.length>o){const p=[];for(let g=0;gf.shape),t);return e.runWebGLProgram(p,i,s)}const{tensors2D:l,outShape:u}=function MG(n,t,e){const s=or(n.map(i=>i.shape),t);return{tensors2D:n.map(i=>Ne({inputs:{x:i},attrs:{shape:[-1,K(i.shape.slice(t))]},backend:e})),outShape:s}}(i,t,e),c=new PG(l.map(p=>p.shape)),h=e.runWebGLProgram(c,l,s);l.forEach(p=>e.disposeIntermediateTensorInfo(p));const d=Ne({inputs:{x:h},attrs:{shape:u},backend:e});return e.disposeIntermediateTensorInfo(h),d}function DT(n){const{inputs:t,backend:e,attrs:s}=n,{axis:r}=s,i=pt(r,t[0].shape)[0];pf(t.map(u=>u.shape),i);const o=or(t.map(u=>u.shape),i);if(0===K(o))return e.makeTensorInfo(o,t[0].dtype,[]);const l=t.filter(u=>K(u.shape)>0);return 1===l.length?hs({inputs:{x:l[0]},backend:e}):Ml(l,i,e)}const VG={kernelName:tu,backendName:"webgl",kernelFunc:DT};class OT{constructor(t,e=!1,s=null,r=!1,i=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;const a=t.padInfo.top,o=t.padInfo.left,l=t.strideHeight,u=t.strideWidth,c=t.dilationHeight,h=t.dilationWidth,d=t.filterHeight,p=t.filterWidth,f=4*Math.floor(t.inChannels/4),g=t.inChannels%4,m="channelsLast"===t.dataFormat,x=m?1:2,y=m?2:3,b=m?3:1;let v="",w="";s&&(v=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${s}\n }`:i?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${s}\n }`:`\n float activation(float x) {\n ${s}\n }\n `,w="result = activation(result);");const S=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),i&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${v}\n\n const ivec2 strides = ivec2(${l}, ${u});\n const ivec2 pads = ivec2(${a}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${b}];\n\n ivec2 xRCCorner =\n ivec2(coords[${x}], 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 * ${c};\n\n if (xR < 0 || xR >= ${t.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${h};\n\n if (xC < 0 || xC >= ${t.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${f}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${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===g}) {\n\n if (${m}) {\n dotProd +=\n getX(batch, xR, xC, ${f}) *\n getW(wR, wC, ${f}, d2);\n } else {\n dotProd +=\n getX(batch, ${f}, xR, xC) *\n getW(wR, wC, ${f}, d2);\n }\n\n } else if (${2===g}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${f}, d2),\n getW(wR, wC, ${f} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${f}),\n getX(batch, xR, xC, ${f} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${f}, xR, xC),\n getX(batch, ${f} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===g}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${f}, d2),\n getW(wR, wC, ${f} + 1, d2),\n getW(wR, wC, ${f} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${f}),\n getX(batch, xR, xC, ${f} + 1),\n getX(batch, xR, xC, ${f} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${f}, xR, xC),\n getX(batch, ${f} + 1, xR, xC),\n getX(batch, ${f} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${S}\n ${w}\n setOutput(result);\n }\n `}}class zG{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;const e=t.padInfo.front,s=t.padInfo.top,r=t.padInfo.left,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,l=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,h=t.filterDepth,d=t.filterHeight,p=t.filterWidth,f=4*Math.floor(t.inChannels/4),g=t.inChannels%4;this.userCode=`\n const ivec3 strides = ivec3(${i}, ${a}, ${o});\n const ivec3 pads = ivec3(${e}, ${s}, ${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 < ${h}; wF++) {\n int xF = xFCorner + wF * ${l};\n\n if (xF < 0 || xF >= ${t.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 >= ${t.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 >= ${t.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${f}; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (${1===g}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${f}) *\n getW(wF, wR, wC, ${f}, d2);\n } else if (${2===g}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${f}),\n getX(batch, xF, xR, xC, ${f} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${f}, d2),\n getW(wF, wR, wC, ${f} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${3===g}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${f}),\n getX(batch, xF, xR, xC, ${f} + 1),\n getX(batch, xF, xR, xC, ${f} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${f}, d2),\n getW(wF, wR, wC, ${f} + 1, d2),\n getW(wF, wR, wC, ${f} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class PT{constructor(t,e=!1,s=null,r=!1,i=!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=t.outShape,this.enableShapeUniforms=Hn(this.outputShape.length);const a=t.padInfo.left,o=t.strideWidth,l=t.dilationWidth,u=t.filterHeight,c=t.filterWidth,h=c;let d="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let m=0;m=0 && xR < inDims[0]) {\n ";for(let m=0;m<(h+1)/2;m++){const x=2*m;if(d+=`\n xC = xCCorner + ${x*l};\n `,1===o){if(x= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {\n xTexelC${x} = 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${x}.zw = vec2(0.0);\n }\n xTexelC${x}Ready = 1;\n }\n `,d+=1===l&&x>0?`\n xC${x} = vec4(xTexelC${x-2}.zw, xTexelC${x}.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${x} = vec4(previous.zw, xTexelC${x}.xy);\n } else {\n xC${x} = vec4(0.0, 0.0, xTexelC${x}.xy);\n }\n `):d+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {\n xTexelC${x} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${x}.zw = vec2(0.0);\n }\n xTexelC${x}Ready = 1;\n }\n\n xC${x} = xTexelC${x};\n `,x+1= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {\n xTexelC${x+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${x+1}.zw = vec2(0.0);\n }\n xTexelC${x+1}Ready = 1;\n }\n `,d+=l>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${x+1} = vec4(previous.zw, xTexelC${x+1}.xy);\n } else {\n xC${x+1} = vec4(0.0, 0.0, xTexelC${x+1}.xy);\n }\n `:`\n xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.xy);\n `):d+=1===y?`\n xC${x+1} = xTexelC${x};\n `:`\n xCOffset = xC + ${y};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {\n xTexelC${x+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${x+1}.zw = vec2(0.0);\n }\n xTexelC${x+1}Ready = 1;\n }\n\n xC${x+1} = xTexelC${x+1};\n `}}else x= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {\n xTexelC${x} = 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${x}.zw = vec2(0.0);\n }\n xTexelC${x}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${x+1}Ready == 0) {\n xTexelC${x+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${x+1}.zw = vec2(0.0);\n }\n xTexelC${x+1}Ready = 1;\n }\n\n xC${x} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);\n `,x+1= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${x+1} = vec4(xTexelC${x+1}.xy, final.xy);\n `)):(d+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {\n xTexelC${x} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${x}.zw = vec2(0.0);\n }\n xTexelC${x}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {\n xTexelC${x+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${x+1}.zw = vec2(0.);\n }\n xTexelC${x+1}Ready = 1;\n }\n\n xC${x} = vec4(\n xTexelC${x}.xy, xTexelC${x+1}.xy);\n `,x+1= 0) {\n // Use custom imod instead mod. On Intel GPU, mod may generate\n // unexpected value.\n // https://github.com/tensorflow/tfjs/issues/5447\n offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n inChannels);\n\n if(d1 < inputShape[${o}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${i}) {\n innerDims = vec2(d1, ch);\n result[${2*c+h}] = getChannel(\n getA(rc.x, d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*c+h}] = 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 Dh(n,t){const e=n.length;return e>=3?t?[...n.slice(0,-3),n[e-3]*n[e-2],n[e-1]]:[...n.slice(0,-3),n[e-3],n[e-2]*n[e-1]]:!t&&1===e&&n[0]>1?[n[0],1]:null}function FT({x:n,filter:t,convInfo:e,backend:s,bias:r=null,preluActivationWeights:i=null,leakyreluAlpha:a=0,activation:o=null}){const l=n.shape,u=s.texData.get(n.dataId),c=e.inChannels,h=l[0]*l[1]*l[2],d=e.outChannels,p="channelsLast"===e.dataFormat,g=!1;let m;const x=[];if(null!=i){const v=Dh(i.shape,p);null!=v&&(i=Ne({inputs:{x:i},backend:s,attrs:{shape:v}}),x.push(i))}if(null!=r){const v=Dh(r.shape,p);null!=v&&(r=Ne({inputs:{x:r},backend:s,attrs:{shape:v}}),x.push(r))}if((1!==h&&1!==d||!(c>1e3))&&u.isPacked&&p&&null!=u.texture&&l[2]%2!=0&&rt(u.shape.slice(-3),l.slice(-3))){const w={dataId:n.dataId,shape:[1,l[0]*l[1]*(l[2]+1),e.inChannels],dtype:n.dtype},S=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,T(wh(u.shape,w.shape),()=>`packed reshape ${u.shape} to ${w.shape} isn't free`);const I=Ne({inputs:{x:t},backend:s,attrs:{shape:[1,e.inChannels,e.outChannels]}});x.push(I);const k=Nh({a:w,b:I,backend:s,transposeA:!1,transposeB:g,bias:r,activation:o,preluActivationWeights:i,leakyreluAlpha:a}),D=s.texData.get(k.dataId);T(D.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=S,D.shape=e.outShape,m=hs({inputs:{x:k},backend:s}),m.shape=e.outShape,x.push(k)}else{const v=e.outHeight*e.outWidth,w=Ne({inputs:{x:n},backend:s,attrs:{shape:p?[e.batchSize,v,e.inChannels]:[e.batchSize,e.inChannels,v]}}),S=Ne({inputs:{x:t},backend:s,attrs:{shape:[1,e.inChannels,e.outChannels]}}),I=Nh({a:p?w:S,b:p?S:w,transposeA:!p,transposeB:g,backend:s,bias:r,activation:o,preluActivationWeights:i,leakyreluAlpha:a});m=Ne({inputs:{x:I},backend:s,attrs:{shape:e.outShape}}),x.push(w),x.push(S),x.push(I)}for(const v of x)s.disposeIntermediateTensorInfo(v);return m}function LT({x:n,filter:t,convInfo:e,backend:s,bias:r=null,preluActivationWeights:i=null,leakyreluAlpha:a=0,activation:o=null}){const{filterWidth:l,filterHeight:u,inChannels:c,outWidth:h,outHeight:d,dataFormat:p}=e,f="channelsLast"===p,g=l*u*c,m=d*h,x=[e.batchSize,g,m],v=[];if(null!=i){const te=Dh(i.shape,f);null!=te&&(i=Ne({inputs:{x:i},backend:s,attrs:{shape:te}}),v.push(i))}if(null!=r){const te=Dh(r.shape,f);null!=te&&(r=Ne({inputs:{x:r},backend:s,attrs:{shape:te}}),v.push(r))}const w=Ne({inputs:{x:t},backend:s,attrs:{shape:[1,g,K(t.shape)/g]}});v.push(w);const S=new BG(x,e),k=s.runWebGLProgram(S,[n],"float32",[n.shape,[e.padInfo.top,e.padInfo.left],[e.strideHeight,e.strideWidth],[e.dilationHeight,e.dilationWidth],[e.inChannels],[e.filterWidth*e.inChannels],[e.outWidth]]),D=Ne({inputs:{x:k},backend:s,attrs:{shape:x}});v.push(k),v.push(D);const P=null!=r,B=null!=i,Y="leakyrelu"===o,Q=o?Pl(o,!0):null,ee=new bT(f?D.shape:w.shape,f?w.shape:D.shape,f?[e.batchSize,m,e.outChannels]:[e.batchSize,e.outChannels,m],!0,!1,P,Q,B,Y),J=f?[D,w]:[w,D];if(r&&J.push(r),B&&J.push(i),Y){const te=s.makeTensorInfo([],"float32",Br(a,"float32"));J.push(te),v.push(te)}const se=s.runWebGLProgram(ee,J,"float32"),ae=Ne({inputs:{x:se},backend:s,attrs:{shape:e.outShape}});v.push(se);for(const te of v)s.disposeIntermediateTensorInfo(te);return ae}const WG={kernelName:nu,backendName:"webgl",kernelFunc:function UG(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,filter:i}=t,{strides:a,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s,h=Sr(l),d=Nn(r.shape,i.shape,a,u,o,c,!1,h);let p;if(1!==d.filterHeight||1!==d.filterWidth||1!==d.dilationHeight||1!==d.dilationWidth||1!==d.strideHeight||1!==d.strideWidth||"SAME"!==d.padInfo.type&&"VALID"!==d.padInfo.type)if(d.strideWidth<=2&&"channelsLast"===h&&E().getBool("WEBGL_EXP_CONV")){const g=new PT(d);p=e.runWebGLProgram(g,[r,i],"float32",[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]])}else if(E().getBool("WEBGL_CONV_IM2COL"))p=LT({x:r,filter:i,convInfo:d,backend:e});else{const g=new OT(d);p=e.runWebGLProgram(g,[r,i],"float32")}else p=FT({x:r,filter:i,convInfo:d,backend:e});const f=Ne({inputs:{x:p},backend:e,attrs:{shape:d.outShape}});return e.disposeIntermediateTensorInfo(p),f}};class GG{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < ${t.batchSize}; b++) {\n for (int yR = 0; yR < ${t.outHeight}; yR++) {\n int xR = wR + yR * ${t.strideHeight} - ${t.padInfo.top};\n\n if (xR < 0 || xR >= ${t.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${t.outWidth}; yC++) {\n int xC = wC + yC * ${t.strideWidth} - ${t.padInfo.left};\n\n if (xC < 0 || xC >= ${t.inWidth}) {\n continue;\n }\n\n ${"channelsLast"===t.dataFormat?"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 HG{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterHeight,s=t.filterWidth,a="channelsLast"===t.dataFormat;this.userCode=`\n const ivec2 pads = ivec2(${e-1-t.padInfo.top}, ${s-1-t.padInfo.left});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${a?3:1}];\n\n ivec2 dyCorner = ivec2(coords[${a?1:2}], coords[${a?2:3}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${e}; wR++) {\n float dyR = float(dyRCorner + wR) / ${t.strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${e} - 1 - wR;\n\n for (int wC = 0; wC < ${s}; wC++) {\n float dyC = float(dyCCorner + wC) / ${t.strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${s} - 1 - wC;\n\n for (int d2 = 0; d2 < ${t.outChannels}; d2++) {\n\n if (${a}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class jG{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape,this.userCode=`\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < ${t.batchSize}; b++) {\n for (int yF = 0; yF < ${t.outDepth}; yF++) {\n int xF = wF + yF * ${t.strideDepth} - ${t.padInfo.front};\n\n if (xF < 0 || xF >= ${t.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${t.outHeight}; yR++) {\n int xR = wR + yR * ${t.strideHeight} - ${t.padInfo.top};\n\n if (xR < 0 || xR >= ${t.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${t.outWidth}; yC++) {\n int xC = wC + yC * ${t.strideWidth} - ${t.padInfo.left};\n\n if (xC < 0 || xC >= ${t.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class XG{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterDepth,s=t.filterHeight,r=t.filterWidth;this.userCode=`\n const ivec3 pads = ivec3(${e-1-t.padInfo.front}, ${s-1-t.padInfo.top}, ${r-1-t.padInfo.left});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < ${e}; wF++) {\n float dyF = float(dyFCorner + wF) / ${t.strideDepth}.0;\n\n if (dyF < 0.0 || dyF >= ${t.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${e} - 1 - wF;\n\n for (int wR = 0; wR < ${s}; wR++) {\n float dyR = float(dyRCorner + wR) / ${t.strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${s} - 1 - wR;\n\n for (int wC = 0; wC < ${r}; wC++) {\n float dyC = float(dyCCorner + wC) / ${t.strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${r} - 1 - wC;\n\n for (int d2 = 0; d2 < ${t.outChannels}; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const qG={kernelName:ld,backendName:"webgl",kernelFunc:function KG(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,dy:i}=t,{strides:a,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:c}=s,h=Sr(l),d=Nn(r.shape,c,a,1,o,u,!1,h),p=new GG(d);return e.runWebGLProgram(p,[r,i],"float32")}};class ZG{constructor(t){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=t.inShape,this.enableShapeUniforms=Hn(this.outputShape.length);const e=t.filterHeight,s=t.filterWidth;this.userCode=`\n const ivec2 pads = ivec2(${e-1-t.padInfo.top}, ${s-1-t.padInfo.left});\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 < ${e}; wR++) {\n float dyR = float(dyRCorner + wR) / strides[0];\n if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n int wRPerm = ${e} - 1 - wR;\n\n for (int wC = 0; wC < ${s}; wC++) {\n int wCPerm = ${s} - 1 - wC;\n\n float dyC = float(dyCCorner + wC) / strides[1];\n bool idyCVal = (dyC >= 0.0) && (dyC < ${t.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 < ${t.outWidth}.0)\n && (fract(dyC2) == 0.0);\n int idyC2 = int(dyC2);\n\n if (idyCVal && idyCVal2) {\n for (int d2 = 0; d2 < ${t.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 < ${t.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 < ${t.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 QG={kernelName:su,backendName:"webgl",kernelFunc:function YG(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,filter:i}=t,{inputShape:a,strides:o,pad:l,dataFormat:u,dimRoundingMode:c}=s,h=Sr(u),d=Nn(a,i.shape,o,1,l,c,!1,h);if(E().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&"channelsLast"===h){const p=[[d.strideHeight,d.strideWidth]],f=new ZG(d);return e.runWebGLProgram(f,[r,i],"float32",p)}{const p=new HG(d);return e.runWebGLProgram(p,[r,i],"float32")}}},eH={kernelName:ru,backendName:"webgl",kernelFunc:function JG(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,filter:i}=t,{strides:a,pad:o,dilations:l}=s,u=qr(r.shape,i.shape,a,l,o),c=new zG(u);return e.runWebGLProgram(c,[r,i],"float32")}},nH={kernelName:ud,backendName:"webgl",kernelFunc:function tH(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,dy:i}=t,{strides:a,pad:o,filterShape:l}=s,u=qr(r.shape,l,a,1,o),c=new jG(u);return e.runWebGLProgram(c,[r,i],"float32")}},rH={kernelName:cd,backendName:"webgl",kernelFunc:function sH(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,filter:i}=t,{pad:a,strides:o,inputShape:l}=s,u=qr(l,i.shape,o,1,a),c=new XG(u);return e.runWebGLProgram(c,[r,i],"float32")}},oH=Nt({opSnippet:Ua+"\n return cos(x);\n",packedOpSnippet:`\n vec4 result = cos(x);\n bvec4 isNaN = isnan(x);\n ${Qi}\n return result;\n`}),lH={kernelName:oo,backendName:"webgl",kernelFunc:oH},uH=Nt({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),cH={kernelName:lo,backendName:"webgl",kernelFunc:uH};class hH{constructor(t,e,s,r,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[a,o,l,u]=t,[c]=e,[h,d]=s;this.outputShape=[c,h,d,u];const p="bilinear"===r?1:0,[f,g]=[o-1+".0",l-1+".0"],[m,x,y]=h>1?[""+(o-1)/(h-1),"(y2-y1) * height_ratio",`y1*${f} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${f}`],[b,v,w]=d>1?[""+(l-1)/(d-1),"(x2-x1) * width_ratio",`x1*${g} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${g}`];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 >= ${a}) {\n return;\n }\n\n float height_scale = ${x};\n float width_scale = ${v};\n\n float in_y = ${y};\n if( in_y < 0.0 || in_y > ${f} ) {\n setOutput(float(${i}));\n return;\n }\n float in_x = ${w};\n if( in_x < 0.0 || in_x > ${g} ) {\n setOutput(float(${i}));\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 dH={kernelName:dd,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{image:r,boxes:i,boxInd:a}=t,{cropSize:o,method:l,extrapolationValue:u}=s,c=new hH(r.shape,i.shape,o,l,u);return e.runWebGLProgram(c,[r,i,a],"float32")}};var Oh=function(n){return n.Prod="*",n.Sum="+",n}(Oh||{});class MT{constructor(t,e,s,r){this.op=t,this.outputShape=e,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const i=this.outputShape.length,o=s?this.op===Oh.Prod?"1.0":"0.0":`getX(${VT(i,"coords",this.op)})`,l=this.outputShape[this.outputShape.length-1];let u="",c="";s?(u=r?"end != "+(l-1):"end != 0",c=r?"end + 1":"end - 1"):(u=r?`end + pow2 < ${l}`:"end >= pow2",c=r?"end + pow2":"end - pow2"),this.userCode=`\n void main() {\n ${Ut(i)} coords = getOutputCoords();\n int end = ${zT(i,"coords",this.op)};\n float val = ${o};\n int pow2 = int(pow(2.0, index));\n if (${u}) {\n int idx = ${c};\n ${zT(i,"coords",this.op)} = idx;\n val ${this.op}= getX(${VT(i,"coords",this.op)});\n }\n setOutput(val);\n }\n `}}function VT(n,t,e){if(1===n)return`${t}`;if(2===n)return`${t}.x, ${t}.y`;if(3===n)return`${t}.x, ${t}.y, ${t}.z`;if(4===n)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${e} for rank ${n} is not yet supported`)}function zT(n,t,e){if(1===n)return`${t}`;if(2===n)return`${t}.y`;if(3===n)return`${t}.z`;if(4===n)return`${t}.w`;throw new Error(`Cumulative ${e} for rank ${n} is not yet supported`)}function BT(n,t,e,s,r,i){const a=t.shape.length,o=rn([s],a);let l=t;null!=o&&(l=es({inputs:{x:t},backend:e,attrs:{perm:o}}));const u=dn(1,a)[0];if(u!==a-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${s}`);const c=l.shape[u];let h=hs({inputs:{x:l},backend:e});for(let d=0;d<=Math.ceil(Math.log2(c))-1;d++){const p=new MT(n,l.shape,!1,i),g=h;h=e.runWebGLProgram(p,[h],h.dtype,[[d]]),e.disposeIntermediateTensorInfo(g)}if(r){const d=new MT(n,l.shape,r,i),p=h;h=e.runWebGLProgram(d,[h],h.dtype),e.disposeIntermediateTensorInfo(p)}if(null!=o){const p=es({inputs:{x:h},backend:e,attrs:{perm:Yr(o)}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(l),p}return h}const fH={kernelName:hd,backendName:"webgl",kernelFunc:function pH(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i,exclusive:a,reverse:o}=s;return BT(Oh.Prod,r,e,i,a,o)}},gH={kernelName:iu,backendName:"webgl",kernelFunc:function mH(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i,exclusive:a,reverse:o}=s;return BT(Oh.Sum,r,e,i,a,o)}},yH={kernelName:pd,backendName:"webgl",kernelFunc:function xH(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,weights:i}=t,{size:a,binaryOutput:o}=s;if(1===r.shape.length){const l=e.readSync(r.dataId),u=e.readSync(i.dataId),c=aT(l,u,i.dtype,i.shape,a);return e.makeTensorInfo([a],i.dtype,c)}if(2===r.shape.length){const l=e.bufferSync(r),u=e.bufferSync(i),c=TU(l,u,a,o);return e.makeTensorInfo(c.shape,i.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}};class bH{constructor(t,e,s){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=s,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${e};\n int offset_h = imod(h, ${e});\n int in_w = w / ${e};\n int offset_w = imod(w, ${e});\n int offset_d = (offset_h * ${e} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `}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 wH={kernelName:fd,backendName:"webgl",kernelFunc:function vH(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{blockSize:i,dataFormat:a}=s,o=r.shape[0],h=("NHWC"===a?r.shape[1]:r.shape[2])*i,d=("NHWC"===a?r.shape[2]:r.shape[3])*i,p=("NHWC"===a?r.shape[3]:r.shape[1])/(i*i),g=new bH("NHWC"===a?[o,h,d,p]:[o,p,h,d],i,a);return e.runWebGLProgram(g,[r],r.dtype)}};class UT{constructor(t,e=!1,s=null,r=!1,i=!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=t.outShape,this.enableShapeUniforms=Hn(this.outputShape.length);const a=t.filterHeight,o=t.filterWidth,l=t.outChannels/t.inChannels;let u="",c="";s&&(u=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${s}\n }`:i?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${s}\n }`:`\n float activation(float x) {\n ${s}\n }\n `,c="result = activation(result);");const h=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),i&&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 / ${l};\n int q = d2 - d1 * ${l};\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 < ${a}; wR++) {\n int xR = xRCorner + wR * dilations[0];\n\n if (xR < 0 || xR >= inDims[0]) {\n continue;\n }\n\n for (int wC = 0; wC < ${o}; wC++) {\n int xC = xCCorner + wC * dilations[1];\n\n if (xC < 0 || xC >= inDims[1]) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${h}\n ${c}\n setOutput(result);\n }\n `}}class WT{constructor(t,e=!1,s=null,r=!1,i=!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=t.outShape,this.enableShapeUniforms=Hn(this.outputShape.length);const a=t.outChannels/t.inChannels,o=t.padInfo.left,l=t.strideWidth,u=t.dilationWidth,c=t.filterHeight,h=t.filterWidth,d=h;let p="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let x=0;x=0 && xR < inDims[0]) {\n ";for(let x=0;x<(d+1)/2;x++){const y=2*x;if(p+=`\n xC = xCCorner + ${y*u};\n `,1===l){if(y= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {\n xTexelC${y} = 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${y}.zw = vec2(0.0);\n }\n xTexelC${y}Ready = 1;\n }\n `,p+=1===u&&y>0?`\n xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.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${y} = vec4(previous.zw, xTexelC${y}.xy);\n } else {\n xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);\n }\n `):p+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {\n xTexelC${y} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${y}.zw = vec2(0.0);\n }\n xTexelC${y}Ready = 1;\n }\n\n xC${y} = xTexelC${y};\n `,y+1= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {\n xTexelC${y+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${y+1}.zw = vec2(0.0);\n }\n xTexelC${y+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${y+1} = vec4(previous.zw, xTexelC${y+1}.xy);\n } else {\n xC${y+1} = vec4(0.0, 0.0, xTexelC${y+1}.xy);\n }\n `:`\n xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);\n `):p+=1===b?`\n xC${y+1} = xTexelC${y};\n `:`\n xCOffset = xC + ${b};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {\n xTexelC${y+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${y+1}.zw = vec2(0.0);\n }\n xTexelC${y+1}Ready = 1;\n }\n\n xC${y+1} = xTexelC${y+1};\n `}}else y= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {\n xTexelC${y} = 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${y}.zw = vec2(0.0);\n }\n xTexelC${y}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) {\n xTexelC${y+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${y+1}.zw = vec2(0.0);\n }\n xTexelC${y+1}Ready = 1;\n }\n\n xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);\n `,y+1= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy);\n `)):(p+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {\n xTexelC${y} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${y}.zw = vec2(0.0);\n }\n xTexelC${y}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {\n xTexelC${y+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${y+1}.zw = vec2(0.);\n }\n xTexelC${y+1}Ready = 1;\n }\n\n xC${y} = vec4(\n xTexelC${y}.xy, xTexelC${y+1}.xy);\n `,y+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);const h=Nn(r.shape,i.shape,a,c,o,u,!0);let d;return d=E().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels==1?new WT(h):new UT(h),e.runWebGLProgram(d,[r,i],"float32",[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]])}};class SH{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape,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 * ${t.outChannels/t.inChannels} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${t.batchSize}; b++) {\n for (int yR = 0; yR < ${t.outHeight}; yR++) {\n int xR = wR + yR * ${t.strideHeight} - ${t.padInfo.top};\n\n if (xR < 0 || xR >= ${t.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${t.outWidth}; yC++) {\n int xC = wC + yC * ${t.strideWidth} - ${t.padInfo.left};\n\n if (xC < 0 || xC >= ${t.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class CH{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterHeight,s=t.filterWidth,l=t.outChannels/t.inChannels;this.userCode=`\n const ivec2 pads = ivec2(${e-1-t.padInfo.top}, ${s-1-t.padInfo.left});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < ${e}; wR++) {\n float dyR = float(dyRCorner + wR) / ${t.strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${e} - 1 - wR;\n\n for (int wC = 0; wC < ${s}; wC++) {\n float dyC = float(dyCCorner + wC) / ${t.strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${s} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${l}; dm++) {\n int d2 = d1 * ${l} + 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 EH={kernelName:md,backendName:"webgl",kernelFunc:function IH(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,dy:i}=t,{strides:a,dilations:o,pad:l,dimRoundingMode:u,filterShape:c}=s,h=Nn(r.shape,c,a,o,l,u,!0),d=new SH(h);return e.runWebGLProgram(d,[r,i],"float32")}},NH={kernelName:gd,backendName:"webgl",kernelFunc:function kH(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,filter:i}=t,{strides:a,dilations:o,pad:l,dimRoundingMode:u,inputShape:c}=s,h=Nn(c,i.shape,a,o,l,u,!0),d=new CH(h);return e.runWebGLProgram(d,[r,i],"float32")}};class AH{constructor(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "}}const $H={kernelName:"Diag",backendName:"webgl",kernelFunc:function RH(n){const{inputs:t,backend:e}=n,{x:s}=t,r=[...s.shape,...s.shape],i=K(s.shape),a=Ne({inputs:{x:s},backend:e,attrs:{shape:[i]}}),o=new AH(i),l=e.runWebGLProgram(o,[a],a.dtype),u=Ne({inputs:{x:l},backend:e,attrs:{shape:r}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(l),u}};class DH{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;const{inHeight:e,inWidth:s,padInfo:r,strideHeight:i,strideWidth:a,filterHeight:o,filterWidth:l,dilationHeight:u,dilationWidth:c}=t,{top:h,left:d}=r;this.userCode=`\n const ivec2 strides = ivec2(${i}, ${a});\n const ivec2 pads = ivec2(${h}, ${d});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${o}; h++) {\n int hIn = hBeg + h * ${u};\n\n if (hIn >= 0 && hIn < ${e}) {\n for (int w = 0; w < ${l}; w++) {\n int wIn = wBeg + w * ${c};\n\n if (wIn >= 0 && wIn < ${s}) {\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 PH={kernelName:ou,backendName:"webgl",kernelFunc:function OH(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,filter:i}=t,{strides:a,pad:o,dilations:l}=s,u=tl(r.shape,i.shape,a,o,"NHWC",l);let c;const h=new DH(u);c=e.runWebGLProgram(h,[r,i],"float32");const d=Ne({inputs:{x:c},backend:e,attrs:{shape:u.outShape}});return e.disposeIntermediateTensorInfo(c),d}},LH={kernelName:vd,backendName:"webgl",kernelFunc:function FH(n){const{inputs:t,backend:e,attrs:s}=n,{equation:r}=s,i=t,{allDims:a,summedDims:o,idDims:l}=Ef(r,i.length);Nf(a.length,l,i);const{path:u,steps:c}=Af(o,l),h=c.length;let d=null,p=a.length;const f=[];for(let g=0;g=0&&(d=kh({inputs:{x:d},backend:e,attrs:{axis:u[g]-(a.length-p),keepDims:!1}}),f.push(d)),p--)}for(const g of f)g!==d&&e.disposeIntermediateTensorInfo(g);return d}},MH=Nt({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"}),VH={kernelName:co,backendName:"webgl",kernelFunc:MH},UH={kernelName:wd,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e}=n,{dy:s,y:r}=t,i=E().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ba("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",s.shape,r.shape):new Yi("return (b >= 0.0) ? a : a * (b + 1.0);",s.shape,r.shape);return e.runWebGLProgram(i,[s,r],s.dtype)}},WH=Ln({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:kU}),GH={kernelName:lu,backendName:"webgl",kernelFunc:WH},jH=Nt({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 = ${bf};\n float a1 = ${vf};\n float a2 = ${wf};\n float a3 = ${_f};\n float a4 = ${Tf};\n float a5 = ${Sf};\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`}),XH={kernelName:ho,backendName:"webgl",kernelFunc:jH},GT=Nt({opSnippet:Ua+"\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:NU,dtype:"float32"}),qH={kernelName:po,backendName:"webgl",kernelFunc:GT};function cg(n){const{inputs:t,attrs:e,backend:s}=n,{dim:r}=e,{input:i}=t,a=i.shape.length,o=i.shape.slice();let l=r;return r<0&&(T(-(a+1)<=r,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+r+1),o.splice(l,0,1),Ne({inputs:{x:i},backend:s,attrs:{shape:o}})}const ZH={kernelName:uu,backendName:"webgl",kernelFunc:cg},HT="return exp(x) - 1.0;",YH=Nt({opSnippet:HT,packedOpSnippet:HT,cpuKernelImpl:AU}),QH={kernelName:fo,backendName:"webgl",kernelFunc:YH};class jT{constructor(t,e,s){this.variableNames=["real","imag"];const r=e[1];this.outputShape=e;const i=s?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=s?`${r}.0`:"1.0";let o;if("real"===t)o="return real * expR - imag * expI;";else{if("imag"!==t)throw new Error(`FFT component must be either "real" or "imag", got ${t}.`);o="return real * expI + imag * expR;"}this.userCode=`\n const float exponentMultiplier = ${i};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${o}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${r});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${r}; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / ${a};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `}}function XT(n,t,e){const s=e.texData.get(n.dataId),r=K(n.shape),i=n.shape[n.shape.length-1],o=Ne({inputs:{x:n},backend:e,attrs:{shape:[r/i,i]}}),l=o.shape,u=new jT("real",l,t),c=new jT("imag",l,t),h=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:l},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:l}],d=e.runWebGLProgram(u,h,"float32"),p=e.runWebGLProgram(c,h,"float32"),f=di({inputs:{real:d,imag:p},backend:e});e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(p);const g=Ne({inputs:{x:f},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(f),g}const ej={kernelName:"FFT",backendName:"webgl",kernelFunc:function JH(n){const{inputs:t,backend:e}=n,{input:s}=t;return XT(s,!1,e)}};class tj{constructor(t,e){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=t,this.userCode="\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}}function Vl(n){const{backend:t,attrs:e}=n,{shape:s,value:r}=e;let{dtype:i}=e;if(i=i||vr(r),"string"===i){const a=$t(i,K(s));return a.fill(r),t.makeTensorInfo(s,i,a)}{const a=new tj(s,r);return t.runWebGLProgram(a,[],i,[[r]])}}const nj={kernelName:Td,backendName:"webgl",kernelFunc:Vl};class sj{constructor(t){this.variableNames=["Image"],this.outputShape=[];const e=t[2];this.outputShape=t,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${e} - x - 1;\n float outputValue;\n if(coordX >= 0 && coordX < ${e}) {\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 rj={kernelName:Sd,backendName:"webgl",kernelFunc:({inputs:n,backend:t})=>{const{image:e}=n,s=t,r=new sj(e.shape);return s.runWebGLProgram(r,[e],e.dtype)}},KT="return floor(x);",ij=Nt({opSnippet:KT,packedOpSnippet:KT,cpuKernelImpl:RU}),aj={kernelName:mo,backendName:"webgl",kernelFunc:ij},oj=Ln({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"}),lj={kernelName:go,backendName:"webgl",kernelFunc:oj};class uj{constructor(t){this.variableNames=["A"];const e=Qn(),[s,r]=t;this.outputShape=t,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${s}.0);\n\n vec4 values = ${e.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `}}class cj{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const e=Qn(),[s,r]=t;this.outputShape=t,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}.0, ${s}.0);\n vec4 values = ${e.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${e.output} = result;\n }\n `}}const hj={kernelName:"FromPixels",backendName:"webgl",kernelFunc:function dj(n){const{inputs:t,backend:e,attrs:s}=n;let{pixels:r}=t;const{numChannels:i}=s,a=typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,[l,u]=a?[r.videoWidth,r.videoHeight]:[r.width,r.height],c=[u,l],h=[u,l,i];if(o||a){const g=E().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(null==Ga||g!==hg)&&(hg=g,Ga=document.createElement("canvas").getContext("2d",{willReadFrequently:hg})),Ga.canvas.width=l,Ga.canvas.height=u,Ga.drawImage(r,0,0,l,u),r=Ga.canvas}const d=e.makeTensorInfo(c,"int32");e.texData.get(d.dataId).usage=Fs.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(d.dataId),r);const p=E().getBool("WEBGL_PACK")?new cj(h):new uj(h),f=e.runWebGLProgram(p,[d],"int32");return e.disposeData(d.dataId),f}};let Ga,hg=E().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const fj={kernelName:qu,backendName:"webgl",kernelFunc:function pj(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,filter:i,bias:a,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:d,activation:p,leakyreluAlpha:f}=s,g=Sr(c),m=Nn(r.shape,i.shape,l,h,u,d,!1,g);let x;const y=[],b=null!=a,v=null!=o,w="leakyrelu"===p,S=()=>{const k=[r,i],D=(P,B)=>{if("NCHW"===B&&1===P.shape.length&&1!==P.shape[0]){const Y=Ne({inputs:{x:P},backend:e,attrs:{shape:[P.shape[0],1,1]}});return y.push(Y),Y}return P};if(b&&k.push(D(a,c)),v&&k.push(D(o,c)),w){const P=e.makeTensorInfo([],"float32",Br(f,"float32"));k.push(P),y.push(P)}return k};if(1!==m.filterHeight||1!==m.filterWidth||1!==m.dilationHeight||1!==m.dilationWidth||1!==m.strideHeight||1!==m.strideWidth||"SAME"!==m.padInfo.type&&"VALID"!==m.padInfo.type)if(m.strideWidth<=2&&"channelsLast"===g&&E().getBool("WEBGL_EXP_CONV")){const k=p?Pl(p,!0):null,D=new PT(m,b,k,v,w),P=[[m.padInfo.top,m.padInfo.left],[m.strideHeight,m.strideWidth],[m.dilationHeight,m.dilationWidth],[m.inHeight,m.inWidth]],B=S();x=e.runWebGLProgram(D,B,"float32",P)}else if(E().getBool("WEBGL_CONV_IM2COL"))x=LT({x:r,filter:i,convInfo:m,backend:e,bias:a,activation:p,preluActivationWeights:o,leakyreluAlpha:f});else{const k=p?Pl(p,!1):null,D=new OT(m,b,k,v,w),P=S();x=e.runWebGLProgram(D,P,"float32")}else x=FT({x:r,filter:i,convInfo:m,backend:e,bias:a,activation:p,preluActivationWeights:o,leakyreluAlpha:f});const I=Ne({inputs:{x},backend:e,attrs:{shape:m.outShape}});return y.push(x),y.forEach(k=>e.disposeIntermediateTensorInfo(k)),I}},gj={kernelName:Zu,backendName:"webgl",kernelFunc:function mj(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,filter:i,bias:a,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:h,activation:d,leakyreluAlpha:p}=s,f=[];let g=c;null==g&&(g=[1,1]),T(Pn(l,g),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${g}'`);const m=Nn(r.shape,i.shape,l,g,u,h,!0),x=E().getBool("WEBGL_PACK_DEPTHWISECONV")&&m.strideWidth<=2&&m.outChannels/m.inChannels==1,y=d?Pl(d,x):null,b=[r,i],v=null!=a,w=null!=o,S="leakyrelu"===d;if(v&&b.push(a),w&&b.push(o),S){const P=e.makeTensorInfo([],"float32",Br(p,"float32"));b.push(P),f.push(P)}let I;I=x?new WT(m,v,y,w,S):new UT(m,v,y,w,S);const D=e.runWebGLProgram(I,b,"float32",[[m.padInfo.top,m.padInfo.left],[m.strideHeight,m.strideWidth],[m.dilationHeight,m.dilationWidth],[m.inHeight,m.inWidth]]);return f.forEach(P=>e.disposeIntermediateTensorInfo(P)),D}};class xj{constructor(t,e,s,r){this.sliceDim=t,this.strides=e,this.paramsShape=r,this.variableNames=["x","indices"],this.outputShape=s;const i=Ut(s.length);let a="\n int index;";for(let o=0;o= ${this.paramsShape[o]};\n flattenIndex += index * ${this.strides[o]};`;this.userCode=`\n void main() {\n ${i} coords = getOutputCoords();\n int flattenIndex = 0;\n bool out_of_bounds = false;\n\n ${a}\n\n setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\n }\n `}}const bj={kernelName:Mg,backendName:"webgl",kernelFunc:function yj(n){const{inputs:t,backend:e}=n,{params:s,indices:r}=t,i=r.shape,a=i[i.length-1],o=K(s.shape),[l,u,c,h]=yf(s,r),d=Ne({inputs:{x:r},backend:e,attrs:{shape:[u,a]}}),p=Ne({inputs:{x:s},backend:e,attrs:{shape:[K(s.shape)/c,c]}});if(e.shouldExecuteOnCPU([s,r])||"string"===s.dtype){const x=e.readSync(r.dataId),y=e.bufferSync(s),b=$U(x,y,s.dtype,u,a,c,h,s.shape,o);return e.makeTensorInfo(l,s.dtype,b.values)}const f=new xj(a,h,[u,c],s.shape),g=e.runWebGLProgram(f,[p,d],p.dtype),m=Ne({inputs:{x:g},backend:e,attrs:{shape:l}});return e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(g),m}};class vj{constructor(t,e){this.variableNames=["A","indices"],this.outputShape=e,this.rank=e.length;const s=Ut(this.rank),r=function wj(n){const e=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r= 0) && (index < ${t[2]}) ? 1.0 : 0.0;\n setOutput(inBounds * getA(${r}));\n }\n `}}function qT(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,indices:i}=t,{axis:a,batchDims:o}=s,l=pt(a,r.shape)[0];if(E().get("DEBUG")){const y=e.readSync(i.dataId),b=r.shape[l];for(let v=0;v=0,()=>`GatherV2: the index value ${w} is not in [0, ${b-1}]`)}}const u=Of(r,i,l,o),c=K(i.shape),h=[],d=Ne({inputs:{x:r},backend:e,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),p=Ne({inputs:{x:i},backend:e,attrs:{shape:[u.batchSize,c/u.batchSize]}});h.push(d),h.push(p);const f=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(e.shouldExecuteOnCPU([r,i])||"string"===r.dtype){const y=e.bufferSync(p),b=e.bufferSync(d),v=DU(b,y,f);return h.forEach(w=>e.disposeIntermediateTensorInfo(w)),e.makeTensorInfo(u.outputShape,v.dtype,v.values)}const g=new vj(d.shape,f),m=e.runWebGLProgram(g,[d,p],d.dtype);h.push(m);const x=Ne({inputs:{x:m},backend:e,attrs:{shape:u.outputShape}});return h.forEach(y=>e.disposeIntermediateTensorInfo(y)),x}const _j={kernelName:hu,backendName:"webgl",kernelFunc:qT},Tj=Ln({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:OU,dtype:"bool"}),Sj={kernelName:du,backendName:"webgl",kernelFunc:Tj},Cj=Ln({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:PU}),Ij={kernelName:xo,backendName:"webgl",kernelFunc:Cj},kj={kernelName:Cd,backendName:"webgl",kernelFunc:function Ej(n){const{inputs:t,backend:e}=n,{input:s}=t;return XT(s,!0,e)}},Nj=Nt({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),Aj={kernelName:bo,backendName:"webgl",kernelFunc:Nj},Rj=Nt({opSnippet:"return float(isinf(x));",dtype:"bool"}),$j={kernelName:vo,backendName:"webgl",kernelFunc:Rj},Dj=Nt({opSnippet:"return float(isnan(x));",dtype:"bool"}),Oj={kernelName:wo,backendName:"webgl",kernelFunc:Dj},Pj=Ln({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:FU,dtype:"bool"}),Fj={kernelName:fu,backendName:"webgl",kernelFunc:Pj},Lj=Ln({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:LU,dtype:"bool"}),Mj={kernelName:mu,backendName:"webgl",kernelFunc:Lj},zj={kernelName:Vg,backendName:"webgl",kernelFunc:function Vj(n){const{backend:t,attrs:e}=n,{start:s,stop:r,num:i}=e,a=MU(s,r,i);return t.makeTensorInfo([a.length],"float32",a)}},Uj=Nt({opSnippet:Ua+"\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:VU}),Wj={kernelName:_o,backendName:"webgl",kernelFunc:Uj},Hj=Nt({opSnippet:Ua+"\n return log(1.0 + x);\n"}),jj={kernelName:To,backendName:"webgl",kernelFunc:Hj},Xj=Ln({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"}),Kj={kernelName:gu,backendName:"webgl",kernelFunc:Xj},qj=Nt({opSnippet:"return float(!(x >= 1.0));"}),Zj={kernelName:xu,backendName:"webgl",kernelFunc:qj},Yj=Ln({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"}),Qj={kernelName:yu,backendName:"webgl",kernelFunc:Yj};class Jj{constructor(t,e,s,r,i){this.variableNames=["x"],this.outputShape=[];const a=e,o=t[3]-1;let l;this.outputShape=t;const u=`float(${s}) + float(${r}) * sum`;l=.5===i?`inversesqrt(${u})`:1===i?`1.0/(${u})`:`exp(log(${u}) * float(-${i}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -${a}; j <= ${a}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${o}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${l};\n setOutput(val);\n }\n `}}class e5{constructor(t,e,s,r,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const a=e,o=t[3]-1;let l;this.outputShape=t;const u=`float(${s}) + float(${r}) * sum`;l=.5===i?`inversesqrt(${u})`:1===i?`1.0/(${u})`:`exp(log(${u}) * float(-${i}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < ${this.outputShape[3]};\n bool hasNextRow = c < ${this.outputShape[2]};\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - ${a};\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - ${a}; j <= ${a}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * ${l};\n setOutput(result);\n }\n `}}const t5={kernelName:bu,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{depthRadius:i,bias:a,alpha:o,beta:l}=s,u=E().getBool("WEBGL_PACK_NORMALIZATION")?new e5(r.shape,i,a,o,l):new Jj(r.shape,i,a,o,l);return e.runWebGLProgram(u,[r],r.dtype)}};class n5{constructor(t,e,s,r,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=s,this.alpha=r,this.beta=i,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < ${this.depth}; ++d) {\n int depthBegin = int(max(0.0, float(d - ${e})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${e} + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = ${this.depth};\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float(${r}) * norm + float(${s});\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(${i})\n * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${i});\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 s5={kernelName:Ed,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:r,y:i,dy:a}=t,{depthRadius:o,bias:l,alpha:u,beta:c}=s,h=new n5(r.shape,o,l,u,c);return e.runWebGLProgram(h,[r,i,a],r.dtype)}};function ZT(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{reductionIndices:i,keepDims:a}=s,o=r.shape.length,l=pt(i,r.shape);let u=l;const c=rn(u,o),h=null!=c,d=e.shouldExecuteOnCPU([r]);let p=r;if(h){if(d){const b=e.texData.get(p.dataId).values,v=new Array(o);for(let I=0;I`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '1'`);const c=ks(r.shape,i,a,1,o,l);if(1===c.filterWidth&&1===c.filterHeight&&rt(c.inShape,c.outShape))return hs({inputs:{x:r},backend:e});const h=new Fl(c,"max",!1);return e.runWebGLProgram(h,[r],r.dtype)}},p5={kernelName:_u,backendName:"webgl",kernelFunc:function d5(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{filterSize:i,strides:a,pad:o,dataFormat:l,dimRoundingMode:u}=s,h=Tr(r.shape,i,a,[1,1,1],o,u,l),d=new og(h,"max",!1);return e.runWebGLProgram(d,[r],r.dtype)}};class f5{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;const i=t.effectiveFilterHeight,a=t.effectiveFilterWidth;this.userCode=`\n const ivec2 pads = ivec2(${i-1-t.padInfo.top}, ${a-1-t.padInfo.left});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${i};\n wR += ${t.dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${t.strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${a}; wC++) {\n float dyC = float(dyCCorner + wC) / ${t.strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = ${i*a-1} - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * ${a} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `}}class m5{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;const l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth;this.userCode=`\n const ivec3 pads = ivec3(${l-1-t.padInfo.front}, ${u-1-t.padInfo.top}, ${c-1-t.padInfo.left});\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 < ${l};\n wD += ${t.dilationDepth}) {\n float dyD = float(dyDCorner + wD) / ${t.strideDepth}.0;\n\n if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${u};\n wR += ${t.dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${t.strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${c};\n wC += ${t.dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${t.strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${l*u*c-1} -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * ${u} * ${c} +\n wR * ${c} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const x5={kernelName:Nd,backendName:"webgl",kernelFunc:function g5(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,input:i}=t,a=i,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,d=Tr(a.shape,o,l,[1,1,1],u,c),p=new og(d,"max",!0),f=e.runWebGLProgram(p,[a],a.dtype),g=new m5(d),m=e.runWebGLProgram(g,[r,f],a.dtype);return e.disposeIntermediateTensorInfo(f),m}},b5={kernelName:kd,backendName:"webgl",kernelFunc:function y5(n){const{inputs:t,backend:e,attrs:s}=n,{dy:r,input:i,output:a}=t,o=i;Dl([i,a],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,d=ks(o.shape,l,u,1,c,h),f=new Fl(d,"max",!0),g=e.runWebGLProgram(f,[o],o.dtype),m=new f5(d),x=e.runWebGLProgram(m,[r,g],o.dtype);return e.disposeIntermediateTensorInfo(g),x}},w5={kernelName:zg,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{filterSize:r,strides:i,pad:a,includeBatchInIndex:o}=t,l=e;T(4===s.shape.length,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const u=[1,1];T(Pn(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);const c=ks(s.shape,r,i,u,a),[h,d]=function v5(n,t,e,s){let r=new Fl(e,"max",!1);const i=s.runWebGLProgram(r,[n],"float32");return r=new Fl(e,"max",!0,!0,t),[i,s.runWebGLProgram(r,[n],"float32")]}(s,o,c,l);return[h,d]}},T5={kernelName:Tu,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{keepDims:r,axis:i}=t,a=e,o=s.shape.length,l=pt(i,s.shape);let u=l;const c=rn(u,o),h=null!=c,d=a.shouldExecuteOnCPU([s]),p=[];let f=s;if(h){if(d){const v=a.texData.get(f.dataId).values,w=new Array(o);for(let k=0;kc[0]+t[h]+c[1]);const r=t.length,i=Ut(r),a=e.map(c=>c[0]).join(","),o=e.map((c,h)=>c[0]+t[h]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),u="reflect"===s?0:1;this.userCode=1!==r?`\n ${i} start = ${i}(${a});\n ${i} end = ${i}(${o});\n\n void main() {\n ${i} 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 ${i} coords = outC - start;\n setOutput(getX(${l}));\n }\n `:`\n int start = ${a};\n int end = ${o};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${u};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${u};\n }\n setOutput(getX(outC - start));\n }\n `}}class R5{constructor(t,e,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((f,g)=>f[0]+t[g]+f[1]);const r=t.length,i=Ut(r),a=e.map(f=>f[0]).join(","),o=e.map((f,g)=>f[0]+t[g]).join(","),l=Jn("rc",r),u=Jn("source",r),c=`${l[r-1]} < ${this.outputShape[r-1]}`,h=1===r?"source":`vec2(${u.slice(-2).join()})`,d="reflect"===s?0:1;let p="";if(1===r){const f=`\n ${i} 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 ${i} rc = outputLoc;\n ${f}\n result[0] = getChannel(getX(${u.join()}), ${h});\n ${l[r-1]} += 1;\n if(${c}) {\n ${f}\n result[1] = getChannel(getX(${u.join()}), ${h});\n }\n `}else{const f=`\n ${i} source = rc;\n ${i} lt = ${i}(lessThan(source, start));\n ${i} gte = ${i}(greaterThanEqual(source, end));\n ${i} 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 ${i} rc = outputLoc;\n ${f}\n result[0] = getChannel(getX(${u.join()}), ${h});\n ${l[r-1]} += 1;\n if(${c}) {\n ${f}\n result[1] = getChannel(getX(${u.join()}), ${h});\n }\n rc = outputLoc;\n ${l[r-2]} += 1;\n if(${l[r-2]} < ${this.outputShape[r-2]}) {\n ${f}\n result[2] = getChannel(getX(${u.join()}), ${h});\n ${l[r-1]} += 1;\n if(${c}) {\n ${f}\n result[3] = getChannel(getX(${u.join()}), ${h});\n }\n }\n `}this.userCode=`\n const ${i} start = ${i}(${a});\n const ${i} end = ${i}(${o});\n\n void main() {\n ${i} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${p}\n setOutput(result);\n }\n `}}const $5={kernelName:Cu,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s}=n,{paddings:r,mode:i}=e,a=E().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new R5(s.shape,r,i):new A5(s.shape,r,i);return t.runWebGLProgram(a,[s],s.dtype)}},P5=Ln({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 "+Qi+"\n return result;\n"}),F5={kernelName:Io,backendName:"webgl",kernelFunc:P5};class L5{constructor(t,e,s){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[t,s],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 < ${e-1}; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(${e-1}));\n }\n `}}const YT=Ln({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}),M5={kernelName:uo,backendName:"webgl",kernelFunc:YT},QT="return a - b;",JT=Ln({opSnippet:QT,packedOpSnippet:QT,supportsComplex:!0,cpuKernelImpl:uW}),V5={kernelName:Uo,backendName:"webgl",kernelFunc:JT};function e1(n){const{inputs:t,backend:e,attrs:s}=n,{logits:r}=t,{dim:i}=s,a=pt([i],r.shape),o=ZT({inputs:{x:r},backend:e,attrs:{reductionIndices:a,keepDims:!1}}),l=hn(o.shape,a),u=Ne({inputs:{x:o},backend:e,attrs:{shape:l}}),c=JT({inputs:{a:r,b:u},backend:e}),h=GT({inputs:{x:c},backend:e}),d=kh({inputs:{x:h},backend:e,attrs:{axis:a,keepDims:!1}}),p=Ne({inputs:{x:d},backend:e,attrs:{shape:l}}),f=YT({inputs:{a:h,b:p},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(c),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(p),f}const z5={kernelName:Wu,backendName:"webgl",kernelFunc:e1},U5={kernelName:Bg,backendName:"webgl",kernelFunc:function B5(n){const{inputs:t,backend:e,attrs:s}=n,{logits:r}=t,{numSamples:i,seed:a,normalized:o}=s,l=o?r:e1({inputs:{logits:r},backend:e,attrs:{dim:r.shape.length-1}}),h=new L5(l.shape[0],l.shape[1],i),p=e.runWebGLProgram(h,[l],"int32",[[a]]);return o||e.disposeIntermediateTensorInfo(l),p}},W5=Ts+"\n return -x;\n",j5={kernelName:Iu,backendName:"webgl",kernelFunc:function H5(n){const{inputs:t,backend:e}=n,{x:s}=t;if(e.shouldExecuteOnCPU([s])){const i=e.texData.get(s.dataId),[a,o]=GU(i.values,s.shape,s.dtype);return e.makeTensorInfo(o,s.dtype,a)}let r;return r=E().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new hi(s.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 xr(s.shape,W5),e.runWebGLProgram(r,[s],s.dtype)}},X5=af,q5={kernelName:Ad,backendName:"webgl",kernelFunc:function K5(n){fs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:r,scores:i}=t,{maxOutputSize:a,iouThreshold:o,scoreThreshold:l}=s,u=e.readSync(r.dataId),c=e.readSync(i.dataId),{selectedIndices:h}=X5(u,c,a,o,l);return e.makeTensorInfo([h.length],"int32",new Int32Array(h))}},Z5=of,Q5={kernelName:Rd,backendName:"webgl",kernelFunc:function Y5(n){fs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:r,scores:i}=t,{maxOutputSize:a,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=s,c=e.readSync(r.dataId),h=e.readSync(i.dataId),{selectedIndices:d,validOutputs:p}=Z5(c,h,a,o,l,u);return[e.makeTensorInfo([d.length],"int32",new Int32Array(d)),e.makeTensorInfo([],"int32",new Int32Array([p]))]}},J5=lf,tX={kernelName:$d,backendName:"webgl",kernelFunc:function eX(n){fs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:r,scores:i}=t,{maxOutputSize:a,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=s,c=e.readSync(r.dataId),h=e.readSync(i.dataId),d=a,p=o,f=l,g=u,{selectedIndices:m,selectedScores:x}=J5(c,h,d,p,f,g);return[e.makeTensorInfo([m.length],"int32",new Int32Array(m)),e.makeTensorInfo([x.length],"float32",new Float32Array(x))]}};class nX{constructor(t,e,s,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${r}), float(${s}),\n float(index == coords.y)));\n }\n `}}const sX={kernelName:Nu,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{indices:r}=t,{dtype:i,depth:a,onValue:o,offValue:l}=s,u=K(r.shape),c=new nX(u,a,o,l),h=Ne({inputs:{x:r},backend:e,attrs:{shape:[u]}}),d=e.runWebGLProgram(c,[h],i);e.disposeIntermediateTensorInfo(h);const f=Ne({inputs:{x:d},backend:e,attrs:{shape:[...r.shape,a]}});return e.disposeIntermediateTensorInfo(d),f}};function Ph(n){const{inputs:t,backend:e}=n,{x:s}=t;if("complex64"===s.dtype){const r=Ll({inputs:{input:s},backend:e}),i=Ph({inputs:{x:r},backend:e}),a=$h({inputs:{input:s},backend:e}),o=Ph({inputs:{x:a},backend:e}),l=di({inputs:{real:i,imag:o},backend:e});return e.disposeIntermediateTensorInfo(r),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(o),l}return Vl({attrs:{shape:s.shape,dtype:s.dtype,value:"string"===s.dtype?"":0},backend:e})}const rX={kernelName:Xu,backendName:"webgl",kernelFunc:Ph},iX={kernelName:ku,backendName:"webgl",kernelFunc:function t1(n){const{inputs:t,backend:e}=n,{x:s}=t;if("string"===s.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===s.dtype){const r=Ll({inputs:{input:s},backend:e}),i=t1({inputs:{x:r},backend:e}),a=$h({inputs:{input:s},backend:e}),o=Ph({inputs:{x:a},backend:e}),l=di({inputs:{real:i,imag:o},backend:e});return e.disposeIntermediateTensorInfo(r),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(o),l}return Vl({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:e})}},oX={kernelName:Au,backendName:"webgl",kernelFunc:function aX(n){const{inputs:t,backend:e,attrs:s}=n,{axis:r}=s;if(1===t.length)return cg({inputs:{input:t[0]},backend:e,attrs:{dim:r}});const i=t[0].shape,a=t[0].dtype;t.forEach(c=>{Me(i,c.shape,"All tensors passed to stack must have matching shapes"),T(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=[],u=DT({inputs:t.map(c=>{const h=cg({inputs:{input:c},backend:e,attrs:{dim:r}});return o.push(h),h}),backend:e,attrs:{axis:r}});return o.forEach(c=>e.disposeIntermediateTensorInfo(c)),u}};class lX{constructor(t,e,s){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((u,c)=>u[0]+t[c]+u[1]);const r=t.length,i=Ut(r),a=e.map(u=>u[0]).join(","),o=e.map((u,c)=>u[0]+t[c]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n ${i} start = ${i}(${a});\n ${i} end = ${i}(${o});\n\n void main() {\n ${i} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${i} coords = outC - start;\n setOutput(getX(${l}));\n }\n }\n `:`\n int start = ${a};\n int end = ${o};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `}}class uX{constructor(t,e,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((g,m)=>g[0]+t[m]+g[1]);const r=t.length,i=Ut(r),a=e.map(g=>g[0]).join(","),o=e.map((g,m)=>g[0]+t[m]).join(","),l=Jn("rc",r),u=Jn("source",r),c=`${l[r-1]} < ${this.outputShape[r-1]}`,h=1===r?"source":`vec2(${u.slice(-2).join()})`,d=[`${i} rc = outputLoc;`,`${l[r-1]} += 1;\n if(${c}) {\n `,1===r?"":`}\n rc = outputLoc;\n ${l[r-2]} += 1;\n if(${l[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":` ${l[r-1]} += 1;\n if(${c}) {`],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let f="";for(let g=0,m=1===r?2:4;g{const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{paddings:i,constantValue:a}=s;if(0===K(r.shape))return Vl({backend:e,attrs:{shape:i.map((c,h)=>c[0]+r.shape[h]+c[1]),value:a,dtype:r.dtype}});const o=E().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new uX(r.shape,i,a):new lX(r.shape,i,a);return e.runWebGLProgram(o,[r],r.dtype,[[a]])},cX={kernelName:Ru,backendName:"webgl",kernelFunc:n1},pX=Ln({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 "+Qi+"\n return result;\n"}),fX={kernelName:ko,backendName:"webgl",kernelFunc:pX},gX={kernelName:Du,backendName:"webgl",kernelFunc:function mX(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{axis:i,keepDims:a}=s,o=r.shape.length,l=[],u=pt(i,r.shape);let c=u;const h=rn(c,o);let p,d=r;if(null!=h&&(d=es({inputs:{x:r},backend:e,attrs:{perm:h}}),c=dn(c.length,o),l.push(d)),Fn("prod",c,o),e.shouldExecuteOnCPU([d])){const f=e.texData.get(d.dataId).values,{outVals:g,outShape:m,outDtype:x}=jU(d.shape,d.dtype,f,c);p=e.makeTensorInfo(m,x,g)}else{const[f,g]=An(d.shape,c),m=K(g),x=Ne({inputs:{x:d},backend:e,attrs:{shape:[-1,m]}}),b=Ji(x,np(r.dtype),"prod",e);p=Ne({inputs:{x:b},backend:e,attrs:{shape:f}}),l.push(x),l.push(b)}if(a){l.push(p);const f=hn(p.shape,u);p=Ne({inputs:{x:p},backend:e,attrs:{shape:f}})}return l.forEach(f=>e.disposeIntermediateTensorInfo(f)),p}},yX={kernelName:Ug,backendName:"webgl",kernelFunc:function xX(n){const{inputs:t,backend:e,attrs:s}=n,{paramsNestedSplits:r,paramsDenseValues:i,indices:a}=t,{outputRaggedRank:o}=s,l=r.map(x=>e.readSync(x.dataId)),u=r.map(x=>x.shape),c=e.readSync(i.dataId),h=e.readSync(a.dataId),[d,p,f]=XU(l,u,c,i.shape,i.dtype,h,a.shape,o),g=d.map(x=>e.makeTensorInfo([x.length],"int32",x)),m=e.makeTensorInfo(f,i.dtype,p);return g.concat([m])}},vX={kernelName:Wg,backendName:"webgl",kernelFunc:function bX(n){const{inputs:t,backend:e}=n,{starts:s,limits:r,deltas:i}=t,a=e.readSync(s.dataId),o=e.readSync(r.dataId),l=e.readSync(i.dataId),[u,c]=KU(a,s.shape,s.dtype,o,r.shape,l,i.shape);return[e.makeTensorInfo([u.length],"int32",u),e.makeTensorInfo([c.length],s.dtype,c)]}},_X={kernelName:Gg,backendName:"webgl",kernelFunc:function wX(n){const{inputs:t,backend:e,attrs:s}=n,{shape:r,values:i,defaultValue:a,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=s,u=e.readSync(r.dataId),c=e.readSync(i.dataId),h=e.readSync(a.dataId),d=o.map(m=>e.readSync(m.dataId)),p=o.map(m=>m.shape),[f,g]=qU(u,r.shape,c,i.shape,i.dtype,h,a.shape,d,p,l);return e.makeTensorInfo(f,i.dtype,g)}},s1=n=>{const{backend:t,attrs:e}=n,{start:s,stop:r,step:i,dtype:a}=e,o=ZU(s,r,i,a);return t.makeTensorInfo([o.length],a,o)},TX={kernelName:Dd,backendName:"webgl",kernelFunc:s1},SX=Nt({opSnippet:"return 1.0 / x;"}),CX={kernelName:No,backendName:"webgl",kernelFunc:SX},EX=Nt({opSnippet:Ts+"\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"}),kX={kernelName:Ao,backendName:"webgl",kernelFunc:EX},AX=Nt({opSnippet:Ts+"\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"}),RX={kernelName:Ro,backendName:"webgl",kernelFunc:AX};class $X{constructor(t,e,s,r,i){this.variableNames=["A"],this.outputShape=[];const[a,o,l,u]=t;this.outputShape=[a,e,s,u];const c=[r&&e>1?o-1:o,r&&s>1?l-1:l],h=[r&&e>1?e-1:e,r&&s>1?s-1:s];let d;d=i?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${c[0]/h[0]},\n ${c[1]/h[1]});\n const vec2 inputShapeRC = vec2(${o}.0, ${l}.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 DX{constructor(t,e,s,r,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,o,l,u]=t;this.outputShape=[a,e,s,u];const c=[r&&e>1?o-1:o,r&&s>1?l-1:l],h=[r&&e>1?e-1:e,r&&s>1?s-1:s];let d;d=i?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${c[0]/h[0]},\n ${c[1]/h[1]},\n ${c[1]/h[1]});\n const vec3 inputShapeRC = vec3(${o}.0, ${l}.0,\n ${l}.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 < ${s-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 PX={kernelName:Fu,backendName:"webgl",kernelFunc:function OX(n){const{inputs:t,backend:e,attrs:s}=n,{images:r}=t,{alignCorners:i,halfPixelCenters:a,size:o}=s,[l,u]=o,c=E().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new DX(r.shape,l,u,i,a):new $X(r.shape,l,u,i,a);return e.runWebGLProgram(c,[r],"float32")}};class FX{constructor(t,e,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;const[,r,i]=e,[,a,o]=t,l=[s&&a>1?r-1:r,s&&o>1?i-1:i],u=[s&&a>1?a-1:a,s&&o>1?o-1:o],c=l[0]/u[0],h=l[1]/u[1],d=1/c,p=1/h,f=2*Math.ceil(d)+2,g=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(${c});\n const float widthScale = float(${h});\n\n const float invHeightScale = float(${d});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${f});\n const int winWidth = int(${g});\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 >= ${a}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${o}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), ${i-1}.0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const MX={kernelName:Fd,backendName:"webgl",kernelFunc:function LX(n){const{inputs:t,backend:e,attrs:s}=n,{images:r,dy:i}=t,{alignCorners:a}=s,o=new FX(i.shape,r.shape,a);return e.runWebGLProgram(o,[i],i.dtype)}};class VX{constructor(t,e,s,r,i){this.variableNames=["A"],this.outputShape=[];const[a,o,l,u]=t;this.outputShape=[a,e,s,u];const c=[r&&e>1?o-1:o,r&&s>1?l-1:l],h=[r&&e>1?e-1:e,r&&s>1?s-1:s];let p;p=i?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${c[0]/h[0]},\n ${c[1]/h[1]});\n const vec2 inputShapeRC = vec2(${o}.0, ${l}.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 + ${r?"0.5":"0.0"})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `}}class zX{constructor(t,e,s,r,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,o,l,u]=t;this.outputShape=[a,e,s,u];const c=[r&&e>1?o-1:o,r&&s>1?l-1:l],h=[r&&e>1?e-1:e,r&&s>1?s-1:s];let p;p=i?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${c[0]/h[0]},\n ${c[1]/h[1]},\n ${c[1]/h[1]});\n const vec3 inputShapeRC = vec3(${o}.0, ${l}.0,\n ${l}.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 + ${r?"0.5":"0.0"})));\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 < ${s-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 UX={kernelName:Pu,backendName:"webgl",kernelFunc:function BX(n){const{inputs:t,backend:e,attrs:s}=n,{images:r}=t,{alignCorners:i,halfPixelCenters:a,size:o}=s,[l,u]=o,c=E().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new zX(r.shape,l,u,i,a):new VX(r.shape,l,u,i,a);return e.runWebGLProgram(c,[r],r.dtype)}};class WX{constructor(t,e,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;const[,r,i]=e,[,a,o]=t,l=[s&&a>1?r-1:r,s&&o>1?i-1:i],u=[s&&a>1?a-1:a,s&&o>1?o-1:o],c=l[0]/u[0],h=l[1]/u[1],d=1/c,p=1/h,f=2*Math.ceil(d)+2,g=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(${c});\n const float widthScale = float(${h});\n\n const float invHeightScale = float(${d});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${f});\n const int winWidth = int(${g});\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 >= ${a}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${o}) {\n continue;\n }\n\n float sourceFracRow =\n float(${l[0]}) *\n (float(dyR) / float(${u[0]}));\n\n float sourceFracCol =\n float(${l[1]}) *\n (float(dyC) / float(${u[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${r}) - 1),\n ${s} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${i}) - 1),\n ${s} ? 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 HX={kernelName:Pd,backendName:"webgl",kernelFunc:function GX(n){const{inputs:t,backend:e,attrs:s}=n,{images:r,dy:i}=t,{alignCorners:a}=s,o=new WX(i.shape,r.shape,a);return e.runWebGLProgram(o,[i],i.dtype)}};class jX{constructor(t,e){this.variableNames=["x"];const s=t.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);if(this.outputShape=t,1===s)return void(this.userCode=`\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${t[0]} - coord - 1));\n }\n `);const i=t.map((o,l)=>(o=>-1!==e.indexOf(o)&&1!==t[o]?`${t[o]} - coords[${o}] - 1`:`coords[${o}]`)(l)).join(","),a=Ut(s);this.userCode=`\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${i}));\n }\n `}}class XX{constructor(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const s=t.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);this.outputShape=t;const r=Jn("rc",s),i=`${r[s-1]} + 1 < ${this.outputShape[s-1]}`,a=`${r[s-2]} + 1 < ${this.outputShape[s-2]}`,o=Ut(s);function d(f){const g=t.map((y,b)=>function p(f,g){return-1!==e.indexOf(f)&&1!==t[f]?`${t[f]} - ${g[f]} - 1`:`${g[f]}`}(b,f));return`getChannel(getX(${g.join(",")}), vec2(${g.slice(-2).join(",")}))`}this.userCode=1===s?`\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${t[0]} - rc - 1),\n ${t[0]} - rc - 1);\n if(${i}){\n result.g = getChannel(getX(${t[0]} - (rc + 1) - 1),\n ${t[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `:`\n void main() {\n ${o} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${function l(f){return d(f)}(r.slice())};\n if(${i}){\n result.g = ${function u(f){return f[s-1]="("+f[s-1]+" + 1)",d(f)}(r.slice())};\n }\n if(${a}) {\n result.b = ${function c(f){return f[s-2]="("+f[s-2]+" + 1)",d(f)}(r.slice())};\n if(${i}) {\n result.a = ${function h(f){return f[s-1]="("+f[s-1]+" + 1)",f[s-2]="("+f[s-2]+" + 1)",d(f)}(r.slice())};\n }\n }\n setOutput(result);\n }\n `}}const qX={kernelName:Lu,backendName:"webgl",kernelFunc:function KX(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{dims:i}=s,a=r.shape.length,o=pt(i,r.shape);if(0===a)return hs({inputs:{x:r},backend:e});const l=E().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new XX(r.shape,o):new jX(r.shape,o);return e.runWebGLProgram(l,[r],r.dtype)}};class ZX{constructor(t,e){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const s=t[1],r=t[2];this.outputShape=t;let i="";i="number"==typeof e?`float outputValue = ${e.toFixed(2)};`:`\n vec3 fill = vec3(${e.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 ${i}\n if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${s}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const YX={kernelName:Zd,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{image:s}=n,{radians:r,fillValue:i,center:a}=t,o=e,l=new ZX(s.shape,i),[u,c]=mf(a,s.shape[1],s.shape[2]),h=[[u,c,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[s],s.dtype,h)}},QX=Nt({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"}),JX={kernelName:$o,backendName:"webgl",kernelFunc:QX},e6=Nt({opSnippet:"return inversesqrt(x);",cpuKernelImpl:YU}),t6={kernelName:Do,backendName:"webgl",kernelFunc:e6};class dg{constructor(t,e,s,r,i,a,o=!0,l=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const u=Ut(i.length),c=Ut(a.length);let h="";1===s?h="i":2===s&&(h="i, j");let p="";1===r?p="i":2===r&&(p="i, coords[1]");let g="";l&&(g="coords[0], coords[1]"),this.userCode=`\n ${u} strides = ${u}(${i});\n\n void main() {\n ${c} coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < ${t}; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < ${e}; j++) {\n int index = round(getIndices(${h}));\n flattenedIndex += index * ${e>1?"strides[j]":"strides"};\n }\n if (flattenedIndex == coords[0]) {\n sum += getUpdates(${p});\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(${g}), sum, float(found)));\n }\n `}}class n6{constructor(t,e,s,r,i,a,o=!0,l=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=a;const u=Ut(i.length),c=Ut(a.length);let h="";1===s?h="i":2===s&&(h="i, j");let p="";1===r?p="i":2===r&&(p="i, coords[1]");let g="";l&&(g="coords[0], coords[1]"),this.userCode=`\n ${u} strides = ${u}(${i});\n\n void main() {\n ${c} coords = getOutputCoords();\n vec4 sum = vec4(0.);\n vec4 found = vec4(0.);\n for (int i = 0; i < ${t}; i+=2) {\n ivec2 flattenedIndex = ivec2(0);\n for (int j = 0; j < ${e}; j+=2) {\n ivec4 index = round(getIndices(${h}));\n flattenedIndex += index.xz * ${e>1?"strides[j]":"strides"};\n if (j + 1 < ${e}) {\n flattenedIndex += index.yw * ${e>1?"strides[j + 1]":"strides"};\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 = getUpdates(${p});\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(getDefaultValue(${g}), sum, found));\n }\n `}}const r6={kernelName:Hg,backendName:"webgl",kernelFunc:function s6(n){const{inputs:t,backend:e,attrs:s}=n,{indices:r,updates:i}=t,{shape:a}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=Mi(0,r,a),d=[h/u,u];if(0===h)return e.makeTensorInfo(a,r.dtype);const p=Ne({inputs:{x:r},backend:e,attrs:{shape:[l,o]}}),f=Ne({inputs:{x:i},backend:e,attrs:{shape:[l,u]}}),g=e.makeTensorInfo([],"float32",new Float32Array([0]));let m;m=E().getBool("WEBGL_PACK")?new n6(l,o,p.shape.length,f.shape.length,c,d):new dg(l,o,p.shape.length,f.shape.length,c,d);const x=e.runWebGLProgram(m,[f,p,g],f.dtype),y=Ne({inputs:{x},backend:e,attrs:{shape:a}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(x),e.disposeIntermediateTensorInfo(g),y}};class i6{constructor(t,e,s,r){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[t,s];const a=`for (int i = 0; i < ${Math.ceil(Math.log2(e+1))}; ++i) { if (left >= right) break;`,o=2===E().getNumber("WEBGL_VERSION")?"while (left < right) {":a;this.userCode=`\n int findBound(int batch, float value) {\n int left = 0;\n int right = numInputs;\n int mid;\n ${o}\n mid = (left + right) / 2;\n if (getSortedSequence(batch, mid) ${"left"===r?"<":"<="} 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 o6={kernelName:Xg,backendName:"webgl",kernelFunc:function a6(n){const{inputs:t,backend:e,attrs:s}=n,{sortedSequence:r,values:i}=t,{side:a}=s,o=new i6(r.shape[0],r.shape[1],i.shape[1],a);return e.runWebGLProgram(o,[r,i],"int32",[[r.shape[1]]])}};class l6{constructor(t,e,s){let r,i;if(this.variableNames=["c","a","b"],this.outputShape=e,s>4)throw Error(`Where for rank ${s} is not yet supported`);if(1===s)i="resRC",r="resRC";else{const o=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],u=[];for(let c=0;c= 1.0) {\n setOutput(getA(${i}));\n } else {\n setOutput(getB(${i}));\n }\n }\n `}}const c6={kernelName:Mu,backendName:"webgl",kernelFunc:function u6(n){const{inputs:t,backend:e}=n,{condition:s,t:r,e:i}=t,a=new l6(s.shape.length,r.shape,r.shape.length);return e.runWebGLProgram(a,[s,r,i],ls(r.dtype,i.dtype))}},d6=Nt({opSnippet:`\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${Tc};\n float scale = ${Sc};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),p6={kernelName:Oo,backendName:"webgl",kernelFunc:d6},m6=Nt({opSnippet:Ua+"\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:JU}),g6={kernelName:Mo,backendName:"webgl",kernelFunc:m6},x6=Nt({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),y6={kernelName:Lo,backendName:"webgl",kernelFunc:x6},w6=Nt({opSnippet:Ua+"\n return sin(x);\n",packedOpSnippet:`\n vec4 result = sin(x);\n bvec4 isNaN = isnan(x);\n ${Qi}\n return result;\n`}),_6={kernelName:Po,backendName:"webgl",kernelFunc:w6},T6=Nt({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),S6={kernelName:Fo,backendName:"webgl",kernelFunc:T6},C6=Nt({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"}),I6={kernelName:Vo,backendName:"webgl",kernelFunc:C6},E6={kernelName:Bu,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{blockShape:i,paddings:a}=s;T(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const o=i.reduce((x,y)=>x*y),l=[[0,0]];l.push(...a);for(let x=1+i.length;xe.disposeIntermediateTensorInfo(x)),m}},N6={kernelName:Ld,backendName:"webgl",kernelFunc:function k6(n){const{inputs:t,backend:e}=n,{indices:s,values:r,denseShape:i,defaultValue:a}=t;if(1!==i.shape.length)throw new Error(`Dense shape must be a vector, saw:\n ${i.shape}`);if(2!==s.shape.length)throw new Error(`Indices must be a matrix, saw:\n ${s.shape}`);if(1!==r.shape.length)throw new Error(`Values must be a vector, saw:\n ${r.shape}`);if(0!==a.shape.length)throw new Error(`Default value must be a scalar, saw:\n ${a.shape}`);const o=e.readSync(s.dataId),l=e.readSync(r.dataId),u=e.readSync(i.dataId),c=e.readSync(a.dataId)[0],[h,d,p,f,g]=tW(o,s.shape,s.dtype,l,r.dtype,u,c);return[e.makeTensorInfo(d,s.dtype,h),e.makeTensorInfo([d[0]],r.dtype,p),e.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(m=>Number(m)))),e.makeTensorInfo([g.length],s.dtype,new Int32Array(g))]}},R6={kernelName:Md,backendName:"webgl",kernelFunc:function A6(n){const{inputs:t,backend:e}=n,{inputIndices:s,inputShape:r,newShape:i}=t;if(2!==s.shape.length)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(1!==r.shape.length)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(1!==i.shape.length)throw new Error(`Target shape should be a vector but received shape ${i.shape}`);const a=Array.from(e.readSync(r.dataId)),o=e.readSync(s.dataId),l=Array.from(e.readSync(i.dataId)),[u,c,h]=nW(o,s.shape,s.dtype,a,l);return[e.makeTensorInfo(c,s.dtype,u),e.makeTensorInfo([h.length],i.dtype,new Int32Array(h))]}},D6={kernelName:Vd,backendName:"webgl",kernelFunc:function $6(n){const{inputs:t,backend:e}=n,{data:s,indices:r,segmentIds:i}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n ${r.shape}`);if(1!==i.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${i.shape}`);const a=e.readSync(s.dataId),o=e.readSync(r.dataId),l=e.readSync(i.dataId),[u,c]=lT(a,s.shape,s.dtype,o,l,!0);return e.makeTensorInfo(c,s.dtype,u)}},P6={kernelName:zd,backendName:"webgl",kernelFunc:function O6(n){const{inputs:t,backend:e}=n,{data:s,indices:r,segmentIds:i}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n ${r.shape}`);if(1!==i.shape.length)throw new Error(`Segment ids should be a vector but received shape\n ${i.shape}`);const a=e.readSync(s.dataId),o=e.readSync(r.dataId),l=e.readSync(i.dataId),[u,c]=lT(a,s.shape,s.dtype,o,l);return e.makeTensorInfo(c,s.dtype,u)}},L6={kernelName:Kg,backendName:"webgl",kernelFunc:function F6(n){const{inputs:t,backend:e,attrs:s}=n,{sparseIndices:r,sparseValues:i,defaultValue:a}=t,{outputShape:o}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:h,outputSize:d}=Mi(0,r,o),p=!1;if("string"===i.dtype){const x=e.bufferSync(r),y=e.bufferSync(i),b=Wr(e.readSync(a.dataId)[0]),v=QU(x,y,o,d,c,u,l,h,b,p);return e.makeTensorInfo(o,v.dtype,v.values)}const f=new dg(u,l,r.shape.length,i.shape.length,h,[d,1],p),g=e.runWebGLProgram(f,[i,r,a],i.dtype),m=Ne({inputs:{x:g},backend:e,attrs:{shape:o}});return e.disposeIntermediateTensorInfo(g),m}},V6={kernelName:Uu,backendName:"webgl",kernelFunc:function M6(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{numOrSizeSplits:i,axis:a}=s,o=pt(a,r.shape)[0],l=$f(r,i,o),c=new Array(r.shape.length).fill(0),h=r.shape.slice();return l.map(d=>{const p=[...h];p[o]=d;const f=Wa({inputs:{x:r},backend:e,attrs:{begin:c,size:p}});return c[o]+=d,f})}},r1="return sqrt(x);",z6=Nt({opSnippet:r1,packedOpSnippet:r1,cpuKernelImpl:sW}),B6={kernelName:zo,backendName:"webgl",kernelFunc:z6},W6={kernelName:Bd,backendName:"webgl",kernelFunc:Nt({opSnippet:"return x * x;"})},i1="return (a - b) * (a - b);",G6=Ln({opSnippet:i1,packedOpSnippet:i1}),H6={kernelName:Bo,backendName:"webgl",kernelFunc:G6},X6={kernelName:Gu,backendName:"webgl",kernelFunc:function j6(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t;if("string"!==r.dtype)throw new Error("Input must be of datatype string");const a=Ar(e.readSync(r.dataId)),o=rW(a,"string",s);return e.makeTensorInfo(r.shape,"string",o)}},q6={kernelName:jo,backendName:"webgl",kernelFunc:function K6({inputs:n,attrs:t,backend:e}){const{x:s}=n,i=new xr(s.shape,Ts+`\n return x > 0.0 ? 1.0 : float(${t.alpha});\n `);return e.runWebGLProgram(i,[s],s.dtype)}};class Z6{constructor(t,e,s){this.variableNames=["x"],this.outputShape=s;const r=s.length,i=Ut(s.length),a=Ut(s.length);let o="";if(1===r)o="coords * strides + begin";else{let l=0;o=s.map((u,c)=>(l++,1===s.length?`coords * strides[${c}] + begin[${c}]`:`coords[${l-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`\n ${i} begin = ${i}(${t});\n ${i} strides = ${i}(${e});\n\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${o}));\n }\n `}}const Q6={kernelName:Ud,backendName:"webgl",kernelFunc:function Y6(n){const{inputs:t,backend:e,attrs:s}=n,{x:r}=t,{begin:i,end:a,strides:o,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:d}=s,{finalShapeSparse:p,finalShape:f,isIdentity:g,sliceDim0:m,isSimpleSlice:x,begin:y,end:b,strides:v}=Pp(r.shape,i,a,o,l,u,c,h,d);let w;if(g)w=Ne({inputs:{x:r},backend:e,attrs:{shape:f}});else if(m||x){T(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);const I=$p(y,b,v),k=Wa({inputs:{x:r},backend:e,attrs:{begin:y,size:I}});w=Ne({inputs:{x:k},backend:e,attrs:{shape:f}}),e.disposeIntermediateTensorInfo(k)}else if(e.shouldExecuteOnCPU([r])){const k=e.readSync(r.dataId),D=vt(r.shape,r.dtype,k),P=iW(p,D,v,y);w=e.makeTensorInfo(f,r.dtype,P.values)}else{const k=new Z6(y,v,p);w=e.runWebGLProgram(k,[r],r.dtype)}const S=Ne({inputs:{x:w},backend:e,attrs:{shape:f}});return e.disposeIntermediateTensorInfo(w),S}},eK={kernelName:Wd,backendName:"webgl",kernelFunc:function J6(n){const{inputs:t,backend:e,attrs:s}=n,{separator:r,nGramWidths:i,leftPad:a,rightPad:o,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=t,d=e.readSync(c.dataId),p=e.readSync(h.dataId),[f,g]=aW(d,p,r,i,a,o,l,u);return[e.makeTensorInfo([f.length],"string",f),e.makeTensorInfo(h.shape,"int32",g)]}},nK={kernelName:Gd,backendName:"webgl",kernelFunc:function tK(n){const{inputs:t,backend:e,attrs:s}=n,{skipEmpty:r}=s,{input:i,delimiter:a}=t;if("string"!==i.dtype)throw new Error("Input must be of datatype string");if(1!==i.shape.length)throw new Error(`Input must be a vector, got shape: ${i.shape}`);if(0!==a.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);const o=e.readSync(i.dataId),l=e.readSync(a.dataId)[0],[u,c,h]=oW(o,l,r),d=c.length;return[e.makeTensorInfo([d,2],"int32",u),e.makeTensorInfo([d],"string",c),e.makeTensorInfo([2],"int32",new Int32Array(h))]}},rK={kernelName:Hd,backendName:"webgl",kernelFunc:function sK(n){const{inputs:t,backend:e,attrs:s}=n,{numBuckets:r}=s,{input:i}=t;if("string"!==i.dtype)throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const a=e.readSync(i.dataId),o=lW(a,r);return e.makeTensorInfo(i.shape,"int32",o)}},iK=Nt({opSnippet:"return tan(x);"}),aK={kernelName:Wo,backendName:"webgl",kernelFunc:iK},oK=Nt({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),lK={kernelName:Go,backendName:"webgl",kernelFunc:oK},cK={kernelName:jg,backendName:"webgl",kernelFunc:function uK(n){const{inputs:t,backend:e}=n,{tensor:r,indices:i,updates:a}=t,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=Mi(0,i,r.shape),d=[h/u,u];if(0===h)return e.makeTensorInfo(r.shape,i.dtype);const p=Ne({inputs:{x:i},backend:e,attrs:{shape:[l,o]}}),f=Ne({inputs:{x:a},backend:e,attrs:{shape:[l,u]}}),g=Ne({inputs:{x:r},backend:e,attrs:{shape:d}}),m=new dg(l,o,p.shape.length,f.shape.length,c,d,!1,!0),x=e.runWebGLProgram(m,[f,p,g],g.dtype),y=Ne({inputs:{x},backend:e,attrs:{shape:r.shape}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(x),y}};class hK{constructor(t,e){this.variableNames=["A"];const s=new Array(t.length);for(let a=0;a5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${n[0]})`;const e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let r=0;r5){const l=e.readSync(r.dataId),u="string"===r.dtype?l.map(d=>Wr(d)):l,c=vt(r.shape,r.dtype,u),h=cW(c,i);return e.makeTensorInfo(h.shape,h.dtype,h.values)}const a=new hK(r.shape,i);return e.runWebGLProgram(a,[r],r.dtype)}const pK={kernelName:Ho,backendName:"webgl",kernelFunc:a1};class fK{constructor(t){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=t,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 mK{constructor(t){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=t,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 ea(n,t){null!==t&&n.disposeIntermediateTensorInfo(t)}function o1(n){let t=1;for(;tl){const P=e.readSync(r.dataId),[B,Y]=hW(P,u,r.dtype,i,a);return[e.makeTensorInfo(B.shape,B.dtype,B.values),e.makeTensorInfo(Y.shape,Y.dtype,Y.values)]}if(0===i)return u[u.length-1]=0,[e.makeTensorInfo(u,r.dtype,[]),e.makeTensorInfo(u,"int32",[])];if(1===c)return[r,Vl({attrs:{shape:u,dtype:"int32",value:0},backend:e})];const h=e.texData.get(r.dataId),d=null!==h&&h.isPacked,p=d?e.unpackTensor(r):r,g=K(u)/c,m=Ne({inputs:{x:p},attrs:{shape:[g,c]},backend:e});d&&ea(e,p);const x=o1(i),y=o1(c);let b=null;const v=()=>null===b?[m,m]:[m,b],w=(P,B,Y)=>{const Q=v(),ee=new fK(Y),ae=b;b=e.runWebGLProgram(ee,Q,"int32",[[c],[null===b?1:0],[Number.NEGATIVE_INFINITY],[P],[B]]),ea(e,ae)};for(let P=1;P=1;Y/=2)w(B,Y,[g,y])}for(let P=y;P>x;P/=2){const B=v(),Y=new mK([g,P/2]),J=b;b=e.runWebGLProgram(Y,B,"int32",[[c],[null===b?1:0],[x]]),ea(e,J);const se=x/2,ae=2*se;for(let te=se;te>=1;te/=2)w(ae,te,b.shape)}let S=b;b=Wa({inputs:{x:b},backend:e,attrs:{begin:0,size:[g,i]}}),ea(e,S);let I=qT({inputs:{x:m,indices:b},backend:e,attrs:{axis:1,batchDims:1}});ea(e,m);const k=u.slice(0,-1);k.push(i),S=b,b=Ne({inputs:{x:b},attrs:{shape:k},backend:e}),ea(e,S);const D=I;return I=Ne({inputs:{x:I},attrs:{shape:k},backend:e}),ea(e,D),[I,b]}};class yK{constructor(t,e,s,r,i,a){this.variableNames=["Image","Transforms"],this.outputShape=a;const o="nearest"===s?1:2;let l;switch(r){case"constant":default:l=1;break;case"reflect":l=2;break;case"wrap":l=3;break;case"nearest":l=4}this.userCode=`\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${l} == 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 (${l} == 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 (${l} == 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 < ${t} && 0 <= coordX && coordX < ${e}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${i});\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(${i});\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(${e}));\n float mapY = mapCoord(inY, float(${t}));\n\n if (${o} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `}}const vK={kernelName:Xd,backendName:"webgl",kernelFunc:function bK(n){const{inputs:t,backend:e,attrs:s}=n,{image:r,transforms:i}=t,{interpolation:a,fillMode:o,fillValue:l,outputShape:u}=s,[c,h,d,p]=r.shape,[f,g]=u??[h,d],x=new yK(h,d,a,o,l,[c,f,g,p]);return e.runWebGLProgram(x,[r,i],"float32")}},_K={kernelName:Kd,backendName:"webgl",kernelFunc:function wK(n){const{inputs:t,attrs:e,backend:s}=n,{axis:r}=e,{x:i}=t;Dl(i,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const a=s.readSync(i.dataId),{outputValues:o,outputShape:l,indices:u}=dW(a,r,i.shape,i.dtype);return[s.makeTensorInfo(l,i.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}},SK={kernelName:Hu,backendName:"webgl",kernelFunc:function TK(n){const{inputs:t,backend:e,attrs:s}=n,{value:r}=t;let{axis:i}=s;i<0&&(i+=r.shape.length);const a=r,o=a.shape.length,l=r.shape[i],u=new Array(o-1);let c=0;for(let g=0;ge.disposeIntermediateTensorInfo(g)),f}};class CK{constructor(t,e){this.variableNames=["x","segmentIds"];const s=t.windowSize,r=t.batchSize,i=t.inSize,a=t.numSegments,o=a*Math.ceil(i/s);this.outputShape=[r,o];const c=4*Math.floor(s/4),h=s%4,d="\n sumValue += dot(values, segFilter);\n ";let p="";i%s>0&&(p=`\n if (inIdx < 0 || inIdx >= ${i}) {\n return initializationValue;\n }\n `);let f="";i%s>0&&(f=`\n if (inIdx < 0 || inIdx >= ${i}) {\n return -1.0;\n }\n `),this.userCode=`\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n ${p}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${f}\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n ${a})) * float(${s}));\n int currentSeg = int(mod(float(outIdx), float(${a})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${c}; 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 ${d}\n }\n\n int inIdx = inOffset + ${c};\n if (${1===h}) {\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 ${d}\n } else if (${2===h}) {\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 ${d}\n } else if (${3===h}) {\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 ${d}\n }\n setOutput(sumValue);\n }\n `}}const kK=[a4,l4,h4,f4,g4,b4,w4,T4,E4,N4,$4,P4,M4,U4,H4,X4,q4,J4,tG,sG,aG,dG,fG,yG,vG,CG,EG,RG,WW,OG,VG,WG,qG,QG,eH,nH,rH,lH,cH,dH,fH,gH,yH,wH,TH,EH,NH,$H,PH,LH,VH,UH,GH,XH,qH,ZH,QH,ej,nj,rj,aj,lj,hj,fj,gj,bj,_j,Sj,Ij,UW,kj,LG,Aj,$j,Oj,HW,Fj,Mj,zj,Wj,jj,Kj,Zj,Qj,t5,s5,i5,u5,h5,p5,x5,b5,w5,T5,C5,N5,$5,F5,U5,KW,j5,q5,Q5,tX,wG,sX,iX,oX,cX,fX,XW,gX,yX,vX,_X,TX,_G,M5,CX,kX,RX,ZW,PX,MX,UX,HX,qX,YX,JX,t6,r6,o6,c6,p6,g6,y6,_6,S6,hG,z5,I6,E6,N6,R6,D6,P6,L6,V6,B6,W6,H6,X6,q6,Q6,eK,nK,rK,V5,s4,aK,lK,cK,pK,xK,vK,r4,_K,SK,{kernelName:ju,backendName:"webgl",kernelFunc:function IK(n){const{inputs:t,backend:e,attrs:s}=n,{x:r,segmentIds:i}=t,{numSegments:a}=s,o=r.shape.length,l=[];let u=0;const c=rn([u],o);let h=r;null!=c&&(h=es({inputs:{x:r},backend:e,attrs:{perm:c}}),l.push(h),u=dn(1,o)[0]);const d=ub(h.shape,u,a),p=K([h.shape[u]]),f=Ne({inputs:{x:h},backend:e,attrs:{shape:[-1,p]}});l.push(f);const g=np(r.dtype),m=(v,w,S,I,k)=>{const D=v.shape[0],P=v.shape[1],B=lb(P,k),Q=new CK({windowSize:B,inSize:P,batchSize:D,numSegments:k},w),ee=e.compileAndRun(Q,[v,S],I);if(l.push(ee),ee.shape[1]===k)return ee;const J=s1({backend:e,attrs:{start:0,stop:k,step:1,dtype:"float32"}}),se=a1({inputs:{x:J},backend:e,attrs:{reps:[P/B]}});return l.push(J),l.push(se),m(ee,w,se,I,k)},y=Ne({inputs:{x:m(f,"unsortedSegmentSum",i,g,a)},backend:e,attrs:{shape:d}});let b=y;if(null!=c){l.push(y);const v=Yr(c);b=es({inputs:{x:b},backend:e,attrs:{perm:v}})}return l.forEach(v=>e.disposeIntermediateTensorInfo(v)),b}},rX];for(const n of kK)Qd(n);function l1(n,t){let e=!1;for(let s=0,r=t.length-1;sn[1]!=l>n[1]&&n[0]<(t[r][0]-i)*(n[1]-a)/(l-a)+i&&(e=!e)}return e}function u1(n,t){const e=[];let s=n[0][0],r=n[0][0],i=n[0][1],a=n[0][1];for(const h of n)h[0]r&&(r=h[0]),h[1]a&&(a=h[1]);let o=Math.ceil(s/t)*t,l=Math.ceil(i/t)*t,u=Math.floor(r/t)*t,c=Math.floor(a/t)*t;o>r&&(o=s),l>a&&(l=i),u{this.uniforms_.push({value:t.uniforms[a],location:e.getUniformLocation(this.renderTargetProgram_,a)})})}getGL(){return this.gl_}init(t){const e=this.getGL(),s=[e.drawingBufferWidth*this.scaleRatio_,e.drawingBufferHeight*this.scaleRatio_];if(e.bindFramebuffer(e.FRAMEBUFFER,this.getFrameBuffer()),e.bindRenderbuffer(e.RENDERBUFFER,this.getDepthBuffer()),e.viewport(0,0,s[0],s[1]),!this.renderTargetTextureSize_||this.renderTargetTextureSize_[0]!==s[0]||this.renderTargetTextureSize_[1]!==s[1]){this.renderTargetTextureSize_=s;const r=0,i=e.RGBA,a=0,o=e.RGBA,l=e.UNSIGNED_BYTE,u=null;e.bindTexture(e.TEXTURE_2D,this.renderTargetTexture_),e.texImage2D(e.TEXTURE_2D,r,i,s[0],s[1],a,o,l,u),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.renderTargetTexture_,0),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,s[0],s[1]),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,this.depthBuffer_)}}apply(t,e,s,r){const i=this.getGL(),a=t.size;if(i.bindFramebuffer(i.FRAMEBUFFER,e?e.getFrameBuffer():null),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.renderTargetTexture_),!e){const l=(0,is.v6)(i.canvas);if(!t.renderTargets[l]){const u=i.getContextAttributes();u&&u.preserveDrawingBuffer&&(i.clearColor(0,0,0,0),i.clearDepth(1),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT)),t.renderTargets[l]=!0}}i.disable(i.DEPTH_TEST),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.viewport(0,0,i.drawingBufferWidth,i.drawingBufferHeight),i.bindBuffer(i.ARRAY_BUFFER,this.renderTargetVerticesBuffer_),i.useProgram(this.renderTargetProgram_),i.enableVertexAttribArray(this.renderTargetAttribLocation_),i.vertexAttribPointer(this.renderTargetAttribLocation_,2,i.FLOAT,!1,0,0),i.uniform2f(this.renderTargetUniformLocation_,a[0],a[1]),i.uniform1i(this.renderTargetTextureLocation_,0),i.uniform1f(this.renderTargetOpacityLocation_,t.layerStatesArray[t.layerIndex].opacity),this.applyUniforms(t),s&&s(i,t),i.drawArrays(i.TRIANGLES,0,6),r&&r(i,t)}getFrameBuffer(){return this.frameBuffer_}getDepthBuffer(){return this.depthBuffer_}applyUniforms(t){const e=this.getGL();let s,r=1;this.uniforms_.forEach(function(i){if(s="function"==typeof i.value?i.value(t):i.value,s instanceof HTMLCanvasElement||s instanceof ImageData)i.texture||(i.texture=e.createTexture()),e.activeTexture(e[`TEXTURE${r}`]),e.bindTexture(e.TEXTURE_2D,i.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),s instanceof ImageData?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,s.width,s.height,0,e.UNSIGNED_BYTE,new Uint8Array(s.data)):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s),e.uniform1i(i.location,r++);else if(Array.isArray(s))switch(s.length){case 2:return void e.uniform2f(i.location,s[0],s[1]);case 3:return void e.uniform3f(i.location,s[0],s[1],s[2]);case 4:return void e.uniform4f(i.location,s[0],s[1],s[2],s[3]);default:return}else"number"==typeof s&&e.uniform1f(i.location,s)})}};var KK=W(973),gn=W(9984);const Wh={};function v1(n){return"shared/"+n}let w1=0;function _1(n){switch(n){case 5121:return Uint8Array.BYTES_PER_ELEMENT;case 5123:return Uint16Array.BYTES_PER_ELEMENT;case 5125:return Uint32Array.BYTES_PER_ELEMENT;default:return Float32Array.BYTES_PER_ELEMENT}}const eq=class QK extends GK.A{constructor(t){super(),t=t||{},this.boundHandleWebGLContextLost_=this.handleWebGLContextLost.bind(this),this.boundHandleWebGLContextRestored_=this.handleWebGLContextRestored.bind(this),this.canvasCacheKey_=t.canvasCacheKey?v1(t.canvasCacheKey):function qK(){const n="unique/"+w1;return w1+=1,n}(),this.gl_=function ZK(n){let t=Wh[n];if(!t){const e=document.createElement("canvas");e.width=1,e.height=1,e.style.position="absolute",e.style.left="0",t={users:0,context:m1(e)},Wh[n]=t}return t.users+=1,t.context}(this.canvasCacheKey_),this.bufferCache_={},this.extensionCache_={},this.currentProgram_=null,this.needsToBeRecreated_=!1;const e=this.gl_.canvas;e.addEventListener("webglcontextlost",this.boundHandleWebGLContextLost_),e.addEventListener("webglcontextrestored",this.boundHandleWebGLContextRestored_),this.offsetRotateMatrix_=(0,gn.vt)(),this.offsetScaleMatrix_=(0,gn.vt)(),this.tmpMat4_=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],this.uniformLocationsByProgram_={},this.attribLocationsByProgram_={},this.uniforms_=[],t.uniforms&&this.setUniforms(t.uniforms),this.postProcessPasses_=t.postProcesses?t.postProcesses.map(s=>new x1({webGlContext:this.gl_,scaleRatio:s.scaleRatio,vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,uniforms:s.uniforms})):[new x1({webGlContext:this.gl_})],this.shaderCompileErrors_=null,this.startTime_=Date.now()}setUniforms(t){this.uniforms_=[],this.addUniforms(t)}addUniforms(t){for(const e in t)this.uniforms_.push({name:e,value:t[e]})}canvasCacheKeyMatches(t){return this.canvasCacheKey_===v1(t)}getExtension(t){if(t in this.extensionCache_)return this.extensionCache_[t];const e=this.gl_.getExtension(t);return this.extensionCache_[t]=e,e}bindBuffer(t){const e=this.gl_,s=(0,is.v6)(t);let r=this.bufferCache_[s];r||(r={buffer:t,webGlBuffer:e.createBuffer()},this.bufferCache_[s]=r),e.bindBuffer(t.getType(),r.webGlBuffer)}flushBufferData(t){const e=this.gl_;this.bindBuffer(t),e.bufferData(t.getType(),t.getArray(),t.getUsage())}deleteBuffer(t){const e=this.gl_,s=(0,is.v6)(t),r=this.bufferCache_[s];r&&!e.isContextLost()&&e.deleteBuffer(r.webGlBuffer),delete this.bufferCache_[s]}disposeInternal(){const t=this.gl_.canvas;t.removeEventListener("webglcontextlost",this.boundHandleWebGLContextLost_),t.removeEventListener("webglcontextrestored",this.boundHandleWebGLContextRestored_),function YK(n){const t=Wh[n];if(!t||(t.users-=1,t.users>0))return;const e=t.context,s=e.getExtension("WEBGL_lose_context");s&&s.loseContext();const r=e.canvas;r.width=1,r.height=1,delete Wh[n]}(this.canvasCacheKey_),delete this.gl_}prepareDraw(t,e,s){const r=this.gl_,i=this.getCanvas(),a=t.size,o=t.pixelRatio;(i.width!==a[0]*o||i.height!==a[1]*o)&&(i.width=a[0]*o,i.height=a[1]*o,i.style.width=a[0]+"px",i.style.height=a[1]+"px");for(let l=this.postProcessPasses_.length-1;l>=0;l--)this.postProcessPasses_[l].init(t);r.bindTexture(r.TEXTURE_2D,null),r.clearColor(0,0,0,0),r.depthRange(0,1),r.clearDepth(1),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),r.enable(r.BLEND),r.blendFunc(r.ONE,e?r.ZERO:r.ONE_MINUS_SRC_ALPHA),s?(r.enable(r.DEPTH_TEST),r.depthFunc(r.LEQUAL)):r.disable(r.DEPTH_TEST)}bindTexture(t,e,s){const r=this.gl_;r.activeTexture(r.TEXTURE0+e),r.bindTexture(r.TEXTURE_2D,t),r.uniform1i(this.getUniformLocation(s),e)}prepareDrawToRenderTarget(t,e,s,r){const i=this.gl_,a=e.getSize();i.bindFramebuffer(i.FRAMEBUFFER,e.getFramebuffer()),i.bindRenderbuffer(i.RENDERBUFFER,e.getDepthbuffer()),i.viewport(0,0,a[0],a[1]),i.bindTexture(i.TEXTURE_2D,e.getTexture()),i.clearColor(0,0,0,0),i.depthRange(0,1),i.clearDepth(1),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),i.enable(i.BLEND),i.blendFunc(i.ONE,s?i.ZERO:i.ONE_MINUS_SRC_ALPHA),r?(i.enable(i.DEPTH_TEST),i.depthFunc(i.LEQUAL)):i.disable(i.DEPTH_TEST)}drawElements(t,e){const s=this.gl_;this.getExtension("OES_element_index_uint"),s.drawElements(s.TRIANGLES,e-t,s.UNSIGNED_INT,4*t)}finalizeDraw(t,e,s){for(let r=0,i=this.postProcessPasses_.length;r{if(s="function"==typeof i.value?i.value(t):i.value,s instanceof HTMLCanvasElement||s instanceof HTMLImageElement||s instanceof ImageData||s instanceof WebGLTexture){s instanceof WebGLTexture&&!i.texture?(i.prevValue=void 0,i.texture=s):i.texture||(i.prevValue=void 0,i.texture=e.createTexture()),this.bindTexture(i.texture,r,i.name),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);const a=!(s instanceof HTMLImageElement)||s.complete;!(s instanceof WebGLTexture)&&a&&i.prevValue!==s&&(i.prevValue=s,e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s)),r++}else if(Array.isArray(s)&&6===s.length)this.setUniformMatrixValue(i.name,function b1(n,t){return n[0]=t[0],n[1]=t[1],n[4]=t[2],n[5]=t[3],n[12]=t[4],n[13]=t[5],n}(this.tmpMat4_,s));else if(Array.isArray(s)&&s.length<=4)switch(s.length){case 2:return void e.uniform2f(this.getUniformLocation(i.name),s[0],s[1]);case 3:return void e.uniform3f(this.getUniformLocation(i.name),s[0],s[1],s[2]);case 4:return void e.uniform4f(this.getUniformLocation(i.name),s[0],s[1],s[2],s[3]);default:return}else"number"==typeof s&&e.uniform1f(this.getUniformLocation(i.name),s)})}useProgram(t,e){this.gl_.useProgram(t),this.currentProgram_=t,this.applyFrameState(e),this.applyUniforms(e)}compileShader(t,e){const s=this.gl_,r=s.createShader(e);return s.shaderSource(r,t),s.compileShader(r),r}getProgram(t,e){const s=this.gl_,r=this.compileShader(t,s.FRAGMENT_SHADER),i=this.compileShader(e,s.VERTEX_SHADER),a=s.createProgram();if(s.attachShader(a,r),s.attachShader(a,i),s.linkProgram(a),!s.getShaderParameter(r,s.COMPILE_STATUS)){const o=`Fragment shader compilation failed: ${s.getShaderInfoLog(r)}`;throw new Error(o)}if(s.deleteShader(r),!s.getShaderParameter(i,s.COMPILE_STATUS)){const o=`Vertex shader compilation failed: ${s.getShaderInfoLog(i)}`;throw new Error(o)}if(s.deleteShader(i),!s.getProgramParameter(a,s.LINK_STATUS)){const o=`GL program linking failed: ${s.getProgramInfoLog(a)}`;throw new Error(o)}return a}getUniformLocation(t){const e=(0,is.v6)(this.currentProgram_);return void 0===this.uniformLocationsByProgram_[e]&&(this.uniformLocationsByProgram_[e]={}),void 0===this.uniformLocationsByProgram_[e][t]&&(this.uniformLocationsByProgram_[e][t]=this.gl_.getUniformLocation(this.currentProgram_,t)),this.uniformLocationsByProgram_[e][t]}getAttributeLocation(t){const e=(0,is.v6)(this.currentProgram_);return void 0===this.attribLocationsByProgram_[e]&&(this.attribLocationsByProgram_[e]={}),void 0===this.attribLocationsByProgram_[e][t]&&(this.attribLocationsByProgram_[e][t]=this.gl_.getAttribLocation(this.currentProgram_,t)),this.attribLocationsByProgram_[e][t]}makeProjectionTransform(t,e){const s=t.size,i=t.viewState.resolution,a=t.viewState.center;return(0,gn.Zz)(e,0,0,2/(i*s[0]),2/(i*s[1]),-t.viewState.rotation,-a[0],-a[1]),e}setUniformFloatValue(t,e){this.gl_.uniform1f(this.getUniformLocation(t),e)}setUniformFloatVec2(t,e){this.gl_.uniform2fv(this.getUniformLocation(t),e)}setUniformFloatVec4(t,e){this.gl_.uniform4fv(this.getUniformLocation(t),e)}setUniformMatrixValue(t,e){this.gl_.uniformMatrix4fv(this.getUniformLocation(t),!1,e)}enableAttributeArray_(t,e,s,r,i){const a=this.getAttributeLocation(t);a<0||(this.gl_.enableVertexAttribArray(a),this.gl_.vertexAttribPointer(a,e,s,!1,r,i))}enableAttributes(t){const e=function JK(n){let t=0;for(let e=0;ethis.size_[0]||e>=this.size_[1])return br[0]=0,br[1]=0,br[2]=0,br[3]=0,br;this.readAll();const s=Math.floor(t)+(this.size_[1]-Math.floor(e)-1)*this.size_[0];return br[0]=this.data_[4*s],br[1]=this.data_[4*s+1],br[2]=this.data_[4*s+2],br[3]=this.data_[4*s+3],br}getTexture(){return this.texture_}getFramebuffer(){return this.framebuffer_}getDepthbuffer(){return this.depthbuffer_}updateSize_(){const t=this.size_,e=this.helper_.getGL();this.texture_=this.helper_.createTexture(t,null,this.texture_),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer_),e.viewport(0,0,t[0],t[1]),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture_,0),e.bindRenderbuffer(e.RENDERBUFFER,this.depthbuffer_),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,t[0],t[1]),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,this.depthbuffer_),this.data_=new Uint8Array(t[0]*t[1]*4)}};var ts=W(4378);function rq(n,t){const e=256,s=255;return(t=t||[])[0]=Math.floor(n/e/e/e)/s,t[1]=Math.floor(n/e/e)%e/s,t[2]=Math.floor(n/e)%e/s,t[3]=n%e/s,t}W(2381);var jh=W(3036),pi=W(7443);const uq=class lq extends T1{constructor(t,e){const s=e.uniforms||{},r=(0,gn.vt)();s.u_projectionMatrix=r,super(t,{uniforms:s,postProcesses:e.postProcesses}),this.sourceRevision_=-1,this.verticesBuffer_=new Bh(34962,35048),this.indicesBuffer_=new Bh(34963,35048),this.vertexShader_=e.vertexShader,this.fragmentShader_=e.fragmentShader,this.hitDetectionEnabled_=e.hitDetectionEnabled??!0;const i=e.attributes?e.attributes.map(function(o){return{name:"a_prop_"+o.name,size:1,type:5126}}):[];this.attributes=[{name:"a_position",size:2,type:5126},{name:"a_index",size:1,type:5126}],this.hitDetectionEnabled_&&(this.attributes.push({name:"a_prop_hitColor",size:4,type:5126}),this.attributes.push({name:"a_featureUid",size:1,type:5126})),this.attributes.push(...i),this.customAttributes=e.attributes?e.attributes:[],this.previousExtent_=(0,ts.S5)(),this.currentTransform_=r,this.renderTransform_=(0,gn.vt)(),this.invertRenderTransform_=(0,gn.vt)(),this.renderInstructions_=new Float32Array(0),this.lastSentId=0,this.worker_=function aq(){const n='const e="GENERATE_POLYGON_BUFFERS",t="GENERATE_POINT_BUFFERS",n="GENERATE_LINE_STRING_BUFFERS";function r(e,t){const n=t[0],r=t[1];return t[0]=e[0]*n+e[2]*r+e[4],t[1]=e[1]*n+e[3]*r+e[5],t}function x(e,t){const n=(r=t)[0]*r[3]-r[1]*r[2];var r;!function(e,t){if(!e)throw new Error(t)}(0!==n,"Transformation matrix cannot be inverted");const x=t[0],i=t[1],u=t[2],o=t[3],f=t[4],s=t[5];return e[0]=o/n,e[1]=-i/n,e[2]=-u/n,e[3]=x/n,e[4]=(u*s-o*f)/n,e[5]=-(x*s-i*f)/n,e}function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}new Array(6);var u={exports:{}};function o(e,t,n){n=n||2;var r,x,i,u,o,s,l,v=t&&t.length,h=v?t[0]*n:e.length,c=f(e,0,h,n,!0),g=[];if(!c||c.next===c.prev)return g;if(v&&(c=function(e,t,n,r){var x,i,u,o=[];for(x=0,i=t.length;x80*n){r=i=e[0],x=u=e[1];for(var b=n;bi&&(i=o),s>u&&(u=s);l=0!==(l=Math.max(i-r,u-x))?32767/l:0}return a(c,g,n,r,x,l,0),g}function f(e,t,n,r,x){var i,u;if(x===O(e,t,n,r)>0)for(i=t;i=t;i-=r)u=P(i,e[i],e[i+1],u);return u&&m(u,u.next)&&(B(u),u=u.next),u}function s(e,t){if(!e)return e;t||(t=e);var n,r=e;do{if(n=!1,r.steiner||!m(r,r.next)&&0!==w(r.prev,r,r.next))r=r.next;else{if(B(r),(r=t=r.prev)===r.next)break;n=!0}}while(n||r!==t);return t}function a(e,t,n,r,x,i,u){if(e){!u&&i&&function(e,t,n,r){var x=e;do{0===x.z&&(x.z=b(x.x,x.y,t,n,r)),x.prevZ=x.prev,x.nextZ=x.next,x=x.next}while(x!==e);x.prevZ.nextZ=null,x.prevZ=null,function(e){var t,n,r,x,i,u,o,f,s=1;do{for(n=e,e=null,i=null,u=0;n;){for(u++,r=n,o=0,t=0;t0||f>0&&r;)0!==o&&(0===f||!r||n.z<=r.z)?(x=n,n=n.nextZ,o--):(x=r,r=r.nextZ,f--),i?i.nextZ=x:e=x,x.prevZ=i,i=x;n=r}i.nextZ=null,s*=2}while(u>1)}(x)}(e,r,x,i);for(var o,f,p=e;e.prev!==e.next;)if(o=e.prev,f=e.next,i?v(e,r,x,i):l(e))t.push(o.i/n|0),t.push(e.i/n|0),t.push(f.i/n|0),B(e),e=f.next,p=f.next;else if((e=f)===p){u?1===u?a(e=h(s(e),t,n),t,n,r,x,i,2):2===u&&c(e,t,n,r,x,i):a(s(e),t,n,r,x,i,1);break}}}function l(e){var t=e.prev,n=e,r=e.next;if(w(t,n,r)>=0)return!1;for(var x=t.x,i=n.x,u=r.x,o=t.y,f=n.y,s=r.y,a=xi?x>u?x:u:i>u?i:u,h=o>f?o>s?o:s:f>s?f:s,c=r.next;c!==t;){if(c.x>=a&&c.x<=v&&c.y>=l&&c.y<=h&&M(x,o,i,f,u,s,c.x,c.y)&&w(c.prev,c,c.next)>=0)return!1;c=c.next}return!0}function v(e,t,n,r){var x=e.prev,i=e,u=e.next;if(w(x,i,u)>=0)return!1;for(var o=x.x,f=i.x,s=u.x,a=x.y,l=i.y,v=u.y,h=of?o>s?o:s:f>s?f:s,y=a>l?a>v?a:v:l>v?l:v,g=b(h,c,t,n,r),d=b(p,y,t,n,r),Z=e.prevZ,m=e.nextZ;Z&&Z.z>=g&&m&&m.z<=d;){if(Z.x>=h&&Z.x<=p&&Z.y>=c&&Z.y<=y&&Z!==x&&Z!==u&&M(o,a,f,l,s,v,Z.x,Z.y)&&w(Z.prev,Z,Z.next)>=0)return!1;if(Z=Z.prevZ,m.x>=h&&m.x<=p&&m.y>=c&&m.y<=y&&m!==x&&m!==u&&M(o,a,f,l,s,v,m.x,m.y)&&w(m.prev,m,m.next)>=0)return!1;m=m.nextZ}for(;Z&&Z.z>=g;){if(Z.x>=h&&Z.x<=p&&Z.y>=c&&Z.y<=y&&Z!==x&&Z!==u&&M(o,a,f,l,s,v,Z.x,Z.y)&&w(Z.prev,Z,Z.next)>=0)return!1;Z=Z.prevZ}for(;m&&m.z<=d;){if(m.x>=h&&m.x<=p&&m.y>=c&&m.y<=y&&m!==x&&m!==u&&M(o,a,f,l,s,v,m.x,m.y)&&w(m.prev,m,m.next)>=0)return!1;m=m.nextZ}return!0}function h(e,t,n){var r=e;do{var x=r.prev,i=r.next.next;!m(x,i)&&A(x,r,r.next,i)&&z(x,i)&&z(i,x)&&(t.push(x.i/n|0),t.push(r.i/n|0),t.push(i.i/n|0),B(r),B(r.next),r=e=i),r=r.next}while(r!==e);return s(r)}function c(e,t,n,r,x,i){var u=e;do{for(var o=u.next.next;o!==u.prev;){if(u.i!==o.i&&Z(u,o)){var f=F(u,o);return u=s(u,u.next),f=s(f,f.next),a(u,t,n,r,x,i,0),void a(f,t,n,r,x,i,0)}o=o.next}u=u.next}while(u!==e)}function p(e,t){return e.x-t.x}function y(e,t){var n=function(e,t){var n,r=t,x=e.x,i=e.y,u=-1/0;do{if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){var o=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(o<=x&&o>u&&(u=o,n=r.x=r.x&&r.x>=a&&x!==r.x&&M(in.x||r.x===n.x&&g(n,r)))&&(n=r,v=f)),r=r.next}while(r!==s);return n}(e,t);if(!n)return t;var r=F(n,e);return s(r,r.next),s(n,n.next)}function g(e,t){return w(e.prev,e,t.prev)<0&&w(t.next,e,e.next)<0}function b(e,t,n,r,x){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*x|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*x|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function d(e){var t=e,n=e;do{(t.x=(e-u)*(i-o)&&(e-u)*(r-o)>=(n-u)*(t-o)&&(n-u)*(i-o)>=(x-u)*(r-o)}function Z(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&A(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1}(e,t)&&(z(e,t)&&z(t,e)&&function(e,t){var n=e,r=!1,x=(e.x+t.x)/2,i=(e.y+t.y)/2;do{n.y>i!=n.next.y>i&&n.next.y!==n.y&&x<(n.next.x-n.x)*(i-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==e);return r}(e,t)&&(w(e.prev,e,t.prev)||w(e,t.prev,t))||m(e,t)&&w(e.prev,e,e.next)>0&&w(t.prev,t,t.next)>0)}function w(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function m(e,t){return e.x===t.x&&e.y===t.y}function A(e,t,n,r){var x=I(w(e,t,n)),i=I(w(e,t,r)),u=I(w(n,r,e)),o=I(w(n,r,t));return x!==i&&u!==o||(!(0!==x||!E(e,n,t))||(!(0!==i||!E(e,r,t))||(!(0!==u||!E(n,e,r))||!(0!==o||!E(n,t,r)))))}function E(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function I(e){return e>0?1:e<0?-1:0}function z(e,t){return w(e.prev,e,e.next)<0?w(e,t,e.next)>=0&&w(e,e.prev,t)>=0:w(e,t,e.prev)<0||w(e,e.next,t)<0}function F(e,t){var n=new _(e.i,e.x,e.y),r=new _(t.i,t.x,t.y),x=e.next,i=t.prev;return e.next=t,t.prev=e,n.next=x,x.prev=n,r.next=n,n.prev=r,i.next=r,r.prev=i,r}function P(e,t,n,r){var x=new _(e,t,n);return r?(x.next=r.next,x.prev=r,r.next.prev=x,r.next=x):(x.prev=x,x.next=x),x}function B(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function _(e,t,n){this.i=e,this.x=t,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function O(e,t,n,r){for(var x=0,i=t,u=n-r;i0&&(r+=e[x-1].length,n.holes.push(r))}return n};var N=i(u.exports);const R=[],S={vertexPosition:0,indexPosition:0};function T(e,t,n,r,x){e[t+0]=n,e[t+1]=r,e[t+2]=x}function U(e,t,n,r,x,i){const u=3+x,o=e[t+0],f=e[t+1],s=R;s.length=x;for(let n=0;n0?f:2*Math.PI-f}let d=-1,M=-1,Z=l;const w=null!==i;if(null!==x){d=b(y,g,r(s,[...[e[x],e[x+1]]])),Math.cos(d)<=.985&&(Z+=Math.tan((d-Math.PI)/2))}if(w){M=b(g,y,r(s,[...[e[i],e[i+1]]])),Math.cos(M)<=.985&&(Z+=Math.tan((Math.PI-M)/2))}function m(e,t){return 0===t?1e4*e:Math.sign(t)*(1e4*e+Math.abs(t))}return u.push(c[0],c[1],p[0],p[1],d,M,a,m(0,l)),u.push(...f),u.push(c[0],c[1],p[0],p[1],d,M,a,m(1,l)),u.push(...f),u.push(c[0],c[1],p[0],p[1],d,M,a,m(2,l)),u.push(...f),u.push(c[0],c[1],p[0],p[1],d,M,a,m(3,l)),u.push(...f),o.push(h,h+1,h+2,h+1,h+3,h+2),{length:a+Math.sqrt((g[0]-y[0])*(g[0]-y[0])+(g[1]-y[1])*(g[1]-y[1])),angle:Z}}function G(e,t,n,r,x){const i=2+x;let u=t;const o=e.slice(u,u+x);u+=x;const f=e[u++];let s=0;const a=new Array(f-1);for(let t=0;t{const i=r.data;switch(i.type){case t:{const e=3,t=2,n=i.customAttributesSize,r=t+n,x=new Float32Array(i.renderInstructions),u=x.length/r,o=4*u*(n+e),f=new Uint32Array(6*u),s=new Float32Array(o);let a;for(let e=0;e0?c=o+(n-1)*r:l&&(c=i-r);let p=null;n"u"?"data:application/javascript;base64,"+Buffer.from(n,"binary").toString("base64"):URL.createObjectURL(new Blob([n],{type:"application/javascript"})))}(),this.worker_.addEventListener("message",o=>{const l=o.data;if("GENERATE_POINT_BUFFERS"===l.type){const u=l.projectionTransform;this.verticesBuffer_.fromArrayBuffer(l.vertexBuffer),this.helper.flushBufferData(this.verticesBuffer_),this.indicesBuffer_.fromArrayBuffer(l.indexBuffer),this.helper.flushBufferData(this.indicesBuffer_),this.renderTransform_=u,(0,gn.T9)(this.invertRenderTransform_,this.renderTransform_),this.renderInstructions_=new Float32Array(o.data.renderInstructions),l.id===this.lastSentId&&(this.ready=!0),this.getLayer().changed()}}),this.featureCache_={},this.featureCount_=0;const a=this.getLayer().getSource();this.sourceListenKeys_=[(0,pi.KT)(a,Mh.A.ADDFEATURE,this.handleSourceFeatureAdded_,this),(0,pi.KT)(a,Mh.A.CHANGEFEATURE,this.handleSourceFeatureChanged_,this),(0,pi.KT)(a,Mh.A.REMOVEFEATURE,this.handleSourceFeatureDelete_,this),(0,pi.KT)(a,Mh.A.CLEAR,this.handleSourceFeatureClear_,this)],a.forEachFeature(o=>{this.featureCache_[(0,is.v6)(o)]={feature:o,properties:o.getProperties(),geometry:o.getGeometry()},this.featureCount_++})}afterHelperCreated(){this.program_=this.helper.getProgram(this.fragmentShader_,this.vertexShader_),this.hitDetectionEnabled_&&(this.hitRenderTarget_=new nq(this.helper))}handleSourceFeatureAdded_(t){const e=t.feature;this.featureCache_[(0,is.v6)(e)]={feature:e,properties:e.getProperties(),geometry:e.getGeometry()},this.featureCount_++}handleSourceFeatureChanged_(t){const e=t.feature;this.featureCache_[(0,is.v6)(e)]={feature:e,properties:e.getProperties(),geometry:e.getGeometry()}}handleSourceFeatureDelete_(t){delete this.featureCache_[(0,is.v6)(t.feature)],this.featureCount_--}handleSourceFeatureClear_(){this.featureCache_={},this.featureCount_=0}renderFrame(t){const e=this.helper.getGL();this.preRender(e,t);const[s,r,i]=function oq(n,t){const e=n.viewState.projection,r=t.getSource().getWrapX()&&e.canWrapX(),i=e.getExtent(),a=n.extent,o=r?(0,ts.RG)(i):null,l=r?Math.ceil((a[2]-i[2])/o)+1:1;return[r?Math.floor((a[0]-i[0])/o):0,l,o]}(t,this.getLayer());return this.renderWorlds(t,!1,s,r,i),this.helper.finalizeDraw(t,this.dispatchPreComposeEvent,this.dispatchPostComposeEvent),this.hitDetectionEnabled_&&(this.renderWorlds(t,!0,s,r,i),this.hitRenderTarget_.clearCachedData()),this.postRender(e,t),this.helper.getCanvas()}prepareFrameInternal(t){const e=this.getLayer(),s=e.getSource(),r=t.viewState,i=!t.viewHints[d1.A.ANIMATING]&&!t.viewHints[d1.A.INTERACTING],a=!(0,ts.aI)(this.previousExtent_,t.extent),o=this.sourceRevision_4)throw new Error("`formatArray` can only output `vec2`, `vec3` or `vec4` arrays.");return`vec${n.length}(${n.map(ta).join(", ")})`}function Kh(n){const t=(0,Ul._j)(n),e=t.length>3?t[3]:1;return Cg([t[0]/255*e,t[1]/255*e,t[2]/255*e,e])}const Ig={};let Pq=0;function Eg(n){return n in Ig||(Ig[n]=Pq++),Ig[n]}function Pr(n){return ta(Eg(n))}function P1(n){return"u_var_"+n}const kg="getBandValue";function Ot(n){return(t,e,s)=>{const r=e.args.length,i=new Array(r);for(let a=0;a{const s=t.args[0].value;return s in n.properties||(n.properties[s]={name:s,type:t.type}),(n.inFragmentShader?"v_prop_":"a_prop_")+s},[he.ZD.GeometryType]:(n,t,e)=>{const s="geometryType";return s in n.properties||(n.properties[s]={name:s,type:he.cT,evaluator:a=>(0,he.Ye)(a.getGeometry())}),(n.inFragmentShader?"v_prop_":"a_prop_")+s},[he.ZD.Var]:(n,t)=>{const s=t.args[0].value;return s in n.variables||(n.variables[s]={name:s,type:t.type}),P1(s)},[he.ZD.Resolution]:()=>"u_resolution",[he.ZD.Zoom]:()=>"u_zoom",[he.ZD.Time]:()=>"u_time",[he.ZD.Any]:Ot(n=>`(${n.join(" || ")})`),[he.ZD.All]:Ot(n=>`(${n.join(" && ")})`),[he.ZD.Not]:Ot(([n])=>`(!${n})`),[he.ZD.Equal]:Ot(([n,t])=>`(${n} == ${t})`),[he.ZD.NotEqual]:Ot(([n,t])=>`(${n} != ${t})`),[he.ZD.GreaterThan]:Ot(([n,t])=>`(${n} > ${t})`),[he.ZD.GreaterThanOrEqualTo]:Ot(([n,t])=>`(${n} >= ${t})`),[he.ZD.LessThan]:Ot(([n,t])=>`(${n} < ${t})`),[he.ZD.LessThanOrEqualTo]:Ot(([n,t])=>`(${n} <= ${t})`),[he.ZD.Multiply]:Ot(n=>`(${n.join(" * ")})`),[he.ZD.Divide]:Ot(([n,t])=>`(${n} / ${t})`),[he.ZD.Add]:Ot(n=>`(${n.join(" + ")})`),[he.ZD.Subtract]:Ot(([n,t])=>`(${n} - ${t})`),[he.ZD.Clamp]:Ot(([n,t,e])=>`clamp(${n}, ${t}, ${e})`),[he.ZD.Mod]:Ot(([n,t])=>`mod(${n}, ${t})`),[he.ZD.Pow]:Ot(([n,t])=>`pow(${n}, ${t})`),[he.ZD.Abs]:Ot(([n])=>`abs(${n})`),[he.ZD.Floor]:Ot(([n])=>`floor(${n})`),[he.ZD.Ceil]:Ot(([n])=>`ceil(${n})`),[he.ZD.Round]:Ot(([n])=>`floor(${n} + 0.5)`),[he.ZD.Sin]:Ot(([n])=>`sin(${n})`),[he.ZD.Cos]:Ot(([n])=>`cos(${n})`),[he.ZD.Atan]:Ot(([n,t])=>void 0!==t?`atan(${n}, ${t})`:`atan(${n})`),[he.ZD.Sqrt]:Ot(([n])=>`sqrt(${n})`),[he.ZD.Match]:Ot(n=>{const t=n[0],e=n[n.length-1];let s=null;for(let r=n.length-3;r>=1;r-=2)s=`(${t} == ${n[r]} ? ${n[r+1]} : ${s||e})`;return s}),[he.ZD.Between]:Ot(([n,t,e])=>`(${n} >= ${t} && ${n} <= ${e})`),[he.ZD.Interpolate]:Ot(([n,t,...e])=>{let s="";for(let r=0;r{const t=n[n.length-1];let e=null;for(let s=n.length-3;s>=0;s-=2)e=`(${n[s]} ? ${n[s+1]} : ${e||t})`;return e}),[he.ZD.In]:Ot(([n,...t],e)=>{const s=function Oq(n,t){return`operator_${n}_${Object.keys(t.functions).length}`}("in",e),r=[];for(let i=0;i`vec${n.length}(${n.join(", ")})`),[he.ZD.Color]:Ot(n=>{if(1===n.length)return`vec4(vec3(${n[0]} / 255.0), 1.0)`;if(2===n.length)return`(${n[1]} * vec4(vec3(${n[0]} / 255.0), 1.0))`;const t=n.slice(0,3).map(s=>`${s} / 255.0`);return 3===n.length?`vec4(${t.join(", ")}, 1.0)`:`(${n[3]} * vec4(${t.join(", ")}, 1.0))`}),[he.ZD.Band]:Ot(([n,t,e],s)=>{if(!(kg in s.functions)){let r="";const i=s.bandCount||1;for(let a=0;a{const[e,...s]=t.args,r=s.length,i=new Uint8Array(4*r);for(let u=0;u0)return ta(n.value);if((n.type&he.T8)>0)return n.value.toString();if((n.type&he.cT)>0)return Pr(n.value.toString());if((n.type&he.mE)>0)return Kh(n.value);if((n.type&he.Fq)>0)return Cg(n.value);throw new Error(`Unexpected expression ${n.value} (expected type ${(0,he.go)(t)})`)}const qa="#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\nuniform mat4 u_projectionMatrix;\nuniform mat4 u_screenToWorldMatrix;\nuniform vec2 u_viewportSizePx;\nuniform float u_pixelRatio;\nuniform float u_globalAlpha;\nuniform float u_time;\nuniform float u_zoom;\nuniform float u_resolution;\nuniform float u_rotation;\nuniform vec4 u_renderExtent;\nuniform vec2 u_patternOrigin;\nuniform float u_depth;\nuniform mediump int u_hitDetection;\n\nconst float PI = 3.141592653589793238;\nconst float TWO_PI = 2.0 * PI;\n\n// this used to produce an alpha-premultiplied color from a texture\nvec4 samplePremultiplied(sampler2D sampler, vec2 texCoord) {\n vec4 color = texture2D(sampler, texCoord);\n return vec4(color.rgb * color.a, color.a);\n}\n",Za_fill_color="rgba(255,255,255,0.4)",Za_stroke_color="#3399CC",Za_stroke_width=1.25,Za_circle_radius=5,Za_circle_fill_color="rgba(255,255,255,0.4)",Za_circle_stroke_width=1.25;class zq{constructor(){this.uniforms_=[],this.attributes_=[],this.varyings_=[],this.hasSymbol_=!1,this.symbolSizeExpression_=`vec2(${ta(Za_circle_radius)} + ${ta(.5*Za_circle_stroke_width)})`,this.symbolRotationExpression_="0.0",this.symbolOffsetExpression_="vec2(0.0)",this.symbolColorExpression_=Kh(Za_circle_fill_color),this.texCoordExpression_="vec4(0.0, 0.0, 1.0, 1.0)",this.discardExpression_="false",this.symbolRotateWithView_=!1,this.hasStroke_=!1,this.strokeWidthExpression_=ta(Za_stroke_width),this.strokeColorExpression_=Kh(Za_stroke_color),this.strokeOffsetExpression_="0.",this.strokeCapExpression_=Pr("round"),this.strokeJoinExpression_=Pr("round"),this.strokeMiterLimitExpression_="10.",this.strokeDistanceFieldExpression_="-1000.",this.hasFill_=!1,this.fillColorExpression_=Kh(Za_fill_color),this.vertexShaderFunctions_=[],this.fragmentShaderFunctions_=[]}addUniform(t){return this.uniforms_.push(t),this}addAttribute(t){return this.attributes_.push(t),this}addVarying(t,e,s){return this.varyings_.push({name:t,type:e,expression:s}),this}setSymbolSizeExpression(t){return this.hasSymbol_=!0,this.symbolSizeExpression_=t,this}getSymbolSizeExpression(){return this.symbolSizeExpression_}setSymbolRotationExpression(t){return this.symbolRotationExpression_=t,this}setSymbolOffsetExpression(t){return this.symbolOffsetExpression_=t,this}getSymbolOffsetExpression(){return this.symbolOffsetExpression_}setSymbolColorExpression(t){return this.hasSymbol_=!0,this.symbolColorExpression_=t,this}getSymbolColorExpression(){return this.symbolColorExpression_}setTextureCoordinateExpression(t){return this.texCoordExpression_=t,this}setFragmentDiscardExpression(t){return this.discardExpression_=t,this}getFragmentDiscardExpression(){return this.discardExpression_}setSymbolRotateWithView(t){return this.symbolRotateWithView_=t,this}setStrokeWidthExpression(t){return this.hasStroke_=!0,this.strokeWidthExpression_=t,this}setStrokeColorExpression(t){return this.hasStroke_=!0,this.strokeColorExpression_=t,this}getStrokeColorExpression(){return this.strokeColorExpression_}setStrokeOffsetExpression(t){return this.strokeOffsetExpression_=t,this}setStrokeCapExpression(t){return this.strokeCapExpression_=t,this}setStrokeJoinExpression(t){return this.strokeJoinExpression_=t,this}setStrokeMiterLimitExpression(t){return this.strokeMiterLimitExpression_=t,this}setStrokeDistanceFieldExpression(t){return this.strokeDistanceFieldExpression_=t,this}setFillColorExpression(t){return this.hasFill_=!0,this.fillColorExpression_=t,this}getFillColorExpression(){return this.fillColorExpression_}addVertexShaderFunction(t){this.vertexShaderFunctions_.includes(t)||this.vertexShaderFunctions_.push(t)}addFragmentShaderFunction(t){this.fragmentShaderFunctions_.includes(t)||this.fragmentShaderFunctions_.push(t)}getSymbolVertexShader(){return this.hasSymbol_?`${qa}\n${this.uniforms_.map(function(t){return"uniform "+t+";"}).join("\n")}\nattribute vec2 a_position;\nattribute float a_index;\nattribute vec4 a_prop_hitColor;\n${this.attributes_.map(function(t){return"attribute "+t+";"}).join("\n")}\nvarying vec2 v_texCoord;\nvarying vec2 v_quadCoord;\nvarying vec4 v_prop_hitColor;\nvarying vec2 v_centerPx;\nvarying float v_angle;\nvarying vec2 v_quadSizePx;\n${this.varyings_.map(function(t){return"varying "+t.type+" "+t.name+";"}).join("\n")}\n${this.vertexShaderFunctions_.join("\n")}\nvec2 pxToScreen(vec2 coordPx) {\n vec2 scaled = coordPx / u_viewportSizePx / 0.5;\n return scaled;\n}\n\nvec2 screenToPx(vec2 coordScreen) {\n return (coordScreen * 0.5 + 0.5) * u_viewportSizePx;\n}\n\nvoid main(void) {\n v_quadSizePx = ${this.symbolSizeExpression_};\n vec2 halfSizePx = v_quadSizePx * 0.5;\n vec2 centerOffsetPx = ${this.symbolOffsetExpression_};\n vec2 offsetPx = centerOffsetPx;\n if (a_index == 0.0) {\n offsetPx -= halfSizePx;\n } else if (a_index == 1.0) {\n offsetPx += halfSizePx * vec2(1., -1.);\n } else if (a_index == 2.0) {\n offsetPx += halfSizePx;\n } else {\n offsetPx += halfSizePx * vec2(-1., 1.);\n }\n float angle = ${this.symbolRotationExpression_};\n ${this.symbolRotateWithView_?"angle += u_rotation;":""}\n float c = cos(-angle);\n float s = sin(-angle);\n offsetPx = vec2(c * offsetPx.x - s * offsetPx.y, s * offsetPx.x + c * offsetPx.y);\n vec4 center = u_projectionMatrix * vec4(a_position, 0.0, 1.0);\n gl_Position = center + vec4(pxToScreen(offsetPx), u_depth, 0.);\n vec4 texCoord = ${this.texCoordExpression_};\n float u = a_index == 0.0 || a_index == 3.0 ? texCoord.s : texCoord.p;\n float v = a_index == 2.0 || a_index == 3.0 ? texCoord.t : texCoord.q;\n v_texCoord = vec2(u, v);\n v_prop_hitColor = a_prop_hitColor;\n v_angle = angle;\n c = cos(-v_angle);\n s = sin(-v_angle);\n centerOffsetPx = vec2(c * centerOffsetPx.x - s * centerOffsetPx.y, s * centerOffsetPx.x + c * centerOffsetPx.y); \n v_centerPx = screenToPx(center.xy) + centerOffsetPx;\n${this.varyings_.map(function(t){return" "+t.name+" = "+t.expression+";"}).join("\n")}\n}`:null}getSymbolFragmentShader(){return this.hasSymbol_?`${qa}\n${this.uniforms_.map(function(t){return"uniform "+t+";"}).join("\n")}\nvarying vec2 v_texCoord;\nvarying vec4 v_prop_hitColor;\nvarying vec2 v_centerPx;\nvarying float v_angle;\nvarying vec2 v_quadSizePx;\n${this.varyings_.map(function(t){return"varying "+t.type+" "+t.name+";"}).join("\n")}\n${this.fragmentShaderFunctions_.join("\n")}\n\nvoid main(void) {\n if (${this.discardExpression_}) { discard; }\n vec2 coordsPx = gl_FragCoord.xy / u_pixelRatio - v_centerPx; // relative to center\n float c = cos(v_angle);\n float s = sin(v_angle);\n coordsPx = vec2(c * coordsPx.x - s * coordsPx.y, s * coordsPx.x + c * coordsPx.y);\n gl_FragColor = ${this.symbolColorExpression_};\n if (u_hitDetection > 0) {\n if (gl_FragColor.a < 0.05) { discard; };\n gl_FragColor = v_prop_hitColor;\n }\n}`:null}getStrokeVertexShader(){return this.hasStroke_?`${qa}\n${this.uniforms_.map(function(t){return"uniform "+t+";"}).join("\n")}\nattribute vec2 a_position;\nattribute float a_index;\nattribute vec2 a_segmentStart;\nattribute vec2 a_segmentEnd;\nattribute float a_parameters;\nattribute float a_distance;\nattribute vec2 a_joinAngles;\nattribute vec4 a_prop_hitColor;\n${this.attributes_.map(function(t){return"attribute "+t+";"}).join("\n")}\nvarying vec2 v_segmentStart;\nvarying vec2 v_segmentEnd;\nvarying float v_angleStart;\nvarying float v_angleEnd;\nvarying float v_width;\nvarying vec4 v_prop_hitColor;\nvarying float v_distanceOffsetPx;\n${this.varyings_.map(function(t){return"varying "+t.type+" "+t.name+";"}).join("\n")}\n${this.vertexShaderFunctions_.join("\n")}\nvec2 worldToPx(vec2 worldPos) {\n vec4 screenPos = u_projectionMatrix * vec4(worldPos, 0.0, 1.0);\n return (0.5 * screenPos.xy + 0.5) * u_viewportSizePx;\n}\n\nvec4 pxToScreen(vec2 pxPos) {\n vec2 screenPos = 2.0 * pxPos / u_viewportSizePx - 1.0;\n return vec4(screenPos, u_depth, 1.0);\n}\n\nbool isCap(float joinAngle) {\n return joinAngle < -0.1;\n}\n\nvec2 getJoinOffsetDirection(vec2 normalPx, float joinAngle) {\n float halfAngle = joinAngle / 2.0;\n float c = cos(halfAngle);\n float s = sin(halfAngle);\n vec2 angleBisectorNormal = vec2(s * normalPx.x + c * normalPx.y, -c * normalPx.x + s * normalPx.y);\n float length = 1.0 / s;\n return angleBisectorNormal * length;\n}\n\nvec2 getOffsetPoint(vec2 point, vec2 normal, float joinAngle, float offsetPx) {\n // if on a cap or the join angle is too high, offset the line along the segment normal\n if (cos(joinAngle) > 0.998 || isCap(joinAngle)) {\n return point - normal * offsetPx;\n }\n // offset is applied along the inverted normal (positive offset goes "right" relative to line direction)\n return point - getJoinOffsetDirection(normal, joinAngle) * offsetPx;\n}\n\nvoid main(void) {\n v_angleStart = a_joinAngles.x;\n v_angleEnd = a_joinAngles.y;\n float vertexNumber = floor(abs(a_parameters) / 10000. + 0.5);\n // we're reading the fractional part while keeping the sign (so -4.12 gives -0.12, 3.45 gives 0.45)\n float angleTangentSum = fract(abs(a_parameters) / 10000.) * 10000. * sign(a_parameters);\n\n float lineWidth = ${this.strokeWidthExpression_};\n float lineOffsetPx = ${this.strokeOffsetExpression_};\n\n // compute segment start/end in px with offset\n vec2 segmentStartPx = worldToPx(a_segmentStart);\n vec2 segmentEndPx = worldToPx(a_segmentEnd);\n vec2 tangentPx = normalize(segmentEndPx - segmentStartPx);\n vec2 normalPx = vec2(-tangentPx.y, tangentPx.x);\n segmentStartPx = getOffsetPoint(segmentStartPx, normalPx, v_angleStart, lineOffsetPx),\n segmentEndPx = getOffsetPoint(segmentEndPx, normalPx, v_angleEnd, lineOffsetPx);\n \n // compute current vertex position\n float normalDir = vertexNumber < 0.5 || (vertexNumber > 1.5 && vertexNumber < 2.5) ? 1.0 : -1.0;\n float tangentDir = vertexNumber < 1.5 ? 1.0 : -1.0;\n float angle = vertexNumber < 1.5 ? v_angleStart : v_angleEnd;\n vec2 joinDirection;\n vec2 positionPx = vertexNumber < 1.5 ? segmentStartPx : segmentEndPx;\n // if angle is too high, do not make a proper join\n if (cos(angle) > 0.985 || isCap(angle)) {\n joinDirection = normalPx * normalDir - tangentPx * tangentDir;\n } else {\n joinDirection = getJoinOffsetDirection(normalPx * normalDir, angle);\n }\n positionPx = positionPx + joinDirection * (lineWidth * 0.5 + 1.); // adding 1 pixel for antialiasing\n gl_Position = pxToScreen(positionPx);\n\n v_segmentStart = segmentStartPx;\n v_segmentEnd = segmentEndPx;\n v_width = lineWidth;\n v_prop_hitColor = a_prop_hitColor;\n v_distanceOffsetPx = a_distance / u_resolution - (lineOffsetPx * angleTangentSum);\n${this.varyings_.map(function(t){return" "+t.name+" = "+t.expression+";"}).join("\n")}\n}`:null}getStrokeFragmentShader(){return this.hasStroke_?`${qa}\n${this.uniforms_.map(function(t){return"uniform "+t+";"}).join("\n")}\nvarying vec2 v_segmentStart;\nvarying vec2 v_segmentEnd;\nvarying float v_angleStart;\nvarying float v_angleEnd;\nvarying float v_width;\nvarying vec4 v_prop_hitColor;\nvarying float v_distanceOffsetPx;\n${this.varyings_.map(function(t){return"varying "+t.type+" "+t.name+";"}).join("\n")}\n${this.fragmentShaderFunctions_.join("\n")}\n\nvec2 pxToWorld(vec2 pxPos) {\n vec2 screenPos = 2.0 * pxPos / u_viewportSizePx - 1.0;\n return (u_screenToWorldMatrix * vec4(screenPos, 0.0, 1.0)).xy;\n}\n\nbool isCap(float joinAngle) {\n return joinAngle < -0.1;\n}\n\nfloat segmentDistanceField(vec2 point, vec2 start, vec2 end, float width) {\n vec2 tangent = normalize(end - start);\n vec2 normal = vec2(-tangent.y, tangent.x);\n vec2 startToPoint = point - start;\n return abs(dot(startToPoint, normal)) - width * 0.5;\n}\n\nfloat buttCapDistanceField(vec2 point, vec2 start, vec2 end) {\n vec2 startToPoint = point - start;\n vec2 tangent = normalize(end - start);\n return dot(startToPoint, -tangent);\n}\n\nfloat squareCapDistanceField(vec2 point, vec2 start, vec2 end, float width) {\n return buttCapDistanceField(point, start, end) - width * 0.5;\n}\n\nfloat roundCapDistanceField(vec2 point, vec2 start, vec2 end, float width) {\n float onSegment = max(0., 1000. * dot(point - start, end - start)); // this is very high when inside the segment\n return length(point - start) - width * 0.5 - onSegment;\n}\n\nfloat roundJoinDistanceField(vec2 point, vec2 start, vec2 end, float width) {\n return roundCapDistanceField(point, start, end, width);\n}\n\nfloat bevelJoinField(vec2 point, vec2 start, vec2 end, float width, float joinAngle) {\n vec2 startToPoint = point - start;\n vec2 tangent = normalize(end - start);\n float c = cos(joinAngle * 0.5);\n float s = sin(joinAngle * 0.5);\n float direction = -sign(sin(joinAngle));\n vec2 bisector = vec2(c * tangent.x - s * tangent.y, s * tangent.x + c * tangent.y);\n float radius = width * 0.5 * s;\n return dot(startToPoint, bisector * direction) - radius;\n}\n\nfloat miterJoinDistanceField(vec2 point, vec2 start, vec2 end, float width, float joinAngle) {\n if (cos(joinAngle) > 0.985) { // avoid risking a division by zero\n return bevelJoinField(point, start, end, width, joinAngle);\n }\n float miterLength = 1. / sin(joinAngle * 0.5);\n float miterLimit = ${this.strokeMiterLimitExpression_};\n if (miterLength > miterLimit) {\n return bevelJoinField(point, start, end, width, joinAngle);\n }\n return -1000.;\n}\n\nfloat capDistanceField(vec2 point, vec2 start, vec2 end, float width, float capType) {\n if (capType == ${Pr("butt")}) {\n return buttCapDistanceField(point, start, end);\n } else if (capType == ${Pr("square")}) {\n return squareCapDistanceField(point, start, end, width);\n }\n return roundCapDistanceField(point, start, end, width);\n}\n\nfloat joinDistanceField(vec2 point, vec2 start, vec2 end, float width, float joinAngle, float joinType) {\n if (joinType == ${Pr("bevel")}) {\n return bevelJoinField(point, start, end, width, joinAngle);\n } else if (joinType == ${Pr("miter")}) {\n return miterJoinDistanceField(point, start, end, width, joinAngle);\n }\n return roundJoinDistanceField(point, start, end, width);\n}\n\nfloat computeSegmentPointDistance(vec2 point, vec2 start, vec2 end, float width, float joinAngle, float capType, float joinType) {\n if (isCap(joinAngle)) {\n return capDistanceField(point, start, end, width, capType);\n }\n return joinDistanceField(point, start, end, width, joinAngle, joinType);\n}\n\nvoid main(void) {\n vec2 currentPoint = gl_FragCoord.xy / u_pixelRatio;\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n vec2 worldPos = pxToWorld(currentPoint);\n if (\n abs(u_renderExtent[0] - u_renderExtent[2]) > 0.0 && (\n worldPos[0] < u_renderExtent[0] ||\n worldPos[1] < u_renderExtent[1] ||\n worldPos[0] > u_renderExtent[2] ||\n worldPos[1] > u_renderExtent[3]\n )\n ) {\n discard;\n }\n #endif\n if (${this.discardExpression_}) { discard; }\n\n float segmentLength = length(v_segmentEnd - v_segmentStart);\n vec2 segmentTangent = (v_segmentEnd - v_segmentStart) / segmentLength;\n vec2 segmentNormal = vec2(-segmentTangent.y, segmentTangent.x);\n vec2 startToPoint = currentPoint - v_segmentStart;\n float currentLengthPx = max(0., min(dot(segmentTangent, startToPoint), segmentLength)) + v_distanceOffsetPx; \n float currentRadiusPx = abs(dot(segmentNormal, startToPoint));\n float currentRadiusRatio = dot(segmentNormal, startToPoint) * 2. / v_width;\n vec4 color = ${this.strokeColorExpression_} * u_globalAlpha;\n float capType = ${this.strokeCapExpression_};\n float joinType = ${this.strokeJoinExpression_};\n float segmentStartDistance = computeSegmentPointDistance(currentPoint, v_segmentStart, v_segmentEnd, v_width, v_angleStart, capType, joinType);\n float segmentEndDistance = computeSegmentPointDistance(currentPoint, v_segmentEnd, v_segmentStart, v_width, v_angleEnd, capType, joinType);\n float distance = max(\n segmentDistanceField(currentPoint, v_segmentStart, v_segmentEnd, v_width),\n max(segmentStartDistance, segmentEndDistance)\n );\n distance = max(distance, ${this.strokeDistanceFieldExpression_});\n gl_FragColor = color * smoothstep(0.5, -0.5, distance);\n if (u_hitDetection > 0) {\n if (gl_FragColor.a < 0.1) { discard; };\n gl_FragColor = v_prop_hitColor;\n }\n}`:null}getFillVertexShader(){return this.hasFill_?`${qa}\n${this.uniforms_.map(function(t){return"uniform "+t+";"}).join("\n")}\nattribute vec2 a_position;\nattribute vec4 a_prop_hitColor;\n${this.attributes_.map(function(t){return"attribute "+t+";"}).join("\n")}\nvarying vec4 v_prop_hitColor;\n${this.varyings_.map(function(t){return"varying "+t.type+" "+t.name+";"}).join("\n")}\n${this.vertexShaderFunctions_.join("\n")}\nvoid main(void) {\n gl_Position = u_projectionMatrix * vec4(a_position, u_depth, 1.0);\n v_prop_hitColor = a_prop_hitColor;\n${this.varyings_.map(function(t){return" "+t.name+" = "+t.expression+";"}).join("\n")}\n}`:null}getFillFragmentShader(){return this.hasFill_?`${qa}\n${this.uniforms_.map(function(t){return"uniform "+t+";"}).join("\n")}\nvarying vec4 v_prop_hitColor;\n${this.varyings_.map(function(t){return"varying "+t.type+" "+t.name+";"}).join("\n")}\n${this.fragmentShaderFunctions_.join("\n")}\nvec2 pxToWorld(vec2 pxPos) {\n vec2 screenPos = 2.0 * pxPos / u_viewportSizePx - 1.0;\n return (u_screenToWorldMatrix * vec4(screenPos, 0.0, 1.0)).xy;\n}\n\nvec2 worldToPx(vec2 worldPos) {\n vec4 screenPos = u_projectionMatrix * vec4(worldPos, 0.0, 1.0);\n return (0.5 * screenPos.xy + 0.5) * u_viewportSizePx;\n}\n\nvoid main(void) {\n vec2 pxPos = gl_FragCoord.xy / u_pixelRatio;\n vec2 pxOrigin = worldToPx(u_patternOrigin);\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n vec2 worldPos = pxToWorld(pxPos);\n if (\n abs(u_renderExtent[0] - u_renderExtent[2]) > 0.0 && (\n worldPos[0] < u_renderExtent[0] ||\n worldPos[1] < u_renderExtent[1] ||\n worldPos[0] > u_renderExtent[2] ||\n worldPos[1] > u_renderExtent[3]\n )\n ) {\n discard;\n }\n #endif\n if (${this.discardExpression_}) { discard; }\n gl_FragColor = ${this.fillColorExpression_} * u_globalAlpha;\n if (u_hitDetection > 0) {\n if (gl_FragColor.a < 0.1) { discard; };\n gl_FragColor = v_prop_hitColor;\n }\n}`:null}}function ft(n,t,e){const s=(0,he.SR)();return s.style=n.style,function Lq(n,t,e,s){const r=(0,he.qg)(n,e,t);if((0,he.Xj)(r.type,he.j))throw new Error("No matching type was found");if(!(0,he.ho)(t,r.type)){const i=(0,he.go)(t),a=(0,he.go)(r.type);throw new Error(`Expected expression to be of type ${i}, got ${a}`)}return Ng(r,t,s)}(t,e,s,n)}function F1(n){const t=(0,Ul._j)(n);return[256*t[0]+t[1],256*t[2]+Math.round(255*t[3])]}function L1(n){return n===he.mE?2:n===he.Fq?4:1}function Ag(n){const t=L1(n);return t>1?`vec${t}`:"float"}function qh(n){return(JSON.stringify(n).split("").reduce((e,s)=>(e<<5)-e+s.charCodeAt(0),0)>>>0).toString()}function Rg(n,t,e,s){if(`${s}radius`in n&&"icon-"!==s){let r=ft(e,n[`${s}radius`],he.wl);`${s}radius2`in n&&(r=`max(${r}, ${ft(e,n[`${s}radius2`],he.wl)})`),`${s}stroke-width`in n&&(r=`(${r} + ${ft(e,n[`${s}stroke-width`],he.wl)} * 0.5)`),t.setSymbolSizeExpression(`vec2(${r} * 2. + 0.5)`)}if(`${s}scale`in n){const r=ft(e,n[`${s}scale`],he.wl|he.Fq);t.setSymbolSizeExpression(`${t.getSymbolSizeExpression()} * ${r}`)}`${s}displacement`in n&&t.setSymbolOffsetExpression(ft(e,n[`${s}displacement`],he.Fq)),`${s}rotation`in n&&t.setSymbolRotationExpression(ft(e,n[`${s}rotation`],he.wl)),`${s}rotate-with-view`in n&&t.setSymbolRotateWithView(!!n[`${s}rotate-with-view`])}function M1(n,t,e,s,r){let i="vec4(0.)";null!==t&&(i=t),null!==e&&null!==s&&(i=`mix(${e}, ${i}, smoothstep(-${s} + 0.63, -${s} - 0.58, ${n}))`);let o=`${i} * (1.0 - smoothstep(-0.63, 0.58, ${n}))`;return null!==r&&(o=`${o} * ${r}`),o}function $g(n,t,e,s,r){const i=new Image;let a;return i.crossOrigin=void 0===n[`${s}cross-origin`]?"anonymous":n[`${s}cross-origin`],i.src=n[`${s}src`],i.complete&&i.width&&i.height?a=Cg([i.width,i.height]):(e[`u_texture${r}_size`]=()=>i.complete?[i.width,i.height]:[0,0],t.addUniform(`vec2 u_texture${r}_size`),a=`u_texture${r}_size`),e[`u_texture${r}`]=i,t.addUniform(`sampler2D u_texture${r}`),a}function Dg(n,t,e,s,r){let i=ft(e,n[`${t}offset`],he.Fq);if(`${t}offset-origin`in n)switch(n[`${t}offset-origin`]){case"top-right":i=`vec2(${s}.x, 0.) + ${r} * vec2(-1., 0.) + ${i} * vec2(-1., 1.)`;break;case"bottom-left":i=`vec2(0., ${s}.y) + ${r} * vec2(0., -1.) + ${i} * vec2(1., -1.)`;break;case"bottom-right":i=`${s} - ${r} - ${i}`}return i}const qq=class Kq extends h1.A{constructor(t){super(Object.assign({},t)),this.parseResult_=function Xq(n){const t={inFragmentShader:!1,properties:{},variables:{},functions:{},style:n},e={inFragmentShader:!0,variables:t.variables,properties:{},functions:{},style:n},s=new zq,r={};if("icon-src"in n?function Gq(n,t,e,s,r){let i="vec4(1.0)";"icon-color"in n&&(i=ft(r,n["icon-color"],he.mE)),"icon-opacity"in n&&(i=`${i} * ${ft(r,n["icon-opacity"],he.wl)}`);const a=qh(n["icon-src"]),o=$g(n,t,e,"icon-",a);if(t.setSymbolColorExpression(`${i} * samplePremultiplied(u_texture${a}, v_texCoord)`).setSymbolSizeExpression(o),"icon-width"in n&&"icon-height"in n&&t.setSymbolSizeExpression(`vec2(${ft(s,n["icon-width"],he.wl)}, ${ft(s,n["icon-height"],he.wl)})`),"icon-offset"in n&&"icon-size"in n){const l=ft(s,n["icon-size"],he.Fq),u=t.getSymbolSizeExpression();t.setSymbolSizeExpression(l);const c=Dg(n,"icon-",s,"v_quadSizePx",l);t.setTextureCoordinateExpression(`(vec4((${c}).xyxy) + vec4(0., 0., ${l})) / (${u}).xyxy`)}if(Rg(n,t,s,"icon-"),"icon-anchor"in n){const l=ft(s,n["icon-anchor"],he.Fq);let c,u="1.0";"icon-scale"in n&&(u=ft(s,n["icon-scale"],he.wl|he.Fq)),c="pixels"===n["icon-anchor-x-units"]&&"pixels"===n["icon-anchor-y-units"]?`${l} * ${u}`:"pixels"===n["icon-anchor-x-units"]?`${l} * vec2(vec2(${u}).x, v_quadSizePx.y)`:"pixels"===n["icon-anchor-y-units"]?`${l} * vec2(v_quadSizePx.x, vec2(${u}).x)`:`${l} * v_quadSizePx`;let h=`v_quadSizePx * vec2(0.5, -0.5) + ${c} * vec2(-1., 1.)`;if("icon-anchor-origin"in n)switch(n["icon-anchor-origin"]){case"top-right":h=`v_quadSizePx * -0.5 + ${c}`;break;case"bottom-left":h=`v_quadSizePx * 0.5 - ${c}`;break;case"bottom-right":h=`v_quadSizePx * vec2(-0.5, 0.5) + ${c} * vec2(1., -1.)`}t.setSymbolOffsetExpression(`${t.getSymbolOffsetExpression()} + ${h}`)}}(n,s,r,t,e):"shape-points"in n?function Wq(n,t,e,s,r){r.functions.round="float round(float v) {\n return sign(v) * floor(abs(v) + 0.5);\n}",r.functions.starDistanceField="float starDistanceField(vec2 point, float numPoints, float radius, float radius2, float angle) {\n float startAngle = -PI * 0.5 + angle; // tip starts upwards and rotates clockwise with angle\n float c = cos(startAngle);\n float s = sin(startAngle);\n vec2 pointRotated = vec2(c * point.x - s * point.y, s * point.x + c * point.y);\n float alpha = TWO_PI / numPoints; // the angle of one sector\n float beta = atan(pointRotated.y, pointRotated.x);\n float gamma = round(beta / alpha) * alpha; // angle in sector\n c = cos(-gamma);\n s = sin(-gamma);\n vec2 inSector = vec2(c * pointRotated.x - s * pointRotated.y, abs(s * pointRotated.x + c * pointRotated.y));\n vec2 tipToPoint = inSector + vec2(-radius, 0.);\n vec2 edgeNormal = vec2(radius2 * sin(alpha * 0.5), -radius2 * cos(alpha * 0.5) + radius);\n return dot(normalize(edgeNormal), tipToPoint);\n}",r.functions.regularDistanceField="float regularDistanceField(vec2 point, float numPoints, float radius, float angle) {\n float startAngle = -PI * 0.5 + angle; // tip starts upwards and rotates clockwise with angle\n float c = cos(startAngle);\n float s = sin(startAngle);\n vec2 pointRotated = vec2(c * point.x - s * point.y, s * point.x + c * point.y);\n float alpha = TWO_PI / numPoints; // the angle of one sector\n float radiusIn = radius * cos(PI / numPoints);\n float beta = atan(pointRotated.y, pointRotated.x);\n float gamma = round((beta - alpha * 0.5) / alpha) * alpha + alpha * 0.5; // angle in sector from mid\n c = cos(-gamma);\n s = sin(-gamma);\n vec2 inSector = vec2(c * pointRotated.x - s * pointRotated.y, abs(s * pointRotated.x + c * pointRotated.y));\n return inSector.x - radiusIn;\n}",Rg(n,t,s,"shape-");let i=null;"shape-opacity"in n&&(i=ft(r,n["shape-opacity"],he.wl));let a="coordsPx";"shape-scale"in n&&(a=`coordsPx / ${ft(r,n["shape-scale"],he.wl|he.Fq)}`);let o=null;"shape-fill-color"in n&&(o=ft(r,n["shape-fill-color"],he.mE));let l=null;"shape-stroke-color"in n&&(l=ft(r,n["shape-stroke-color"],he.mE));let u=null;"shape-stroke-width"in n&&(u=ft(r,n["shape-stroke-width"],he.wl));const c=ft(r,n["shape-points"],he.wl);let h="0.";"shape-angle"in n&&(h=ft(r,n["shape-angle"],he.wl));let d,p=ft(r,n["shape-radius"],he.wl);if(null!==u&&(p=`${p} + ${u} * 0.5`),"shape-radius2"in n){let g=ft(r,n["shape-radius2"],he.wl);null!==u&&(g=`${g} + ${u} * 0.5`),d=`starDistanceField(${a}, ${c}, ${p}, ${g}, ${h})`}else d=`regularDistanceField(${a}, ${c}, ${p}, ${h})`;const f=M1(d,o,l,u,i);t.setSymbolColorExpression(f)}(n,s,0,t,e):"circle-radius"in n&&function Uq(n,t,e,s,r){r.functions.circleDistanceField="float circleDistanceField(vec2 point, float radius) {\n return length(point) - radius;\n}",Rg(n,t,s,"circle-");let i=null;"circle-opacity"in n&&(i=ft(r,n["circle-opacity"],he.wl));let a="coordsPx";"circle-scale"in n&&(a=`coordsPx / ${ft(r,n["circle-scale"],he.wl|he.Fq)}`);let o=null;"circle-fill-color"in n&&(o=ft(r,n["circle-fill-color"],he.mE));let l=null;"circle-stroke-color"in n&&(l=ft(r,n["circle-stroke-color"],he.mE));let u=ft(r,n["circle-radius"],he.wl),c=null;"circle-stroke-width"in n&&(c=ft(r,n["circle-stroke-width"],he.wl),u=`(${u} + ${c} * 0.5)`);const d=M1(`circleDistanceField(${a}, ${u})`,o,l,c,i);t.setSymbolColorExpression(d)}(n,s,0,t,e),function Hq(n,t,e,s,r){if("stroke-color"in n&&t.setStrokeColorExpression(ft(r,n["stroke-color"],he.mE)),"stroke-pattern-src"in n){const i=qh(n["stroke-pattern-src"]),a=$g(n,t,e,"stroke-pattern-",i);let o=a,l="vec2(0.)";"stroke-pattern-offset"in n&&"stroke-pattern-size"in n&&(o=ft(r,n["stroke-pattern-size"],he.Fq),l=Dg(n,"stroke-pattern-",r,a,o));let u="0.";"stroke-pattern-spacing"in n&&(u=ft(r,n["stroke-pattern-spacing"],he.wl)),r.functions.sampleStrokePattern="vec4 sampleStrokePattern(sampler2D texture, vec2 textureSize, vec2 textureOffset, vec2 sampleSize, float spacingPx, float currentLengthPx, float currentRadiusRatio, float lineWidth) {\n float currentLengthScaled = currentLengthPx * sampleSize.y / lineWidth;\n float spacingScaled = spacingPx * sampleSize.y / lineWidth;\n float uCoordPx = mod(currentLengthScaled, (sampleSize.x + spacingScaled));\n // make sure that we're not sampling too close to the borders to avoid interpolation with outside pixels\n uCoordPx = clamp(uCoordPx, 0.5, sampleSize.x - 0.5);\n float vCoordPx = (-currentRadiusRatio * 0.5 + 0.5) * sampleSize.y;\n vec2 texCoord = (vec2(uCoordPx, vCoordPx) + textureOffset) / textureSize;\n return samplePremultiplied(texture, texCoord);\n}";const c=`u_texture${i}`;let h="1.";"stroke-color"in n&&(h=t.getStrokeColorExpression()),t.setStrokeColorExpression(`${h} * sampleStrokePattern(${c}, ${a}, ${l}, ${o}, ${u}, currentLengthPx, currentRadiusRatio, v_width)`)}if("stroke-width"in n&&t.setStrokeWidthExpression(ft(s,n["stroke-width"],he.wl)),"stroke-offset"in n&&t.setStrokeOffsetExpression(ft(s,n["stroke-offset"],he.wl)),"stroke-line-cap"in n&&t.setStrokeCapExpression(ft(s,n["stroke-line-cap"],he.cT)),"stroke-line-join"in n&&t.setStrokeJoinExpression(ft(s,n["stroke-line-join"],he.cT)),"stroke-miter-limit"in n&&t.setStrokeMiterLimitExpression(ft(s,n["stroke-miter-limit"],he.wl)),"stroke-line-dash"in n){r.functions.getSingleDashDistance=`float getSingleDashDistance(float distance, float radius, float dashOffset, float dashLength, float dashLengthTotal, float capType) {\n float localDistance = mod(distance, dashLengthTotal);\n float distanceSegment = abs(localDistance - dashOffset - dashLength * 0.5) - dashLength * 0.5;\n distanceSegment = min(distanceSegment, dashLengthTotal - localDistance);\n if (capType == ${Pr("square")}) {\n distanceSegment -= v_width * 0.5;\n } else if (capType == ${Pr("round")}) {\n distanceSegment = min(distanceSegment, sqrt(distanceSegment * distanceSegment + radius * radius) - v_width * 0.5);\n }\n return distanceSegment;\n}`;let i=n["stroke-line-dash"].map(p=>ft(r,p,he.wl));i.length%2==1&&(i=[...i,...i]);let a="0.";"stroke-line-dash-offset"in n&&(a=ft(s,n["stroke-line-dash-offset"],he.wl));const l=`dashDistanceField_${qh(n["stroke-line-dash"])}`,u=i.map((p,f)=>`float dashLength${f} = ${p};`),c=i.map((p,f)=>`dashLength${f}`).join(" + ");let h="0.",d=`getSingleDashDistance(distance, radius, ${h}, dashLength0, totalDashLength, capType)`;for(let p=2;pEg(n.variables[o.name]):o.type===he.mE?()=>F1([...(0,Ul._j)(n.variables[o.name]||"#eee")]):o.type===he.T8?()=>n.variables[o.name]?1:0:()=>n.variables[o.name],r[l]=u}),Object.keys(e.properties).forEach(function(a){const o=e.properties[a];t.properties[a]||(t.properties[a]=o);let l=Ag(o.type),u=`a_prop_${o.name}`;o.type===he.mE&&(l="vec4",u=`unpackColor(${u})`,s.addVertexShaderFunction("vec4 unpackColor(vec2 packedColor) {\n return fract(packedColor[1] / 256.0) * vec4(\n fract(floor(packedColor[0] / 256.0) / 256.0),\n fract(packedColor[0] / 256.0),\n fract(floor(packedColor[1] / 256.0) / 256.0),\n 1.0\n );\n}")),s.addVarying(`v_prop_${o.name}`,l,u)}),Object.keys(t.properties).forEach(function(a){const o=t.properties[a];s.addAttribute(`${Ag(o.type)} a_prop_${o.name}`)});const i=Object.keys(t.properties).map(function(a){const o=t.properties[a];let l;return l=o.evaluator?o.evaluator:o.type===he.cT?u=>Eg(u.get(o.name)):o.type===he.mE?u=>F1([...(0,Ul._j)(u.get(o.name)||"#eee")]):o.type===he.T8?u=>u.get(o.name)?1:0:u=>u.get(o.name),{name:o.name,size:L1(o.type),callback:l}});for(const a in t.functions)s.addVertexShaderFunction(t.functions[a]);for(const a in e.functions)s.addFragmentShaderFunction(e.functions[a]);return{builder:s,attributes:i.reduce((a,o)=>({...a,[o.name]:{callback:o.callback,size:o.size}}),{}),uniforms:r}}(t.style),this.styleVariables_=t.style.variables||{},this.hitDetectionDisabled_=!!t.disableHitDetection}createRenderer(){const t=Object.keys(this.parseResult_.attributes).map(e=>({name:e,...this.parseResult_.attributes[e]}));return new uq(this,{vertexShader:this.parseResult_.builder.getSymbolVertexShader(),fragmentShader:this.parseResult_.builder.getSymbolFragmentShader(),hitDetectionEnabled:!this.hitDetectionDisabled_,uniforms:this.parseResult_.uniforms,attributes:t})}updateStyleVariables(t){Object.assign(this.styleVariables_,t),this.changed()}};var Zq=W(5862),Yq=W(2723),Qq=W(1413),Jq=W(3726),e8=W(152),Wl=W(4438),t8=W(1626),n8=W(6372),s8=W(5416),r8=W(3738);var Ms=function(n){return n[n.OutlierTissueDetector=0]="OutlierTissueDetector",n[n.SimilarTissueWithLinearProbe=1]="SimilarTissueWithLinearProbe",n}(Ms||{});function Yh(n,t){const e=n.byteLength/Float32Array.BYTES_PER_ELEMENT;if(e%t!=0)throw new Error("Data length is not a multiple of EMBEDDING_SIZE");return Array.from({length:e/t},(r,i)=>new Float32Array(n,i*t*Float32Array.BYTES_PER_ELEMENT,t))}let i8=(()=>{class n{constructor(e,s,r,i){this.http=e,this.imageViewerPageStore=s,this.snackBar=r,this.dicomwebService=i,this.patchSize=224,this.pixelWidth=1,this.pointLayer=void 0,this.olMap=void 0,this.slideInfo=void 0,this.pointFeatures=new Map,this.slideDescriptor=void 0,this.normalTissueEmbeddings=[],this.normalTissueEmbeddingsElementStd=[],this.tissueMask=[],this.activatePolygonToolSubject=new Qq.B,this.activatePolygonTool$=this.activatePolygonToolSubject.asObservable(),this.layerStyle={"shape-radius":4,"shape-points":["case",["==",["get","weight"],-1],3,6],"shape-fill-color":["case",["==",["get","weight"],-1],"#000000",["interpolate",["linear"],["get","weight"],["var","minWindowLevel"],"#0000ff",["/",["+",["var","minWindowLevel"],["var","minWindowLevel"],["var","maxWindowLevel"]],3],"#00ffff",["/",["+",["var","minWindowLevel"],["var","maxWindowLevel"],["var","maxWindowLevel"]],3],"#ffff00",["var","maxWindowLevel"],"#ff0000"]],"shape-stroke-color":["case",["==",["get","weight"],100],"#000000","rgba(0, 0, 0, 0)"],"shape-stroke-width":["case",["==",["get","weight"],100],2,0],variables:{minWindowLevel:0,maxWindowLevel:50,scale:1}},this.token="",this.serverUrl="",this.tissueMaskPixelWidth=1,this.minWindowLevel=20,this.maxWindowLevel=30,this.classifier=void 0,this.svgContainer=document.createElement("div"),this.svgResolution=1,this.demoType=Ms.OutlierTissueDetector,this.http.get("/assets/config.json",{responseType:"text"}).pipe((0,Ce.M)(a=>{const o=JSON.parse(a);this.token=o.apiKey,this.serverUrl=o?.serverUrl??"/",this.serverUrl.startsWith("/")&&(this.serverUrl=location.origin+this.serverUrl),console.log("Loaded config",this.serverUrl)}),(0,q.W)(a=>{throw console.error("Error loading config:",a),new Error("Failed to load config")}),(0,de.Z)(()=>this.http.get(`${this.serverUrl}/assets/base_centroids_500_v3.bin`,{headers:{Accept:"application/octet-stream"},responseType:"arraybuffer"})),(0,Ce.M)(a=>{this.normalTissueEmbeddings=Yh(a,384),console.log("Loaded normal tissue embeddings. Count:",this.normalTissueEmbeddings.length)}),(0,de.Z)(()=>this.http.get(`${this.serverUrl}/assets/cluster_sd_500_v3.bin`,{headers:{Accept:"application/octet-stream"},responseType:"arraybuffer"})),(0,Ce.M)(a=>{this.normalTissueEmbeddingsElementStd=Yh(a,384),console.log("Loaded normal tissue embeddings srd. Count:",this.normalTissueEmbeddingsElementStd.length)}),(0,de.Z)(()=>this.http.get(`${this.serverUrl}/assets/background_centroids_500_v3.bin`,{headers:{Accept:"application/octet-stream"},responseType:"arraybuffer"})),(0,Ce.M)(a=>{this.normalTissueEmbeddings.push(...Yh(a,384)),console.log("Loaded normal tissue embeddings. Count:",this.normalTissueEmbeddings.length)}),(0,de.Z)(()=>this.http.get(`${this.serverUrl}/assets/background_cluster_sd_500_v3.bin`,{headers:{Accept:"application/octet-stream"},responseType:"arraybuffer"})),(0,Ce.M)(a=>{this.normalTissueEmbeddingsElementStd.push(...Yh(a,384)),console.log("Loaded normal tissue embeddings srd. Count:",this.normalTissueEmbeddingsElementStd.length)}),(0,q.W)(a=>(console.error("Error loading embeddings:",a),this.showText("Failed to load normaltissue embeddings"),(0,nt.of)(void 0)))).subscribe()}setup(e){console.log("setup",e),void 0!==e&&(this.demoType=e),this.olMap||(this.setupOlMap(),this.setupSlideInfo()),this.pointFeatures.clear(),this.updatePointLayer(!0)}setupSlideInfo(){(0,Xe.z)([this.imageViewerPageStore.selectedSplitViewSlideDescriptor$,this.imageViewerPageStore.slideInfoBySlideDescriptorId$]).pipe((0,Ce.M)(([e,s])=>{if(!e||!s||(this.slideInfo=s.get(e.id),!this.slideInfo))return;this.pixelWidth=(this.slideInfo?.levelMap?.[0]?.pixelWidth??1e3)/1e3,this.patchSize=224*this.pixelWidth;const r=this.slideInfo?.levelMap[this.slideInfo.levelMap.length-1];r?.pixelWidth&&(this.tissueMaskPixelWidth=r.pixelWidth/1e3,this.dicomwebService.getEncodedImageTile(e.id,r.properties[0].instanceUid,1).pipe((0,de.Z)(i=>function RK(n){return new et.c(t=>{const e=new Image;e.onload=()=>{try{const s=document.createElement("canvas");s.width=e.width,s.height=e.height;const r=s.getContext("2d");if(!r)return void t.error(new Error("Could not get 2D context from canvas"));r.drawImage(e,0,0),t.next(r.getImageData(0,0,e.width,e.height)),t.complete()}catch(s){t.error(s)}},e.onerror=s=>t.error(s),e.src=`data:image/png;base64,${n}`})}(i)),(0,Ce.M)(i=>{const a=i.data,o=i.width,l=i.height;for(let u=0;u10}}})).subscribe())})).subscribe()}setupOlMap(){(0,Xe.z)([this.imageViewerPageStore.selectedSplitViewSlideDescriptor$,this.imageViewerPageStore.olMapBySlideDescriptorId$,this.imageViewerPageStore.slideInfoBySlideDescriptorId$]).pipe((0,Ce.M)(([e,s,r])=>{const i=s.get(e?.id);this.slideDescriptor=e,this.slideInfo=r.get(e?.id),this.olMap=i,this.olMap&&this.setupWebGlPointLayer()})).subscribe()}setupWebGlPointLayer(){if(!this.olMap)return;this.pointLayer&&(this.olMap.removeLayer(this.pointLayer),this.pointLayer=void 0);const e=new Zq.A({wrapX:!1}),s=new qq({className:"point-layer",source:e,style:this.layerStyle});s.set("name","point-layer"),this.olMap.addLayer(s),this.pointLayer=s,this.layerStyle.variables.scale=this.pixelWidth/(this.olMap.getView().getResolution()??1),this.pointFeatures.clear(),this.slideDescriptor?.id.includes("studies/1.3.6.1.4.1.11129.5.7.999.186491099540.49863605.1739421115085495/series/1.3.6.1.4.1.11129.5.7.0.1.483053107310.39424756.1739422414030669")&&this.http.get(`assets/studies_1.3.6.1.4.1.11129.5.7.999.186491099540.49863605.1739421115085495_series_1.3.6.1.4.1.11129.5.7.0.1.483053107310.39424756.1739422414030669_annotation_${this.demoType===Ms.SimilarTissueWithLinearProbe?"classifier":"outlier"}.svg`,{responseType:"text"}).pipe((0,_e.p)(a=>void 0!==a),(0,Ce.M)(a=>{const o=this.olMap.getLayers().getArray().find(h=>"svg-layer"===h.get("name"));o&&this.olMap.removeLayer(o);const l=this.slideInfo.size.x,u=this.slideInfo.size.y;this.svgContainer.innerHTML=a,this.svgContainer.style.position="absolute",this.svgContainer.style.left="0",this.svgContainer.style.top="0",this.svgContainer.style.minWidth=this.slideInfo?.size.x.toString()??"100%",this.svgContainer.style.minHeight=this.slideInfo?.size.y.toString()??"100%",this.svgContainer.style.pointerEvents="none",this.svgContainer.style.transformOrigin="top left",this.svgContainer.style.opacity="1";const c=this.svgContainer.querySelector("svg");if(c){c.style.width=l.toString(),c.style.height=u.toString(),console.log({width:l,height:u});const h=new h1.A({render:d=>{const p=this.pixelWidth/d.viewState.resolution,f=d.viewState.center,g=d.size,m=(0,gn.MY)(g[0]/2,g[1]/2,p,p,d.viewState.rotation,-f[0]/this.pixelWidth,f[1]/this.pixelWidth);return this.svgContainer.style.transform=m,this.svgContainer}});h.set("name","svg-layer"),this.olMap.addLayer(h)}})).subscribe();const r=this.olMap?.getView();r&&(0,Jq.R)(r,"change:resolution").pipe((0,e8.B)(200)).subscribe(()=>{const a=r.getResolution();if(void 0!==a){const o=this.pixelWidth/a;this.layerStyle.variables.scale=o<.6?o:1.2-o}});const i=document.querySelector("image-viewer-side-nav");i&&(i.style.display=this.demoType===Ms.OutlierTissueDetector?"none":"")}selectPolygonTool(){this.activatePolygonToolSubject.next()}toggleGuidance(){this.svgContainer.style.display="none"===this.svgContainer.style.display?"":"none"}setWindow(e,s){this.minWindowLevel=e*(this.demoType===Ms.OutlierTissueDetector?40:1),this.maxWindowLevel=s*(this.demoType===Ms.OutlierTissueDetector?40:1),this.olMap&&(this.layerStyle.variables.maxWindowLevel=this.maxWindowLevel,this.layerStyle.variables.minWindowLevel=this.minWindowLevel,this.olMap.render(),console.log("windowLevel=",this.minWindowLevel,this.maxWindowLevel))}toPixels(e){return[e[0]/this.pixelWidth,-e[1]/this.pixelWidth]}toMM(e){return[e[0]*this.pixelWidth,-e[1]*this.pixelWidth]}isTissue(e){const s=e[0]/this.tissueMaskPixelWidth-.5,r=-e[1]/this.tissueMaskPixelWidth-.5,i=Math.floor(s),a=Math.ceil(s),o=Math.floor(r),l=Math.ceil(r);if(o<0||l>=this.tissueMask.length||i<0||a>=this.tissueMask[0].length)return this.tissueMask[Math.round(r)][Math.round(s)];const p=s-i,f=r-o;return(1-p)*((1-f)*(this.tissueMask[o][i]?1:0)+f*(this.tissueMask[l][i]?1:0))+p*((1-f)*(this.tissueMask[o][a]?1:0)+f*(this.tissueMask[l][a]?1:0))>=.5}setTargetPolygon(){if(!this.olMap||!this.slideDescriptor)return;const e=this.getTargetFeature()?.getGeometry()?.getCoordinates();if(!e)return void this.showText("Select a polygon to identify target region, then click button.");this.pointLayer?.getSource()?.clear(),this.pointFeatures.clear();const s=u1(e[0],this.patchSize/4);for(const r of s){const i=new Fh.A({geometry:new Lh.A(r)});i.set("weight",-1),this.insertFeature(i)}this.showText(`Computing ${s.length} embeddings for target region. Please wait...`),this.getEmbeddings(s).pipe((0,ue.T)((r,i)=>[...r,...i],[]),(0,de.Z)(r=>{const i=r.map(a=>a.embedding_vector);for(const a of r){const o=new Fh.A({geometry:new Lh.A([a.patch_coordinate.x_origin,a.patch_coordinate.y_origin])});o.set("weight",100),this.insertFeature(o)}return this.updatePointLayer(),this.showText("Classifier training started, please wait..."),function $K(n,t){const e=n[0].length;return new Promise((s,r)=>{const i=n.length,a=t.length,o=i+a,l=Qr([...n,...t].map(h=>Array.from(h)),[o,e]),u=Un([...Array(i).fill(1),...Array(a).fill(0)],"int32"),c=function zD(n){return new I0(n)}();c.add(Bv({units:64,activation:"relu",inputShape:[e]})),c.add(Bv({units:1,activation:"sigmoid"})),c.compile({optimizer:"adam",loss:"binaryCrossentropy",metrics:["accuracy"]}),c.fit(l,u,{epochs:10,batchSize:32,callbacks:{onEpochEnd:(h,d)=>{console.log(`Epoch ${h+1}: Loss = ${d?.loss?.toFixed(4)}, Accuracy = ${d?.acc?.toFixed(4)}`)}}}).then(h=>{console.log("Training complete:",h.history),s(c)}).catch(h=>{console.error("Error training model:",h),r(h)})})}(i,this.normalTissueEmbeddings)}),(0,Ce.M)((r,i)=>{if(this.classifier=r,i){const a=i.history.accuracy,o=i.history.loss,l=a.reduce((d,p)=>d+p,0)/a.length,u=a[a.length-1],c=o.reduce((d,p)=>d+p,0)/o.length,h=o[o.length-1];this.showText(`Classifier training completed. Avg Accuracy: ${l.toFixed(2)}, Last Epoch Accuracy: ${u.toFixed(2)}, Avg Loss: ${c.toFixed(2)}, Last Epoch Loss: ${h.toFixed(2)}`)}else this.showText("Classifier training completed.")})).subscribe()}refineHeatMap(e,s,r){if(e<=0)return void this.showText("Complete.");const i=new Set;for(const a of this.pointFeatures.values()){const o=a.get("weight");if(o<.5&&this.demoType===Ms.SimilarTissueWithLinearProbe||o<15&&this.demoType===Ms.OutlierTissueDetector)continue;const l=a.getGeometry()?.getCoordinates();if(!l1(l,r))continue;const u=56*this.pixelWidth;if(i.add([l[0]+u,l[1]]),i.add([l[0]-u,l[1]]),i.add([l[0],l[1]+u]),i.add([l[0],l[1]-u]),i.add([l[0]+u,l[1]+u]),i.add([l[0]-u,l[1]+u]),i.add([l[0]-u,l[1]-u]),i.add([l[0]+u,l[1]-u]),i.size>1e4)return}this.coordToGraphics([...i.values()]).pipe((0,fe.$)(),(0,Ce.M)(()=>{this.refineHeatMap(e-1,s,r)})).subscribe()}coordToGraphics(e){let s=e.filter(r=>!this.pointFeatures.has(this.coordinatesToHash(r)));s=s.filter(r=>this.isTissue(r));for(const r of s){const i=new Fh.A({geometry:new Lh.A(r)});i.set("weight",-1),this.insertFeature(i)}return this.updatePointLayer(),this.getEmbeddings(s).pipe((0,de.Z)(r=>(0,st.H)(r)),(0,de.Z)(r=>{let i=0;return this.demoType===Ms.OutlierTissueDetector?(i=function AK(n,t,e){let s=1/0;for(let r=0;r(e.dispose(),s.dispose(),r[0])))}(this.classifier,r.embedding_vector).pipe((0,Pe.T)(a=>[r,a]))}),(0,Ce.M)(([r,i])=>{const a=new Fh.A({geometry:new Lh.A([r.patch_coordinate.x_origin,r.patch_coordinate.y_origin])});a.set("weight",i),this.insertFeature(a),this.updatePointLayer(),console.log("!@# weight=",i)}))}showText(e){this.snackBar.open(e,"Close",{duration:5e3})}drawHeatMapForViewport(){if(!this.slideDescriptor||!this.olMap)return;if(0===this.normalTissueEmbeddings.length&&this.demoType===Ms.OutlierTissueDetector)return void this.showText("ERROR: Common embeddings not loaded.");if(void 0===this.classifier&&this.demoType===Ms.SimilarTissueWithLinearProbe)return void this.showText('To use this feature, you must first train a classifier. Please select the polygon drawing tool (if not already selected), draw a polygon around the tissue of interest, and then click "Train".');const e=this.olMap.getView().getResolution();if(e&&e>1e-5)return void this.showText("This feature works best at higher zoom levels. Please zoom in closer to the tissue and try again.");const[s,r,i,a]=this.olMap.getView().calculateExtent(this.olMap.getSize()),o=[[s,r],[i,r],[i,a],[s,a]],l=this.toMM([0,0]),u=this.toMM([this.slideInfo?.size.x,this.slideInfo?.size.y]),h=(o.map(([d,p])=>[Math.max(l[0],Math.min(u[0],d)),Math.max(u[0],Math.min(l[1],p))]),u1(o,this.patchSize));console.log("Viewport grid size= ",h.length),this.showText(`Searching for matching tissue in viewport. Course search ${h.length} points.`),this.coordToGraphics(h).pipe((0,fe.$)(),(0,Ce.M)(()=>{this.showText("Starting fine search."),this.refineHeatMap(4,h,o)})).subscribe()}coordinatesToHash(e){const s=this.toPixels(e);return`${Math.round(s[0]/224*4)},${Math.round(s[1]/224*4)}`}insertFeature(e){const s=this.pointLayer.getSource(),r=this.coordinatesToHash(e.getGeometry()?.getCoordinates());this.pointFeatures.has(r)&&s.removeFeature(this.pointFeatures.get(r)),this.pointFeatures.set(r,e),this.pointLayer?.getSource().addFeature(e)}updatePointLayer(e=!1){if(!this.pointLayer)return;const s=this.pointLayer.getSource();s&&(e&&(s.clear(),s.addFeatures(Array.from(this.pointFeatures.values()))),this.pointLayer.changed())}getTargetFeature(){const e=this.olMap?.getInteractions().getArray().filter(r=>r instanceof Yq.A)[0];if(!e)return;const s=e.getFeatures().getArray();if(1===s.length){const r=s[0];return e.getFeatures().clear(),r}}getEmbeddings(e){if(!this.slideDescriptor)return(0,nt.of)([]);const s=this.slideDescriptor.id,r=e.map(h=>this.toPixels(h));let i=[];const o=[];for(let h=0;h(0,st.H)(i)),(0,Te.S)(128),(0,lt.E)(c),(0,de.Z)(([h,d])=>{if(console.log("coordsBatch.length=",h.length),!this.slideDescriptor||!this.slideInfo)return(0,nt.of)([]);const p={authorization:`Bearer ${d}`,"Accept-Encoding":"gzip, deflate, br"},f=h.map(m=>({x_origin:Math.floor(m[0]-u),y_origin:Math.floor(m[1]-u),width:224,height:224}));return this.http.post(`${this.serverUrl}/predict`,{instances:[{dicom_path:{series_path:s,instance_uids:[this.slideInfo.levelMap[0].properties[0].instanceUid]},bearer_token:d,patch_coordinates:f}]},{headers:p}).pipe((0,Pe.T)(m=>m.predictions[0].result.patch_embeddings),(0,Pe.T)(m=>m.map(x=>{const y=this.toMM([x.patch_coordinate.x_origin+u,x.patch_coordinate.y_origin+u]);return x.patch_coordinate.x_origin=y[0],x.patch_coordinate.y_origin=y[1],x})),function Qe(n=1/0){let t;t=n&&"object"==typeof n?n:{count:n};const{count:e=1/0,delay:s,resetOnSuccess:r=!1}=t;return e<=0?jt.D:(0,Ht.N)((i,a)=>{let l,o=0;const u=()=>{let c=!1;l=i.subscribe((0,at._)(a,h=>{r&&(o=0),a.next(h)},void 0,h=>{if(o++{l?(l.unsubscribe(),l=null,u()):c=!0};if(null!=s){const p="number"==typeof s?(0,Ee.O)(s):(0,Be.Tg)(s(h,o)),f=(0,at._)(a,()=>{f.unsubscribe(),d()},()=>{a.complete()});p.subscribe(f)}else d()}else a.error(h)})),c&&(l.unsubscribe(),l=null,u())};u()})}(2),(0,q.W)(m=>{throw console.error("Error in getEmbeddings:",m),new Error("Failed to get embeddings")}))},6))}static{this.\u0275fac=function(s){return new(s||n)(Wl.KVO(t8.Qq),Wl.KVO(n8.y),Wl.KVO(s8.UG),Wl.KVO(r8.w))}}static{this.\u0275prov=Wl.jDH({token:n,factory:n.\u0275fac,providedIn:"root"})}}return n})()},2381:_t=>{"use strict";function ct(R,G,C){C=C||2;var T,Me,Ye,K,Pt,Rt,rt,M=G&&G.length,X=M?G[0]*C:R.length,re=W(R,0,X,C,!0),ie=[];if(!re||re.next===re.prev)return ie;if(M&&(re=function st(R,G,C,M){var re,ie,Ye,X=[];for(re=0,ie=G.length;re80*C){T=Ye=R[0],Me=K=R[1];for(var St=C;StYe&&(Ye=Pt),Rt>K&&(K=Rt);rt=0!==(rt=Math.max(Ye-T,K-Me))?32767/rt:0}return Re(re,ie,C,T,Me,rt,0),ie}function W(R,G,C,M,X){var re,ie;if(X===qe(R,G,C,M)>0)for(re=G;re=G;re-=M)ie=we(re,R[re],R[re+1],ie);return ie&&jt(ie,ie.next)&&(Fe(ie),ie=ie.next),ie}function F(R,G){if(!R)return R;G||(G=R);var M,C=R;do{if(M=!1,C.steiner||!jt(C,C.next)&&0!==at(C.prev,C,C.next))C=C.next;else{if(Fe(C),(C=G=C.prev)===C.next)break;M=!0}}while(M||C!==G);return G}function Re(R,G,C,M,X,re,ie){if(R){!ie&&re&&function ue(R,G,C,M){var X=R;do{0===X.z&&(X.z=Pe(X.x,X.y,G,C,M)),X.prevZ=X.prev,X.nextZ=X.next,X=X.next}while(X!==R);X.prevZ.nextZ=null,X.prevZ=null,function fe(R){var G,C,M,X,re,ie,T,Me,Ye=1;do{for(C=R,R=null,re=null,ie=0;C;){for(ie++,M=C,T=0,G=0;G0||Me>0&&M;)0!==T&&(0===Me||!M||C.z<=M.z)?(X=C,C=C.nextZ,T--):(X=M,M=M.nextZ,Me--),re?re.nextZ=X:R=X,X.prevZ=re,re=X;C=M}re.nextZ=null,Ye*=2}while(ie>1)}(X)}(R,M,X,re);for(var Me,Ye,T=R;R.prev!==R.next;)if(Me=R.prev,Ye=R.next,re?Tt(R,M,X,re):Ke(R))G.push(Me.i/C|0),G.push(R.i/C|0),G.push(Ye.i/C|0),Fe(R),R=Ye.next,T=Ye.next;else if((R=Ye)===T){ie?1===ie?Re(R=nt(F(R),G,C),G,C,M,X,re,2):2===ie&&Xe(R,G,C,M,X,re):Re(F(R),G,C,M,X,re,1);break}}}function Ke(R){var G=R.prev,C=R,M=R.next;if(at(G,C,M)>=0)return!1;for(var X=G.x,re=C.x,ie=M.x,T=G.y,Me=C.y,Ye=M.y,K=Xre?X>ie?X:ie:re>ie?re:ie,rt=T>Me?T>Ye?T:Ye:Me>Ye?Me:Ye,St=M.next;St!==G;){if(St.x>=K&&St.x<=Rt&&St.y>=Pt&&St.y<=rt&<(X,T,re,Me,ie,Ye,St.x,St.y)&&at(St.prev,St,St.next)>=0)return!1;St=St.next}return!0}function Tt(R,G,C,M){var X=R.prev,re=R,ie=R.next;if(at(X,re,ie)>=0)return!1;for(var T=X.x,Me=re.x,Ye=ie.x,K=X.y,Pt=re.y,Rt=ie.y,rt=TMe?T>Ye?T:Ye:Me>Ye?Me:Ye,Vs=K>Pt?K>Rt?K:Rt:Pt>Rt?Pt:Rt,Ya=Pe(rt,St,G,C,M),zs=Pe(Mr,Vs,G,C,M),Ct=R.prevZ,It=R.nextZ;Ct&&Ct.z>=Ya&&It&&It.z<=zs;){if(Ct.x>=rt&&Ct.x<=Mr&&Ct.y>=St&&Ct.y<=Vs&&Ct!==X&&Ct!==ie&<(T,K,Me,Pt,Ye,Rt,Ct.x,Ct.y)&&at(Ct.prev,Ct,Ct.next)>=0||(Ct=Ct.prevZ,It.x>=rt&&It.x<=Mr&&It.y>=St&&It.y<=Vs&&It!==X&&It!==ie&<(T,K,Me,Pt,Ye,Rt,It.x,It.y)&&at(It.prev,It,It.next)>=0))return!1;It=It.nextZ}for(;Ct&&Ct.z>=Ya;){if(Ct.x>=rt&&Ct.x<=Mr&&Ct.y>=St&&Ct.y<=Vs&&Ct!==X&&Ct!==ie&<(T,K,Me,Pt,Ye,Rt,Ct.x,Ct.y)&&at(Ct.prev,Ct,Ct.next)>=0)return!1;Ct=Ct.prevZ}for(;It&&It.z<=zs;){if(It.x>=rt&&It.x<=Mr&&It.y>=St&&It.y<=Vs&&It!==X&&It!==ie&<(T,K,Me,Pt,Ye,Rt,It.x,It.y)&&at(It.prev,It,It.next)>=0)return!1;It=It.nextZ}return!0}function nt(R,G,C){var M=R;do{var X=M.prev,re=M.next.next;!jt(X,re)&&Ee(X,M,M.next,re)&&N(X,re)&&N(re,X)&&(G.push(X.i/C|0),G.push(M.i/C|0),G.push(re.i/C|0),Fe(M),Fe(M.next),M=R=re),M=M.next}while(M!==R);return F(M)}function Xe(R,G,C,M,X,re){var ie=R;do{for(var T=ie.next.next;T!==ie.prev;){if(ie.i!==T.i&&Ht(ie,T)){var Me=O(ie,T);return ie=F(ie,ie.next),Me=F(Me,Me.next),Re(ie,G,C,M,X,re,0),void Re(Me,G,C,M,X,re,0)}T=T.next}ie=ie.next}while(ie!==R)}function Ce(R,G){return R.x-G.x}function q(R,G){var C=function de(R,G){var ie,C=G,M=R.x,X=R.y,re=-1/0;do{if(X<=C.y&&X>=C.next.y&&C.next.y!==C.y){var T=C.x+(X-C.y)*(C.next.x-C.x)/(C.next.y-C.y);if(T<=M&&T>re&&(re=T,ie=C.x=C.x&&C.x>=Ye&&M!==C.x&<(Xie.x||C.x===ie.x&&_e(ie,C)))&&(ie=C,Pt=Rt)),C=C.next}while(C!==Me);return ie}(R,G);if(!C)return G;var M=O(C,R);return F(M,M.next),F(C,C.next)}function _e(R,G){return at(R.prev,R,G.prev)<0&&at(G.next,R,R.next)<0}function Pe(R,G,C,M,X){return(R=1431655765&((R=858993459&((R=252645135&((R=16711935&((R=(R-C)*X|0)|R<<8))|R<<4))|R<<2))|R<<1))|(G=1431655765&((G=858993459&((G=252645135&((G=16711935&((G=(G-M)*X|0)|G<<8))|G<<4))|G<<2))|G<<1))<<1}function Te(R){var G=R,C=R;do{(G.x=(R-ie)*(re-T)&&(R-ie)*(M-T)>=(C-ie)*(G-T)&&(C-ie)*(re-T)>=(X-ie)*(M-T)}function Ht(R,G){return R.next.i!==G.i&&R.prev.i!==G.i&&!function et(R,G){var C=R;do{if(C.i!==R.i&&C.next.i!==R.i&&C.i!==G.i&&C.next.i!==G.i&&Ee(C,C.next,R,G))return!0;C=C.next}while(C!==R);return!1}(R,G)&&(N(R,G)&&N(G,R)&&function oe(R,G){var C=R,M=!1,X=(R.x+G.x)/2,re=(R.y+G.y)/2;do{C.y>re!=C.next.y>re&&C.next.y!==C.y&&X<(C.next.x-C.x)*(re-C.y)/(C.next.y-C.y)+C.x&&(M=!M),C=C.next}while(C!==R);return M}(R,G)&&(at(R.prev,R,G.prev)||at(R,G.prev,G))||jt(R,G)&&at(R.prev,R,R.next)>0&&at(G.prev,G,G.next)>0)}function at(R,G,C){return(G.y-R.y)*(C.x-G.x)-(G.x-R.x)*(C.y-G.y)}function jt(R,G){return R.x===G.x&&R.y===G.y}function Ee(R,G,C,M){var X=Qe(at(R,G,C)),re=Qe(at(R,G,M)),ie=Qe(at(C,M,R)),T=Qe(at(C,M,G));return!!(X!==re&&ie!==T||0===X&&Be(R,C,G)||0===re&&Be(R,M,G)||0===ie&&Be(C,R,M)||0===T&&Be(C,G,M))}function Be(R,G,C){return G.x<=Math.max(R.x,C.x)&&G.x>=Math.min(R.x,C.x)&&G.y<=Math.max(R.y,C.y)&&G.y>=Math.min(R.y,C.y)}function Qe(R){return R>0?1:R<0?-1:0}function N(R,G){return at(R.prev,R,R.next)<0?at(R,G,R.next)>=0&&at(R,R.prev,G)>=0:at(R,G,R.prev)<0||at(R,R.next,G)<0}function O(R,G){var C=new $e(R.i,R.x,R.y),M=new $e(G.i,G.x,G.y),X=R.next,re=G.prev;return R.next=G,G.prev=R,C.next=X,X.prev=C,M.next=C,C.prev=M,re.next=M,M.prev=re,M}function we(R,G,C,M){var X=new $e(R,G,C);return M?(X.next=M.next,X.prev=M,M.next.prev=X,M.next=X):(X.prev=X,X.next=X),X}function Fe(R){R.next.prev=R.prev,R.prev.next=R.next,R.prevZ&&(R.prevZ.nextZ=R.nextZ),R.nextZ&&(R.nextZ.prevZ=R.prevZ)}function $e(R,G,C){this.i=R,this.x=G,this.y=C,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function qe(R,G,C,M){for(var X=0,re=G,ie=C-M;re0&&C.holes.push(M+=R[X-1].length)}return C}},1929:_t=>{_t.exports=W;var ct=null;try{ct=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{}function W(oe,O,we){this.low=0|oe,this.high=0|O,this.unsigned=!!we}function F(oe){return!0===(oe&&oe.__isLong__)}Object.defineProperty(W.prototype,"__isLong__",{value:!0}),W.isLong=F;var Re={},Ke={};function Tt(oe,O){var we,Fe,$e;return O?($e=0<=(oe>>>=0)&&oe<256)&&(Fe=Ke[oe])?Fe:(we=Xe(oe,(0|oe)<0?-1:0,!0),$e&&(Ke[oe]=we),we):($e=-128<=(oe|=0)&&oe<128)&&(Fe=Re[oe])?Fe:(we=Xe(oe,oe<0?-1:0,!1),$e&&(Re[oe]=we),we)}function nt(oe,O){if(isNaN(oe))return O?Ht:lt;if(O){if(oe<0)return Ht;if(oe>=fe)return Qe}else{if(oe<=-Pe)return et;if(oe+1>=Pe)return Be}return oe<0?nt(-oe,O).neg():Xe(oe%ue|0,oe/ue|0,O)}function Xe(oe,O,we){return new W(oe,O,we)}W.fromInt=Tt,W.fromNumber=nt,W.fromBits=Xe;var st=Math.pow;function Ce(oe,O,we){if(0===oe.length)throw Error("empty string");if("NaN"===oe||"Infinity"===oe||"+Infinity"===oe||"-Infinity"===oe)return lt;if("number"==typeof O?(we=O,O=!1):O=!!O,(we=we||10)<2||360)throw Error("interior hyphen");if(0===Fe)return Ce(oe.substring(1),O,we).neg();for(var $e=nt(st(we,8)),qe=lt,R=0;R>>0:this.low},N.toNumber=function(){return this.unsigned?(this.high>>>0)*ue+(this.low>>>0):this.high*ue+(this.low>>>0)},N.toString=function(O){if((O=O||10)<2||36>>0).toString(O);if((R=C).isZero())return X+G;for(;X.length<6;)X="0"+X;G=""+X+G}},N.getHighBits=function(){return this.high},N.getHighBitsUnsigned=function(){return this.high>>>0},N.getLowBits=function(){return this.low},N.getLowBitsUnsigned=function(){return this.low>>>0},N.getNumBitsAbs=function(){if(this.isNegative())return this.eq(et)?64:this.neg().getNumBitsAbs();for(var O=0!=this.high?this.high:this.low,we=31;we>0&&!(O&1<=0},N.isOdd=function(){return!(1&~this.low)},N.isEven=function(){return!(1&this.low)},N.equals=function(O){return F(O)||(O=q(O)),(this.unsigned===O.unsigned||this.high>>>31!=1||O.high>>>31!=1)&&this.high===O.high&&this.low===O.low},N.eq=N.equals,N.notEquals=function(O){return!this.eq(O)},N.neq=N.notEquals,N.ne=N.notEquals,N.lessThan=function(O){return this.comp(O)<0},N.lt=N.lessThan,N.lessThanOrEqual=function(O){return this.comp(O)<=0},N.lte=N.lessThanOrEqual,N.le=N.lessThanOrEqual,N.greaterThan=function(O){return this.comp(O)>0},N.gt=N.greaterThan,N.greaterThanOrEqual=function(O){return this.comp(O)>=0},N.gte=N.greaterThanOrEqual,N.ge=N.greaterThanOrEqual,N.compare=function(O){if(F(O)||(O=q(O)),this.eq(O))return 0;var we=this.isNegative(),Fe=O.isNegative();return we&&!Fe?-1:!we&&Fe?1:this.unsigned?O.high>>>0>this.high>>>0||O.high===this.high&&O.low>>>0>this.low>>>0?-1:1:this.sub(O).isNegative()?-1:1},N.comp=N.compare,N.negate=function(){return!this.unsigned&&this.eq(et)?et:this.not().add(at)},N.neg=N.negate,N.add=function(O){F(O)||(O=q(O));var X=0,re=0,ie=0,T=0;return ie+=(T+=(65535&this.low)+(65535&O.low))>>>16,re+=(ie+=(this.low>>>16)+(O.low>>>16))>>>16,X+=(re+=(65535&this.high)+(65535&O.high))>>>16,X+=(this.high>>>16)+(O.high>>>16),Xe((ie&=65535)<<16|(T&=65535),(X&=65535)<<16|(re&=65535),this.unsigned)},N.subtract=function(O){return F(O)||(O=q(O)),this.add(O.neg())},N.sub=N.subtract,N.multiply=function(O){if(this.isZero())return lt;if(F(O)||(O=q(O)),ct)return Xe(ct.mul(this.low,this.high,O.low,O.high),ct.get_high(),this.unsigned);if(O.isZero())return lt;if(this.eq(et))return O.isOdd()?et:lt;if(O.eq(et))return this.isOdd()?et:lt;if(this.isNegative())return O.isNegative()?this.neg().mul(O.neg()):this.neg().mul(O).neg();if(O.isNegative())return this.mul(O.neg()).neg();if(this.lt(Te)&&O.lt(Te))return nt(this.toNumber()*O.toNumber(),this.unsigned);var $e=65535&this.high,qe=this.low>>>16,R=65535&this.low,C=65535&O.high,M=O.low>>>16,X=65535&O.low,re=0,ie=0,T=0,Me=0;return T+=(Me+=R*X)>>>16,ie+=(T+=qe*X)>>>16,T&=65535,ie+=(T+=R*M)>>>16,re+=(ie+=$e*X)>>>16,ie&=65535,re+=(ie+=qe*M)>>>16,ie&=65535,re+=(ie+=R*C)>>>16,re+=(this.high>>>16)*X+$e*M+qe*C+R*(O.high>>>16),Xe((T&=65535)<<16|(Me&=65535),(re&=65535)<<16|(ie&=65535),this.unsigned)},N.mul=N.multiply,N.divide=function(O){if(F(O)||(O=q(O)),O.isZero())throw Error("division by zero");var Fe,$e,qe;if(ct)return this.unsigned||-2147483648!==this.high||-1!==O.low||-1!==O.high?Xe((this.unsigned?ct.div_u:ct.div_s)(this.low,this.high,O.low,O.high),ct.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Ht:lt;if(this.unsigned){if(O.unsigned||(O=O.toUnsigned()),O.gt(this))return Ht;if(O.gt(this.shru(1)))return jt;qe=Ht}else{if(this.eq(et))return O.eq(at)||O.eq(Ee)?et:O.eq(et)?at:(Fe=this.shr(1).div(O).shl(1)).eq(lt)?O.isNegative()?at:Ee:($e=this.sub(O.mul(Fe)),qe=Fe.add($e.div(O)));if(O.eq(et))return this.unsigned?Ht:lt;if(this.isNegative())return O.isNegative()?this.neg().div(O.neg()):this.neg().div(O).neg();if(O.isNegative())return this.div(O.neg()).neg();qe=lt}for($e=this;$e.gte(O);){Fe=Math.max(1,Math.floor($e.toNumber()/O.toNumber()));for(var G=Math.ceil(Math.log(Fe)/Math.LN2),C=G<=48?1:st(2,G-48),M=nt(Fe),X=M.mul(O);X.isNegative()||X.gt($e);)X=(M=nt(Fe-=C,this.unsigned)).mul(O);M.isZero()&&(M=at),qe=qe.add(M),$e=$e.sub(X)}return qe},N.div=N.divide,N.modulo=function(O){return F(O)||(O=q(O)),ct?Xe((this.unsigned?ct.rem_u:ct.rem_s)(this.low,this.high,O.low,O.high),ct.get_high(),this.unsigned):this.sub(this.div(O).mul(O))},N.mod=N.modulo,N.rem=N.modulo,N.not=function(){return Xe(~this.low,~this.high,this.unsigned)},N.and=function(O){return F(O)||(O=q(O)),Xe(this.low&O.low,this.high&O.high,this.unsigned)},N.or=function(O){return F(O)||(O=q(O)),Xe(this.low|O.low,this.high|O.high,this.unsigned)},N.xor=function(O){return F(O)||(O=q(O)),Xe(this.low^O.low,this.high^O.high,this.unsigned)},N.shiftLeft=function(O){return F(O)&&(O=O.toInt()),0==(O&=63)?this:O<32?Xe(this.low<>>32-O,this.unsigned):Xe(0,this.low<>>O|this.high<<32-O,this.high>>O,this.unsigned):Xe(this.high>>O-32,this.high>=0?0:-1,this.unsigned)},N.shr=N.shiftRight,N.shiftRightUnsigned=function(O){if(F(O)&&(O=O.toInt()),0==(O&=63))return this;var we=this.high;return O<32?Xe(this.low>>>O|we<<32-O,we>>>O,this.unsigned):Xe(32===O?we:we>>>O-32,0,this.unsigned)},N.shru=N.shiftRightUnsigned,N.shr_u=N.shiftRightUnsigned,N.toSigned=function(){return this.unsigned?Xe(this.low,this.high,!1):this},N.toUnsigned=function(){return this.unsigned?this:Xe(this.low,this.high,!0)},N.toBytes=function(O){return O?this.toBytesLE():this.toBytesBE()},N.toBytesLE=function(){var O=this.high,we=this.low;return[255&we,we>>>8&255,we>>>16&255,we>>>24,255&O,O>>>8&255,O>>>16&255,O>>>24]},N.toBytesBE=function(){var O=this.high,we=this.low;return[O>>>24,O>>>16&255,O>>>8&255,255&O,we>>>24,we>>>16&255,we>>>8&255,255&we]},W.fromBytes=function(O,we,Fe){return Fe?W.fromBytesLE(O,we):W.fromBytesBE(O,we)},W.fromBytesLE=function(O,we){return new W(O[0]|O[1]<<8|O[2]<<16|O[3]<<24,O[4]|O[5]<<8|O[6]<<16|O[7]<<24,we)},W.fromBytesBE=function(O,we){return new W(O[4]<<24|O[5]<<16|O[6]<<8|O[7],O[0]<<24|O[1]<<16|O[2]<<8|O[3],we)}},8814:(_t,ct,W)=>{var F=W(2495),Re=W(7850),Ke=W(5704),Tt=W(8114),nt=W(9040),Xe=W(4478),st=W(7454);st.alea=F,st.xor128=Re,st.xorwow=Ke,st.xorshift7=Tt,st.xor4096=nt,st.tychei=Xe,_t.exports=st},2495:function(_t,ct,W){var F;!function(Re,Ke){function nt(q){var de=this,_e=function Ce(){var q=4022871197;return function(_e){_e=String(_e);for(var ue=0;ue<_e.length;ue++){var fe=.02519603282416938*(q+=_e.charCodeAt(ue));fe-=q=fe>>>0,q=(fe*=q)>>>0,q+=4294967296*(fe-=q)}return 2.3283064365386963e-10*(q>>>0)}}();de.next=function(){var ue=2091639*de.s0+2.3283064365386963e-10*de.c;return de.s0=de.s1,de.s1=de.s2,de.s2=ue-(de.c=0|ue)},de.c=1,de.s0=_e(" "),de.s1=_e(" "),de.s2=_e(" "),de.s0-=_e(q),de.s0<0&&(de.s0+=1),de.s1-=_e(q),de.s1<0&&(de.s1+=1),de.s2-=_e(q),de.s2<0&&(de.s2+=1),_e=null}function Xe(q,de){return de.c=q.c,de.s0=q.s0,de.s1=q.s1,de.s2=q.s2,de}function st(q,de){var _e=new nt(q),ue=de&&de.state,fe=_e.next;return fe.int32=function(){return 4294967296*_e.next()|0},fe.double=function(){return fe()+11102230246251565e-32*(2097152*fe()|0)},fe.quick=fe,ue&&("object"==typeof ue&&Xe(ue,_e),fe.state=function(){return Xe(_e,{})}),fe}Ke&&Ke.exports?Ke.exports=st:W.amdD&&W.amdO?void 0!==(F=function(){return st}.call(ct,W,ct,Ke))&&(Ke.exports=F):this.alea=st}(0,_t=W.nmd(_t))},4478:function(_t,ct,W){var F;!function(Re,Ke){function nt(Ce){var q=this,de="";q.next=function(){var ue=q.b,fe=q.c,Pe=q.d,Te=q.a;return ue=ue<<25^ue>>>7^fe,fe=fe-Pe|0,Pe=Pe<<24^Pe>>>8^Te,Te=Te-ue|0,q.b=ue=ue<<20^ue>>>12^fe,q.c=fe=fe-Pe|0,q.d=Pe<<16^fe>>>16^Te,q.a=Te-ue|0},q.a=0,q.b=0,q.c=-1640531527,q.d=1367130551,Ce===Math.floor(Ce)?(q.a=Ce/4294967296|0,q.b=0|Ce):de+=Ce;for(var _e=0;_e>>0)/4294967296};return ue.double=function(){do{var Te=((de.next()>>>11)+(de.next()>>>0)/4294967296)/(1<<21)}while(0===Te);return Te},ue.int32=de.next,ue.quick=ue,_e&&("object"==typeof _e&&Xe(_e,de),ue.state=function(){return Xe(de,{})}),ue}Ke&&Ke.exports?Ke.exports=st:W.amdD&&W.amdO?void 0!==(F=function(){return st}.call(ct,W,ct,Ke))&&(Ke.exports=F):this.tychei=st}(0,_t=W.nmd(_t))},7850:function(_t,ct,W){var F;!function(Re,Ke){function nt(Ce){var q=this,de="";q.x=0,q.y=0,q.z=0,q.w=0,q.next=function(){var ue=q.x^q.x<<11;return q.x=q.y,q.y=q.z,q.z=q.w,q.w^=q.w>>>19^ue^ue>>>8},Ce===(0|Ce)?q.x=Ce:de+=Ce;for(var _e=0;_e>>0)/4294967296};return ue.double=function(){do{var Te=((de.next()>>>11)+(de.next()>>>0)/4294967296)/(1<<21)}while(0===Te);return Te},ue.int32=de.next,ue.quick=ue,_e&&("object"==typeof _e&&Xe(_e,de),ue.state=function(){return Xe(de,{})}),ue}Ke&&Ke.exports?Ke.exports=st:W.amdD&&W.amdO?void 0!==(F=function(){return st}.call(ct,W,ct,Ke))&&(Ke.exports=F):this.xor128=st}(0,_t=W.nmd(_t))},9040:function(_t,ct,W){var F;!function(Re,Ke){function nt(Ce){var q=this;q.next=function(){var Pe,Te,_e=q.w,ue=q.X,fe=q.i;return q.w=_e=_e+1640531527|0,Te=ue[fe+34&127],Pe=ue[fe=fe+1&127],Te^=Te<<13,Pe^=Pe<<17,Te=ue[fe]=(Te^=Te>>>15)^(Pe^=Pe>>>12),q.i=fe,Te+(_e^_e>>>16)|0},function de(_e,ue){var fe,Pe,Te,lt,Ht,at=[],jt=128;for(ue===(0|ue)?(Pe=ue,ue=null):(ue+="\0",Pe=0,jt=Math.max(jt,ue.length)),Te=0,lt=-32;lt>>15,Pe^=Pe<<4,Pe^=Pe>>>13,lt>=0&&(Te=0==(fe=at[127<]^=Pe+(Ht=Ht+1640531527|0))?Te+1:0);for(Te>=128&&(at[127&(ue&&ue.length||0)]=-1),Te=127,lt=512;lt>0;--lt)Pe=at[Te+34&127],fe=at[Te=Te+1&127],Pe^=Pe<<13,fe^=fe<<17,at[Te]=(Pe^=Pe>>>15)^(fe^=fe>>>12);_e.w=Ht,_e.X=at,_e.i=Te}(q,Ce)}function Xe(Ce,q){return q.i=Ce.i,q.w=Ce.w,q.X=Ce.X.slice(),q}function st(Ce,q){null==Ce&&(Ce=+new Date);var de=new nt(Ce),_e=q&&q.state,ue=function(){return(de.next()>>>0)/4294967296};return ue.double=function(){do{var Te=((de.next()>>>11)+(de.next()>>>0)/4294967296)/(1<<21)}while(0===Te);return Te},ue.int32=de.next,ue.quick=ue,_e&&(_e.X&&Xe(_e,de),ue.state=function(){return Xe(de,{})}),ue}Ke&&Ke.exports?Ke.exports=st:W.amdD&&W.amdO?void 0!==(F=function(){return st}.call(ct,W,ct,Ke))&&(Ke.exports=F):this.xor4096=st}(0,_t=W.nmd(_t))},8114:function(_t,ct,W){var F;!function(Re,Ke){function nt(Ce){var q=this;q.next=function(){var fe,Pe,_e=q.x,ue=q.i;return fe=_e[ue],Pe=(fe^=fe>>>7)^fe<<24,Pe^=(fe=_e[ue+1&7])^fe>>>10,Pe^=(fe=_e[ue+3&7])^fe>>>3,Pe^=(fe=_e[ue+4&7])^fe<<7,fe=_e[ue+7&7],_e[ue]=Pe^=(fe^=fe<<13)^fe<<9,q.i=ue+1&7,Pe},function de(_e,ue){var fe,Te=[];if(ue===(0|ue))Te[0]=ue;else for(ue=""+ue,fe=0;fe0;--fe)_e.next()}(q,Ce)}function Xe(Ce,q){return q.x=Ce.x.slice(),q.i=Ce.i,q}function st(Ce,q){null==Ce&&(Ce=+new Date);var de=new nt(Ce),_e=q&&q.state,ue=function(){return(de.next()>>>0)/4294967296};return ue.double=function(){do{var Te=((de.next()>>>11)+(de.next()>>>0)/4294967296)/(1<<21)}while(0===Te);return Te},ue.int32=de.next,ue.quick=ue,_e&&(_e.x&&Xe(_e,de),ue.state=function(){return Xe(de,{})}),ue}Ke&&Ke.exports?Ke.exports=st:W.amdD&&W.amdO?void 0!==(F=function(){return st}.call(ct,W,ct,Ke))&&(Ke.exports=F):this.xorshift7=st}(0,_t=W.nmd(_t))},5704:function(_t,ct,W){var F;!function(Re,Ke){function nt(Ce){var q=this,de="";q.next=function(){var ue=q.x^q.x>>>2;return q.x=q.y,q.y=q.z,q.z=q.w,q.w=q.v,(q.d=q.d+362437|0)+(q.v=q.v^q.v<<4^ue^ue<<1)|0},q.x=0,q.y=0,q.z=0,q.w=0,q.v=0,Ce===(0|Ce)?q.x=Ce:de+=Ce;for(var _e=0;_e>>4),q.next()}function Xe(Ce,q){return q.x=Ce.x,q.y=Ce.y,q.z=Ce.z,q.w=Ce.w,q.v=Ce.v,q.d=Ce.d,q}function st(Ce,q){var de=new nt(Ce),_e=q&&q.state,ue=function(){return(de.next()>>>0)/4294967296};return ue.double=function(){do{var Te=((de.next()>>>11)+(de.next()>>>0)/4294967296)/(1<<21)}while(0===Te);return Te},ue.int32=de.next,ue.quick=ue,_e&&("object"==typeof _e&&Xe(_e,de),ue.state=function(){return Xe(de,{})}),ue}Ke&&Ke.exports?Ke.exports=st:W.amdD&&W.amdO?void 0!==(F=function(){return st}.call(ct,W,ct,Ke))&&(Ke.exports=F):this.xorwow=st}(0,_t=W.nmd(_t))},7454:function(_t,ct,W){var F;!function(Re,Ke,Tt){var fe,nt=256,q=Tt.pow(nt,6),de=Tt.pow(2,52),_e=2*de;function Pe(Be,Qe,et){var N=[],oe=at(Ht((Qe=1==Qe?{entropy:!0}:Qe||{}).entropy?[Be,Ee(Ke)]:Be??function jt(){try{var Be;return fe&&(Be=fe.randomBytes)?Be=Be(nt):(Be=new Uint8Array(nt),(Re.crypto||Re.msCrypto).getRandomValues(Be)),Ee(Be)}catch{var Qe=Re.navigator,et=Qe&&Qe.plugins;return[+new Date,Re,et,Re.screen,Ee(Ke)]}}(),3),N),O=new Te(N),we=function(){for(var Fe=O.g(6),$e=q,qe=0;Fe=_e;)Fe/=2,$e/=2,qe>>>=1;return(Fe+qe)/$e};return we.int32=function(){return 0|O.g(4)},we.quick=function(){return O.g(4)/4294967296},we.double=we,at(Ee(O.S),Ke),(Qe.pass||et||function(Fe,$e,qe,R){return R&&(R.S&<(R,O),Fe.state=function(){return lt(O,{})}),qe?(Tt.random=Fe,$e):Fe})(we,oe,"global"in Qe?Qe.global:this==Tt,Qe.state)}function Te(Be){var Qe,et=Be.length,N=this,oe=0,O=N.i=N.j=0,we=N.S=[];for(et||(Be=[et++]);oe{},8590:()=>{},4530:()=>{},8108:()=>{},551:()=>{},1234:()=>{},6493:(_t,ct,W)=>{"use strict";W.d(ct,{Ti:()=>aa,d1:()=>wr});var F=W(4438),Re=W(177),Ke=W(9417),Tt=W(1413),nt=W(3236),Xe=W(9974),st=W(4360),Ce=W(8750),de=W(1584);function _e(ve,Oe=nt.E,_){const A=(0,de.O)(ve,Oe);return function q(ve,Oe){return(0,Xe.N)((_,A)=>{const{leading:H=!0,trailing:E=!1}=Oe??{};let ye=!1,Je=null,gt=null,zt=!1;const bt=()=>{gt?.unsubscribe(),gt=null,E&&(jn(),zt&&A.complete())},xn=()=>{gt=null,zt&&A.complete()},In=ps=>gt=(0,Ce.Tg)(ve(ps)).subscribe((0,st._)(A,bt,xn)),jn=()=>{if(ye){ye=!1;const ps=Je;Je=null,A.next(ps),!zt&&In(ps)}};_.subscribe((0,st._)(A,ps=>{ye=!0,Je=ps,(!gt||gt.closed)&&(H?jn():In(ps))},()=>{zt=!0,(!(E&&ye&>)||gt.closed)&&A.complete()}))})}(()=>A,_)}var ue=W(8141),fe=W(3294),Pe=W(5964),Te=typeof window<"u"?window:{screen:{},navigator:{}},lt=(Te.matchMedia||function(){return{matches:!1}}).bind(Te),Ht=!1,jt=function(){};Te.addEventListener&&Te.addEventListener("p",jt,{get passive(){return Ht=!0}}),Te.removeEventListener&&Te.removeEventListener("p",jt,!1);var Ee=Ht,Qe="ontouchstart"in Te,O=(Qe||"TouchEvent"in Te&<("(any-pointer: coarse)"),Te.navigator.userAgent||"");lt("(pointer: coarse)").matches&&/iPad|Macintosh/.test(O)&&Math.min(Te.screen.width||0,Te.screen.height||0);(lt("(pointer: coarse)").matches||!lt("(pointer: fine)").matches&&Qe)&&/Windows.*Firefox/.test(O),lt("(any-pointer: fine)").matches||lt("(any-hover: hover)");const G=(ve,Oe,_)=>({tooltip:ve,placement:Oe,content:_});function C(ve,Oe){}function M(ve,Oe){1&ve&&F.DNE(0,C,0,0,"ng-template")}function X(ve,Oe){if(1&ve&&(F.qex(0),F.DNE(1,M,1,0,null,1),F.bVm()),2&ve){const _=F.XpG();F.R7$(),F.Y8G("ngTemplateOutlet",_.template)("ngTemplateOutletContext",F.sMw(2,G,_.tooltip,_.placement,_.content))}}function re(ve,Oe){if(1&ve&&(F.qex(0),F.j41(1,"div",2),F.EFF(2),F.k0s(),F.bVm()),2&ve){const _=F.XpG();F.R7$(),F.BMQ("title",_.tooltip)("data-tooltip-placement",_.placement),F.R7$(),F.SpI(" ",_.content," ")}}const ie=["tooltipTemplate"],T=["leftOuterSelectionBar"],Me=["rightOuterSelectionBar"],Ye=["fullBar"],K=["selectionBar"],Pt=["minHandle"],Rt=["maxHandle"],rt=["floorLabel"],St=["ceilLabel"],Mr=["minHandleLabel"],Vs=["maxHandleLabel"],Ya=["combinedLabel"],zs=["ticksElement"],Ct=ve=>({"ngx-slider-selected":ve});function It(ve,Oe){if(1&ve&&F.nrm(0,"ngx-slider-tooltip-wrapper",32),2&ve){const _=F.XpG().$implicit,A=F.XpG();F.Y8G("template",A.tooltipTemplate)("tooltip",_.valueTooltip)("placement",_.valueTooltipPlacement)("content",_.value)}}function pt(ve,Oe){if(1&ve&&F.nrm(0,"span",33),2&ve){const _=F.XpG().$implicit;F.Y8G("innerText",_.legend)}}function Qs(ve,Oe){if(1&ve&&F.nrm(0,"span",34),2&ve){const _=F.XpG().$implicit;F.Y8G("innerHTML",_.legend,F.npT)}}function Cn(ve,Oe){if(1&ve&&(F.j41(0,"span",27),F.nrm(1,"ngx-slider-tooltip-wrapper",28),F.DNE(2,It,1,4,"ngx-slider-tooltip-wrapper",29)(3,pt,1,1,"span",30)(4,Qs,1,1,"span",31),F.k0s()),2&ve){const _=Oe.$implicit,A=F.XpG();F.Y8G("ngClass",F.eq3(8,Ct,_.selected))("ngStyle",_.style),F.R7$(),F.Y8G("template",A.tooltipTemplate)("tooltip",_.tooltip)("placement",_.tooltipPlacement),F.R7$(),F.Y8G("ngIf",null!=_.value),F.R7$(),F.Y8G("ngIf",null!=_.legend&&!1===A.allowUnsafeHtmlInSlider),F.R7$(),F.Y8G("ngIf",null!=_.legend&&(null==A.allowUnsafeHtmlInSlider||A.allowUnsafeHtmlInSlider))}}var $t=function(ve){return ve[ve.Low=0]="Low",ve[ve.High=1]="High",ve[ve.Floor=2]="Floor",ve[ve.Ceil=3]="Ceil",ve[ve.TickValue=4]="TickValue",ve}($t||{});class sa{floor=0;ceil=null;step=1;minRange=null;maxRange=null;pushRange=!1;minLimit=null;maxLimit=null;translate=null;combineLabels=null;getLegend=null;getStepLegend=null;stepsArray=null;bindIndexForStepsArray=!1;draggableRange=!1;draggableRangeOnly=!1;showSelectionBar=!1;showSelectionBarEnd=!1;showSelectionBarFromValue=null;showOuterSelectionBars=!1;hidePointerLabels=!1;hideLimitLabels=!1;autoHideLimitLabels=!0;readOnly=!1;disabled=!1;showTicks=!1;showTicksValues=!1;tickStep=null;tickValueStep=null;ticksArray=null;ticksTooltip=null;ticksValuesTooltip=null;vertical=!1;getSelectionBarColor=null;getTickColor=null;getPointerColor=null;keyboardSupport=!0;scale=1;rotate=0;enforceStep=!0;enforceRange=!0;enforceStepsArray=!0;noSwitching=!1;onlyBindHandles=!1;rightToLeft=!1;reversedControls=!1;boundPointerLabels=!0;logScale=!1;customValueToPosition=null;customPositionToValue=null;precisionLimit=12;selectionBarGradient=null;ariaLabel="ngx-slider";ariaLabelledBy=null;ariaLabelHigh="ngx-slider-max";ariaLabelledByHigh=null;handleDimension=null;barDimension=null;animate=!0;animateOnMove=!1}const Hl=new F.nKC("AllowUnsafeHtmlInSlider");var Ve=function(ve){return ve[ve.Min=0]="Min",ve[ve.Max=1]="Max",ve}(Ve||{});class ra{value;highValue;pointerType}class ce{static isNullOrUndefined(Oe){return null==Oe}static areArraysEqual(Oe,_){if(Oe.length!==_.length)return!1;for(let A=0;AMath.abs(Oe-E.value));let H=0;for(let E=0;E<_.length;E++)A[E]!==A[H]&&A[E]{E.events.next(Je)};return Oe.addEventListener(_,ye,{passive:!0,capture:!1}),E.teardownCallback=()=>{Oe.removeEventListener(_,ye,{passive:!0,capture:!1})},E.eventsSubscription=E.events.pipe(ce.isNullOrUndefined(H)?(0,ue.M)(()=>{}):_e(H,void 0,{leading:!0,trailing:!0})).subscribe(Je=>{A(Je)}),E}detachEventListener(Oe){ce.isNullOrUndefined(Oe.eventsSubscription)||(Oe.eventsSubscription.unsubscribe(),Oe.eventsSubscription=null),ce.isNullOrUndefined(Oe.events)||(Oe.events.complete(),Oe.events=null),ce.isNullOrUndefined(Oe.teardownCallback)||(Oe.teardownCallback(),Oe.teardownCallback=null)}attachEventListener(Oe,_,A,H){const E=new ia;return E.eventName=_,E.events=new Tt.B,E.teardownCallback=this.renderer.listen(Oe,_,Je=>{E.events.next(Je)}),E.eventsSubscription=E.events.pipe(ce.isNullOrUndefined(H)?(0,ue.M)(()=>{}):_e(H,void 0,{leading:!0,trailing:!0})).subscribe(Je=>{A(Je)}),E}}let Cs=(()=>{class ve{elemRef;renderer;changeDetectionRef;_position=0;get position(){return this._position}_dimension=0;get dimension(){return this._dimension}_alwaysHide=!1;get alwaysHide(){return this._alwaysHide}_vertical=!1;get vertical(){return this._vertical}_scale=1;get scale(){return this._scale}_rotate=0;get rotate(){return this._rotate}opacity=1;visibility="visible";left="";bottom="";height="";width="";transform="";eventListenerHelper;eventListeners=[];constructor(_,A,H){this.elemRef=_,this.renderer=A,this.changeDetectionRef=H,this.eventListenerHelper=new vr(this.renderer)}setAlwaysHide(_){this._alwaysHide=_,this.visibility=_?"hidden":"visible"}hide(){this.opacity=0}show(){this.alwaysHide||(this.opacity=1)}isVisible(){return!this.alwaysHide&&0!==this.opacity}setVertical(_){this._vertical=_,this._vertical?(this.left="",this.width=""):(this.bottom="",this.height="")}setScale(_){this._scale=_}setRotate(_){this._rotate=_,this.transform="rotate("+_+"deg)"}getRotate(){return this._rotate}setPosition(_){this._position!==_&&!this.isRefDestroyed()&&this.changeDetectionRef.markForCheck(),this._position=_,this._vertical?this.bottom=Math.round(_)+"px":this.left=Math.round(_)+"px"}calculateDimension(){const _=this.getBoundingClientRect();this._dimension=this.vertical?(_.bottom-_.top)*this.scale:(_.right-_.left)*this.scale}setDimension(_){this._dimension!==_&&!this.isRefDestroyed()&&this.changeDetectionRef.markForCheck(),this._dimension=_,this._vertical?this.height=Math.round(_)+"px":this.width=Math.round(_)+"px"}getBoundingClientRect(){return this.elemRef.nativeElement.getBoundingClientRect()}on(_,A,H){const E=this.eventListenerHelper.attachEventListener(this.elemRef.nativeElement,_,A,H);this.eventListeners.push(E)}onPassive(_,A,H){const E=this.eventListenerHelper.attachPassiveEventListener(this.elemRef.nativeElement,_,A,H);this.eventListeners.push(E)}off(_){let A,H;ce.isNullOrUndefined(_)?(A=[],H=this.eventListeners):(A=this.eventListeners.filter(E=>E.eventName!==_),H=this.eventListeners.filter(E=>E.eventName===_));for(const E of H)this.eventListenerHelper.detachEventListener(E);this.eventListeners=A}isRefDestroyed(){return ce.isNullOrUndefined(this.changeDetectionRef)||this.changeDetectionRef.destroyed}static \u0275fac=function(A){return new(A||ve)(F.rXU(F.aKT),F.rXU(F.sFG),F.rXU(F.gRc))};static \u0275dir=F.FsC({type:ve,selectors:[["","ngxSliderElement",""]],hostVars:14,hostBindings:function(A,H){2&A&&F.xc7("opacity",H.opacity)("visibility",H.visibility)("left",H.left)("bottom",H.bottom)("height",H.height)("width",H.width)("transform",H.transform)},standalone:!1})}return ve})(),vi=(()=>{class ve extends Cs{active=!1;role="";tabindex="";ariaOrientation="";ariaLabel="";ariaLabelledBy="";ariaValueNow="";ariaValueText="";ariaValueMin="";ariaValueMax="";focus(){this.elemRef.nativeElement.focus()}focusIfNeeded(){document.activeElement!==this.elemRef.nativeElement&&this.elemRef.nativeElement.focus()}constructor(_,A,H){super(_,A,H)}static \u0275fac=function(A){return new(A||ve)(F.rXU(F.aKT),F.rXU(F.sFG),F.rXU(F.gRc))};static \u0275dir=F.FsC({type:ve,selectors:[["","ngxSliderHandle",""]],hostVars:11,hostBindings:function(A,H){2&A&&(F.BMQ("role",H.role)("tabindex",H.tabindex)("aria-orientation",H.ariaOrientation)("aria-label",H.ariaLabel)("aria-labelledby",H.ariaLabelledBy)("aria-valuenow",H.ariaValueNow)("aria-valuetext",H.ariaValueText)("aria-valuemin",H.ariaValueMin)("aria-valuemax",H.ariaValueMax),F.AVh("ngx-slider-active",H.active))},standalone:!1,features:[F.Vt3]})}return ve})(),Ue=(()=>{class ve extends Cs{allowUnsafeHtmlInSlider;_value=null;get value(){return this._value}constructor(_,A,H,E){super(_,A,H),this.allowUnsafeHtmlInSlider=E}setValue(_){let A=!1;!this.alwaysHide&&(ce.isNullOrUndefined(this.value)||this.value.length!==_.length||this.value.length>0&&0===this.dimension)&&(A=!0),this._value=_,!1===this.allowUnsafeHtmlInSlider?this.elemRef.nativeElement.innerText=_:this.elemRef.nativeElement.innerHTML=_,A&&this.calculateDimension()}static \u0275fac=function(A){return new(A||ve)(F.rXU(F.aKT),F.rXU(F.sFG),F.rXU(F.gRc),F.rXU(Hl,8))};static \u0275dir=F.FsC({type:ve,selectors:[["","ngxSliderLabel",""]],standalone:!1,features:[F.Vt3]})}return ve})(),jl=(()=>{class ve{template;tooltip;placement;content;static \u0275fac=function(A){return new(A||ve)};static \u0275cmp=F.VBU({type:ve,selectors:[["ngx-slider-tooltip-wrapper"]],inputs:{template:"template",tooltip:"tooltip",placement:"placement",content:"content"},standalone:!1,decls:2,vars:2,consts:[[4,"ngIf"],[4,"ngTemplateOutlet","ngTemplateOutletContext"],[1,"ngx-slider-inner-tooltip"]],template:function(A,H){1&A&&F.DNE(0,X,2,6,"ng-container",0)(1,re,3,3,"ng-container",0),2&A&&(F.Y8G("ngIf",H.template),F.R7$(),F.Y8G("ngIf",!H.template))},dependencies:[Re.bT,Re.T3],styles:[".ngx-slider-inner-tooltip[_ngcontent-%COMP%]{height:100%}"]})}return ve})();class ds{selected=!1;style={};tooltip=null;tooltipPlacement=null;value=null;valueTooltip=null;valueTooltipPlacement=null;legend=null}class Xl{active=!1;value=0;difference=0;position=0;lowLimit=0;highLimit=0}class Vr{value;highValue;static compare(Oe,_){return!(ce.isNullOrUndefined(Oe)&&ce.isNullOrUndefined(_)||ce.isNullOrUndefined(Oe)!==ce.isNullOrUndefined(_))&&Oe.value===_.value&&Oe.highValue===_.highValue}}class yn extends Vr{forceChange;static compare(Oe,_){return!(ce.isNullOrUndefined(Oe)&&ce.isNullOrUndefined(_)||ce.isNullOrUndefined(Oe)!==ce.isNullOrUndefined(_))&&Oe.value===_.value&&Oe.highValue===_.highValue&&Oe.forceChange===_.forceChange}}const Is={provide:Ke.kq,useExisting:(0,F.Rfq)(()=>wr),multi:!0};let wr=(()=>{class ve{renderer;elementRef;changeDetectionRef;zone;allowUnsafeHtmlInSlider;sliderElementNgxSliderClass=!0;value=null;valueChange=new F.bkB;highValue=null;highValueChange=new F.bkB;options=new sa;userChangeStart=new F.bkB;userChange=new F.bkB;userChangeEnd=new F.bkB;manualRefreshSubscription;set manualRefresh(_){this.unsubscribeManualRefresh(),this.manualRefreshSubscription=_.subscribe(()=>{setTimeout(()=>this.calculateViewDimensionsAndDetectChanges())})}triggerFocusSubscription;set triggerFocus(_){this.unsubscribeTriggerFocus(),this.triggerFocusSubscription=_.subscribe(A=>{this.focusPointer(A)})}cancelUserChangeSubscription;set cancelUserChange(_){this.unsubscribeCancelUserChange(),this.cancelUserChangeSubscription=_.subscribe(()=>{this.moving&&(this.positionTrackingHandle(this.preStartHandleValue),this.forceEnd(!0))})}get range(){return!ce.isNullOrUndefined(this.value)&&!ce.isNullOrUndefined(this.highValue)}initHasRun=!1;inputModelChangeSubject=new Tt.B;inputModelChangeSubscription=null;outputModelChangeSubject=new Tt.B;outputModelChangeSubscription=null;viewLowValue=null;viewHighValue=null;viewOptions=new sa;handleHalfDimension=0;maxHandlePosition=0;currentTrackingPointer=null;currentFocusPointer=null;firstKeyDown=!1;touchId=null;dragging=new Xl;preStartHandleValue=null;leftOuterSelectionBarElement;rightOuterSelectionBarElement;fullBarElement;selectionBarElement;minHandleElement;maxHandleElement;floorLabelElement;ceilLabelElement;minHandleLabelElement;maxHandleLabelElement;combinedLabelElement;ticksElement;tooltipTemplate;sliderElementVerticalClass=!1;sliderElementAnimateClass=!1;sliderElementWithLegendClass=!1;sliderElementDisabledAttr=null;sliderElementAriaLabel="ngx-slider";barStyle={};minPointerStyle={};maxPointerStyle={};fullBarTransparentClass=!1;selectionBarDraggableClass=!1;ticksUnderValuesClass=!1;get showTicks(){return this.viewOptions.showTicks}intermediateTicks=!1;ticks=[];eventListenerHelper=null;onMoveEventListener=null;onEndEventListener=null;moving=!1;resizeObserver=null;onTouchedCallback=null;onChangeCallback=null;constructor(_,A,H,E,ye){this.renderer=_,this.elementRef=A,this.changeDetectionRef=H,this.zone=E,this.allowUnsafeHtmlInSlider=ye,this.eventListenerHelper=new vr(this.renderer)}ngOnInit(){this.viewOptions=new sa,Object.assign(this.viewOptions,this.options),this.updateDisabledState(),this.updateVerticalState(),this.updateAriaLabel()}ngAfterViewInit(){this.applyOptions(),this.subscribeInputModelChangeSubject(),this.subscribeOutputModelChangeSubject(),this.renormaliseModelValues(),this.viewLowValue=this.modelValueToViewValue(this.value),this.viewHighValue=this.range?this.modelValueToViewValue(this.highValue):null,this.updateVerticalState(),this.manageElementsStyle(),this.updateDisabledState(),this.calculateViewDimensions(),this.addAccessibility(),this.updateCeilLabel(),this.updateFloorLabel(),this.initHandles(),this.manageEventsBindings(),this.updateAriaLabel(),this.subscribeResizeObserver(),this.initHasRun=!0,this.isRefDestroyed()||this.changeDetectionRef.detectChanges()}ngOnChanges(_){!ce.isNullOrUndefined(_.options)&&JSON.stringify(_.options.previousValue)!==JSON.stringify(_.options.currentValue)&&this.onChangeOptions(),(!ce.isNullOrUndefined(_.value)||!ce.isNullOrUndefined(_.highValue))&&this.inputModelChangeSubject.next({value:this.value,highValue:this.highValue,controlAccessorChange:!1,forceChange:!1,internalChange:!1})}ngOnDestroy(){this.unbindEvents(),this.unsubscribeResizeObserver(),this.unsubscribeInputModelChangeSubject(),this.unsubscribeOutputModelChangeSubject(),this.unsubscribeManualRefresh(),this.unsubscribeTriggerFocus()}writeValue(_){_ instanceof Array?(this.value=_[0],this.highValue=_[1]):this.value=_,this.inputModelChangeSubject.next({value:this.value,highValue:this.highValue,forceChange:!1,internalChange:!1,controlAccessorChange:!0})}registerOnChange(_){this.onChangeCallback=_}registerOnTouched(_){this.onTouchedCallback=_}setDisabledState(_){this.viewOptions.disabled=_,this.updateDisabledState(),this.initHasRun&&this.manageEventsBindings()}setAriaLabel(_){this.viewOptions.ariaLabel=_,this.updateAriaLabel()}onResize(_){this.calculateViewDimensionsAndDetectChanges()}subscribeInputModelChangeSubject(){this.inputModelChangeSubscription=this.inputModelChangeSubject.pipe((0,fe.F)(yn.compare),(0,Pe.p)(_=>!_.forceChange&&!_.internalChange)).subscribe(_=>this.applyInputModelChange(_))}subscribeOutputModelChangeSubject(){this.outputModelChangeSubscription=this.outputModelChangeSubject.pipe((0,fe.F)(yn.compare)).subscribe(_=>this.publishOutputModelChange(_))}subscribeResizeObserver(){os.isResizeObserverAvailable()&&(this.resizeObserver=new ResizeObserver(()=>this.calculateViewDimensionsAndDetectChanges()),this.resizeObserver.observe(this.elementRef.nativeElement))}unsubscribeResizeObserver(){os.isResizeObserverAvailable()&&null!==this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null)}unsubscribeOnMove(){ce.isNullOrUndefined(this.onMoveEventListener)||(this.eventListenerHelper.detachEventListener(this.onMoveEventListener),this.onMoveEventListener=null)}unsubscribeOnEnd(){ce.isNullOrUndefined(this.onEndEventListener)||(this.eventListenerHelper.detachEventListener(this.onEndEventListener),this.onEndEventListener=null)}unsubscribeInputModelChangeSubject(){ce.isNullOrUndefined(this.inputModelChangeSubscription)||(this.inputModelChangeSubscription.unsubscribe(),this.inputModelChangeSubscription=null)}unsubscribeOutputModelChangeSubject(){ce.isNullOrUndefined(this.outputModelChangeSubscription)||(this.outputModelChangeSubscription.unsubscribe(),this.outputModelChangeSubscription=null)}unsubscribeManualRefresh(){ce.isNullOrUndefined(this.manualRefreshSubscription)||(this.manualRefreshSubscription.unsubscribe(),this.manualRefreshSubscription=null)}unsubscribeTriggerFocus(){ce.isNullOrUndefined(this.triggerFocusSubscription)||(this.triggerFocusSubscription.unsubscribe(),this.triggerFocusSubscription=null)}unsubscribeCancelUserChange(){ce.isNullOrUndefined(this.cancelUserChangeSubscription)||(this.cancelUserChangeSubscription.unsubscribe(),this.cancelUserChangeSubscription=null)}getPointerElement(_){return _===Ve.Min?this.minHandleElement:_===Ve.Max?this.maxHandleElement:null}getCurrentTrackingValue(){return this.currentTrackingPointer===Ve.Min?this.viewLowValue:this.currentTrackingPointer===Ve.Max?this.viewHighValue:null}modelValueToViewValue(_){return ce.isNullOrUndefined(_)?NaN:ce.isNullOrUndefined(this.viewOptions.stepsArray)||this.viewOptions.bindIndexForStepsArray?+_:ce.findStepIndex(+_,this.viewOptions.stepsArray)}viewValueToModelValue(_){return ce.isNullOrUndefined(this.viewOptions.stepsArray)||this.viewOptions.bindIndexForStepsArray?_:this.getStepValue(_)}getStepValue(_){const A=this.viewOptions.stepsArray[_];return ce.isNullOrUndefined(A)?NaN:A.value}applyViewChange(){this.value=this.viewValueToModelValue(this.viewLowValue),this.range&&(this.highValue=this.viewValueToModelValue(this.viewHighValue)),this.outputModelChangeSubject.next({value:this.value,highValue:this.highValue,controlAccessorChange:!1,userEventInitiated:!0,forceChange:!1}),this.inputModelChangeSubject.next({value:this.value,highValue:this.highValue,controlAccessorChange:!1,forceChange:!1,internalChange:!0})}applyInputModelChange(_){const A=this.normaliseModelValues(_),H=!Vr.compare(_,A);H&&(this.value=A.value,this.highValue=A.highValue),this.viewLowValue=this.modelValueToViewValue(A.value),this.viewHighValue=this.range?this.modelValueToViewValue(A.highValue):null,this.updateLowHandle(this.valueToPosition(this.viewLowValue)),this.range&&this.updateHighHandle(this.valueToPosition(this.viewHighValue)),this.updateSelectionBar(),this.updateTicksScale(),this.updateAriaAttributes(),this.range&&this.updateCombinedLabel(),this.outputModelChangeSubject.next({value:A.value,highValue:A.highValue,controlAccessorChange:_.controlAccessorChange,forceChange:H,userEventInitiated:!1})}publishOutputModelChange(_){const A=()=>{this.valueChange.emit(_.value),this.range&&this.highValueChange.emit(_.highValue),!_.controlAccessorChange&&(ce.isNullOrUndefined(this.onChangeCallback)||this.onChangeCallback(this.range?[_.value,_.highValue]:_.value),ce.isNullOrUndefined(this.onTouchedCallback)||this.onTouchedCallback(this.range?[_.value,_.highValue]:_.value))};_.userEventInitiated?(A(),this.userChange.emit(this.getChangeContext())):setTimeout(()=>{A()})}normaliseModelValues(_){const A=new Vr;if(A.value=_.value,A.highValue=_.highValue,!ce.isNullOrUndefined(this.viewOptions.stepsArray)){if(this.viewOptions.enforceStepsArray){const H=ce.findStepIndex(A.value,this.viewOptions.stepsArray);if(A.value=this.viewOptions.stepsArray[H].value,this.range){const E=ce.findStepIndex(A.highValue,this.viewOptions.stepsArray);A.highValue=this.viewOptions.stepsArray[E].value}}return A}if(this.viewOptions.enforceStep&&(A.value=this.roundStep(A.value),this.range&&(A.highValue=this.roundStep(A.highValue))),this.viewOptions.enforceRange&&(A.value=ln.clampToRange(A.value,this.viewOptions.floor,this.viewOptions.ceil),this.range&&(A.highValue=ln.clampToRange(A.highValue,this.viewOptions.floor,this.viewOptions.ceil)),this.range&&_.value>_.highValue))if(this.viewOptions.noSwitching)A.value=A.highValue;else{const H=_.value;A.value=_.highValue,A.highValue=H}return A}renormaliseModelValues(){const _={value:this.value,highValue:this.highValue},A=this.normaliseModelValues(_);Vr.compare(A,_)||(this.value=A.value,this.highValue=A.highValue,this.outputModelChangeSubject.next({value:this.value,highValue:this.highValue,controlAccessorChange:!1,forceChange:!0,userEventInitiated:!1}))}onChangeOptions(){if(!this.initHasRun)return;const _=this.getOptionsInfluencingEventBindings(this.viewOptions);this.applyOptions();const A=this.getOptionsInfluencingEventBindings(this.viewOptions),H=!ce.areArraysEqual(_,A);this.renormaliseModelValues(),this.viewLowValue=this.modelValueToViewValue(this.value),this.viewHighValue=this.range?this.modelValueToViewValue(this.highValue):null,this.resetSlider(H)}applyOptions(){if(this.viewOptions=new sa,Object.assign(this.viewOptions,this.options),this.viewOptions.draggableRange=this.range&&this.viewOptions.draggableRange,this.viewOptions.draggableRangeOnly=this.range&&this.viewOptions.draggableRangeOnly,this.viewOptions.draggableRangeOnly&&(this.viewOptions.draggableRange=!0),this.viewOptions.showTicks=this.viewOptions.showTicks||this.viewOptions.showTicksValues||!ce.isNullOrUndefined(this.viewOptions.ticksArray),this.viewOptions.showTicks&&(!ce.isNullOrUndefined(this.viewOptions.tickStep)||!ce.isNullOrUndefined(this.viewOptions.ticksArray))&&(this.intermediateTicks=!0),this.viewOptions.showSelectionBar=this.viewOptions.showSelectionBar||this.viewOptions.showSelectionBarEnd||!ce.isNullOrUndefined(this.viewOptions.showSelectionBarFromValue),ce.isNullOrUndefined(this.viewOptions.stepsArray)?this.applyFloorCeilOptions():this.applyStepsArrayOptions(),ce.isNullOrUndefined(this.viewOptions.combineLabels)&&(this.viewOptions.combineLabels=(_,A)=>_+" - "+A),this.viewOptions.logScale&&0===this.viewOptions.floor)throw Error("Can't use floor=0 with logarithmic scale")}applyStepsArrayOptions(){this.viewOptions.floor=0,this.viewOptions.ceil=this.viewOptions.stepsArray.length-1,this.viewOptions.step=1,ce.isNullOrUndefined(this.viewOptions.translate)&&(this.viewOptions.translate=_=>String(this.viewOptions.bindIndexForStepsArray?this.getStepValue(_):_))}applyFloorCeilOptions(){if(ce.isNullOrUndefined(this.viewOptions.step)?this.viewOptions.step=1:(this.viewOptions.step=+this.viewOptions.step,this.viewOptions.step<=0&&(this.viewOptions.step=1)),ce.isNullOrUndefined(this.viewOptions.ceil)||ce.isNullOrUndefined(this.viewOptions.floor))throw Error("floor and ceil options must be supplied");this.viewOptions.ceil=+this.viewOptions.ceil,this.viewOptions.floor=+this.viewOptions.floor,ce.isNullOrUndefined(this.viewOptions.translate)&&(this.viewOptions.translate=_=>String(_))}resetSlider(_=!0){this.manageElementsStyle(),this.addAccessibility(),this.updateCeilLabel(),this.updateFloorLabel(),_&&(this.unbindEvents(),this.manageEventsBindings()),this.updateDisabledState(),this.updateAriaLabel(),this.calculateViewDimensions(),this.refocusPointerIfNeeded()}focusPointer(_){_!==Ve.Min&&_!==Ve.Max&&(_=Ve.Min),_===Ve.Min?this.minHandleElement.focus():this.range&&_===Ve.Max&&this.maxHandleElement.focus()}refocusPointerIfNeeded(){ce.isNullOrUndefined(this.currentFocusPointer)||this.getPointerElement(this.currentFocusPointer).focusIfNeeded()}manageElementsStyle(){this.updateScale(),this.floorLabelElement.setAlwaysHide(this.viewOptions.showTicksValues||this.viewOptions.hideLimitLabels),this.ceilLabelElement.setAlwaysHide(this.viewOptions.showTicksValues||this.viewOptions.hideLimitLabels);const _=this.viewOptions.showTicksValues&&!this.intermediateTicks;this.minHandleLabelElement.setAlwaysHide(_||this.viewOptions.hidePointerLabels),this.maxHandleLabelElement.setAlwaysHide(_||!this.range||this.viewOptions.hidePointerLabels),this.combinedLabelElement.setAlwaysHide(_||!this.range||this.viewOptions.hidePointerLabels),this.selectionBarElement.setAlwaysHide(!this.range&&!this.viewOptions.showSelectionBar),this.leftOuterSelectionBarElement.setAlwaysHide(!this.range||!this.viewOptions.showOuterSelectionBars),this.rightOuterSelectionBarElement.setAlwaysHide(!this.range||!this.viewOptions.showOuterSelectionBars),this.fullBarTransparentClass=this.range&&this.viewOptions.showOuterSelectionBars,this.selectionBarDraggableClass=this.viewOptions.draggableRange&&!this.viewOptions.onlyBindHandles,this.ticksUnderValuesClass=this.intermediateTicks&&this.options.showTicksValues,this.sliderElementVerticalClass!==this.viewOptions.vertical&&(this.updateVerticalState(),setTimeout(()=>{this.resetSlider()})),this.sliderElementAnimateClass!==this.viewOptions.animate&&setTimeout(()=>{this.sliderElementAnimateClass=this.viewOptions.animate}),this.updateRotate()}manageEventsBindings(){this.viewOptions.disabled||this.viewOptions.readOnly?this.unbindEvents():this.bindEvents()}updateDisabledState(){this.sliderElementDisabledAttr=this.viewOptions.disabled?"disabled":null}updateAriaLabel(){this.sliderElementAriaLabel=this.viewOptions.ariaLabel||"nxg-slider"}updateVerticalState(){this.sliderElementVerticalClass=this.viewOptions.vertical;for(const _ of this.getAllSliderElements())ce.isNullOrUndefined(_)||_.setVertical(this.viewOptions.vertical)}updateScale(){for(const _ of this.getAllSliderElements())_.setScale(this.viewOptions.scale)}updateRotate(){for(const _ of this.getAllSliderElements())_.setRotate(this.viewOptions.rotate)}getAllSliderElements(){return[this.leftOuterSelectionBarElement,this.rightOuterSelectionBarElement,this.fullBarElement,this.selectionBarElement,this.minHandleElement,this.maxHandleElement,this.floorLabelElement,this.ceilLabelElement,this.minHandleLabelElement,this.maxHandleLabelElement,this.combinedLabelElement,this.ticksElement]}initHandles(){this.updateLowHandle(this.valueToPosition(this.viewLowValue)),this.range&&this.updateHighHandle(this.valueToPosition(this.viewHighValue)),this.updateSelectionBar(),this.range&&this.updateCombinedLabel(),this.updateTicksScale()}addAccessibility(){this.updateAriaAttributes(),this.minHandleElement.role="slider",this.minHandleElement.tabindex=!this.viewOptions.keyboardSupport||this.viewOptions.readOnly||this.viewOptions.disabled?"":"0",this.minHandleElement.ariaOrientation=this.viewOptions.vertical||0!==this.viewOptions.rotate?"vertical":"horizontal",ce.isNullOrUndefined(this.viewOptions.ariaLabel)?ce.isNullOrUndefined(this.viewOptions.ariaLabelledBy)||(this.minHandleElement.ariaLabelledBy=this.viewOptions.ariaLabelledBy):this.minHandleElement.ariaLabel=this.viewOptions.ariaLabel,this.range&&(this.maxHandleElement.role="slider",this.maxHandleElement.tabindex=!this.viewOptions.keyboardSupport||this.viewOptions.readOnly||this.viewOptions.disabled?"":"0",this.maxHandleElement.ariaOrientation=this.viewOptions.vertical||0!==this.viewOptions.rotate?"vertical":"horizontal",ce.isNullOrUndefined(this.viewOptions.ariaLabelHigh)?ce.isNullOrUndefined(this.viewOptions.ariaLabelledByHigh)||(this.maxHandleElement.ariaLabelledBy=this.viewOptions.ariaLabelledByHigh):this.maxHandleElement.ariaLabel=this.viewOptions.ariaLabelHigh)}updateAriaAttributes(){this.minHandleElement.ariaValueNow=(+this.value).toString(),this.minHandleElement.ariaValueText=this.viewOptions.translate(+this.value,$t.Low),this.minHandleElement.ariaValueMin=this.viewOptions.floor.toString(),this.minHandleElement.ariaValueMax=this.viewOptions.ceil.toString(),this.range&&(this.maxHandleElement.ariaValueNow=(+this.highValue).toString(),this.maxHandleElement.ariaValueText=this.viewOptions.translate(+this.highValue,$t.High),this.maxHandleElement.ariaValueMin=this.viewOptions.floor.toString(),this.maxHandleElement.ariaValueMax=this.viewOptions.ceil.toString())}calculateViewDimensions(){ce.isNullOrUndefined(this.viewOptions.handleDimension)?this.minHandleElement.calculateDimension():this.minHandleElement.setDimension(this.viewOptions.handleDimension);const _=this.minHandleElement.dimension;this.handleHalfDimension=_/2,ce.isNullOrUndefined(this.viewOptions.barDimension)?this.fullBarElement.calculateDimension():this.fullBarElement.setDimension(this.viewOptions.barDimension),this.maxHandlePosition=this.fullBarElement.dimension-_,this.initHasRun&&(this.updateFloorLabel(),this.updateCeilLabel(),this.initHandles())}calculateViewDimensionsAndDetectChanges(){this.calculateViewDimensions(),this.isRefDestroyed()||this.changeDetectionRef.detectChanges()}isRefDestroyed(){return this.changeDetectionRef.destroyed}updateTicksScale(){if(!this.viewOptions.showTicks&&this.sliderElementWithLegendClass)return void setTimeout(()=>{this.sliderElementWithLegendClass=!1});const _=ce.isNullOrUndefined(this.viewOptions.ticksArray)?this.getTicksArray():this.viewOptions.ticksArray,A=this.viewOptions.vertical?"translateY":"translateX";this.viewOptions.rightToLeft&&_.reverse();const H=ce.isNullOrUndefined(this.viewOptions.tickValueStep)?ce.isNullOrUndefined(this.viewOptions.tickStep)?this.viewOptions.step:this.viewOptions.tickStep:this.viewOptions.tickValueStep;let E=!1;const ye=_.map(Je=>{let gt=this.valueToPosition(Je);this.viewOptions.vertical&&(gt=this.maxHandlePosition-gt);const zt=A+"("+Math.round(gt)+"px)",bt=new ds;bt.selected=this.isTickSelected(Je),bt.style={"-webkit-transform":zt,"-moz-transform":zt,"-o-transform":zt,"-ms-transform":zt,transform:zt},bt.selected&&!ce.isNullOrUndefined(this.viewOptions.getSelectionBarColor)&&(bt.style["background-color"]=this.getSelectionBarColor()),!bt.selected&&!ce.isNullOrUndefined(this.viewOptions.getTickColor)&&(bt.style["background-color"]=this.getTickColor(Je)),ce.isNullOrUndefined(this.viewOptions.ticksTooltip)||(bt.tooltip=this.viewOptions.ticksTooltip(Je),bt.tooltipPlacement=this.viewOptions.vertical?"right":"top"),this.viewOptions.showTicksValues&&!ce.isNullOrUndefined(H)&&ln.isModuloWithinPrecisionLimit(Je,H,this.viewOptions.precisionLimit)&&(bt.value=this.getDisplayValue(Je,$t.TickValue),ce.isNullOrUndefined(this.viewOptions.ticksValuesTooltip)||(bt.valueTooltip=this.viewOptions.ticksValuesTooltip(Je),bt.valueTooltipPlacement=this.viewOptions.vertical?"right":"top"));let xn=null;if(ce.isNullOrUndefined(this.viewOptions.stepsArray))ce.isNullOrUndefined(this.viewOptions.getLegend)||(xn=this.viewOptions.getLegend(Je));else{const In=this.viewOptions.stepsArray[Je];ce.isNullOrUndefined(this.viewOptions.getStepLegend)?ce.isNullOrUndefined(In)||(xn=In.legend):xn=this.viewOptions.getStepLegend(In)}return ce.isNullOrUndefined(xn)||(bt.legend=xn,E=!0),bt});if(this.sliderElementWithLegendClass!==E&&setTimeout(()=>{this.sliderElementWithLegendClass=E}),ce.isNullOrUndefined(this.ticks)||this.ticks.length!==ye.length)this.ticks=ye,this.isRefDestroyed()||this.changeDetectionRef.detectChanges();else for(let Je=0;Je=this.viewLowValue)return!0}else if(this.viewOptions.showSelectionBar&&_<=this.viewLowValue)return!0}else{const A=this.viewOptions.showSelectionBarFromValue;if(this.viewLowValue>A&&_>=A&&_<=this.viewLowValue)return!0;if(this.viewLowValue=this.viewLowValue)return!0}return!!(this.range&&_>=this.viewLowValue&&_<=this.viewHighValue)}updateFloorLabel(){this.floorLabelElement.alwaysHide||(this.floorLabelElement.setValue(this.getDisplayValue(this.viewOptions.floor,$t.Floor)),this.floorLabelElement.calculateDimension(),this.floorLabelElement.setPosition(this.viewOptions.rightToLeft?this.fullBarElement.dimension-this.floorLabelElement.dimension:0))}updateCeilLabel(){this.ceilLabelElement.alwaysHide||(this.ceilLabelElement.setValue(this.getDisplayValue(this.viewOptions.ceil,$t.Ceil)),this.ceilLabelElement.calculateDimension(),this.ceilLabelElement.setPosition(this.viewOptions.rightToLeft?0:this.fullBarElement.dimension-this.ceilLabelElement.dimension))}updateHandles(_,A){_===Ve.Min?this.updateLowHandle(A):_===Ve.Max&&this.updateHighHandle(A),this.updateSelectionBar(),this.updateTicksScale(),this.range&&this.updateCombinedLabel()}getHandleLabelPos(_,A){const H=_===Ve.Min?this.minHandleLabelElement.dimension:this.maxHandleLabelElement.dimension,E=A-H/2+this.handleHalfDimension,ye=this.fullBarElement.dimension-H;return this.viewOptions.boundPointerLabels?this.viewOptions.rightToLeft&&_===Ve.Min||!this.viewOptions.rightToLeft&&_===Ve.Max?Math.min(E,ye):Math.min(Math.max(E,0),ye):E}updateLowHandle(_){this.minHandleElement.setPosition(_),this.minHandleLabelElement.setValue(this.getDisplayValue(this.viewLowValue,$t.Low)),this.minHandleLabelElement.setPosition(this.getHandleLabelPos(Ve.Min,_)),ce.isNullOrUndefined(this.viewOptions.getPointerColor)||(this.minPointerStyle={backgroundColor:this.getPointerColor(Ve.Min)}),this.viewOptions.autoHideLimitLabels&&this.updateFloorAndCeilLabelsVisibility()}updateHighHandle(_){this.maxHandleElement.setPosition(_),this.maxHandleLabelElement.setValue(this.getDisplayValue(this.viewHighValue,$t.High)),this.maxHandleLabelElement.setPosition(this.getHandleLabelPos(Ve.Max,_)),ce.isNullOrUndefined(this.viewOptions.getPointerColor)||(this.maxPointerStyle={backgroundColor:this.getPointerColor(Ve.Max)}),this.viewOptions.autoHideLimitLabels&&this.updateFloorAndCeilLabelsVisibility()}updateFloorAndCeilLabelsVisibility(){if(this.viewOptions.hidePointerLabels)return;let _=!1,A=!1;const H=this.isLabelBelowFloorLabel(this.minHandleLabelElement),E=this.isLabelAboveCeilLabel(this.minHandleLabelElement),ye=this.isLabelAboveCeilLabel(this.maxHandleLabelElement),Je=this.isLabelBelowFloorLabel(this.combinedLabelElement),gt=this.isLabelAboveCeilLabel(this.combinedLabelElement);if(H?(_=!0,this.floorLabelElement.hide()):(_=!1,this.floorLabelElement.show()),E?(A=!0,this.ceilLabelElement.hide()):(A=!1,this.ceilLabelElement.show()),this.range){const zt=this.combinedLabelElement.isVisible()?gt:ye,bt=this.combinedLabelElement.isVisible()?Je:H;zt?this.ceilLabelElement.hide():A||this.ceilLabelElement.show(),bt?this.floorLabelElement.hide():_||this.floorLabelElement.show()}}isLabelBelowFloorLabel(_){const A=_.position,E=this.floorLabelElement.position;return this.viewOptions.rightToLeft?A+_.dimension>=E-2:A<=E+this.floorLabelElement.dimension+2}isLabelAboveCeilLabel(_){const A=_.position,E=this.ceilLabelElement.position;return this.viewOptions.rightToLeft?A<=E+this.ceilLabelElement.dimension+2:A+_.dimension>=E-2}updateSelectionBar(){let _=0,A=0;const H=this.viewOptions.rightToLeft?!this.viewOptions.showSelectionBarEnd:this.viewOptions.showSelectionBarEnd,E=this.viewOptions.rightToLeft?this.maxHandleElement.position+this.handleHalfDimension:this.minHandleElement.position+this.handleHalfDimension;if(this.range)A=Math.abs(this.maxHandleElement.position-this.minHandleElement.position),_=E;else if(ce.isNullOrUndefined(this.viewOptions.showSelectionBarFromValue))H?(A=Math.ceil(Math.abs(this.maxHandlePosition-this.minHandleElement.position)+this.handleHalfDimension),_=Math.floor(this.minHandleElement.position+this.handleHalfDimension)):(A=this.minHandleElement.position+this.handleHalfDimension,_=0);else{const ye=this.viewOptions.showSelectionBarFromValue,Je=this.valueToPosition(ye);(this.viewOptions.rightToLeft?this.viewLowValue<=ye:this.viewLowValue>ye)?(A=this.minHandleElement.position-Je,_=Je+this.handleHalfDimension):(A=Je-this.minHandleElement.position,_=this.minHandleElement.position+this.handleHalfDimension)}if(this.selectionBarElement.setDimension(A),this.selectionBarElement.setPosition(_),this.range&&this.viewOptions.showOuterSelectionBars&&(this.viewOptions.rightToLeft?(this.rightOuterSelectionBarElement.setDimension(_),this.rightOuterSelectionBarElement.setPosition(0),this.fullBarElement.calculateDimension(),this.leftOuterSelectionBarElement.setDimension(this.fullBarElement.dimension-(_+A)),this.leftOuterSelectionBarElement.setPosition(_+A)):(this.leftOuterSelectionBarElement.setDimension(_),this.leftOuterSelectionBarElement.setPosition(0),this.fullBarElement.calculateDimension(),this.rightOuterSelectionBarElement.setDimension(this.fullBarElement.dimension-(_+A)),this.rightOuterSelectionBarElement.setPosition(_+A))),ce.isNullOrUndefined(this.viewOptions.getSelectionBarColor)){if(!ce.isNullOrUndefined(this.viewOptions.selectionBarGradient)){const ye=ce.isNullOrUndefined(this.viewOptions.showSelectionBarFromValue)?0:this.valueToPosition(this.viewOptions.showSelectionBarFromValue),Je=ye-_>0&&!H||ye-_<=0&&H;this.barStyle={backgroundImage:"linear-gradient(to "+(this.viewOptions.vertical?Je?"bottom":"top":Je?"left":"right")+", "+this.viewOptions.selectionBarGradient.from+" 0%,"+this.viewOptions.selectionBarGradient.to+" 100%)"},this.viewOptions.vertical?(this.barStyle.backgroundPosition="center "+(ye+A+_+(Je?-this.handleHalfDimension:0))+"px",this.barStyle.backgroundSize="100% "+(this.fullBarElement.dimension-this.handleHalfDimension)+"px"):(this.barStyle.backgroundPosition=ye-_+(Je?this.handleHalfDimension:0)+"px center",this.barStyle.backgroundSize=this.fullBarElement.dimension-this.handleHalfDimension+"px 100%")}}else{const ye=this.getSelectionBarColor();this.barStyle={backgroundColor:ye}}}getSelectionBarColor(){return this.range?this.viewOptions.getSelectionBarColor(this.value,this.highValue):this.viewOptions.getSelectionBarColor(this.value)}getPointerColor(_){return this.viewOptions.getPointerColor(_===Ve.Max?this.highValue:this.value,_)}getTickColor(_){return this.viewOptions.getTickColor(_)}updateCombinedLabel(){let _=null;if(_=this.viewOptions.rightToLeft?this.minHandleLabelElement.position-this.minHandleLabelElement.dimension-10<=this.maxHandleLabelElement.position:this.minHandleLabelElement.position+this.minHandleLabelElement.dimension+10>=this.maxHandleLabelElement.position,_){const A=this.getDisplayValue(this.viewLowValue,$t.Low),H=this.getDisplayValue(this.viewHighValue,$t.High),E=this.viewOptions.rightToLeft?this.viewOptions.combineLabels(H,A):this.viewOptions.combineLabels(A,H);this.combinedLabelElement.setValue(E);const ye=this.viewOptions.boundPointerLabels?Math.min(Math.max(this.selectionBarElement.position+this.selectionBarElement.dimension/2-this.combinedLabelElement.dimension/2,0),this.fullBarElement.dimension-this.combinedLabelElement.dimension):this.selectionBarElement.position+this.selectionBarElement.dimension/2-this.combinedLabelElement.dimension/2;this.combinedLabelElement.setPosition(ye),this.minHandleLabelElement.hide(),this.maxHandleLabelElement.hide(),this.combinedLabelElement.show()}else this.updateHighHandle(this.valueToPosition(this.viewHighValue)),this.updateLowHandle(this.valueToPosition(this.viewLowValue)),this.maxHandleLabelElement.show(),this.minHandleLabelElement.show(),this.combinedLabelElement.hide();this.viewOptions.autoHideLimitLabels&&this.updateFloorAndCeilLabelsVisibility()}getDisplayValue(_,A){return!ce.isNullOrUndefined(this.viewOptions.stepsArray)&&!this.viewOptions.bindIndexForStepsArray&&(_=this.getStepValue(_)),this.viewOptions.translate(_,A)}roundStep(_,A){const H=ce.isNullOrUndefined(A)?this.viewOptions.step:A;let E=ln.roundToPrecisionLimit((_-this.viewOptions.floor)/H,this.viewOptions.precisionLimit);return E=Math.round(E)*H,ln.roundToPrecisionLimit(this.viewOptions.floor+E,this.viewOptions.precisionLimit)}valueToPosition(_){let A=ce.linearValueToPosition;ce.isNullOrUndefined(this.viewOptions.customValueToPosition)?this.viewOptions.logScale&&(A=ce.logValueToPosition):A=this.viewOptions.customValueToPosition;let H=A(_=ln.clampToRange(_,this.viewOptions.floor,this.viewOptions.ceil),this.viewOptions.floor,this.viewOptions.ceil);return ce.isNullOrUndefined(H)&&(H=0),this.viewOptions.rightToLeft&&(H=1-H),H*this.maxHandlePosition}positionToValue(_){let A=_/this.maxHandlePosition;this.viewOptions.rightToLeft&&(A=1-A);let H=ce.linearPositionToValue;ce.isNullOrUndefined(this.viewOptions.customPositionToValue)?this.viewOptions.logScale&&(H=ce.logPositionToValue):H=this.viewOptions.customPositionToValue;const E=H(A,this.viewOptions.floor,this.viewOptions.ceil);return ce.isNullOrUndefined(E)?0:E}getEventXY(_,A){if(_ instanceof MouseEvent)return this.viewOptions.vertical||0!==this.viewOptions.rotate?_.clientY:_.clientX;let H=0;const E=_.touches;if(!ce.isNullOrUndefined(A))for(let ye=0;yeE?Ve.Max:this.viewOptions.rightToLeft?A>this.minHandleElement.position?Ve.Min:Ve.Max:Athis.onBarStart(null,_,A,!0,!0,!0)),this.viewOptions.draggableRangeOnly?(this.minHandleElement.on("mousedown",A=>this.onBarStart(Ve.Min,_,A,!0,!0)),this.maxHandleElement.on("mousedown",A=>this.onBarStart(Ve.Max,_,A,!0,!0))):(this.minHandleElement.on("mousedown",A=>this.onStart(Ve.Min,A,!0,!0)),this.range&&this.maxHandleElement.on("mousedown",A=>this.onStart(Ve.Max,A,!0,!0)),this.viewOptions.onlyBindHandles||(this.fullBarElement.on("mousedown",A=>this.onStart(null,A,!0,!0,!0)),this.ticksElement.on("mousedown",A=>this.onStart(null,A,!0,!0,!0,!0)))),this.viewOptions.onlyBindHandles||this.selectionBarElement.onPassive("touchstart",A=>this.onBarStart(null,_,A,!0,!0,!0)),this.viewOptions.draggableRangeOnly?(this.minHandleElement.onPassive("touchstart",A=>this.onBarStart(Ve.Min,_,A,!0,!0)),this.maxHandleElement.onPassive("touchstart",A=>this.onBarStart(Ve.Max,_,A,!0,!0))):(this.minHandleElement.onPassive("touchstart",A=>this.onStart(Ve.Min,A,!0,!0)),this.range&&this.maxHandleElement.onPassive("touchstart",A=>this.onStart(Ve.Max,A,!0,!0)),this.viewOptions.onlyBindHandles||(this.fullBarElement.onPassive("touchstart",A=>this.onStart(null,A,!0,!0,!0)),this.ticksElement.onPassive("touchstart",A=>this.onStart(null,A,!1,!1,!0,!0)))),this.viewOptions.keyboardSupport&&(this.minHandleElement.on("focus",()=>this.onPointerFocus(Ve.Min)),this.range&&this.maxHandleElement.on("focus",()=>this.onPointerFocus(Ve.Max)))}getOptionsInfluencingEventBindings(_){return[_.disabled,_.readOnly,_.draggableRange,_.draggableRangeOnly,_.onlyBindHandles,_.keyboardSupport]}unbindEvents(){this.unsubscribeOnMove(),this.unsubscribeOnEnd();for(const _ of this.getAllSliderElements())ce.isNullOrUndefined(_)||_.off()}onBarStart(_,A,H,E,ye,Je,gt){A?this.onDragStart(_,H,E,ye):this.onStart(_,H,E,ye,Je,gt)}onStart(_,A,H,E,ye,Je){A.stopPropagation(),!os.isTouchEvent(A)&&!Ee&&A.preventDefault(),this.moving=!1,this.calculateViewDimensions(),ce.isNullOrUndefined(_)&&(_=this.getNearestHandle(A)),this.currentTrackingPointer=_;const gt=this.getPointerElement(_);if(gt.active=!0,this.preStartHandleValue=this.getCurrentTrackingValue(),this.viewOptions.keyboardSupport&>.focus(),H){this.unsubscribeOnMove();const zt=bt=>this.dragging.active?this.onDragMove(bt):this.onMove(bt);this.onMoveEventListener=os.isTouchEvent(A)?this.eventListenerHelper.attachPassiveEventListener(document,"touchmove",zt):this.eventListenerHelper.attachEventListener(document,"mousemove",zt)}if(E){this.unsubscribeOnEnd();const zt=bt=>this.onEnd(bt);this.onEndEventListener=os.isTouchEvent(A)?this.eventListenerHelper.attachPassiveEventListener(document,"touchend",zt):this.eventListenerHelper.attachEventListener(document,"mouseup",zt)}this.userChangeStart.emit(this.getChangeContext()),os.isTouchEvent(A)&&!ce.isNullOrUndefined(A.changedTouches)&&ce.isNullOrUndefined(this.touchId)&&(this.touchId=A.changedTouches[0].identifier),ye&&this.onMove(A,!0),Je&&this.onEnd(A)}onMove(_,A){let H=null;if(os.isTouchEvent(_)){const zt=_.changedTouches;for(let bt=0;bt=this.maxHandlePosition?ye=this.viewOptions.rightToLeft?this.viewOptions.floor:this.viewOptions.ceil:(ye=this.positionToValue(E),ye=A&&!ce.isNullOrUndefined(this.viewOptions.tickStep)?this.roundStep(ye,this.viewOptions.tickStep):this.roundStep(ye)),this.positionTrackingHandle(ye)}forceEnd(_=!1){this.moving=!1,this.viewOptions.animate&&(this.sliderElementAnimateClass=!0),_&&(this.sliderElementAnimateClass=!1,setTimeout(()=>{this.sliderElementAnimateClass=this.viewOptions.animate})),this.touchId=null,this.viewOptions.keyboardSupport||(this.minHandleElement.active=!1,this.maxHandleElement.active=!1,this.currentTrackingPointer=null),this.dragging.active=!1,this.unsubscribeOnMove(),this.unsubscribeOnEnd(),this.userChangeEnd.emit(this.getChangeContext())}onEnd(_){os.isTouchEvent(_)&&_.changedTouches[0].identifier!==this.touchId||this.forceEnd()}onPointerFocus(_){const A=this.getPointerElement(_);A.on("blur",()=>this.onPointerBlur(A)),A.on("keydown",H=>this.onKeyboardEvent(H)),A.on("keyup",()=>this.onKeyUp()),A.active=!0,this.currentTrackingPointer=_,this.currentFocusPointer=_,this.firstKeyDown=!0}onKeyUp(){this.firstKeyDown=!0,this.userChangeEnd.emit(this.getChangeContext())}onPointerBlur(_){_.off("blur"),_.off("keydown"),_.off("keyup"),_.active=!1,ce.isNullOrUndefined(this.touchId)&&(this.currentTrackingPointer=null,this.currentFocusPointer=null)}getKeyActions(_){const A=this.viewOptions.ceil-this.viewOptions.floor;let H=_+this.viewOptions.step,E=_-this.viewOptions.step,ye=_+A/10,Je=_-A/10;this.viewOptions.reversedControls&&(H=_-this.viewOptions.step,E=_+this.viewOptions.step,ye=_-A/10,Je=_+A/10);const gt={UP:H,DOWN:E,LEFT:E,RIGHT:H,PAGEUP:ye,PAGEDOWN:Je,HOME:this.viewOptions.reversedControls?this.viewOptions.ceil:this.viewOptions.floor,END:this.viewOptions.reversedControls?this.viewOptions.floor:this.viewOptions.ceil};return this.viewOptions.rightToLeft&&(gt.LEFT=H,gt.RIGHT=E,(this.viewOptions.vertical||0!==this.viewOptions.rotate)&&(gt.UP=E,gt.DOWN=H)),gt}onKeyboardEvent(_){const A=this.getCurrentTrackingValue(),H=ce.isNullOrUndefined(_.keyCode)?_.which:_.keyCode,gt=this.getKeyActions(A)[{38:"UP",40:"DOWN",37:"LEFT",39:"RIGHT",33:"PAGEUP",34:"PAGEDOWN",36:"HOME",35:"END"}[H]];if(ce.isNullOrUndefined(gt)||ce.isNullOrUndefined(this.currentTrackingPointer))return;_.preventDefault(),this.firstKeyDown&&(this.firstKeyDown=!1,this.userChangeStart.emit(this.getChangeContext()));const zt=ln.clampToRange(gt,this.viewOptions.floor,this.viewOptions.ceil),bt=this.roundStep(zt);if(this.viewOptions.draggableRangeOnly){const xn=this.viewHighValue-this.viewLowValue;let In,jn;this.currentTrackingPointer===Ve.Min?(In=bt,jn=bt+xn,jn>this.viewOptions.ceil&&(jn=this.viewOptions.ceil,In=jn-xn)):this.currentTrackingPointer===Ve.Max&&(jn=bt,In=bt-xn,In=this.maxHandlePosition-H;let bt,xn;if(A<=E){if(0===ye.position)return;bt=this.getMinValue(A,!0,!1),xn=this.getMaxValue(A,!0,!1)}else if(zt){if(Je.position===this.maxHandlePosition)return;xn=this.getMaxValue(A,!0,!0),bt=this.getMinValue(A,!0,!0)}else bt=this.getMinValue(A,!1,!1),xn=this.getMaxValue(A,!1,!1);this.positionTrackingBar(bt,xn)}positionTrackingBar(_,A){!ce.isNullOrUndefined(this.viewOptions.minLimit)&&_this.viewOptions.maxLimit&&(_=ln.roundToPrecisionLimit((A=this.viewOptions.maxLimit)-this.dragging.difference,this.viewOptions.precisionLimit)),this.viewLowValue=_,this.viewHighValue=A,this.applyViewChange(),this.updateHandles(Ve.Min,this.valueToPosition(_)),this.updateHandles(Ve.Max,this.valueToPosition(A))}positionTrackingHandle(_){_=this.applyMinMaxLimit(_),this.range&&(this.viewOptions.pushRange?_=this.applyPushRange(_):(this.viewOptions.noSwitching&&(this.currentTrackingPointer===Ve.Min&&_>this.viewHighValue?_=this.applyMinMaxRange(this.viewHighValue):this.currentTrackingPointer===Ve.Max&&_this.viewHighValue?(this.viewLowValue=this.viewHighValue,this.applyViewChange(),this.updateHandles(Ve.Min,this.maxHandleElement.position),this.updateAriaAttributes(),this.currentTrackingPointer=Ve.Max,this.minHandleElement.active=!1,this.maxHandleElement.active=!0,this.viewOptions.keyboardSupport&&this.maxHandleElement.focus()):this.currentTrackingPointer===Ve.Max&&_this.viewOptions.maxLimit?this.viewOptions.maxLimit:_}applyMinMaxRange(_){const H=Math.abs(_-(this.currentTrackingPointer===Ve.Min?this.viewHighValue:this.viewLowValue));if(!ce.isNullOrUndefined(this.viewOptions.minRange)&&Hthis.viewOptions.maxRange){if(this.currentTrackingPointer===Ve.Min)return ln.roundToPrecisionLimit(this.viewHighValue-this.viewOptions.maxRange,this.viewOptions.precisionLimit);if(this.currentTrackingPointer===Ve.Max)return ln.roundToPrecisionLimit(this.viewLowValue+this.viewOptions.maxRange,this.viewOptions.precisionLimit)}return _}applyPushRange(_){const A=this.currentTrackingPointer===Ve.Min?this.viewHighValue-_:_-this.viewLowValue,H=ce.isNullOrUndefined(this.viewOptions.minRange)?this.viewOptions.step:this.viewOptions.minRange,E=this.viewOptions.maxRange;return AE&&(this.currentTrackingPointer===Ve.Min?(this.viewHighValue=ln.roundToPrecisionLimit(_+E,this.viewOptions.precisionLimit),this.applyViewChange(),this.updateHandles(Ve.Max,this.valueToPosition(this.viewHighValue))):this.currentTrackingPointer===Ve.Max&&(this.viewLowValue=ln.roundToPrecisionLimit(_-E,this.viewOptions.precisionLimit),this.applyViewChange(),this.updateHandles(Ve.Min,this.valueToPosition(this.viewLowValue))),this.updateAriaAttributes()),_}getChangeContext(){const _=new ra;return _.pointerType=this.currentTrackingPointer,_.value=+this.value,this.range&&(_.highValue=+this.highValue),_}static \u0275fac=function(A){return new(A||ve)(F.rXU(F.sFG),F.rXU(F.aKT),F.rXU(F.gRc),F.rXU(F.SKi),F.rXU(Hl,8))};static \u0275cmp=F.VBU({type:ve,selectors:[["ngx-slider"]],contentQueries:function(A,H,E){if(1&A&&F.wni(E,ie,5),2&A){let ye;F.mGM(ye=F.lsd())&&(H.tooltipTemplate=ye.first)}},viewQuery:function(A,H){if(1&A&&(F.GBs(T,5,Cs),F.GBs(Me,5,Cs),F.GBs(Ye,5,Cs),F.GBs(K,5,Cs),F.GBs(Pt,5,vi),F.GBs(Rt,5,vi),F.GBs(rt,5,Ue),F.GBs(St,5,Ue),F.GBs(Mr,5,Ue),F.GBs(Vs,5,Ue),F.GBs(Ya,5,Ue),F.GBs(zs,5,Cs)),2&A){let E;F.mGM(E=F.lsd())&&(H.leftOuterSelectionBarElement=E.first),F.mGM(E=F.lsd())&&(H.rightOuterSelectionBarElement=E.first),F.mGM(E=F.lsd())&&(H.fullBarElement=E.first),F.mGM(E=F.lsd())&&(H.selectionBarElement=E.first),F.mGM(E=F.lsd())&&(H.minHandleElement=E.first),F.mGM(E=F.lsd())&&(H.maxHandleElement=E.first),F.mGM(E=F.lsd())&&(H.floorLabelElement=E.first),F.mGM(E=F.lsd())&&(H.ceilLabelElement=E.first),F.mGM(E=F.lsd())&&(H.minHandleLabelElement=E.first),F.mGM(E=F.lsd())&&(H.maxHandleLabelElement=E.first),F.mGM(E=F.lsd())&&(H.combinedLabelElement=E.first),F.mGM(E=F.lsd())&&(H.ticksElement=E.first)}},hostVars:10,hostBindings:function(A,H){1&A&&F.bIt("resize",function(ye){return H.onResize(ye)},!1,F.tSv),2&A&&(F.BMQ("disabled",H.sliderElementDisabledAttr)("aria-label",H.sliderElementAriaLabel),F.AVh("ngx-slider",H.sliderElementNgxSliderClass)("vertical",H.sliderElementVerticalClass)("animate",H.sliderElementAnimateClass)("with-legend",H.sliderElementWithLegendClass))},inputs:{value:"value",highValue:"highValue",options:"options",manualRefresh:"manualRefresh",triggerFocus:"triggerFocus",cancelUserChange:"cancelUserChange"},outputs:{valueChange:"valueChange",highValueChange:"highValueChange",userChangeStart:"userChangeStart",userChange:"userChange",userChangeEnd:"userChangeEnd"},standalone:!1,features:[F.Jv_([Is]),F.OA$],decls:29,vars:13,consts:[["leftOuterSelectionBar",""],["rightOuterSelectionBar",""],["fullBar",""],["selectionBar",""],["minHandle",""],["maxHandle",""],["floorLabel",""],["ceilLabel",""],["minHandleLabel",""],["maxHandleLabel",""],["combinedLabel",""],["ticksElement",""],["ngxSliderElement","",1,"ngx-slider-span","ngx-slider-bar-wrapper","ngx-slider-left-out-selection"],[1,"ngx-slider-span","ngx-slider-bar"],["ngxSliderElement","",1,"ngx-slider-span","ngx-slider-bar-wrapper","ngx-slider-right-out-selection"],["ngxSliderElement","",1,"ngx-slider-span","ngx-slider-bar-wrapper","ngx-slider-full-bar"],["ngxSliderElement","",1,"ngx-slider-span","ngx-slider-bar-wrapper","ngx-slider-selection-bar"],[1,"ngx-slider-span","ngx-slider-bar","ngx-slider-selection",3,"ngStyle"],["ngxSliderHandle","",1,"ngx-slider-span","ngx-slider-pointer","ngx-slider-pointer-min",3,"ngStyle"],["ngxSliderHandle","",1,"ngx-slider-span","ngx-slider-pointer","ngx-slider-pointer-max",3,"ngStyle"],["ngxSliderLabel","",1,"ngx-slider-span","ngx-slider-bubble","ngx-slider-limit","ngx-slider-floor"],["ngxSliderLabel","",1,"ngx-slider-span","ngx-slider-bubble","ngx-slider-limit","ngx-slider-ceil"],["ngxSliderLabel","",1,"ngx-slider-span","ngx-slider-bubble","ngx-slider-model-value"],["ngxSliderLabel","",1,"ngx-slider-span","ngx-slider-bubble","ngx-slider-model-high"],["ngxSliderLabel","",1,"ngx-slider-span","ngx-slider-bubble","ngx-slider-combined"],["ngxSliderElement","",1,"ngx-slider-ticks",3,"hidden"],["class","ngx-slider-tick",3,"ngClass","ngStyle",4,"ngFor","ngForOf"],[1,"ngx-slider-tick",3,"ngClass","ngStyle"],[3,"template","tooltip","placement"],["class","ngx-slider-span ngx-slider-tick-value",3,"template","tooltip","placement","content",4,"ngIf"],["class","ngx-slider-span ngx-slider-tick-legend",3,"innerText",4,"ngIf"],["class","ngx-slider-span ngx-slider-tick-legend",3,"innerHTML",4,"ngIf"],[1,"ngx-slider-span","ngx-slider-tick-value",3,"template","tooltip","placement","content"],[1,"ngx-slider-span","ngx-slider-tick-legend",3,"innerText"],[1,"ngx-slider-span","ngx-slider-tick-legend",3,"innerHTML"]],template:function(A,H){1&A&&(F.j41(0,"span",12,0),F.nrm(2,"span",13),F.k0s(),F.j41(3,"span",14,1),F.nrm(5,"span",13),F.k0s(),F.j41(6,"span",15,2),F.nrm(8,"span",13),F.k0s(),F.j41(9,"span",16,3),F.nrm(11,"span",17),F.k0s(),F.nrm(12,"span",18,4)(14,"span",19,5)(16,"span",20,6)(18,"span",21,7)(20,"span",22,8)(22,"span",23,9)(24,"span",24,10),F.j41(26,"span",25,11),F.DNE(28,Cn,5,10,"span",26),F.k0s()),2&A&&(F.R7$(6),F.AVh("ngx-slider-transparent",H.fullBarTransparentClass),F.R7$(3),F.AVh("ngx-slider-draggable",H.selectionBarDraggableClass),F.R7$(2),F.Y8G("ngStyle",H.barStyle),F.R7$(),F.Y8G("ngStyle",H.minPointerStyle),F.R7$(2),F.xc7("display",H.range?"inherit":"none"),F.Y8G("ngStyle",H.maxPointerStyle),F.R7$(12),F.AVh("ngx-slider-ticks-values-under",H.ticksUnderValuesClass),F.Y8G("hidden",!H.showTicks),F.R7$(2),F.Y8G("ngForOf",H.ticks))},dependencies:[Re.YU,Re.Sq,Re.bT,Re.B3,Cs,vi,Ue,jl],styles:['.ngx-slider{display:inline-block;position:relative;height:4px;width:100%;margin:35px 0 15px;vertical-align:middle;-webkit-user-select:none;user-select:none;touch-action:pan-y} .ngx-slider.with-legend{margin-bottom:40px} .ngx-slider[disabled]{cursor:not-allowed} .ngx-slider[disabled] .ngx-slider-pointer{cursor:not-allowed;background-color:#d8e0f3} .ngx-slider[disabled] .ngx-slider-draggable{cursor:not-allowed} .ngx-slider[disabled] .ngx-slider-selection{background:#8b91a2} .ngx-slider[disabled] .ngx-slider-tick{cursor:not-allowed} .ngx-slider[disabled] .ngx-slider-tick.ngx-slider-selected{background:#8b91a2} .ngx-slider .ngx-slider-span{white-space:nowrap;position:absolute;display:inline-block} .ngx-slider .ngx-slider-base{width:100%;height:100%;padding:0} .ngx-slider .ngx-slider-bar-wrapper{left:0;box-sizing:border-box;margin-top:-16px;padding-top:16px;width:100%;height:32px;z-index:1} .ngx-slider .ngx-slider-draggable{cursor:move} .ngx-slider .ngx-slider-bar{left:0;width:100%;height:4px;z-index:1;background:#d8e0f3;-webkit-border-radius:2px;-moz-border-radius:2px;border-radius:2px} .ngx-slider .ngx-slider-bar-wrapper.ngx-slider-transparent .ngx-slider-bar{background:transparent} .ngx-slider .ngx-slider-bar-wrapper.ngx-slider-left-out-selection .ngx-slider-bar{background:#df002d} .ngx-slider .ngx-slider-bar-wrapper.ngx-slider-right-out-selection .ngx-slider-bar{background:#03a688} .ngx-slider .ngx-slider-selection{z-index:2;background:#0db9f0;-webkit-border-radius:2px;-moz-border-radius:2px;border-radius:2px} .ngx-slider .ngx-slider-pointer{cursor:pointer;width:32px;height:32px;top:-14px;background-color:#0db9f0;z-index:3;-webkit-border-radius:16px;-moz-border-radius:16px;border-radius:16px} .ngx-slider .ngx-slider-pointer:after{content:"";width:8px;height:8px;position:absolute;top:12px;left:12px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;background:#fff} .ngx-slider .ngx-slider-pointer:hover:after{background-color:#fff} .ngx-slider .ngx-slider-pointer.ngx-slider-active{z-index:4} .ngx-slider .ngx-slider-pointer.ngx-slider-active:after{background-color:#451aff} .ngx-slider .ngx-slider-bubble{cursor:default;bottom:16px;padding:1px 3px;color:#55637d;font-size:16px} .ngx-slider .ngx-slider-bubble.ngx-slider-limit{color:#55637d} .ngx-slider .ngx-slider-ticks{box-sizing:border-box;width:100%;height:0;position:absolute;left:0;top:-3px;margin:0;z-index:1;list-style:none} .ngx-slider .ngx-slider-ticks-values-under .ngx-slider-tick-value{top:auto;bottom:-36px} .ngx-slider .ngx-slider-tick{text-align:center;cursor:pointer;width:10px;height:10px;background:#d8e0f3;border-radius:50%;position:absolute;top:0;left:0;margin-left:11px} .ngx-slider .ngx-slider-tick.ngx-slider-selected{background:#0db9f0} .ngx-slider .ngx-slider-tick-value{position:absolute;top:-34px;transform:translate(-50%)} .ngx-slider .ngx-slider-tick-legend{position:absolute;top:24px;transform:translate(-50%);max-width:50px;white-space:normal} .ngx-slider.vertical{position:relative;width:4px;height:100%;margin:0 20px;padding:0;vertical-align:baseline;touch-action:pan-x} .ngx-slider.vertical .ngx-slider-base{width:100%;height:100%;padding:0} .ngx-slider.vertical .ngx-slider-bar-wrapper{top:auto;left:0;margin:0 0 0 -16px;padding:0 0 0 16px;height:100%;width:32px} .ngx-slider.vertical .ngx-slider-bar{bottom:0;left:auto;width:4px;height:100%} .ngx-slider.vertical .ngx-slider-pointer{left:-14px!important;top:auto;bottom:0} .ngx-slider.vertical .ngx-slider-bubble{left:16px!important;bottom:0} .ngx-slider.vertical .ngx-slider-ticks{height:100%;width:0;left:-3px;top:0;z-index:1} .ngx-slider.vertical .ngx-slider-tick{vertical-align:middle;margin-left:auto;margin-top:11px} .ngx-slider.vertical .ngx-slider-tick-value{left:24px;top:auto;transform:translateY(-28%)} .ngx-slider.vertical .ngx-slider-tick-legend{top:auto;right:24px;transform:translateY(-28%);max-width:none;white-space:nowrap} .ngx-slider.vertical .ngx-slider-ticks-values-under .ngx-slider-tick-value{bottom:auto;left:auto;right:24px} .ngx-slider *{transition:none} .ngx-slider.animate .ngx-slider-bar-wrapper{transition:all linear .3s} .ngx-slider.animate .ngx-slider-selection{transition:background-color linear .3s} .ngx-slider.animate .ngx-slider-pointer{transition:all linear .3s} .ngx-slider.animate .ngx-slider-pointer:after{transition:all linear .3s} .ngx-slider.animate .ngx-slider-bubble{transition:all linear .3s} .ngx-slider.animate .ngx-slider-bubble.ngx-slider-limit{transition:opacity linear .3s} .ngx-slider.animate .ngx-slider-bubble.ngx-slider-combined{transition:opacity linear .3s} .ngx-slider.animate .ngx-slider-tick{transition:background-color linear .3s}']})}return ve})(),aa=(()=>{class ve{static \u0275fac=function(A){return new(A||ve)};static \u0275mod=F.$C({type:ve});static \u0275inj=F.G2t({imports:[Re.MD]})}return ve})()},3881:(_t,ct,W)=>{"use strict";W.d(ct,{Ez:()=>qe}),W(6860);var Re=W(4438),Ke=W(3);W(9417),W(1413);let qe=(()=>{class R{static \u0275fac=function(M){return new(M||R)};static \u0275mod=Re.$C({type:R});static \u0275inj=Re.G2t({imports:[Ke.yE,Ke.pZ]})}return R})()},2723:(_t,ct,W)=>{"use strict";W.d(ct,{A:()=>at});var F=W(4786),Re=W(6832),Ke=W(4888),Tt=W(4958),nt=W(9539),Xe=W(6210),st=W(6401),Ce=W(973),q=W(1043),de=W(9609),_e=W(8618),ue=W(3301);class Pe extends Ke.Ay{constructor(Ee,Be,Qe,et){super(Ee),this.selected=Be,this.deselected=Qe,this.mapBrowserEvent=et}}const Te={};class lt extends nt.Ay{constructor(Ee){let Be;if(super(),Ee=Ee||{},this.boundAddFeature_=this.addFeature_.bind(this),this.boundRemoveFeature_=this.removeFeature_.bind(this),this.condition_=Ee.condition?Ee.condition:ue.t5,this.addCondition_=Ee.addCondition?Ee.addCondition:ue.Zm,this.removeCondition_=Ee.removeCondition?Ee.removeCondition:ue.Zm,this.toggleCondition_=Ee.toggleCondition?Ee.toggleCondition:ue.Kg,this.multi_=!!Ee.multi&&Ee.multi,this.filter_=Ee.filter?Ee.filter:st.rT,this.hitTolerance_=Ee.hitTolerance?Ee.hitTolerance:0,this.style_=void 0!==Ee.style?Ee.style:function Ht(){const jt=(0,q.mY)();return(0,de.X$)(jt.Polygon,jt.LineString),(0,de.X$)(jt.GeometryCollection,jt.LineString),function(Ee){return Ee.getGeometry()?jt[Ee.getGeometry().getType()]:null}}(),this.features_=Ee.features||new F.A,Ee.layers)if("function"==typeof Ee.layers)Be=Ee.layers;else{const Qe=Ee.layers;Be=function(et){return Qe.includes(et)}}else Be=st.rT;this.layerFilter_=Be,this.featureLayerAssociation_={}}addFeatureLayerAssociation_(Ee,Be){this.featureLayerAssociation_[(0,_e.v6)(Ee)]=Be}getFeatures(){return this.features_}getHitTolerance(){return this.hitTolerance_}getLayer(Ee){return this.featureLayerAssociation_[(0,_e.v6)(Ee)]}setHitTolerance(Ee){this.hitTolerance_=Ee}setMap(Ee){this.getMap()&&this.style_&&this.features_.forEach(this.restorePreviousStyle_.bind(this)),super.setMap(Ee),Ee?(this.features_.addEventListener(Re.A.ADD,this.boundAddFeature_),this.features_.addEventListener(Re.A.REMOVE,this.boundRemoveFeature_),this.style_&&this.features_.forEach(this.applySelectedStyle_.bind(this))):(this.features_.removeEventListener(Re.A.ADD,this.boundAddFeature_),this.features_.removeEventListener(Re.A.REMOVE,this.boundRemoveFeature_))}addFeature_(Ee){const Be=Ee.element;if(this.style_&&this.applySelectedStyle_(Be),!this.getLayer(Be)){const Qe=this.getMap().getAllLayers().find(function(et){if(et instanceof Xe.A&&et.getSource()&&et.getSource().hasFeature(Be))return et});Qe&&this.addFeatureLayerAssociation_(Be,Qe)}}removeFeature_(Ee){this.style_&&this.restorePreviousStyle_(Ee.element)}getStyle(){return this.style_}applySelectedStyle_(Ee){const Be=(0,_e.v6)(Ee);Be in Te||(Te[Be]=Ee.getStyle()),Ee.setStyle(this.style_)}restorePreviousStyle_(Ee){const Be=this.getMap().getInteractions().getArray();for(let et=Be.length-1;et>=0;--et){const N=Be[et];if(N!==this&&N instanceof lt&&N.getStyle()&&-1!==N.getFeatures().getArray().lastIndexOf(Ee))return void Ee.setStyle(N.getStyle())}const Qe=(0,_e.v6)(Ee);Ee.setStyle(Te[Qe]),delete Te[Qe]}removeFeatureLayerAssociation_(Ee){delete this.featureLayerAssociation_[(0,_e.v6)(Ee)]}handleEvent(Ee){if(!this.condition_(Ee))return!0;const Be=this.addCondition_(Ee),Qe=this.removeCondition_(Ee),et=this.toggleCondition_(Ee),N=!Be&&!Qe&&!et,oe=Ee.map,O=this.getFeatures(),we=[],Fe=[];if(N){(0,Ce.I)(this.featureLayerAssociation_),oe.forEachFeatureAtPixel(Ee.pixel,($e,qe)=>{if($e instanceof Tt.A&&this.filter_($e,qe))return this.addFeatureLayerAssociation_($e,qe),Fe.push($e),!this.multi_},{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});for(let $e=O.getLength()-1;$e>=0;--$e){const qe=O.item($e),R=Fe.indexOf(qe);R>-1?Fe.splice(R,1):(O.remove(qe),we.push(qe))}0!==Fe.length&&O.extend(Fe)}else{oe.forEachFeatureAtPixel(Ee.pixel,($e,qe)=>{if($e instanceof Tt.A&&this.filter_($e,qe))return!Be&&!et||O.getArray().includes($e)?(Qe||et)&&O.getArray().includes($e)&&(we.push($e),this.removeFeatureLayerAssociation_($e)):(this.addFeatureLayerAssociation_($e,qe),Fe.push($e)),!this.multi_},{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});for(let $e=we.length-1;$e>=0;--$e)O.remove(we[$e]);O.extend(Fe)}return(Fe.length>0||we.length>0)&&this.dispatchEvent(new Pe("select",Fe,we,Ee)),!0}}const at=lt}}]); \ No newline at end of file