face-api/dist/face-api.js

3977 lines
935 KiB
JavaScript

var faceapi=(()=>{var Ku=Object.defineProperty,JE=Object.prototype.hasOwnProperty,qs=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),yL=e=>Ku(e,"__esModule",{value:!0}),Ee=(e,t)=>{yL(e);for(var s in t)Ku(e,s,{get:t[s],enumerable:!0})},ZE=(e,t)=>{if(yL(e),typeof t=="object"||typeof t=="function")for(let s in t)!JE.call(e,s)&&s!=="default"&&Ku(e,s,{get:()=>t[s],enumerable:!0});return e},vc=e=>e&&e.__esModule?e:ZE(Ku({},"default",{value:e,enumerable:!0}),e);var wL=qs((bL,Ug)=>{(function(e,t,s){function n(a){var l=this,c=o();l.next=function(){var p=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=p-(l.c=p|0)},l.c=1,l.s0=c(" "),l.s1=c(" "),l.s2=c(" "),l.s0-=c(a),l.s0<0&&(l.s0+=1),l.s1-=c(a),l.s1<0&&(l.s1+=1),l.s2-=c(a),l.s2<0&&(l.s2+=1),c=null}function i(a,l){return l.c=a.c,l.s0=a.s0,l.s1=a.s1,l.s2=a.s2,l}function r(a,l){var c=new n(a),p=l&&l.state,u=c.next;return u.int32=function(){return c.next()*4294967296|0},u.double=function(){return u()+(u()*2097152|0)*11102230246251565e-32},u.quick=u,p&&(typeof p=="object"&&i(p,c),u.state=function(){return i(c,{})}),u}function o(){var a=4022871197,l=function(c){c=c.toString();for(var p=0;p<c.length;p++){a+=c.charCodeAt(p);var u=.02519603282416938*a;a=u>>>0,u-=a,u*=a,a=u>>>0,u-=a,a+=u*4294967296}return(a>>>0)*23283064365386963e-26};return l}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.alea=r})(bL,typeof Ug=="object"&&Ug,typeof define=="function"&&define)});var LL=qs((xL,$g)=>{(function(e,t,s){function n(o){var a=this,l="";a.x=0,a.y=0,a.z=0,a.w=0,a.next=function(){var p=a.x^a.x<<11;return a.x=a.y,a.y=a.z,a.z=a.w,a.w^=a.w>>>19^p^p>>>8},o===(o|0)?a.x=o:l+=o;for(var c=0;c<l.length+64;c++)a.x^=l.charCodeAt(c)|0,a.next()}function i(o,a){return a.x=o.x,a.y=o.y,a.z=o.z,a.w=o.w,a}function r(o,a){var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(typeof c=="object"&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xor128=r})(xL,typeof $g=="object"&&$g,typeof define=="function"&&define)});var IL=qs((SL,Wg)=>{(function(e,t,s){function n(o){var a=this,l="";a.next=function(){var p=a.x^a.x>>>2;return a.x=a.y,a.y=a.z,a.z=a.w,a.w=a.v,(a.d=a.d+362437|0)+(a.v=a.v^a.v<<4^(p^p<<1))|0},a.x=0,a.y=0,a.z=0,a.w=0,a.v=0,o===(o|0)?a.x=o:l+=o;for(var c=0;c<l.length+64;c++)a.x^=l.charCodeAt(c)|0,c==l.length&&(a.d=a.x<<10^a.x>>>4),a.next()}function i(o,a){return a.x=o.x,a.y=o.y,a.z=o.z,a.w=o.w,a.v=o.v,a.d=o.d,a}function r(o,a){var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(typeof c=="object"&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xorwow=r})(SL,typeof Wg=="object"&&Wg,typeof define=="function"&&define)});var TL=qs((vL,zg)=>{(function(e,t,s){function n(o){var a=this;a.next=function(){var c=a.x,p=a.i,u,h,d;return u=c[p],u^=u>>>7,h=u^u<<24,u=c[p+1&7],h^=u^u>>>10,u=c[p+3&7],h^=u^u>>>3,u=c[p+4&7],h^=u^u<<7,u=c[p+7&7],u=u^u<<13,h^=u^u<<9,c[p]=h,a.i=p+1&7,h};function l(c,p){var u,h,d=[];if(p===(p|0))h=d[0]=p;else for(p=""+p,u=0;u<p.length;++u)d[u&7]=d[u&7]<<15^p.charCodeAt(u)+d[u+1&7]<<13;for(;d.length<8;)d.push(0);for(u=0;u<8&&d[u]===0;++u);for(u==8?h=d[7]=-1:h=d[u],c.x=d,c.i=0,u=256;u>0;--u)c.next()}l(a,o)}function i(o,a){return a.x=o.x.slice(),a.i=o.i,a}function r(o,a){o==null&&(o=+new Date);var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(c.x&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xorshift7=r})(vL,typeof zg=="object"&&zg,typeof define=="function"&&define)});var NL=qs((AL,Pg)=>{(function(e,t,s){function n(o){var a=this;a.next=function(){var c=a.w,p=a.X,u=a.i,h,d;return a.w=c=c+1640531527|0,d=p[u+34&127],h=p[u=u+1&127],d^=d<<13,h^=h<<17,d^=d>>>15,h^=h>>>12,d=p[u]=d^h,a.i=u,d+(c^c>>>16)|0};function l(c,p){var u,h,d,m,f,g=[],y=128;for(p===(p|0)?(h=p,p=null):(p=p+"\0",h=0,y=Math.max(y,p.length)),d=0,m=-32;m<y;++m)p&&(h^=p.charCodeAt((m+32)%p.length)),m===0&&(f=h),h^=h<<10,h^=h>>>15,h^=h<<4,h^=h>>>13,m>=0&&(f=f+1640531527|0,u=g[m&127]^=h+f,d=u==0?d+1:0);for(d>=128&&(g[(p&&p.length||0)&127]=-1),d=127,m=4*128;m>0;--m)h=g[d+34&127],u=g[d=d+1&127],h^=h<<13,u^=u<<17,h^=h>>>15,u^=u>>>12,g[d]=h^u;c.w=f,c.X=g,c.i=d}l(a,o)}function i(o,a){return a.i=o.i,a.w=o.w,a.X=o.X.slice(),a}function r(o,a){o==null&&(o=+new Date);var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(c.X&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xor4096=r})(AL,typeof Pg=="object"&&Pg,typeof define=="function"&&define)});var RL=qs((CL,Bg)=>{(function(e,t,s){function n(o){var a=this,l="";a.next=function(){var p=a.b,u=a.c,h=a.d,d=a.a;return p=p<<25^p>>>7^u,u=u-h|0,h=h<<24^h>>>8^d,d=d-p|0,a.b=p=p<<20^p>>>12^u,a.c=u=u-h|0,a.d=h<<16^u>>>16^d,a.a=d-p|0},a.a=0,a.b=0,a.c=2654435769|0,a.d=1367130551,o===Math.floor(o)?(a.a=o/4294967296|0,a.b=o|0):l+=o;for(var c=0;c<l.length+20;c++)a.b^=l.charCodeAt(c)|0,a.next()}function i(o,a){return a.a=o.a,a.b=o.b,a.c=o.c,a.d=o.d,a}function r(o,a){var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(typeof c=="object"&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.tychei=r})(CL,typeof Bg=="object"&&Bg,typeof define=="function"&&define)});var OL=qs(()=>{});var EL=qs((QG,Xu)=>{(function(e,t){var s=this,n=256,i=6,r=52,o="random",a=t.pow(n,i),l=t.pow(2,r),c=l*2,p=n-1,u;function h(x,T,A){var _=[];T=T==!0?{entropy:!0}:T||{};var E=g(f(T.entropy?[x,w(e)]:x??y(),3),_),F=new d(_),D=function(){for(var M=F.g(i),P=a,B=0;M<l;)M=(M+B)*n,P*=n,B=F.g(1);for(;M>=c;)M/=2,P/=2,B>>>=1;return(M+B)/P};return D.int32=function(){return F.g(4)|0},D.quick=function(){return F.g(4)/4294967296},D.double=D,g(w(F.S),e),(T.pass||A||function(M,P,B,Y){return Y&&(Y.S&&m(Y,F),M.state=function(){return m(F,{})}),B?(t[o]=M,P):M})(D,E,"global"in T?T.global:this==t,T.state)}t["seed"+o]=h;function d(x){var T,A=x.length,_=this,E=0,F=_.i=_.j=0,D=_.S=[];for(A||(x=[A++]);E<n;)D[E]=E++;for(E=0;E<n;E++)D[E]=D[F=p&F+x[E%A]+(T=D[E])],D[F]=T;(_.g=function(M){for(var P,B=0,Y=_.i,q=_.j,K=_.S;M--;)P=K[Y=p&Y+1],B=B*n+K[p&(K[Y]=K[q=p&q+P])+(K[q]=P)];return _.i=Y,_.j=q,B})(n)}function m(x,T){return T.i=x.i,T.j=x.j,T.S=x.S.slice(),T}function f(x,T){var A=[],_=typeof x,E;if(T&&_=="object")for(E in x)try{A.push(f(x[E],T-1))}catch(F){}return A.length?A:_=="string"?x:x+"\0"}function g(x,T){for(var A=x+"",_,E=0;E<A.length;)T[p&E]=p&(_^=T[p&E]*19)+A.charCodeAt(E++);return w(T)}function y(){try{var x;return u&&(x=u.randomBytes)?x=x(n):(x=new Uint8Array(n),(s.crypto||s.msCrypto).getRandomValues(x)),w(x)}catch(_){var T=s.navigator,A=T&&T.plugins;return[+new Date,s,A,s.screen,w(e)]}}function w(x){return String.fromCharCode.apply(0,x)}if(g(t.random(),e),typeof Xu=="object"&&Xu.exports){Xu.exports=h;try{u=OL()}catch(x){}}else typeof define=="function"&&define.amd&&define(function(){return h})})([],Math)});var Tc=qs((eq,_L)=>{var QE=wL(),e_=LL(),t_=IL(),s_=TL(),n_=NL(),i_=RL(),vo=EL();vo.alea=QE;vo.xor128=e_;vo.xorwow=t_;vo.xorshift7=s_;vo.xor4096=n_;vo.tychei=i_;_L.exports=vo});var kL=qs(()=>{});var DL=qs(()=>{});var ML=qs((r_,FL)=>{Ee(r_,{isNodejs:()=>o_});function o_(){return typeof global=="object"&&!0&&typeof FL!="undefined"&&typeof process!="undefined"&&!!process.version}});var wS=qs(a_=>{Ee(a_,{AgeGenderNet:()=>vh,BoundingBox:()=>Ga,Box:()=>it,ComposableTask:()=>hn,ComputeAllFaceDescriptorsTask:()=>ir,ComputeFaceDescriptorsTaskBase:()=>hh,ComputeSingleFaceDescriptorTask:()=>rr,DetectAllFaceLandmarksTask:()=>ph,DetectAllFacesTask:()=>Nc,DetectFaceLandmarksTaskBase:()=>ch,DetectFacesTaskBase:()=>ah,DetectSingleFaceLandmarksTask:()=>uh,DetectSingleFaceTask:()=>lh,Dimensions:()=>Ts,FACE_EXPRESSION_LABELS:()=>fh,FaceDetection:()=>ht,FaceDetectionNet:()=>BL,FaceExpressionNet:()=>gh,FaceExpressions:()=>lr,FaceLandmark68Net:()=>za,FaceLandmark68TinyNet:()=>mh,FaceLandmarkNet:()=>dS,FaceLandmarks:()=>Hs,FaceLandmarks5:()=>bS,FaceLandmarks68:()=>Va,FaceMatch:()=>Dc,FaceMatcher:()=>Kg,FaceRecognitionNet:()=>Wa,Gender:()=>Jn,LabeledBox:()=>kc,LabeledFaceDescriptors:()=>hr,NetInput:()=>vi,NeuralNetwork:()=>Zt,ObjectDetection:()=>Oo,Point:()=>_e,PredictedBox:()=>yS,Rect:()=>ja,SsdMobilenetv1:()=>To,SsdMobilenetv1Options:()=>pn,TinyFaceDetector:()=>Ua,TinyFaceDetectorOptions:()=>sh,TinyYolov2:()=>Ma,TinyYolov2Options:()=>Xn,TinyYolov2SizeType:()=>th,allFaces:()=>cS,allFacesSsdMobilenetv1:()=>Yg,allFacesTinyYolov2:()=>lS,awaitMediaLoaded:()=>Ih,bufferToImage:()=>Sh,computeFaceDescriptor:()=>YL,createCanvas:()=>Ro,createCanvasFromMedia:()=>Ba,createFaceDetectionNet:()=>PL,createFaceRecognitionNet:()=>hS,createSsdMobilenetv1:()=>jg,createTinyFaceDetector:()=>zL,createTinyYolov2:()=>WL,detectAllFaces:()=>Ac,detectFaceLandmarks:()=>qg,detectFaceLandmarksTiny:()=>HL,detectLandmarks:()=>oS,detectSingleFace:()=>aS,draw:()=>Zu,env:()=>Ve,euclideanDistance:()=>yh,extendWithAge:()=>Ec,extendWithFaceDescriptor:()=>Oc,extendWithFaceDetection:()=>ar,extendWithFaceExpressions:()=>Rc,extendWithFaceLandmarks:()=>Ao,extendWithGender:()=>Cc,extractFaceTensors:()=>Co,extractFaces:()=>No,fetchImage:()=>gS,fetchJson:()=>Lh,fetchNetWeights:()=>fS,fetchOrThrow:()=>ur,getContext2dOrThrow:()=>us,getMediaDimensions:()=>pr,imageTensorToCanvas:()=>xh,imageToSquare:()=>wh,inverseSigmoid:()=>VL,iou:()=>oh,isMediaElement:()=>_c,isMediaLoaded:()=>Pa,isWithAge:()=>uS,isWithFaceDetection:()=>Mn,isWithFaceExpressions:()=>dh,isWithFaceLandmarks:()=>or,isWithGender:()=>pS,loadAgeGenderModel:()=>nS,loadFaceDetectionModel:()=>iS,loadFaceExpressionModel:()=>sS,loadFaceLandmarkModel:()=>QL,loadFaceLandmarkTinyModel:()=>eS,loadFaceRecognitionModel:()=>tS,loadSsdMobilenetv1Model:()=>Hg,loadTinyFaceDetectorModel:()=>JL,loadTinyYolov2Model:()=>ZL,loadWeightMap:()=>bh,locateFaces:()=>rS,matchDimensions:()=>mS,minBbox:()=>rh,nets:()=>Be,nonMaxSuppression:()=>ih,normalize:()=>un,padToSquare:()=>nh,predictAgeAndGender:()=>XL,recognizeFaceExpressions:()=>KL,resizeResults:()=>Vg,resolveInput:()=>cr,shuffleArray:()=>jL,sigmoid:()=>$a,ssdMobilenetv1:()=>Gg,tf:()=>Ju,tinyFaceDetector:()=>GL,tinyYolov2:()=>qL,toNetInput:()=>nt,utils:()=>Qu,validateConfig:()=>eh,version:()=>$L});const l_=typeof process!="undefined",c_=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",$L={faceapi:UL,node:l_,browser:c_}});const p_=1e-7,u_=1e-4;class Fc{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class Eo{time(e){return z("time")}read(e){return z("read")}readSync(e){return z("readSync")}numDataIds(){return z("numDataIds")}disposeData(e){return z("disposeData")}write(e,t,s){return z("write")}move(e,t,s,n){return z("move")}memory(){return z("memory")}floatPrecision(){return z("floatPrecision")}epsilon(){return this.floatPrecision()===32?p_:u_}batchMatMul(e,t,s,n){return z("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:s,transposeB:n,bias:i,activation:r,preluActivationWeights:o}){return z("fusedBatchMatMul")}slice(e,t,s){return z("slice")}stridedSlice(e,t,s,n){return z("stridedSlice")}unstack(e,t){return z("unstack")}reverse(e,t){return z("reverse")}concat(e,t){return z("concat")}neg(e){return z("neg")}add(e,t){return z("add")}addN(e){return z("addN")}subtract(e,t){return z("subtract")}multiply(e,t){return z("multiply")}realDivide(e,t){return z("realDivide")}floorDiv(e,t){return z("floorDiv")}sum(e,t){return z("sum")}prod(e,t){return z("prod")}unsortedSegmentSum(e,t,s){return z("unsortedSegmentSum")}argMin(e,t){return z("argMin")}argMax(e,t){return z("argMax")}equal(e,t){return z("equal")}notEqual(e,t){return z("notEqual")}less(e,t){return z("less")}lessEqual(e,t){return z("lessEqual")}greater(e,t){return z("greater")}greaterEqual(e,t){return z("greaterEqual")}logicalNot(e){return z("logicalNot")}logicalAnd(e,t){return z("logicalAnd")}logicalOr(e,t){return z("logicalOr")}where(e){return z("where")}select(e,t,s){return z("select")}topk(e,t,s){return z("topk")}min(e,t){return z("min")}minimum(e,t){return z("minimum")}mod(e,t){return z("mod")}max(e,t){return z("max")}maximum(e,t){return z("maximum")}all(e,t){return z("all")}any(e,t){return z("any")}squaredDifference(e,t){return z("squaredDifference")}ceil(e){return z("ceil")}floor(e){return z("floor")}round(e){return z("round")}sign(e){return z("sign")}isNaN(e){return z("isNaN")}isInf(e){return z("isInf")}isFinite(e){return z("isFinite")}pow(e,t){return z("pow")}exp(e){return z("exp")}expm1(e){return z("expm1")}softmax(e,t){return z("softmax")}log(e){return z("log")}log1p(e){return z("log1p")}sqrt(e){return z("sqrt")}rsqrt(e){return z("rsqrt")}square(e){return z("square")}reciprocal(e){return z("reciprocal")}relu(e){return z("relu")}relu6(e){return z("relu6")}prelu(e,t){return z("prelu")}elu(e){return z("elu")}eluDer(e,t){return z("eluDer")}selu(e){return z("selu")}int(e){return z("int")}clip(e,t,s){return z("clip")}abs(e){return z("abs")}complexAbs(e){return z("complexAbs")}sigmoid(e){return z("sigmoid")}softplus(e){return z("softplus")}sin(e){return z("sin")}cos(e){return z("cos")}tan(e){return z("tan")}asin(e){return z("asin")}acos(e){return z("acos")}atan(e){return z("atan")}atan2(e,t){return z("atan2")}sinh(e){return z("sinh")}cosh(e){return z("cosh")}tanh(e){return z("tanh")}asinh(e){return z("asinh")}acosh(e){return z("acosh")}atanh(e){return z("atanh")}erf(e){return z("erf")}step(e,t){return z("step")}fusedConv2d({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){return z("fusedConv2d")}conv2d(e,t,s){return z("conv2d")}conv2dDerInput(e,t,s){return z("conv2dDerInput")}conv2dDerFilter(e,t,s){return z("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){return z("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,s){return z("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,s){return z("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,s){return z("depthwiseConv2DDerFilter")}conv3d(e,t,s){return z("conv3d")}conv3dDerInput(e,t,s){return z("conv3dDerInput")}conv3dDerFilter(e,t,s){return z("conv3dDerFilter")}maxPool(e,t){return z("maxPool")}maxPoolBackprop(e,t,s,n){return z("maxPoolBackprop")}avgPool(e,t){return z("avgPool")}avgPoolBackprop(e,t,s){return z("avgPoolBackprop")}avgPool3d(e,t){return z("avgPool3d")}avgPool3dBackprop(e,t,s){return z("avgPool3dBackprop")}maxPool3d(e,t){return z("maxPool3d")}maxPool3dBackprop(e,t,s,n){return z("maxPool3dBackprop")}reshape(e,t){return z("reshape")}cast(e,t){return z("cast")}tile(e,t){return z("tile")}pad(e,t,s){return z("pad")}transpose(e,t){return z("transpose")}gather(e,t,s){return z("gather")}gatherND(e,t){return z("gatherND")}scatterND(e,t,s){return z("scatterND")}batchToSpaceND(e,t,s){return z("batchToSpaceND")}spaceToBatchND(e,t,s){return z("spaceToBatchND")}resizeBilinear(e,t,s,n){return z("resizeBilinear")}resizeBilinearBackprop(e,t,s){return z("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,s,n){return z("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,s){return z("resizeNearestNeighborBackprop")}batchNorm(e,t,s,n,i,r){return z("batchNorm")}localResponseNormalization4D(e,t,s,n,i){return z("localResponseNormalization4D")}LRNGrad(e,t,s,n,i,r,o){return z("LRNGrad")}multinomial(e,t,s,n){return z("multinomial")}oneHot(e,t,s,n){return z("oneHot")}cumsum(e,t,s,n){return z("cumsum")}nonMaxSuppression(e,t,s,n,i){return z("nonMaxSuppression")}fft(e){return z("fft")}ifft(e){return z("ifft")}complex(e,t){return z("complex")}real(e){return z("real")}imag(e){return z("imag")}cropAndResize(e,t,s,n,i,r){return z("cropAndResize")}depthToSpace(e,t,s){return z("depthToSpace")}split(e,t,s){return z("split")}sparseToDense(e,t,s,n){return z("sparseToDense")}diag(e){return z("diag")}fill(e,t,s){return z("fill")}onesLike(e){return z("onesLike")}zerosLike(e){return z("zerosLike")}linspace(e,t,s){return z("linspace")}dispose(){return z("dispose")}}function z(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}const xS="tfjsflags";class Xg{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,s){if(this.flagRegistry[e]={evaluationFn:t,setHook:s},this.urlFlags[e]!=null){const n=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${n}.`),this.set(e,n)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(t instanceof Promise)throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const e=h_(this.global.location.search);if(xS in e){const t=e[xS].split(",");t.forEach(s=>{const[n,i]=s.split(":");this.urlFlags[n]=d_(n,i)})}}}function h_(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(s,...n)=>(m_(t,n[0],n[1]),n.join("="))),t}function m_(e,t,s){e[decodeURIComponent(t)]=decodeURIComponent(s||"")}function d_(e,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}function W(){return Jg}let Jg=null;function LS(e){Jg=e}let Zg;function Qg(){if(Zg==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");Zg=e}return Zg}function f_(){const e=Qg();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function ey(e,t){const s=f_();if(s.has(e))return s.get(e);{const n=t();return s.set(e,n),s.get(e)}}const _o="Abs",dr="Acos",mr="Acosh",Zn="Add",Mc="AddN",ty="All",sy="Any",Uc="ArgMax",$c="ArgMin",fr="Asin",gr="Asinh",yr="Atan",br="Atanh",ko="Atan2",Ti="AvgPool",Do="AvgPoolBackprop",Wc="AvgPool3D",ny="AvgPool3DBackprop",zc="BatchMatMul",Pc="BatchToSpaceND",Bc="BroadcastTo",Ai="Cast",wr="Ceil",xr="ClipByValue",jc="Complex",Fo="Concat",Vc="Conv2D",iy="Conv2DBackpropFilter",Gc="Conv2DBackpropInput",qc="Conv3D",ry="Conv3DBackpropFilterV2",oy="Conv3DBackpropInputV2",Qn="Cos",Lr="Cosh",Hc="Cumsum",ay="CropAndResize",ly="DepthToSpace",Yc="DepthwiseConv2dNative",cy="DepthwiseConv2dNativeBackpropFilter",py="DepthwiseConv2dNativeBackpropInput",uy="Diag",Mo="Dilation2D",qa="Dilation2DBackpropInput",Ha="Dilation2DBackpropFilter",ei="Div",Sr="Elu",hy="EluGrad",Ir="Erf",dy="Equal",vr="Exp",Tr="Expm1",Kc="FFT",my="Fill",Uo="FlipLeftRight",Ar="Floor",Xc="FloorDiv",Ni="FusedBatchNorm",Jc="GatherV2",fy="GatherNd",gy="Greater",Zc="GreaterEqual",Ci="Identity",Qc="IFFT",ep="Imag",Nr="IsFinite",Cr="IsInf",Rr="IsNan",yy="Less",by="LessEqual",wy="LinSpace",Or="Log",Er="Log1p",xy="LogicalAnd",Ya="LogicalNot",Ly="LogicalOr",tp="LogSoftmax",sp="LRN",Sy="LRNBackprop",Ri="Max",np="Maximum",Oi="MaxPool",$o="MaxPoolBackprop",ip="MaxPool3D",Iy="MaxPool3DBackprop",Wo="MaxPoolWithArgmax",g_="Mean",rp="Min",op="Minimum",ap="Mod",_r="Multiply",lp="Negate",Ka="NotEqual",cp="NonMaxSuppressionV3",zo="NonMaxSuppressionV4",Po="NonMaxSuppressionV5",pp="OnesLike",up="OneHot",Bo="PadV2",y_="Pool",hp="Pow",dp="Prelu",vy="Prod",Ty="Range",mp="Real",kr="Reciprocal",fp="Relu",Ei="Reshape",gp="ResizeNearestNeighbor",Ay="ResizeNearestNeighborGrad",yp="ResizeBilinear",Ny="ResizeBilinearGrad",bp="Relu6",wp="Reverse",Dr="Round",Fr="Rsqrt",Cy="ScatterNd",xp="SelectV2",Mr="Selu",jo="Slice",ti="Sin",Ur="Sinh",$r="Sign",Wr="Sigmoid",zr="Softplus",Pr="Sqrt",Lp="Sum",Vo="SpaceToBatchND",Sp="SplitV",Ip="Softmax",si="SquaredDifference",Go="Square",Br="Sub",Ry="SparseToDense",Oy="StridedSlice",ni="Tan",jr="Tanh",vp="Tile",Ey="TopK",_i="Transpose",qo="Unique",Tp="Unpack",Ap="UnsortedSegmentSum",Np="ZerosLike",Vr="Step",Xa="FromPixels",Ho="RotateWithOffset",Th="_FusedMatMul",Ah="FusedConv2D",Nh="FusedDepthwiseConv2D";const Ja=ey("kernelRegistry",()=>new Map),Cp=ey("gradRegistry",()=>new Map);function Rp(e,t){const s=_y(e,t);return Ja.get(s)}function Ch(e){return Cp.get(e)}function Op(e){const t=Ja.entries(),s=[];for(;;){const{done:n,value:i}=t.next();if(n)break;const[r,o]=i,[a]=r.split("_");a===e&&s.push(o)}return s}function Za(e){const{kernelName:t,backendName:s}=e,n=_y(t,s);Ja.has(n)&&console.warn(`The kernel '${t}' for backend '${s}' is already registered`),Ja.set(n,e)}function ky(e){const{kernelName:t}=e;Cp.has(t)&&(W().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),Cp.set(t,e)}function b_(e,t){const s=_y(e,t);if(!Ja.has(s))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Ja.delete(s)}function w_(e){if(!Cp.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Cp.delete(e)}function x_(e,t){const s=Op(e);s.forEach(n=>{const i=Object.assign({},n,{backendName:t});Za(i)})}function _y(e,t){return`${t}_${e}`}const N={};Ee(N,{arraysEqual:()=>Nt,assert:()=>I,assertNonNegativeIntegerDimensions:()=>_p,assertNonNull:()=>Ys,assertShapesMatch:()=>Se,bytesFromStringArray:()=>zy,bytesPerElement:()=>Wy,checkConversionForErrors:()=>IS,clamp:()=>Qa,computeStrides:()=>oi,createScalarValue:()=>O_,createShuffledIndices:()=>C_,decodeString:()=>Eh,distSquared:()=>v_,encodeString:()=>Rh,fetch:()=>k_,flatten:()=>ii,getArrayFromDType:()=>My,getTypedArrayFromDType:()=>el,hasEncodingLoss:()=>$y,indexToLoc:()=>F_,inferDtype:()=>tl,inferFromImplicitShape:()=>Dy,isBoolean:()=>vS,isFunction:()=>ri,isInt:()=>De,isNumber:()=>TS,isScalarShape:()=>T_,isString:()=>Un,isTypedArray:()=>Dt,isValidDtype:()=>Uy,locToIndex:()=>D_,makeOnesTypedArray:()=>Ep,makeZerosNestedTypedArray:()=>__,makeZerosTypedArray:()=>ai,nearestDivisor:()=>sl,nearestLargerEven:()=>L_,now:()=>Oh,parseAxisParam:()=>Ne,randUniform:()=>I_,repeatedTry:()=>R_,rightPad:()=>Yo,shuffle:()=>SS,sizeFromShape:()=>We,sizeToSquarishShape:()=>N_,squeezeShape:()=>Fy,sum:()=>S_,tanh:()=>A_,toNestedArray:()=>Ko,toTypedArray:()=>nl});function SS(e){let t=e.length,s=0,n=0;for(;t>0;)n=Math.random()*t|0,t--,s=e[t],e[t]=e[n],e[n]=s}function Qa(e,t,s){return Math.max(e,Math.min(t,s))}function L_(e){return e%2===0?e:e+1}function S_(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s];return t}function I_(e,t){const s=Math.random();return t*s+(1-s)*e}function v_(e,t){let s=0;for(let n=0;n<e.length;n++){const i=Number(e[n])-Number(t[n]);s+=i*i}return s}function I(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function Se(e,t,s=""){I(Nt(e,t),()=>s+` Shapes ${e} and ${t} must match`)}function Ys(e){I(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ii(e,t=[],s=!1){if(t==null&&(t=[]),Array.isArray(e)||Dt(e)&&!s)for(let n=0;n<e.length;++n)ii(e[n],t,s);else t.push(e);return t}function We(e){if(e.length===0)return 1;let t=e[0];for(let s=1;s<e.length;s++)t*=e[s];return t}function T_(e){return e.length===0}function Nt(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;return!0}function De(e){return e%1===0}function A_(e){if(Math.tanh!=null)return Math.tanh(e);if(e===Infinity)return 1;if(e===-Infinity)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function N_(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function C_(e){const t=new Uint32Array(e);for(let s=0;s<e;++s)t[s]=s;return SS(t),t}function Yo(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function R_(e,t=n=>0,s){return new Promise((n,i)=>{let r=0;const o=()=>{if(e()){n();return}r++;const a=t(r);if(s!=null&&r>=s){i();return}setTimeout(o,a)};o()})}function Dy(e,t){let s=1,n=-1;for(let r=0;r<e.length;++r)if(e[r]>=0)s*=e[r];else if(e[r]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${r}`);n=r}else if(e[r]<0)throw Error(`Shapes can not be < 0. Found ${e[r]} at dim ${r}`);if(n===-1){if(t>0&&t!==s)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(s===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%s!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${s}`);const i=e.slice();return i[n]=t/s,i}function Ne(e,t){const s=t.length;return e=e==null?t.map((n,i)=>i):[].concat(e),I(e.every(n=>n>=-s&&n<s),()=>`All values in axis param must be in range [-${s}, ${s}) but got axis ${e}`),I(e.every(n=>De(n)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(n=>n<0?s+n:n)}function Fy(e,t){const s=[],n=[],i=t!=null&&Array.isArray(t)&&t.length===0,r=t==null||i?null:Ne(t,e).sort();let o=0;for(let a=0;a<e.length;++a){if(r!=null){if(r[o]===a&&e[a]!==1)throw new Error(`Can't squeeze axis ${a} since its dim '${e[a]}' is not 1`);(r[o]==null||r[o]>a)&&e[a]===1&&(s.push(e[a]),n.push(a)),r[o]<=a&&o++}e[a]!==1&&(s.push(e[a]),n.push(a))}return{newShape:s,keptDims:n}}function el(e,t){let s=null;if(e==null||e==="float32")s=new Float32Array(t);else if(e==="int32")s=new Int32Array(t);else if(e==="bool")s=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return s}function My(e,t){let s=null;if(e==null||e==="float32")s=new Float32Array(t);else if(e==="int32")s=new Int32Array(t);else if(e==="bool")s=new Uint8Array(t);else if(e==="string")s=new Array(t);else throw new Error(`Unknown data type ${e}`);return s}function IS(e,t){for(let s=0;s<e.length;s++){const n=e[s];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${t} being uploaded contains ${n}.`)}}function Uy(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function $y(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function Dt(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function Wy(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function zy(e){if(e==null)return 0;let t=0;return e.forEach(s=>t+=s.length),t}function Un(e){return typeof e=="string"||e instanceof String}function vS(e){return typeof e=="boolean"}function TS(e){return typeof e=="number"}function tl(e){return Array.isArray(e)?tl(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":TS(e)?"float32":Un(e)?"string":vS(e)?"bool":"float32"}function ri(e){return!!(e&&e.constructor&&e.call&&e.apply)}function sl(e,t){for(let s=t;s<e;++s)if(e%s===0)return s;return e}function oi(e){const t=e.length;if(t<2)return[];const s=new Array(t-1);s[t-2]=e[t-1];for(let n=t-3;n>=0;--n)s[n]=s[n+1]*e[n+1];return s}function O_(e,t){return t==="string"?Rh(e):nl([e],t)}function nl(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ii(e)),W().getBool("DEBUG")&&IS(e,t),E_(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){const s=new Uint8Array(e.length);for(let n=0;n<s.length;++n)Math.round(e[n])!==0&&(s[n]=1);return s}else throw new Error(`Unknown data type ${t}`)}function AS(e,t,s){const n=new Array;if(t.length===1){const i=t[0];for(let r=0;r<i;r++)n[r]=s[e+r]}else{const i=t[0],r=t.slice(1),o=r.reduce((a,l)=>a*l);for(let a=0;a<i;a++)n[a]=AS(e+a*o,r,s)}return n}function Ko(e,t){if(e.length===0)return t[0];const s=e.reduce((n,i)=>n*i);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return AS(0,e,t)}function E_(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Ep(e,t){const s=ai(e,t);for(let n=0;n<s.length;n++)s[n]=1;return s}function ai(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function __(e,t){const s=e.reduce((n,i)=>n*i,1);if(t==null||t==="float32")return Ko(e,new Float32Array(s));if(t==="int32")return Ko(e,new Int32Array(s));if(t==="bool")return Ko(e,new Uint8Array(s));throw new Error(`Unknown data type ${t}`)}function Oh(){return W().platform.now()}function _p(e){e.forEach(t=>{I(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function k_(e,t){return W().platform.fetch(e,t)}function Rh(e,t="utf-8"){return t=t||"utf-8",W().platform.encode(e,t)}function Eh(e,t="utf-8"){return t=t||"utf-8",W().platform.decode(e,t)}function D_(e,t,s){if(t===0)return 0;if(t===1)return e[0];let n=e[e.length-1];for(let i=0;i<e.length-1;++i)n+=s[i]*e[i];return n}function F_(e,t,s){if(t===0)return[];if(t===1)return[e];const n=new Array(t);for(let i=0;i<n.length-1;++i)n[i]=Math.floor(e/s[i]),e-=n[i]*s[i];return n[n.length-1]=e,n}class NS{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new U_)}profileKernel(e,t,s){let n;const i=()=>{n=s()},r=this.backendTimer.time(i);for(let a=0;a<n.length;a++){const l=n[a];l.data().then(c=>{M_(c,l.dtype,e)})}const o={kernelName:e,outputs:n,inputs:t,timeMs:r.then(a=>a.kernelMs),extraInfo:r.then(a=>a.getExtraProfileInfo!=null?a.getExtraProfileInfo():"")};return o}logKernelProfile(e){const{kernelName:t,outputs:s,timeMs:n,inputs:i,extraInfo:r}=e;s.forEach(o=>{Promise.all([o.data(),n,r]).then(a=>{this.logger.logKernelProfile(t,o,a[0],a[1],i,a[2])})})}}function M_(e,t,s){if(t!=="float32")return!1;for(let n=0;n<e.length;n++){const i=e[n];if(isNaN(i)||!isFinite(i))return console.warn(`Found ${i} in the result of '${s}'`),!0}return!1}class U_{logKernelProfile(e,t,s,n,i,r){const o=typeof n=="number"?Yo(`${n}ms`,9):n.error,a=Yo(e,25),l=t.rank,c=t.size,p=Yo(t.shape.toString(),14);let u="";for(const h in i){const d=i[h];if(d!=null){const m=d.shape||t.shape,f=m.length;u+=`${h}: ${f}D ${f>0?m:""} `}}console.log(`%c${a} %c${o} %c${l}D ${p} %c${c} %c${u} %c${r}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function CS(e,t,s){const n={},i={};for(let l=0;l<t.length;l++)n[t[l].id]=!0;for(let l=0;l<e.length;l++){const c=e[l],p=c.inputs;for(const u in p){const h=p[u];let d=!1;for(let m=0;m<t.length;m++)if(n[h.id]){c.outputs.forEach(f=>n[f.id]=!0),d=!0,i[c.id]=!0;break}if(d)break}}const r={};r[s.id]=!0;const o={};for(let l=e.length-1;l>=0;l--){const c=e[l],p=c.inputs;for(let u=0;u<c.outputs.length;u++)if(r[c.outputs[u].id]){for(const h in p)r[p[h].id]=!0,o[c.id]=!0;break}}const a=[];for(let l=0;l<e.length;l++){const c=e[l];if(i[c.id]&&o[c.id]){const p={};for(const h in c.inputs){const d=c.inputs[h];n[d.id]&&(p[h]=d)}const u=Object.assign({},c);u.inputs=p,u.outputs=c.outputs,a.push(u)}}return a}function RS(e,t,s,n){for(let i=t.length-1;i>=0;i--){const r=t[i],o=[];if(r.outputs.forEach(l=>{const c=e[l.id];c!=null?o.push(c):o.push(null)}),r.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${r.kernelName}.`);const a=r.gradient(o);for(const l in r.inputs){if(!(l in a))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(a)}.`);const c=s(()=>a[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);const p=r.inputs[l];if(!Nt(c.shape,p.shape))throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${p.shape}'`);if(e[p.id]==null)e[p.id]=c;else{const u=e[p.id];e[p.id]=n(u,c),u.dispose()}}}}const OS=20,kp=3,Py=7;function ES(e,t,s,n){const i=oi(t),r=$_(e,t,s,i),o=t.length,a=_h(e,t,s,i,r),l=["Tensor"];return n&&(l.push(` dtype: ${s}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(a.map(c=>" "+c).join(`
`)),l.join(`
`)}function $_(e,t,s,n){const i=We(t),r=n[n.length-1],o=new Array(r).fill(0),a=t.length,l=s==="complex64"?Fp(e):e;if(a>1)for(let c=0;c<i/r;c++){const p=c*r;for(let u=0;u<r;u++)o[u]=Math.max(o[u],Dp(l[p+u],0,s).length)}return o}function Dp(e,t,s){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed(Py))} + ${parseFloat(e[1].toFixed(Py))}j`:Un(e)?n=`'${e}'`:s==="bool"?n=_S(e):n=parseFloat(e.toFixed(Py)).toString(),Yo(n,t)}function _S(e){return e===0?"false":"true"}function _h(e,t,s,n,i,r=!0){const o=s==="complex64"?2:1,a=t[0],l=t.length;if(l===0){if(s==="complex64"){const f=Fp(e);return[Dp(f[0],0,s)]}return s==="bool"?[_S(e[0])]:[e[0].toString()]}if(l===1){if(a>OS){const g=kp*o;let y=Array.from(e.slice(0,g)),w=Array.from(e.slice((a-kp)*o,a*o));return s==="complex64"&&(y=Fp(y),w=Fp(w)),["["+y.map((x,T)=>Dp(x,i[T],s)).join(", ")+", ..., "+w.map((x,T)=>Dp(x,i[a-kp+T],s)).join(", ")+"]"]}const f=s==="complex64"?Fp(e):Array.from(e);return["["+f.map((g,y)=>Dp(g,i[y],s)).join(", ")+"]"]}const c=t.slice(1),p=n.slice(1),u=n[0]*o,h=[];if(a>OS){for(let f=0;f<kp;f++){const g=f*u,y=g+u;h.push(..._h(e.slice(g,y),c,s,p,i,!1))}h.push("...");for(let f=a-kp;f<a;f++){const g=f*u,y=g+u;h.push(..._h(e.slice(g,y),c,s,p,i,f===a-1))}}else for(let f=0;f<a;f++){const g=f*u,y=g+u;h.push(..._h(e.slice(g,y),c,s,p,i,f===a-1))}const d=l===2?",":"";h[0]="["+h[0]+d;for(let f=1;f<h.length-1;f++)h[f]=" "+h[f]+d;let m=`,
`;for(let f=2;f<l;f++)m+=`
`;return h[h.length-1]=" "+h[h.length-1]+"]"+(r?"":m),h}function Fp(e){const t=[];for(let s=0;s<e.length;s+=2)t.push([e[s],e[s+1]]);return t}class dn{constructor(e,t,s){if(this.dtype=t,this.shape=e.slice(),this.size=We(e),s!=null){const n=s.length;I(n===this.size,()=>`Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=s||My(t,this.size),this.strides=oi(e)}set(e,...t){t.length===0&&(t=[0]),I(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const s=this.locToIndex(t);this.values[s]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let s=e[e.length-1];for(let n=0;n<e.length-1;++n)s+=this.strides[n]*e[n];return this.values[s]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let s=0;s<e.length-1;++s)t+=this.strides[s]*e[s];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let s=0;s<t.length-1;++s)t[s]=Math.floor(e/this.strides[s]),e-=t[s]*this.strides[s];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return li().makeTensor(this.values,this.shape,this.dtype)}}let li=null,il=null,W_=null;function kS(e){li=e}function DS(e){il=e}function FS(e){W_=e}class me{constructor(e,t,s,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=We(e),this.strides=oi(e),this.dataId=s,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return il.buffer(this.shape,this.dtype,e)}bufferSync(){return il.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ko(this.shape,e)}arraySync(){return Ko(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=li().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(s=>Eh(s))}catch(s){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=li().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Eh(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await li().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;li().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return il.print(this,e)}clone(){return this.throwIfDisposed(),il.clone(this)}toString(e=!1){const t=this.dataSync();return ES(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),il.cast(this,e)}variable(e=!0,t,s){return this.throwIfDisposed(),li().makeVariable(this,e,t,s)}}Object.defineProperty(me,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class ci extends me{constructor(e,t,s,n){super(e.shape,e.dtype,e.dataId,n);this.trainable=t,this.name=s}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Nt(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);li().disposeTensor(this),this.dataId=e.dataId,li().incRef(this,null)}dispose(){li().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(ci,Symbol.hasInstance,{value:e=>e instanceof me&&e.assign!=null&&e.assign instanceof Function});var By;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(By||(By={}));var jy;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(jy||(jy={}));var Vy;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Vy||(Vy={}));var Gy;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Gy||(Gy={}));var qy;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(qy||(qy={}));const z_={float32:Gy,int32:jy,bool:Vy,complex64:qy};function Ft(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return z_[e][t]}function Mp(e){return Ft(e,"int32")}const mn={};Ee(mn,{assertTypesMatch:()=>Hy,getTensorsInContainer:()=>Up,isTensorInList:()=>P_,makeTypesMatch:()=>Ce});function Ce(e,t){if(e.dtype===t.dtype)return[e,t];const s=Ft(e.dtype,t.dtype);return[e.cast(s),t.cast(s)]}function Hy(e,t){I(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function P_(e,t){return t.some(s=>s.id===e.id)}function Up(e){const t=[],s=new Set;return MS(e,t,s),t}function MS(e,t,s){if(e==null)return;if(e instanceof me){t.push(e);return}if(!B_(e))return;const n=e;for(const i in n){const r=n[i];s.has(r)||(s.add(r),MS(r,t,s))}}function B_(e){return Array.isArray(e)||typeof e=="object"}class US{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}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class $p{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new US}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const s=e[t],n=await this.initializeBackend(s).success;if(n){await this.setBackend(s);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){const{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,s=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:s},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;const{success:t,asyncInit:s}=this.initializeBackend(e),n=s?await t:t;if(!n)return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new NS(this.backendInstance),!0}setupRegisteredKernels(){const e=Op(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=Op(e);t.forEach(s=>{s.disposeFunc!=null&&s.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const s=t.factory();if(s&&!(s instanceof Eo)&&typeof s.then=="function"){const n=++this.pendingBackendInitId,i=s.then(r=>n<this.pendingBackendInitId?!1:(this.registry[e]=r,this.pendingBackendInit=null,!0)).catch(r=>(n<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(r.stack||r.message)),!1));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}else return this.registry[e]=s,{success:!0,asyncInit:!1}}catch(s){return console.warn(`Initialization of backend ${e} failed`),console.warn(s.stack||s.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const s=e[t],{success:n,asyncInit:i}=this.initializeBackend(s);if(i||n)return{name:s,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const s=this.state.tensorInfo.get(t),n=s.backend,i=this.readSync(t);n.disposeData(t),s.backend=e,e.move(t,i,s.shape,s.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let s=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");s=e}let n;return this.scopedRun(()=>this.startScope(s),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,s){e();try{const n=s();return t(),n}catch(n){throw t(),n}}nextTensorId(){return $p.nextTensorId++}nextVariableId(){return $p.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),s={x:e},n=r=>({x:()=>{const o="float32",a={x:r},l={dtype:o};return v.runKernelFunc(c=>c.cast(r,o),a,null,Ai,l)}}),i=[];return this.addTapeNode(this.state.activeScope.name,s,[t],n,i,{}),t}runKernel(e,t,s,n,i){const r=null,o=null;return this.runKernelFunc(r,t,o,e,s,n,i)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,s){const n=this.backend.numDataIds();let i=0;s.forEach(a=>{i+=a.dtype==="complex64"?3:1});const r=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=n-t-i-r;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e,t,s,n,i,r,o){let a,l=[];const c=this.isTapeOn();n==null&&(n=this.state.activeScope!=null?this.state.activeScope.name:"");const p=this.state.numBytes,u=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let h;const d=Rp(n,this.backendName);let m;if(d!=null)h=()=>{const g=this.backend.numDataIds();m=d.kernelFunc({inputs:t,attrs:i,backend:this.backend});const y=Array.isArray(m)?m:[m];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(n,g,y);const w=y.map(({dataId:x,shape:T,dtype:A})=>this.makeTensorFromDataId(x,T,A));if(c){let x=this.getTensorsForGradient(n,t,w);if(x==null){o==null&&(o=[]);const T=w.filter((A,_)=>o[_]);x=(r||[]).slice().concat(T)}l=this.saveTensorsForBackwardMode(x)}return w};else{const g=y=>{if(!c)return;l=y.map(w=>this.keep(this.clone(w)))};h=()=>{const y=this.backend.numDataIds();m=this.tidy(()=>e(this.backend,g));const w=Array.isArray(m)?m:[m];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(n,y,w),w}}let f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?a=h():(f=this.profiler.profileKernel(n,t,()=>h()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),a=f.outputs)}),c&&this.addTapeNode(n,t,a,s,l,i),this.state.profiling&&this.state.activeProfile.kernels.push({name:n,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-u,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(g=>t[g]!=null?t[g].shape:null),outputShapes:a.map(g=>g.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(m)?a:a[0]}saveTensorsForBackwardMode(e){const t=e.map(s=>this.keep(this.clone(s)));return t}getTensorsForGradient(e,t,s){const n=Ch(e);if(n!=null){const i=n.inputsToSave||[],r=n.outputsToSave||[];let o;n.saveAllInputs?(I(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=i.map(l=>t[l]);const a=s.filter((l,c)=>r[c]);return o.concat(a)}return null}makeTensor(e,t,s,n){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");s=s||"float32",n=n||this.backend;let i=e;s==="string"&&Un(e[0])&&(i=e.map(a=>Rh(a)));const r=n.write(i,t,s),o=new me(t,s,r,this.nextTensorId());if(this.incRef(o,n),s==="string"){const a=this.state.tensorInfo.get(r),l=zy(i);this.state.numBytes+=l-a.bytes,a.bytes=l}return o}makeTensorFromDataId(e,t,s,n){s=s||"float32";const i=new me(t,s,e,this.nextTensorId());return this.incRef(i,n),i}makeVariable(e,t=!0,s,n){s=s||this.nextVariableId().toString(),n!=null&&n!==e.dtype&&(e=e.cast(n));const i=new ci(e,t,s,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw new Error(`Variable with name ${i.name} was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i}incRef(e,t){const s=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,s===0){this.state.numDataBuffers++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*Wy(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n,refCount:0}),this.state.numBytes+=n}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof ci||this.track(e)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;const t=this.state.tensorInfo.get(e.dataId),s=t.refCount;s<=1?(e.dtype!=="complex64"&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&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,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,s=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(n=>n.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-s;for(const n of this.state.activeProfile.kernels)n.kernelTimeMs=await n.kernelTimeMs,n.extraInfo=await n.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,s,n,i,r){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:s,saved:i},a=Ch(e);a!=null&&(n=a.gradFunc),n!=null&&(o.gradient=l=>(l=l.map((c,p)=>{if(c==null){const u=s[p],h=ai(u.size,u.dtype);return this.makeTensor(h,u.shape,u.dtype)}return c}),n(l.length>1?l:l[0],i,r))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Up(e),s=new Set(t.map(i=>i.id));for(let i=0;i<this.state.activeScope.track.length;i++){const r=this.state.activeScope.track[i];!r.kept&&!s.has(r.id)&&r.dispose()}const n=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(i=>{!i.kept&&i.scopeId===n.id&&this.track(i)})}gradients(e,t,s,n=!1){if(I(t.length>0,()=>"gradients() received an empty list of xs."),s!=null&&s.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${s.dtype}'`);const i=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));I(i instanceof me,()=>"The result y returned by f() must be a tensor.");const r=CS(this.state.activeTape,t,i);if(!n&&r.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const o={};o[i.id]=s??j_(i.shape),RS(o,r,l=>this.tidy(l),V_);const a=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(const c of l.saved)c.dispose()}),this.state.activeTape=null),{value:i,grads:a}})}customGrad(e){return I(ri(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{I(t.every(i=>i instanceof me),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let s;const n={};return t.forEach((i,r)=>{n[r]=i}),this.runKernelFunc((i,r)=>(s=e(...t,r),I(s.value instanceof me,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),I(ri(s.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),s.value),n,(i,r)=>{const o=s.gradFunc(i,r),a=Array.isArray(o)?o:[o];I(a.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),I(a.every(c=>c instanceof me),()=>"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 l={};return a.forEach((c,p)=>{l[p]=()=>c}),l})}}readSync(e){const t=this.state.tensorInfo.get(e);return t.backend.readSync(e)}read(e){const t=this.state.tensorInfo.get(e);return t.backend.read(e)}async time(e){const t=Oh(),s=await this.backend.time(e);return s.wallMs=Oh()-t,s}track(e){return this.state.activeScope!=null&&(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 US;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}}$p.nextTensorId=0;$p.nextVariableId=0;function j_(e){const t=Ep(We(e),"float32");return v.makeTensor(t,e,"float32")}function Yy(){const e=Qg();if(e._tfengine==null){const t=new Xg(e);e._tfengine=new $p(t)}return LS(e._tfengine.ENV),kS(()=>e._tfengine),e._tfengine}const v=Yy();function V_(e,t){const s={a:e,b:t};return v.runKernelFunc((n,i)=>{const r=n.add(e,t);return i([e,t]),r},s,null,Zn)}const rl={};Ee(rl,{isBrowser:()=>Ky,isMobile:()=>q_});function G_(){return typeof navigator!="undefined"&&navigator!=null}function q_(){if(G_()){const e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/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(e.substr(0,4))}return!1}function Ky(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const ki=W();ki.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});ki.registerFlag("IS_BROWSER",()=>Ky());ki.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");ki.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));ki.registerFlag("PROD",()=>!1);ki.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>ki.getBool("DEBUG"));ki.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);ki.registerFlag("IS_TEST",()=>!1);function Qt(e,t){let s=e;if(Dt(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const n=[];for(;Array.isArray(s)||Dt(s)&&t!=="string";)n.push(s.length),s=s[0];return Array.isArray(e)&&W().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&$S(e,n,[]),n}function $S(e,t,s){if(s=s||[],!Array.isArray(e)&&!Dt(e)){I(t.length===0,()=>`Element arr[${s.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}I(t.length>0,()=>`Element arr[${s.join("][")}] should be a primitive, but is an array of ${e.length} elements`),I(e.length===t[0],()=>`Element arr[${s.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const n=t.slice(1);for(let i=0;i<e.length;++i)$S(e[i],n,s.concat(i))}function WS(e,t,s,n){if(e==null)return;if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${s}' passed to '${n}' must be ${e} tensor, but got ${t} tensor`)}function b(e,t,s,n="numeric"){if(e instanceof me)return WS(n,e.dtype,t,s),e;let i=tl(e);if(i!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(i=n),WS(n,i,t,s),e==null||!Dt(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){const l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${s}' must be a Tensor or TensorLike, but got '${l}'`)}const r=Qt(e,i);!Dt(e)&&!Array.isArray(e)&&(e=[e]);const o=!0,a=i!=="string"?nl(e,i):ii(e,[],o);return v.makeTensor(a,r,i)}function Di(e,t,s,n="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${s} must be a \`Tensor[]\` or \`TensorLike[]\``);const i=e;return i.map((r,o)=>b(r,`${t}[${o}]`,s),n)}const Xy="__op";function S(e){const t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let s=t[0];const n=e[s];s.endsWith("_")&&(s=s.substring(0,s.length-1)),s=s+Xy;const i=(...r)=>{v.startScope(s);try{const o=n(...r);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),v.endScope(o),o}catch(o){throw v.endScope(null),o}};return Object.defineProperty(i,"name",{value:s,configurable:!0}),i}function H_(e,t){const s=b(e,"real","complex"),n=b(t,"imag","complex");Se(s.shape,n.shape,`real and imag shapes, ${s.shape} and ${n.shape}, must match in call to tf.complex().`);const i=o=>o.complex(s,n),r={real:s,imag:n};return v.runKernelFunc(i,r,null,jc)}const Gt=S({complex_:H_});function hs(e,t,s,n){if(n==null&&(n=tl(e)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Dt(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){_p(t);const i=We(t),r=We(s);I(i===r,()=>`Based on the provided shape, [${t}], the tensor should have ${i} values but has ${r}`);for(let o=0;o<s.length;++o){const a=s[o],l=o===s.length-1?a!==We(t.slice(o)):!0;I(s[o]===t[o]||!l,()=>`Error creating a new Tensor. Inferred shape (${s}) does not match the provided shape (${t}). `)}}return!Dt(e)&&!Array.isArray(e)&&(e=[e]),t=t||s,e=n!=="string"?nl(e,n):ii(e,[],!0),v.makeTensor(e,t,n)}function ze(e,t,s){const n=Qt(e,s);return hs(e,t,n,s)}const Wp={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const kh=4;async function K_(e,t){const s=[],n=[],i=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o<i.length;++o){const a=i[o],l=Array.isArray(e)?e[o].tensor:e[a];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${a}': ${l.dtype}`);const c={name:a,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){const p=new Promise(async u=>{const h=await l.bytes(),d=h.reduce((g,y)=>g+y.length,0)+kh*h.length,m=new Uint8Array(d);let f=0;for(let g=0;g<h.length;g++){const y=h[g],w=new Uint8Array(new Uint32Array([y.length]).buffer);m.set(w,f),f+=kh,m.set(y,f),f+=y.length}u(m)});n.push(p)}else n.push(l.data());t!=null&&(c.group=t),s.push(c)}const r=await Promise.all(n);return{data:Y_(r),specs:s}}function Jy(e,t){const s={};let n,i=0;for(const r of t){const o=r.name,a=r.dtype,l=r.shape,c=We(l);let p;if("quantization"in r){const u=r.quantization;if(u.dtype==="uint8"||u.dtype==="uint16"){if(!("min"in u&&"scale"in u))throw new Error(`Weight ${r.name} with quantization ${u.dtype} doesn't have corresponding metadata min and scale.`)}else if(u.dtype==="float16"){if(a!=="float32")throw new Error(`Weight ${r.name} is quantized with ${u.dtype} which only supports weights of type float32 not ${a}.`)}else throw new Error(`Weight ${r.name} has unknown quantization dtype ${u.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);const h=Wp[u.dtype],d=e.slice(i,i+c*h),m=u.dtype==="uint8"?new Uint8Array(d):new Uint16Array(d);if(a==="float32")if(u.dtype==="uint8"||u.dtype==="uint16"){p=new Float32Array(m.length);for(let f=0;f<m.length;f++){const g=m[f];p[f]=g*u.scale+u.min}}else if(u.dtype==="float16")n===void 0&&(n=X_()),p=n(m);else throw new Error(`Unsupported quantization type ${u.dtype} for weight type float32.`);else if(a==="int32"){if(u.dtype!=="uint8"&&u.dtype!=="uint16")throw new Error(`Unsupported quantization type ${u.dtype} for weight type int32.`);p=new Int32Array(m.length);for(let f=0;f<m.length;f++){const g=m[f];p[f]=Math.round(g*u.scale+u.min)}}else throw new Error(`Unsupported dtype in weight '${o}': ${a}`);i+=c*h}else if(a==="string"){const u=We(r.shape);p=[];for(let h=0;h<u;h++){const d=new Uint32Array(e.slice(i,i+kh))[0];i+=kh;const m=new Uint8Array(e.slice(i,i+d));p.push(m),i+=d}}else{const u=Wp[a],h=e.slice(i,i+c*u);if(a==="float32")p=new Float32Array(h);else if(a==="int32")p=new Int32Array(h);else if(a==="bool")p=new Uint8Array(h);else if(a==="complex64"){p=new Float32Array(h);const d=new Float32Array(p.length/2),m=new Float32Array(p.length/2);for(let y=0;y<d.length;y++)d[y]=p[y*2],m[y]=p[y*2+1];const f=ze(d,l,"float32"),g=ze(m,l,"float32");s[o]=Gt(f,g)}else throw new Error(`Unsupported dtype in weight '${o}': ${a}`);i+=c*u}a!=="complex64"&&(s[o]=ze(p,l,a))}return s}function Y_(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const s=[];e.forEach(r=>{if(t+=r.byteLength,s.push(r.byteLength===r.buffer.byteLength?r:new r.constructor(r)),!(r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${r.constructor.name}`)});const n=new Uint8Array(t);let i=0;return s.forEach(r=>{n.set(new Uint8Array(r.buffer),i),i+=r.byteLength}),n.buffer}const J_=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function zS(e){return J_?Buffer.byteLength(e):new Blob([e]).size}function zp(e){if(e.length===1)return e[0];let t=0;e.forEach(i=>{t+=i.byteLength});const s=new Uint8Array(t);let n=0;return e.forEach(i=>{s.set(new Uint8Array(i),n),n+=i.byteLength}),s.buffer}function Zy(e){const t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);const s=e.split(t);return s[s.length-1]}function Pp(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:e.modelTopology==null?0:zS(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:zS(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function Z_(){const e=s=>{let n=s<<13,i=0;for(;(n&8388608)===0;)i-=8388608,n<<=1;return n&=~8388608,i+=947912704,n|i},t=new Uint32Array(2048);t[0]=0;for(let s=1;s<1024;s++)t[s]=e(s);for(let s=1024;s<2048;s++)t[s]=939524096+(s-1024<<13);return t}function Q_(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}function ek(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function X_(){const e=Z_(),t=Q_(),s=ek();return n=>{const i=new ArrayBuffer(4*n.length),r=new Uint32Array(i);for(let o=0;o<n.length;o++){const a=n[o],l=e[s[a>>10]+(a&1023)]+t[a>>10];r[o]=l}return new Float32Array(i)}}class Ct{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Ct.instance==null&&(Ct.instance=new Ct),Ct.instance}static registerSaveRouter(e){Ct.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ct.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ct.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ct.getHandlers(e,"load",t)}static getHandlers(e,t,s){const n=[],i=t==="load"?Ct.getInstance().loadRouters:Ct.getInstance().saveRouters;return i.forEach(r=>{const o=r(e,s);o!==null&&n.push(o)}),n}}const tk=e=>Ct.registerSaveRouter(e),sk=e=>Ct.registerLoadRouter(e),nk=e=>Ct.getSaveHandlers(e),ik=(e,t)=>Ct.getLoadHandlers(e,t);const ol="://";class $n{constructor(){this.managers={}}static getInstance(){return $n.instance==null&&($n.instance=new $n),$n.instance}static registerManager(e,t){I(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(ol)&&(e=e.slice(0,e.indexOf(ol))),I(e.length>0,()=>"scheme must not be an empty string.");const s=$n.getInstance();I(s.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),s.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}function Dh(e){if(e.indexOf(ol)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${$n.getSchemes().join(",")}`);return{scheme:e.split(ol)[0],path:e.split(ol)[1]}}async function PS(e,t,s=!1){I(e!==t,()=>`Old path and new path are the same: '${e}'`);const n=Ct.getLoadHandlers(e);I(n.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),I(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${e}.`);const i=n[0],r=Ct.getSaveHandlers(t);I(r.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),I(r.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${t}.`);const o=r[0],a=Dh(e).scheme,l=Dh(e).path,c=a===Dh(e).scheme,p=await i.load();s&&c&&await $n.getManager(a).removeModel(l);const u=await o.save(p);return s&&!c&&await $n.getManager(a).removeModel(l),u.modelArtifactsInfo}async function BS(){const e=$n.getSchemes(),t={};for(const s of e){const n=await $n.getManager(s).listModels();for(const i in n){const r=s+ol+i;t[r]=n[i]}}return t}async function jS(e){const t=Dh(e),s=$n.getManager(t.scheme);return s.removeModel(t.path)}async function VS(e,t){const s=!1;return PS(e,t,s)}async function GS(e,t){const s=!0;return PS(e,t,s)}function ge(e,t="float32",s){return t=t||"float32",_p(e),new dn(e,t,s)}function rk(e,t){const s=b(e,"x","cast");if(!Uy(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&s.dtype!=="string"||t!=="string"&&s.dtype==="string")throw new Error("Only strings can be casted to strings");const n={x:s},i={dtype:t};return v.runKernelFunc(r=>r.cast(s,t),n,null,Ai,i)}const G=S({cast_:rk});function ok(e){const t=b(e,"x","clone",null),s=()=>v.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return v.runKernelFunc(s,n,null,Ci)}const Fs=S({clone_:ok});function Fh(e,t=!1){console.log(e.toString(t))}Yy();const ak={buffer:ge,cast:G,clone:Fs,print:Fh};DS(ak);const lk="model",ck=".json",pk=".weights.bin";function qS(e){return new Promise(t=>setTimeout(t)).then(e)}class al{constructor(e){if(!W().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(al.URL_SCHEME)&&(e=e.slice(al.URL_SCHEME.length)),(e==null||e.length===0)&&(e=lk),this.modelTopologyFileName=e+ck,this.weightDataFileName=e+pk}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{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 s=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:s},i=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),r=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(r.download=this.modelTopologyFileName,r.href=i,await qS(()=>r.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await qS(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Pp(e)}}}}al.URL_SCHEME="downloads://";class uk{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.files=e}async load(){const e=this.files[0],t=this.files.slice(1);return new Promise((s,n)=>{const i=new FileReader;i.onload=r=>{const o=JSON.parse(r.target.result),a=o.modelTopology;if(a==null){n(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&s({modelTopology:a});const l=o.weightsManifest;if(l==null){n(new Error(`weightManifest field is missing from file ${e.name}`));return}let c;try{c=this.checkManifestAndWeightFiles(l,t)}catch(d){n(d);return}const p=[],u=[],h=[];l.forEach(d=>{d.paths.forEach(m=>{u.push(m),h.push(null)}),p.push(...d.weights)}),l.forEach(d=>{d.paths.forEach(m=>{const f=new FileReader;f.onload=g=>{const y=g.target.result,w=u.indexOf(m);h[w]=y,h.indexOf(null)===-1&&s({modelTopology:a,weightSpecs:p,weightData:zp(h),format:o.format,generatedBy:o.generatedBy,convertedBy:o.convertedBy,userDefinedMetadata:o.userDefinedMetadata})},f.onerror=g=>n(`Failed to weights data from file of path '${m}'.`),f.readAsArrayBuffer(c[m])})})},i.onerror=r=>n(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),i.readAsText(e)})}checkManifestAndWeightFiles(e,t){const s=[],n=t.map(r=>Zy(r.name)),i={};for(const r of e)r.paths.forEach(o=>{const a=Zy(o);if(s.indexOf(a)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(s.push(a),n.indexOf(a)===-1)throw new Error(`Weight file with basename '${a}' is not provided.`);i[o]=t[n.indexOf(a)]});if(s.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${s.length}) and the number of weight files provided (${t.length}).`);return i}}const dk=e=>W().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(al.URL_SCHEME))?hk(e.slice(al.URL_SCHEME.length)):null;Ct.registerSaveRouter(dk);function hk(e="model"){return new al(e)}function mk(e){return new uk(e)}function Qy(e,t,s,n){o(e),s=s??0,n=n??1,a(s,n);let i=0;const r=l=>(l.then(c=>{const p=s+ ++i/e.length*(n-s);return t(p),c}),l);function o(l){I(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function a(l,c){I(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),I(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),I(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(r))}async function eb(e,t){t==null&&(t={});const s=t.fetchFunc==null?W().platform.fetch:t.fetchFunc,n=e.map(u=>s(u,t.requestInit,{isBinary:!0})),i=0,r=.5,o=t.onProgress==null?await Promise.all(n):await Qy(n,t.onProgress,i,r),a=o.map(u=>u.arrayBuffer()),l=.5,c=1,p=t.onProgress==null?await Promise.all(a):await Qy(a,t.onProgress,l,c);return p}async function fk(e,t="",s,n){const i=o=>eb(o,{requestInit:n}),r=HS(i);return r(e,t,s)}function HS(e){return async(t,s="",n)=>{const i=t.map(()=>!1),r={},o=n!=null?n.map(()=>!1):[],a=[];if(t.forEach((d,m)=>{let f=0;d.weights.forEach(g=>{const y="quantization"in g?g.quantization.dtype:g.dtype,w=Wp[y]*We(g.shape),x=()=>{i[m]=!0,r[m]==null&&(r[m]=[]),r[m].push({manifestEntry:g,groupOffset:f,sizeBytes:w})};n!=null?n.forEach((T,A)=>{T===g.name&&(x(),o[A]=!0)}):x(),a.push(g.name),f+=w})}),!o.every(d=>d)){const d=n.filter((m,f)=>!o[f]);throw new Error(`Could not find weights in manifest with names: ${d.join(", ")}.
Manifest JSON has weights with names: ${a.join(", ")}.`)}const l=i.reduce((d,m,f)=>(m&&d.push(f),d),[]),c=[];l.forEach(d=>{t[d].paths.forEach(m=>{const f=s+(s.endsWith("/")?"":"/")+m;c.push(f)})});const p=await e(c),u={};let h=0;return l.forEach(d=>{const m=t[d].paths.length;let f=0;for(let T=0;T<m;T++)f+=p[h+T].byteLength;const g=new ArrayBuffer(f),y=new Uint8Array(g);let w=0;for(let T=0;T<m;T++){const A=new Uint8Array(p[h+T]);y.set(A,w),w+=A.byteLength}const x=r[d];x.forEach(T=>{const A=g.slice(T.groupOffset,T.groupOffset+T.sizeBytes),_=Jy(A,[T.manifestEntry]);for(const E in _)u[E]=_[E]}),h+=m}),u}}const gk="application/octet-stream",yk="application/json";class tb{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(I(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=W().platform.fetch,I(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&I(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const s=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:s};t.body.append("model.json",new Blob([JSON.stringify(n)],{type:yk}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:gk}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Pp(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(h){let d=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?d+=" 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.":d+=" Please make sure the server is serving valid JSON for this request.",new Error(d)}const s=t.modelTopology,n=t.weightsManifest,i=t.generatedBy,r=t.convertedBy,o=t.format,a=t.userDefinedMetadata;if(s==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let l,c;if(n!=null){const h=await this.loadWeights(n);[l,c]=h}const p={modelTopology:s,weightSpecs:l,weightData:c,userDefinedMetadata:a,generatedBy:i,convertedBy:r,format:o},u=t.modelInitializer;return u&&(p.modelInitializer=u),p}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[s,n]=bk(t),i=this.weightPathPrefix||s,r=[];for(const c of e)r.push(...c.weights);const o=[],a=[];for(const c of e)for(const p of c.paths)this.weightUrlConverter!=null?a.push(this.weightUrlConverter(p)):o.push(i+p+n);this.weightUrlConverter&&o.push(...await Promise.all(a));const l=await eb(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[r,zp(l)]}}tb.URL_SCHEME_REGEX=/^https?:\/\//;function bk(e){const t=e.lastIndexOf("/"),s=e.lastIndexOf("?"),n=e.substring(0,t),i=s>t?e.substring(s):"";return[n+"/",i]}function sb(e){return e.match(tb.URL_SCHEME_REGEX)!=null}const YS=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let s=!0;if(Array.isArray(e)?s=e.every(n=>sb(n)):s=sb(e),s)return nb(e,t)}return null};Ct.registerSaveRouter(YS);Ct.registerLoadRouter(YS);function nb(e,t){return new tb(e,t)}function wk(e,t){return nb(e,t)}class ib{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class xk{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function Lk(e,t,s,n){if(arguments.length===1){const i=e.modelTopology!=null||e.weightSpecs!=null;return i?new ib(e):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new ib({modelTopology:e}))}else return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new ib({modelTopology:e,weightSpecs:t,weightData:s,trainingConfig:n})}function Sk(e){return new xk(e)}const Rt={};Ee(Rt,{browserFiles:()=>mk,browserHTTPRequest:()=>wk,concatenateArrayBuffers:()=>zp,copyModel:()=>VS,decodeWeights:()=>Jy,encodeWeights:()=>K_,fromMemory:()=>Lk,getLoadHandlers:()=>ik,getModelArtifactsInfoForJSON:()=>Pp,getSaveHandlers:()=>nk,http:()=>nb,isHTTPScheme:()=>sb,listModels:()=>BS,loadWeights:()=>fk,moveModel:()=>GS,registerLoadRouter:()=>sk,registerSaveRouter:()=>tk,removeModel:()=>jS,weightsLoaderFactory:()=>HS,withSaveHandler:()=>Sk});function Ik(e,t){const s=b(e,"x","reshape",null),n={x:s},i={shape:t},r=(o,a)=>(t=Dy(t,s.size),I(s.size===We(t),()=>"new shape and old shape must have the same number of elements."),a([s]),o.reshape(s,t));return v.runKernelFunc(r,n,null,Ei,i)}const O=S({reshape_:Ik});function vk(e,t,s=!1,n=!1){let i=b(e,"a","matMul"),r=b(t,"b","matMul");[i,r]=Ce(i,r),I(i.rank>=2&&r.rank>=2&&i.rank===r.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${i.rank} and ${r.rank}.`);const o=s?i.shape[i.rank-2]:i.shape[i.rank-1],a=n?r.shape[r.rank-1]:r.shape[r.rank-2],l=s?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?r.shape[r.rank-2]:r.shape[r.rank-1],p=i.shape.slice(0,-2),u=r.shape.slice(0,-2),h=We(p),d=We(u);I(Nt(p,u),()=>`Error in matMul: outer dimensions (${p}) and (${u}) of Tensors with shapes ${i.shape} and ${r.shape} must match.`),I(o===a,()=>`Error in matMul: inner shapes (${o}) and (${a}) of Tensors with shapes ${i.shape} and ${r.shape} and transposeA=${s} and transposeB=${n} must match.`);const m=i.shape.slice(0,-2).concat([l,c]),f=s?O(i,[h,o,l]):O(i,[h,l,o]),g=n?O(r,[d,c,a]):O(r,[d,a,c]),y=(A,_)=>(_([f,g]),A.batchMatMul(f,g,s,n)),w={a:f,b:g},x={transposeA:s,transposeB:n},T=v.runKernelFunc(y,w,null,zc,x);return O(T,m)}const Te=S({matMul_:vk});function Tk(e,t,s=1,n=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const i=b(e,"indices","oneHot","int32"),r=[...i.shape,t],o=(c,p)=>(p([i]),O(c.oneHot(O(i,[i.size]),t,s,n),r)),a={indices:i},l={depth:t,onValue:s,offValue:n};return v.runKernelFunc(o,a,null,up,l)}const pi=S({oneHot_:Tk});function Ak(e,t){const s=b(e,"x","transpose");if(t==null&&(t=s.shape.map((r,o)=>o).reverse()),I(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`),t.forEach(r=>{I(r>=0&&r<s.rank,()=>`All entries in 'perm' must be between 0 and ${s.rank-1} but got ${t}`)}),s.rank<=1)return s.clone();const n={x:s},i={perm:t};return v.runKernelFunc(r=>r.transpose(s,t),n,null,_i,i)}const se=S({transpose_:Ak});function Nk(e,t,s){const n=b(e,"labels","confusionMatrix"),i=b(t,"predictions","confusionMatrix");I(s==null||s>0&&Number.isInteger(s),()=>`If provided, numClasses must be a positive integer, but got ${s}`),I(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),I(i.rank===1,()=>`Expected the rank of predictions to be 1, but got ${i.rank}`),I(n.shape[0]===i.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${i.shape[0]}. Labels and predictions should have the same number of elements.`),I(s>0&&Number.isInteger(s),()=>`numClasses is required to be a positive integer, but got ${s}`);const r=pi(G(n,"int32"),s),o=pi(G(i,"int32"),s),a=se(r);return G(Te(a,o),"int32")}const Ck=S({confusionMatrix_:Nk});const KS={};Ee(KS,{confusionMatrix:()=>Ck});function ll(e,t,s){if(Ys(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const n=Qt(e,s);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return hs(e,t,n,s)}const Gr={};Ee(Gr,{fromPixels:()=>Ek,toPixels:()=>Ok});let cl;function Rk(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let s=!1,n=!1,i=!1,r=!1,o=!1;if(e.data instanceof Uint8Array)s=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)i=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)r=!0;else if(e.getContext!=null)o=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(i){const d=2;if(i&&e.readyState<d)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const a=Rp(Xa,v.backendName);if(a!=null){const d={pixels:e},m={numChannels:t};return v.runKernel(Xa,d,m)}const[l,c]=i?[e.videoWidth,e.videoHeight]:[e.width,e.height];let p;o?p=e.getContext("2d").getImageData(0,0,l,c).data:n||s?p=e.data:(r||i)&&(cl==null&&(cl=document.createElement("canvas").getContext("2d")),cl.canvas.width=l,cl.canvas.height=c,cl.drawImage(e,0,0,l,c),p=cl.getImageData(0,0,l,c).data);let u;if(t===4)u=new Int32Array(p);else{const d=l*c;u=new Int32Array(d*t);for(let m=0;m<d;m++)for(let f=0;f<t;++f)u[m*t+f]=p[m*4+f]}const h=[c,l,t];return ll(u,h,"int32")}async function Ok(e,t){let s=b(e,"img","toPixels");if(!(e instanceof me)){const c=s;s=G(c,"int32"),c.dispose()}if(s.rank!==2&&s.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${s.rank}.`);const[n,i]=s.shape.slice(0,2),r=s.rank===2?1:s.shape[2];if(r>4||r===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${r}`);if(s.dtype!=="float32"&&s.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${s.dtype}. Please use float32 or int32 tensors.`);const o=await s.data(),a=s.dtype==="float32"?255:1,l=new Uint8ClampedArray(i*n*4);for(let c=0;c<n*i;++c){const p=[0,0,0,255];for(let h=0;h<r;h++){const d=o[c*r+h];if(s.dtype==="float32"){if(d<0||d>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${d}.`)}else if(s.dtype==="int32"&&(d<0||d>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${d}.`);r===1?(p[0]=d*a,p[1]=d*a,p[2]=d*a):p[h]=d*a}const u=c*4;l[u+0]=Math.round(p[0]),l[u+1]=Math.round(p[1]),l[u+2]=Math.round(p[2]),l[u+3]=Math.round(p[3])}if(t!=null){t.width=i,t.height=n;const c=t.getContext("2d"),p=new ImageData(l,i,n);c.putImageData(p,0,0)}return s!==e&&s.dispose(),l}const Ek=S({fromPixels_:Rk});const XS={};Ee(XS,{prepareAndValidate:()=>JS});function JS(e,t){if(e.rank<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.rank<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[t.rank-1]>e.rank)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[t.rank-1]} vs. ${e.rank}`);if(e.size===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const s=t.shape,n=s[s.length-1];let i=1;for(let c=0;c<s.length-1;++c)i*=s[c];const r=e.shape,o=s.slice();o.pop();let a=1;for(let c=n;c<e.rank;++c)a*=r[c],o.push(r[c]);const l=[...oi(e.shape).map(c=>c/a),1].slice(0,n);return[o,i,a,l]}const ZS={};Ee(ZS,{calculateShapes:()=>QS,validateInput:()=>Mh,validateUpdateShape:()=>rb});function rb(e,t,s){const n=t.rank>1?t.shape[t.rank-1]:1,i=t.rank>1?t.rank-1:1,r=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${s.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${n}, and batchDim: ${i}.`;if(s.rank<i)throw new Error(r+` update.rank < ${i}. `);if(e.length<n+(s.rank-i))throw new Error(r+` Output shape length < ${n+(s.rank-i)}`);if(s.rank!==i+e.length-n)throw new Error(r+` update.rank != ${i+e.length-n}`);for(let o=0;o<i;++o)if(s.shape[o]!==t.shape[o])throw new Error(r+` updates.shape[${o}] (${s.shape[o]}) != indices.shape[${o}] (${t.shape[o]}).`);for(let o=0;o<s.rank-i;++o)if(s.shape[o+i]!==e[o+n])throw new Error(r+` updates.shape[${o+i}] (${s.shape[o+i]}) != shape[${o+i}] (${e[o+i]})`)}function Mh(e,t,s){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(s.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${s}`);if(s.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}rb(s,t,e)}function QS(e,t,s){const n=t.shape.length,i=n>1?t.shape[n-1]:1,r=s.length;let o=1;for(let u=i;u<r;++u)o*=s[u];const a=i<1?1:i,l=We(t.shape)/a,c=[...oi(s.slice(0,i)),1],p=We(s);return{sliceRank:i,numUpdates:l,sliceSize:o,strides:c,outputSize:p}}const Ms={};Ee(Ms,{assertParamsValid:()=>ob,computeFlatOffset:()=>kk,computeOutShape:()=>ab,getNormalizedAxes:()=>lb,isSliceContinous:()=>_k,maskToAxes:()=>Bp,parseSliceParams:()=>jp,startForAxis:()=>oI,startIndicesWithElidedDims:()=>nI,stopForAxis:()=>aI,stopIndicesWithElidedDims:()=>iI,stridesForAxis:()=>rI,stridesWithElidedDims:()=>eI});function ob(e,t,s){const n=e.shape.length;I(n===t.length,()=>`Error in slice${n}D: Length of begin ${t} must match the rank of the array (${n}).`),I(n===s.length,()=>`Error in slice${n}D: Length of size ${s} must match the rank of the array (${n}).`);for(let i=0;i<n;++i)I(t[i]+s[i]<=e.shape[i],()=>`Error in slice${n}D: begin[${i}] + size[${i}] (${t[i]+s[i]}) would overflow input.shape[${i}] (${e.shape[i]})`)}function Bp(e){const t=[];let s=0;for(;e>0;)e&1&&t.push(s),e/=2,s++;return t}function ab(e,t,s){const n=[];for(let i=0;i<e.length;i++)n[i]=Math.ceil((t[i]-e[i])/s[i]);return n}function eI(e,t,s,n){const i=[...e];for(let r=i.length;r<n.length;r++)i.push(1);for(let r=0;r<s;r++)r===0?i[t]=1:(i.splice(t,0,1),i.pop());return i}function tI(e,t,s){return s<=e?s:s-(t-1)}function sI(e,t){const s=[];for(let n=0;n<e;n++)s.push(t+n);return s}function lb(e,t,s,n,i,r,o,a,l){const c=e.length;let p=new Array(c),u=new Array(c),h=new Array(c);if(t.length&&s>0){const d=t[0],m=s+1;p=nI(o,d,m,n,e),u=iI(a,d,m,i,e),h=eI(r,d,m,e)}else for(let d=0;d<c;d++)p[d]=oI(o,n,r,e,d,l),u[d]=aI(a,i,r,e,d,l),h[d]=rI(r,d,l);return{begin:p,end:u,strides:h}}function nI(e,t,s,n,i){const r=[...i],o=sI(s,t);for(let a=0;a<r.length;a++)if(o.indexOf(a)>-1)r[a]=0;else{const l=tI(t,s,a);let c=n[l];e&1<<l&&(c=0),r[a]=c}return r}function iI(e,t,s,n,i){const r=[...i],o=sI(s,t);for(let a=0;a<r.length;a++)if(o.indexOf(a)>-1)r[a]=Number.MAX_SAFE_INTEGER;else{const l=tI(t,s,a);let c=n[l];e&1<<l&&(c=Number.MAX_SAFE_INTEGER),r[a]=c}for(let a=0;a<r.length;a++){const l=i[a];r[a]<0&&(r[a]+=l),r[a]=Qa(0,r[a],i[a])}return r}function rI(e,t,s){let n=e[t];return(s&1<<t||n==null)&&(n=1),n}function oI(e,t,s,n,i,r){let o=t[i];const a=s[i]||1;(e&1<<i||r&1<<i||o==null)&&(a>0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);const l=n[i];return o<0&&(o+=l),o=Qa(0,o,l-1),o}function aI(e,t,s,n,i,r){let o=t[i];const a=s[i]||1;(e&1<<i||r&1<<i||o==null)&&(a>0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);const l=n[i];return o<0&&(o+=l),a>0?o=Qa(0,o,l):o=Qa(-1,o,l-1),o}function _k(e,t,s){let n=s.length;for(let i=0;i<s.length;i++)if(s[i]>1){n=i;break}for(let i=n+1;i<s.length;i++)if(t[i]>0||s[i]!==e[i])return!1;return!0}function kk(e,t){let s=e.length>0?e[e.length-1]:1;for(let n=0;n<e.length-1;n++)s+=e[n]*t[n];return s}function jp(e,t,s){let n;const i=e.shape.length;typeof t=="number"?n=[t,...new Array(i-1).fill(0)]:t.length<i?n=t.concat(new Array(i-t.length).fill(0)):n=t.slice(),n.forEach(o=>{I(o!==-1,()=>"slice() does not support negative begin indexing.")});let r;return s==null?r=new Array(i).fill(-1):typeof s=="number"?r=[s,...new Array(i-1).fill(-1)]:s.length<i?r=s.concat(new Array(i-s.length).fill(-1)):r=s,r=r.map((o,a)=>o>=0?o:(I(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${a}.`),e.shape[a]-n[a])),[n,r]}const V={};Ee(V,{Serializable:()=>cb,SerializationMap:()=>Xo,registerClass:()=>As});class cb{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Xo{constructor(){this.classNameMap={}}static getMap(){return Xo.instance==null&&(Xo.instance=new Xo),Xo.instance}static register(e){Xo.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function As(e){I(e.className!=null,()=>"Class being registered does not have the static className property defined."),I(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),I(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Xo.register(e)}const lI={};Ee(lI,{TEST_EPSILON_FLOAT16:()=>cI,expectArrayBuffersEqual:()=>zk,expectArraysClose:()=>Fk,expectArraysEqual:()=>Uk,expectNumbersClose:()=>$k,expectPromiseToFail:()=>Mk,expectValuesInRange:()=>Wk,testEpsilon:()=>pb});const Dk=.001,cI=.1;function Fk(e,t,s){return s==null&&(s=pb()),ub(e,t,(n,i)=>hb(n,i,s))}function pb(){return v.backend.floatPrecision()===32?Dk:cI}function ub(e,t,s){let n=!0;if((Dt(e)||Dt(t))&&(n=!1),Dt(e)&&Dt(t)&&(n=!0),n){const o=e.constructor.name,a=t.constructor.name;if(o!==a)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${a}`)}if(Array.isArray(e)&&Array.isArray(t)){const o=Qt(e),a=Qt(t);if(!Nt(o,a))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${a}]`)}const i=Dt(e)?e:ii(e),r=Dt(t)?t:ii(t);if(i.length!==r.length)throw new Error(`Arrays have different lengths actual: ${i.length} vs expected: ${r.length}.
Actual: ${i}.
Expected: ${r}.`);for(let o=0;o<r.length;++o){const a=i[o],l=r[o];if(!s(a,l))throw new Error(`Arrays differ: actual[${o}] = ${a}, expected[${o}] = ${l}.
Actual: ${i}.
Expected: ${r}.`)}}function Mk(e,t){e().then(()=>t.fail(),()=>t())}function Uk(e,t){const s=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Un(e)||Un(e[0])||Un(t)||Un(t[0])?ub(e,s,(n,i)=>n==i):ub(e,t,(n,i)=>hb(n,i,0))}function $k(e,t,s){if(s==null&&(s=pb()),!hb(e,t,s))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function hb(e,t,s){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>s)}function Wk(e,t,s){for(let n=0;n<e.length;n++)if(e[n]<t||e[n]>s)throw new Error(`Value out of range:${e[n]} low: ${t}, high: ${s}`)}function zk(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const db="2.6.0";function Pk(){W().set("PROD",!0)}function Bk(){W().set("DEBUG",!0)}function jk(){W().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function It(e){W().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}FS(It);function Vk(){v.disposeVariables()}function Us(){return v}function pl(){return v.memory()}function Gk(e){return v.profile(e)}function C(e,t){return v.tidy(e,t)}function ce(e){const t=Up(e);t.forEach(s=>s.dispose())}function pt(e){return v.keep(e)}function qk(e){return v.time(e)}function pI(e){return v.setBackend(e)}function Hk(){return v.ready()}function Yk(){return v.backendName}function Kk(e){v.removeBackend(e)}function Xk(e){return v.findBackend(e)}function Jk(e){return v.findBackendFactory(e)}function Vp(e,t,s=1){return v.registerBackend(e,t,s)}function mb(){return v.backend}function Zk(e,t){W().setPlatform(e,t)}function Qk(e,t){let s=b(e,"a","add"),n=b(t,"b","add");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.add(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Zn)}const $=S({add_:Qk});function eD(e,t){let s=b(e,"a","floorDiv"),n=b(t,"b","floorDiv");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.floorDiv(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Xc)}const ul=S({floorDiv_:eD});function tD(e,t){let s=b(e,"a","div"),n=b(t,"b","div");if([s,n]=Ce(s,n),s.dtype==="int32"&&n.dtype==="int32")return ul(s,n);const i=(a,l)=>{const c=a.realDivide(s,n);return l([s,n]),c},r={a:s,b:n},o={};return v.runKernelFunc(i,r,null,ei,o)}const Z=S({div_:tD});function sD(e,t){let s=b(e,"a","mul"),n=b(t,"b","mul");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.multiply(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,_r)}const R=S({mul_:sD});function nD(e){const t=b(e,"x","abs"),s={x:t};return v.runKernelFunc((n,i)=>(i([t]),t.dtype==="complex64"?n.complexAbs(t):n.abs(t)),s,null,_o)}const et=S({abs_:nD});function iD(e){const t=b(e,"x","acos"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.acos(t);return i([t]),r},s,null,dr)}const Uh=S({acos_:iD});function rD(e){const t=b(e,"x","acosh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.acosh(t);return i([t]),r},s,null,mr)}const $h=S({acosh_:rD});function oD(e){I(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),I(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((r,o)=>b(r,`tensors${o}`,"addN")),s=t[0];t.forEach(r=>{if(r.dtype!==s.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Nt(r.shape,s.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const n=(r,o)=>{const a=r.addN(t);return o(t),a},i=t;return v.runKernelFunc(n,i,null,Mc)}const Wh=S({addN_:oD});function fb(e,t){for(let s=0;s<e.length;++s)if(e[e.length-s-1]!==t-1-s)return!1;return!0}function uI(e,t,s){const n=e.length+t.length,i=[];let r=0,o=0;for(let a=0;a<n;a++)s.indexOf(a)===-1?i.push(e[r++]):i.push(t[o++]);return i}function gb(e,t){const s=[],n=e.length;for(let r=0;r<n;r++)t.indexOf(r)===-1&&s.push(e[r]);const i=t.map(r=>e[r]);return[s,i]}function wt(e,t){const s=t.map(n=>1);return uI(e,s,t)}function aD(e,t,s){I(fb(t,s),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${s} input.`)}function dt(e,t){if(fb(e,t))return null;const s=[];for(let n=0;n<t;++n)e.indexOf(n)===-1&&s.push(n);return e.forEach(n=>s.push(n)),s}function Jo(e){return e.map((t,s)=>[s,t]).sort((t,s)=>t[1]-s[1]).map(t=>t[0])}function qt(e,t){const s=[];for(let n=t-e;n<t;++n)s.push(n);return s}function lD(e,t=null,s=!1){let n=b(e,"x","all","bool");const i=a=>{const l=Ne(t,n.shape);let c=l;const p=dt(c,n.rank);p!=null&&(n=se(n,p),c=qt(c.length,n.rank));const u=a.all(n,c);if(s){const h=wt(u.shape,l);return O(u,h)}return u},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,ty,o)}const hl=S({all_:lD});function cD(e,t=null,s=!1){let n=b(e,"x","any","bool");const i=a=>{const l=Ne(t,n.shape);let c=l;const p=dt(c,n.rank);p!=null&&(n=se(n,p),c=qt(c.length,n.rank));const u=a.any(n,c);if(s){const h=wt(u.shape,l);return O(u,h)}return u},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,sy,o)}const Zo=S({any_:cD});function pD(e,t=0){let s=b(e,"x","argMax");const n=(o,a)=>{a([s]);let l=Ne(t,s.shape);const c=dt(l,s.rank);return c!=null&&(s=se(s,c),l=qt(l.length,s.rank)),o.argMax(s,l[0])},i={x:s},r={axis:t};return v.runKernelFunc(n,i,null,Uc,r)}const Qo=S({argMax_:pD});function uD(e,t=0){let s=b(e,"x","argMin");const n=(o,a)=>{a([s]),t==null&&(t=0);let l=Ne(t,s.shape);const c=dt(l,s.rank);return c!=null&&(s=se(s,c),l=qt(l.length,s.rank)),o.argMin(s,l[0])},i={x:s},r={axis:t};return v.runKernelFunc(n,i,null,$c,r)}const zh=S({argMin_:uD});function hD(e){const t=b(e,"x","asin"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.asin(t);return i([t]),r},s,null,fr)}const Ph=S({asin_:hD});function dD(e){const t=b(e,"x","asinh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.asinh(t);return i([t]),r},s,null,gr)}const Bh=S({asinh_:dD});function mD(e){const t=b(e,"x","atan"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.atan(t);return i([t]),r},s,null,yr)}const jh=S({atan_:mD});function fD(e,t){let s=b(e,"a","atan2"),n=b(t,"b","atan2");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.atan2(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,ko)}const Vh=S({atan2_:fD});function gD(e){const t=b(e,"x","atanh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.atanh(t);return i([t]),r},s,null,br)}const Gh=S({atanh_:gD});function yD(e,t,s,n,i="NHWC",r){const o=e[3],a=[...t,o],l=qr(i);return rs(e,a,s,r,n,null,null,l)}function Wn(e,t,s,n,i,r,o="channelsLast"){const[a,l]=qh(t);let c;if(o==="channelsLast")c=[a,l,e[3],e[3]];else if(o==="channelsFirst")c=[a,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return rs(e,c,s,n,i,r,!1,o)}function Fi(e,t,s,n,i,r,o="NDHWC"){const[a,l,c]=yb(t);let p,u;if(o==="NDHWC")u="channelsLast",p=[a,l,c,e[4],e[4]];else if(o==="NCDHW")u="channelsFirst",p=[a,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return Hr(e,p,s,n,i,!1,u,r)}function rs(e,t,s,n,i,r,o=!1,a="channelsLast"){let[l,c,p,u]=[-1,-1,-1,-1];if(a==="channelsLast")[l,c,p,u]=e;else if(a==="channelsFirst")[l,u,c,p]=e;else throw new Error(`Unknown dataFormat ${a}`);const[h,d,,m]=t,[f,g]=qh(s),[y,w]=qh(n),x=dl(h,y),T=dl(d,w),{padInfo:A,outHeight:_,outWidth:E}=bD(i,c,p,f,g,x,T,r,a),F=o?m*u:m;let D;return a==="channelsFirst"?D=[l,F,_,E]:a==="channelsLast"&&(D=[l,_,E,F]),{batchSize:l,dataFormat:a,inHeight:c,inWidth:p,inChannels:u,outHeight:_,outWidth:E,outChannels:F,padInfo:A,strideHeight:f,strideWidth:g,filterHeight:h,filterWidth:d,effectiveFilterHeight:x,effectiveFilterWidth:T,dilationHeight:y,dilationWidth:w,inShape:e,outShape:D,filterShape:t}}function Hr(e,t,s,n,i,r=!1,o="channelsLast",a){let[l,c,p,u,h]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,p,u,h]=e;else if(o==="channelsFirst")[l,h,c,p,u]=e;else throw new Error(`Unknown dataFormat ${o}`);const[d,m,f,,g]=t,[y,w,x]=yb(s),[T,A,_]=yb(n),E=dl(d,T),F=dl(m,A),D=dl(f,_),{padInfo:M,outDepth:P,outHeight:B,outWidth:Y}=wD(i,c,p,u,y,w,x,E,F,D,a),q=r?g*h:g;let K;return o==="channelsFirst"?K=[l,q,P,B,Y]:o==="channelsLast"&&(K=[l,P,B,Y,q]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:p,inWidth:u,inChannels:h,outDepth:P,outHeight:B,outWidth:Y,outChannels:q,padInfo:M,strideDepth:y,strideHeight:w,strideWidth:x,filterDepth:d,filterHeight:m,filterWidth:f,effectiveFilterDepth:E,effectiveFilterHeight:F,effectiveFilterWidth:D,dilationDepth:T,dilationHeight:A,dilationWidth:_,inShape:e,outShape:K,filterShape:t}}function xD(e,t,s,n,i){n==null&&(n=bb(e,t,s));const r=e[0],o=e[1],a=ea((r-t+2*n)/s+1,i);I(De(a),()=>`The output # of rows (${a}) must be an integer. Change the stride and/or zero pad parameters`);const l=ea((o-t+2*n)/s+1,i);return I(De(l),()=>`The output # of columns (${l}) must be an integer. Change the stride and/or zero pad parameters`),[a,l]}function LD(e,t,s,n,i,r){i==null&&(i=bb(e,t,n));const o=e[0],a=e[1],l=e[2],c=ea((o-t+2*i)/n+1,r);I(De(c),()=>`The output # of depths (${c}) must be an integer. Change the stride and/or zero pad parameters`);const p=ea((a-t+2*i)/n+1,r);I(De(p),()=>`The output # of rows (${p}) must be an integer. Change the stride and/or zero pad parameters`);const u=ea((l-t+2*i)/n+1,r);return I(De(u),()=>`The output # of columns (${u}) must be an integer. Change the stride and/or zero pad parameters`),[c,p,u,s]}function bb(e,t,s,n=1){const i=dl(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)}function qh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function yb(e){return typeof e=="number"?[e,e,e]:e}function dl(e,t){return t<=1?e:e+(e-1)*(t-1)}function bD(e,t,s,n,i,r,o,a,l){let c,p,u;if(typeof e=="number"){const h=e===0?"VALID":"NUMBER";c={top:e,bottom:e,left:e,right:e,type:h};const d=xD([t,s],r,n,e,a);p=d[0],u=d[1]}else if(e==="same"){p=Math.ceil(t/n),u=Math.ceil(s/i);const h=Math.max(0,(p-1)*n+r-t),d=Math.max(0,(u-1)*i+o-s),m=Math.floor(h/2),f=h-m,g=Math.floor(d/2),y=d-g;c={top:m,bottom:f,left:g,right:y,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((t-r+1)/n),u=Math.ceil((s-o+1)/i);else if(typeof e=="object"){const h=l==="channelsLast"?e[1][0]:e[2][0],d=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1],g=h===0&&d===0&&m===0&&f===0?"VALID":"EXPLICIT";c={top:h,bottom:d,left:m,right:f,type:g},p=ea((t-r+h+d)/n+1,a),u=ea((s-o+m+f)/i+1,a)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:p,outWidth:u}}function wD(e,t,s,n,i,r,o,a,l,c,p){let u,h,d,m;if(typeof e=="number"){const f=e===0?"VALID":"NUMBER";u={top:e,bottom:e,left:e,right:e,front:e,back:e,type:f};const g=LD([t,s,n,1],a,1,i,e,p);h=g[0],d=g[1],m=g[2]}else if(e==="same"){h=Math.ceil(t/i),d=Math.ceil(s/r),m=Math.ceil(n/o);const f=(h-1)*i+a-t,g=(d-1)*r+l-s,y=(m-1)*o+c-n,w=Math.floor(f/2),x=f-w,T=Math.floor(g/2),A=g-T,_=Math.floor(y/2),E=y-_;u={top:T,bottom:A,left:_,right:E,front:w,back:x,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},h=Math.ceil((t-a+1)/i),d=Math.ceil((s-l+1)/r),m=Math.ceil((n-c+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outDepth:h,outHeight:d,outWidth:m}}function ea(e,t){if(!t)return e;switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function Ks(e){const[t,s,n]=qh(e);return t===1&&s===1&&n===1}function tt(e,t){return Ks(e)||Ks(t)}function qr(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function SD(e,t,s,n,i){const r=b(e,"x","avgPool","float32"),o=1;I(tt(s,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`);let a=r,l=!1;r.rank===3&&(l=!0,a=O(r,[1,r.shape[0],r.shape[1],r.shape[2]])),I(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),i!=null&&I(De(n),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const c=(d,m)=>{const f=Wn(a.shape,t,s,1,n,i);return m([a]),f.filterWidth===1&&f.filterHeight===1&&Nt(f.inShape,f.outShape)?a.clone():d.avgPool(a,f)},p={x:a},u={filterSize:t,strides:s,pad:n,dimRoundingMode:i};let h=v.runKernelFunc(c,p,null,Ti,u);return h=G(h,r.dtype),l?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const ds=S({avgPool_:SD});function ID(e,t,s,n,i,r="NDHWC",o){o==null?o=[1,1,1]:It("dilations is deprecated, this field will be gone in v3.0.0.");const a=b(e,"x","avgPool3d","float32");let l=a,c=!1;a.rank===4&&(c=!0,l=O(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),I(l.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${l.rank}.`),I(r==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),I(tt(s,o),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&I(De(n),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const p=(m,f)=>{o==null&&(o=[1,1,1]);const g=Fi(l.shape,t,s,o,n,i,r);return f([l]),m.avgPool3d(l,g)},u={x:l},h={filterSize:t,strides:s,pad:n,dimRoundingMode:i,dataFormat:r,dilations:o};let d=v.runKernelFunc(p,u,null,Wc,h);return d=G(d,l.dtype),c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const ml=S({avgPool3d_:ID});function wb(e,t){const s=e[0].length;e.forEach((i,r)=>{I(i.length===s,()=>`Error in concat${s}D: rank of tensors[${r}] must be the same as the rank of the rest (${s})`)}),I(t>=0&&t<s,()=>`Error in concat${s}D: axis must be between 0 and ${s-1}.`);const n=e[0];e.forEach((i,r)=>{for(let o=0;o<s;o++)I(o===t||i[o]===n[o],()=>`Error in concat${s}D: Shape of tensors[${r}] (${i}) does not match the shape of the rest (${n}) along the non-concatenated axis ${r}.`)})}function xb(e,t){const s=e[0].slice();for(let n=1;n<e.length;n++)s[t]+=e[n][t];return s}function vD(e,t=0){I(e.length>=1,()=>"Pass at least one tensor to concat");let s=Di(e,"tensors","concat");s[0].dtype==="complex64"&&s.forEach(o=>{if(o.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${o.dtype}. `)});const n=(o,a)=>{const l=Ne(t,s[0].shape)[0],c=xb(s.map(h=>h.shape),l);if(We(c)===0)return ze([],c);if(s=s.filter(h=>h.size>0),s.length===1)return s[0];const p=s.map(h=>h.shape);wb(p,l);const u=o.concat(s,l);return a(s),u},i=s,r={axis:t};return v.runKernelFunc(n,i,null,Fo,r)}const be=S({concat_:vD});function TD(e){const t=b(e,"x","sigmoid"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sigmoid(t);return i([r]),r},s,null,Wr)}const os=S({sigmoid_:TD});function AD(e,t,s){const n=b(e,"x","slice");if(n.rank===0)throw new Error("Slicing scalar is not possible");const i=(a,l)=>{const[c,p]=jp(n,t,s);return ob(n,c,p),l([n]),a.slice(n,c,p)},r={x:n},o={begin:t,size:s};return v.runKernelFunc(i,r,null,jo,o)}const he=S({slice_:AD});function ND(e){const t=b(e,"x","tanh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.tanh(t);return i([r]),r},s,null,jr)}const Mi=S({tanh_:ND});function CD(e,t,s,n,i,r){const o=b(e,"forgetBias","basicLSTMCell"),a=b(t,"lstmKernel","basicLSTMCell"),l=b(s,"lstmBias","basicLSTMCell"),c=b(n,"data","basicLSTMCell"),p=b(i,"c","basicLSTMCell"),u=b(r,"h","basicLSTMCell"),h=be([c,u],1),d=Te(h,a),m=$(d,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],w=he(m,[0,0],y),x=he(m,[0,g],y),T=he(m,[0,g*2],y),A=he(m,[0,g*3],y),_=$(R(os(w),Mi(x)),R(p,os($(o,T)))),E=R(Mi(_),os(A));return[_,E]}const hI=S({basicLSTMCell_:CD});function RD(e,t,s){const n=b(e,"x","batchToSpaceND"),i=t.reduce((l,c)=>l*c);I(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),I(s.length===t.length,()=>`crops.length is ${s.length} but should be equal to blockShape.length ${t.length}`),I(n.shape[0]%i===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const r=l=>l.batchToSpaceND(n,t,s),o={x:n},a={blockShape:t,crops:s};return v.runKernelFunc(r,o,null,Pc,a)}const Yr=S({batchToSpaceND_:RD});function dI(e){let t;return e.rank===0||e.rank===1?t=O(e,[1,1,1,e.size]):e.rank===2?t=O(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=O(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function OD(e,t,s,n,i,r){r==null&&(r=.001);const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;n!=null&&(p=b(n,"offset","batchNorm")),I(a.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),I(p==null||a.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),I(c==null||a.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const u=dI(o),h=(g,y)=>(y([u,a,l,c]),g.batchNorm(u,Hh(a),Hh(l),Hh(p),Hh(c),r)),d={x:u,scale:c,offset:p,mean:a,variance:l},m={varianceEpsilon:r},f=v.runKernelFunc(h,d,null,Ni,m);return O(f,o.shape)}function Hh(e){return e==null?null:e.rank===0?O(e,[e.size]):e.rank===1?e:e.rank===2?O(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?O(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const Xs=S({batchNorm_:OD});function ED(e,t,s,n,i,r){const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;return n!=null&&(p=b(n,"offset","batchNorm")),I(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),I(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),I(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&I(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),p!=null&&I(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),Xs(o,a,l,p,c,r)}const Yh=S({batchNorm2d_:ED});function _D(e,t,s,n,i,r){const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;return n!=null&&(p=b(n,"offset","batchNorm")),I(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),I(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),I(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&I(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),p!=null&&I(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),Xs(o,a,l,p,c,r)}const Kh=S({batchNorm3d_:_D});function kD(e,t,s,n,i,r){const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;return n!=null&&(p=b(n,"offset","batchNorm")),I(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),I(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),I(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&I(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),p!=null&&I(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),Xs(o,a,l,p,c,r)}const Xh=S({batchNorm4d_:kD});function DD(e,t){let s=b(e,"broadcastTo","x");const n=s.shape;if(t.some(p=>!(p>0)||p%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<s.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${s.rank}.`);if(t.length>s.rank){const p=s.shape.slice();for(;p.length<t.length;)p.unshift(1);s=O(s,p)}const i=s.shape,r=Array.from(t);for(let p=t.length-1;p>=0;p--)if(i[p]===t[p])r[p]=1;else if(s.shape[p]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${t}].`);const o=r.map((p,u)=>p>1?u:-1).filter(p=>p>=0);if(o.length===0)return Fs(s);const a=p=>p.tile(s,r),l={x:s},c={shape:t,inputShape:i};return v.runKernelFunc(a,l,null,Bc,c)}const ta=S({broadcastTo_:DD});function FD(e){const t=b(e,"x","ceil"),s={x:t};return v.runKernelFunc(n=>n.ceil(t),s,null,wr)}const Jh=S({ceil_:FD});function MD(e,t,s){const n=b(e,"x","clipByValue");I(t<=s,()=>`Error in clip: min (${t}) must be less than or equal to max (${s}).`);const i={x:n},r={clipValueMin:t,clipValueMax:s};return v.runKernelFunc((o,a)=>{const l=o.clip(n,t,s);return a([n]),l},i,null,xr,r)}const xt=S({clipByValue_:MD});function UD(e){return be(e,0)}const Zh=S({concat1d_:UD});function $D(e,t){return be(e,t)}const Qh=S({concat2d_:$D});function WD(e,t){return be(e,t)}const ed=S({concat3d_:WD});function zD(e,t){return be(e,t)}const td=S({concat4d_:zD});function PD(e,t,s,n,i="NHWC",r=[1,1],o){const a=b(e,"x","conv2d"),l=b(t,"filter","conv2d");let c=a,p=!1;a.rank===3&&(p=!0,c=O(a,[1,a.shape[0],a.shape[1],a.shape[2]])),I(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),I(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&I(De(n),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);const u=i==="NHWC"?c.shape[3]:c.shape[1];I(u===l.shape[2],()=>`Error in conv2d: depth of input (${u}) must match input depth for filter ${l.shape[2]}.`),I(tt(s,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);const h=(g,y)=>{const w=qr(i),x=rs(c.shape,l.shape,s,r,n,o,!1,w),T=g.conv2d(c,l,x);return y([c,l]),T},d={x:c,filter:l},m={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o},f=v.runKernelFunc(h,d,null,Vc,m);return p?O(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const rt=S({conv2d_:PD});function BD(e,t,s,n,i="NWC",r=1,o){const a=b(e,"x","conv1d"),l=b(t,"filter","conv1d");let c=a,p=!1;a.rank===2&&(p=!0,c=O(a,[1,a.shape[0],a.shape[1]])),I(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),I(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&I(De(n),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`),I(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),I(tt(s,r),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${s} and dilation '${r}'`),I(i==="NWC",()=>`Error in conv1d: got dataFormat of ${i} but only NWC is currently supported.`);const u=O(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=O(c,[c.shape[0],1,c.shape[1],c.shape[2]]),d=[1,s],m=[1,r],f="NHWC",g=rt(h,u,d,n,f,m,o);return p?O(g,[g.shape[2],g.shape[3]]):O(g,[g.shape[0],g.shape[2],g.shape[3]])}const fl=S({conv1d_:BD});function jD(e,t,s,n,i,r="NHWC",o){I(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,l=t,c=!1;t.rank===3&&(c=!0,l=O(t,[1,t.shape[0],t.shape[1],t.shape[2]]),a=[1,e[0],e[1],e[2]]),I(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),I(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),I(s.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${s.rank}`);const p=r==="NHWC"?a[3]:a[1],u=r==="NHWC"?l.shape[3]:l.shape[1];I(p===s.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${s.shape[2]}.`),I(u===s.shape[3],()=>`Error in conv2dDerInput: depth of output (${u}) must match output depth for filter ${s.shape[3]}.`),o!=null&&I(De(i),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${i}.`);const h=(g,y)=>{const w=1,x=qr(r),T=rs(a,s.shape,n,w,i,o,!1,x),A=g.conv2dDerInput(l,s,T);return y([l,s]),A},d={dy:l,filter:s},m={strides:n,pad:i,dataFormat:r,dimRoundingMode:o,inputShape:a},f=v.runKernelFunc(h,d,null,Gc,m);return c?O(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const gl=S({conv2DBackpropInput_:jD});function VD(e,t,s,n,i,r){const o=b(e,"x","conv2dTranspose"),a=b(t,"filter","conv2dTranspose");return gl(s,o,a,n,i,"NHWC",r)}const yl=S({conv2dTranspose_:VD});function GD(e,t,s,n,i="NDHWC",r=[1,1,1]){const o=b(e,"x","conv3d"),a=b(t,"filter","conv3d");let l=o,c=!1;o.rank===4&&(c=!0,l=O(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),I(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),I(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),I(l.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${a.shape[3]}.`),I(tt(s,r),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),I(i==="NDHWC",()=>`Error in conv3d: got dataFormat of ${i} but only NDHWC is currently supported.`);const p=(m,f)=>{const g=Hr(l.shape,a.shape,s,r,n),y=m.conv3d(l,a,g);return f([l,a]),y},u={x:l,filter:a},h={strides:s,pad:n,dataFormat:i,dilations:r},d=v.runKernelFunc(p,u,null,qc,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const bl=S({conv3d_:GD});function qD(e,t,s,n,i){I(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let r=e,o=t,a=!1;t.rank===4&&(a=!0,o=O(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),r=[1,e[0],e[1],e[2],e[3]]);const l=r[4],c=o.shape[4];I(r.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${r.length}.`),I(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),I(s.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${s.rank}`),I(l===s.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${s.shape[3]}.`),I(c===s.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${s.shape[4]}.`);const p=m=>{const f=1,g=Hr(r,s.shape,n,f,i);return m.conv3dDerInput(o,s,g)},u={dy:o},h={pad:i},d=v.runKernelFunc(p,u,null,oy,h);return a?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const sd=S({conv3DBackpropInput_:qD});function HD(e,t,s,n,i){const r=b(e,"x","conv3dTranspose"),o=b(t,"filter","conv3dTranspose");return sd(s,r,o,n,i)}const mI=S({conv3dTranspose_:HD});function YD(e){const t=b(e,"x","cos"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.cos(t);return i([t]),r},s,null,Qn)}const Kr=S({cos_:YD});function KD(e){const t=b(e,"x","cosh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.cosh(t);return i([t]),r},s,null,Lr)}const wl=S({cosh_:KD});function XD(e,t=0,s=!1,n=!1){const i=b(e,"x","cumsum"),r=(l,c)=>{const p=dt([t],i.rank);let u=i;p!=null&&(u=se(i,p));const h=qt(1,i.rank)[0];let d=l.cumsum(u,h,s,n);if(c([i]),p!=null){const m=Jo(p);d=se(d,m)}return d},o={x:i},a={axis:t,exclusive:s,reverse:n};return v.runKernelFunc(r,o,null,Hc,a)}const xl=S({cumsum_:XD});function JD(e,t,s="NHWC"){const n=b(e,"x","depthToSpace"),i=s==="NHWC"?n.shape[1]:n.shape[2],r=s==="NHWC"?n.shape[2]:n.shape[3],o=s==="NHWC"?n.shape[3]:n.shape[1];I(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${n.shape}`),I(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${n.shape}`),I(o%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${n.shape}`);const a=p=>p.depthToSpace(n,t,s),l={x:n},c={blockSize:t,dataFormat:s};return v.runKernelFunc(a,l,null,ly,c)}const nd=S({depthToSpace_:JD});function ZD(e,t,s,n,i="NHWC",r=[1,1],o){const a=b(e,"x","depthwiseConv2d"),l=b(t,"filter","depthwiseConv2d");let c=a,p=!1;a.rank===3&&(p=!0,c=O(a,[1,a.shape[0],a.shape[1],a.shape[2]])),I(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),I(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),I(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&I(De(n),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);const u=(f,g)=>{r==null&&(r=[1,1]),I(tt(s,r),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);const y=rs(c.shape,l.shape,s,r,n,o,!0),w=f.depthwiseConv2D(c,l,y);return g([c,l]),w},h={x:c,filter:l},d={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o},m=v.runKernelFunc(u,h,null,Yc,d);return p?O(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const fn=S({depthwiseConv2d_:ZD});function QD(e){const t=b(e,"x","diag"),s=i=>{const r=O(t,[t.size]),o=i.diag(r),a=[...e.shape,...e.shape];return O(o,a)},n={x:t};return v.runKernelFunc(s,n,null,uy)}const fI=S({diag_:QD});function eF(e,t,s,n,i=[1,1],r="NHWC"){const o=b(e,"x","dilation2d"),a=b(t,"filter","dilation2d");I(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),I(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),I(r==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${r}`);let l=o,c=!1;o.rank===3&&(l=O(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);const p={x:l,filter:a},u={strides:s,pad:n,dilations:i},h=v.runKernel(Mo,p,u);return c?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const id=S({dilation2d_:eF});function tF(e,t){const s=e.length,n=[];for(let i=0;i<s;i++){const r=s-1-i,o=e[r]||1,a=t[t.length-1-i]||1;a>1&&o===1&&n.unshift(r)}return n}function Ke(e,t){const s=[];for(let n=0;n<t.length;n++){const i=e[e.length-n-1],r=t.length-n-1,o=t[r];(i==null||i===1&&o>1)&&s.unshift(r)}return s}function Ie(e,t){const s=[],n=Math.max(e.length,t.length);for(let i=0;i<n;i++){let r=e[e.length-i-1];r==null&&(r=1);let o=t[t.length-i-1];if(o==null&&(o=1),r===1)s.unshift(o);else if(o===1)s.unshift(r);else if(r!==o){const a=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(a)}else s.unshift(r)}return s}function sF(e,t){let s=b(e,"a","equal"),n=b(t,"b","equal");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.equal(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,dy)}const as=S({equal_:sF});function nF(e,t,s){const n=b(t,"a","where"),i=b(s,"b","where"),r=b(e,"condition","where","bool"),o=Ie(n.shape,i.shape),a=ta(n,o),l=ta(i,o);r.rank===1&&I(r.shape[0]===n.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),r.rank!==1&&Se(r.shape,l.shape,"Error in where: ");const c=(u,h)=>{const d=u.select(r,a,l);return h([r]),d},p={condition:r,t:a,e:l};return v.runKernelFunc(c,p,null,xp)}const mt=S({where_:nF});function iF(e){const t=b(e,"x","zerosLike"),s={x:t};return v.runKernelFunc(n=>n.zerosLike(t),s,null,Np)}const re=S({zerosLike_:iF});function rF(e,t){let s=b(e,"a","div"),n=b(t,"b","div");[s,n]=Ce(s,n);const i=Z(s,n),r=re(i),o=as(n,r);return mt(o,r,i)}const rd=S({divNoNan_:rF});function oF(e,t){const s=b(e,"t1","dot"),n=b(t,"t2","dot");I((s.rank===1||s.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${s.rank} and ${n.rank}.`);const i=s.rank===1?s.size:s.shape[1],r=n.rank===1?n.size:n.shape[0];if(I(i===r,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${r}.`),s.rank===1&&n.rank===1){const o=O(s,[1,-1]),a=O(n,[-1,1]),l=Te(o,a);return O(l,[])}else if(s.rank===1&&n.rank===2){const o=O(s,[1,-1]),a=O(n,[n.shape[0],n.shape[1]]),l=Te(o,a);return O(l,[l.size])}else if(s.rank===2&&n.rank===1){const o=O(n,[-1,1]),a=Te(s,o);return O(a,[a.size])}else{const o=O(n,[n.shape[0],n.shape[1]]),a=Te(s,o);return a}}const gI=S({dot_:oF});function aF(e){const t=b(e,"x","elu"),s=(i,r)=>{const o=i.elu(t);return r([o]),o},n={x:t};return v.runKernelFunc(s,n,null,Sr)}const gn=S({elu_:aF});function lF(e){let t=b(e,"x","erf");I(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=G(t,"float32"));const s={x:t};return v.runKernelFunc((n,i)=>{const r=n.erf(t);return i([t]),r},s,null,Ir)}const od=S({erf_:lF});function cF(e){const t=b(e,"x","exp"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.exp(t);return i([r]),r},s,null,vr)}const ut=S({exp_:cF});function pF(e,t=0){const s=null,n=b(e,"x","expandDims",s);I(t<=n.rank,()=>"Axis must be <= rank of the tensor");const i=n.shape.slice();return t<0&&(I(-(n.rank+1)<=t,()=>`Axis must be in the interval [${-(n.rank+1)}, ${n.rank}]`),t=n.rank+t+1),i.splice(t,0,1),O(n,i)}const Mt=S({expandDims_:pF});function uF(e){const t=b(e,"x","expm1"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.expm1(t);return i([t]),r},s,null,Tr)}const ad=S({expm1_:uF});function hF(e,t){const s=null,n=b(e,"x","tile",s);I(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);const i=(l,c)=>{const p=l.tile(n,t);return c([n]),p},r=[n],o={x:n},a={reps:t};return v.runKernelFunc(i,o,null,vp,a,r)}const $s=S({tile_:hF});function dF(e,t,s,n="float32"){t==null&&(t=e);const i=ge([e,t],n),r=e<=t?e:t;for(let a=0;a<r;++a)i.set(1,a,a);const o=O(i.toTensor(),[e,t]);if(s==null)return o;if(s.length===1)return $s(Mt(o,0),[s[0],1,1]);if(s.length===2)return $s(Mt(Mt(o,0),0),[s[0],s[1],1,1]);if(s.length===3)return $s(Mt(Mt(Mt(o,0),0),0),[s[0],s[1],s[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${s.length}D.`)}const sa=S({eye_:dF});function Wt(e,t,s){const n={shape:e,value:t,dtype:s};return v.runKernelFunc(i=>i.fill(e,t,s),{},null,my,n)}function mF(e){const t=b(e,"x","floor"),s={x:t};return v.runKernelFunc(n=>n.floor(t),s,null,Ar)}const ui=S({floor_:mF});const ld=30;function fF(e){return e<=ld?e:sl(e,Math.floor(Math.sqrt(e)))}const yI={};Ee(yI,{collectGatherOpShapeInfo:()=>Lb,computeOutShape:()=>yF,segOpComputeOptimalWindowSize:()=>gF});function gF(e,t){let s=!1,n;for(e<=ld?(n=e,s=!0):n=sl(e,Math.floor(Math.sqrt(e)));!s;)n>t||n===e?s=!0:n=sl(e,n+1);return n}function yF(e,t,s){const n=[],i=e.length;for(let r=0;r<i;r++)r!==t?n.push(e[r]):n.push(s);return n}function Lb(e,t,s){const n=e.shape[s],i=[];let r=1,o=1;for(let a=0;a<s;a++)i.push(e.shape[a]),r*=e.shape[a];for(let a=0;a<t.rank;a++)i.push(t.shape[a]);for(let a=s+1;a<e.rank;a++)i.push(e.shape[a]),o*=e.shape[a];return{batchSize:r,sliceSize:o,dimSize:n,outputShape:i}}function bF(e,t,s=0){const n=b(e,"x","gather"),i=b(t,"indices","gather","int32"),r={x:n,indices:i},o={axis:s},a=(l,c)=>{const p=Ne(s,n.shape)[0],u=Lb(n,i,p),h=l.gather(n,O(i,[i.size]),p);return c([n,i]),O(h,u.outputShape)};return v.runKernelFunc(a,r,null,Jc,o)}const hi=S({gather_:bF});function wF(e,t){let s=b(e,"a","greater"),n=b(t,"b","greater");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.greater(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,gy)}const Ut=S({greater_:wF});function xF(e,t){let s=b(e,"a","greaterEqual"),n=b(t,"b","greaterEqual");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=(o,a)=>{const l=o.greaterEqual(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Zc)}const ms=S({greaterEqual_:xF});function LF(e){const t=b(e,"input","imag"),s=i=>i.imag(t),n={input:t};return v.runKernelFunc(s,n,null,ep)}const yn=S({imag_:LF});function SF(e){const t=b(e,"x","isFinite"),s={x:t};return v.runKernelFunc(n=>n.isFinite(t),s,null,Nr)}const bI=S({isFinite_:SF});function IF(e){const t=b(e,"x","isInf"),s={x:t};return v.runKernelFunc(n=>n.isInf(t),s,null,Cr)}const wI=S({isInf_:IF});function vF(e){const t=b(e,"x","isNaN"),s={x:t};return v.runKernelFunc(n=>n.isNaN(t),s,null,Rr)}const xI=S({isNaN_:vF});function TF(e,t){let s=b(e,"a","maximum"),n=b(t,"b","maximum");[s,n]=Ce(s,n),s.dtype==="bool"&&(s=G(s,"int32"),n=G(n,"int32")),Ie(s.shape,n.shape);const i=(o,a)=>{const l=o.maximum(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,np)}const Ht=S({maximum_:TF});function j(e,t){if((Dt(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&Dt(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const s=[],n=[];return hs(e,s,n,t)}function AF(e,t=.2){const s=b(e,"x","leakyRelu");return Ht(R(j(t),s),s)}const Ll=S({leakyRelu_:AF});function NF(e,t){let s=b(e,"a","less"),n=b(t,"b","less");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.less(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,yy)}const Xr=S({less_:NF});function CF(e,t){let s=b(e,"a","lessEqual"),n=b(t,"b","lessEqual");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=(o,a)=>{const l=o.lessEqual(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,by)}const Ws=S({lessEqual_:CF});function cd(e,t,s){if(s<=0)throw new Error("The number of values should be positive.");const n={start:e,stop:t,num:s};return v.runKernelFunc(i=>i.linspace(e,t,s),{},null,wy,n)}function RF(e,t=5,s=1,n=1,i=.5){const r=b(e,"x","localResponseNormalization");I(r.rank===4||r.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${r.rank}.`),I(De(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=r,a=!1;r.rank===3&&(a=!0,o=O(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const l=(h,d)=>{const m=h.localResponseNormalization4D(o,t,s,n,i);return d([o,m]),m},c={x:o},p={depthRadius:t,bias:s,alpha:n,beta:i},u=v.runKernelFunc(l,c,null,sp,p);return a?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const pd=S({localResponseNormalization_:RF});function OF(e){const t=b(e,"x","log"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.log(t);return i([t]),r},s,null,Or)}const zt=S({log_:OF});function EF(e){const t=b(e,"x","log1p"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.log1p(t);return i([t]),r},s,null,Er)}const Sl=S({log1p_:EF});function _F(e){return I(ri(e),()=>"The f passed in grad(f) must be a function"),(t,s)=>{const n=b(t,"x","tf.grad",null),i=s!=null?b(s,"dy","tf.grad"):null;return v.tidy(()=>{const{value:r,grads:o}=v.gradients(()=>e(n),[n],i);return i!=null&&Se(r.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),ud(o),o[0]})}}function kF(e){return I(ri(e),()=>"The f passed in grads(f) must be a function"),(t,s)=>{I(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const n=Di(t,"args","tf.grads",null),i=s!=null?b(s,"dy","tf.grads"):null;return v.tidy(()=>{const{value:r,grads:o}=v.gradients(()=>e(...n),n,i);return i!=null&&Se(r.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ud(o),o})}}function DF(e){return I(ri(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,s)=>{I(t instanceof me,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),I(s==null||s instanceof me,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:n,value:i}=v.gradients(()=>e(t),[t],s);return ud(n),{grad:n[0],value:i}}}function FF(e){return I(ri(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,s)=>{I(Array.isArray(t)&&t.every(i=>i instanceof me),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),I(s==null||s instanceof me,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const n=v.gradients(()=>e(...t),t,s);return s!=null&&Se(n.value.shape,s.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ud(n.grads),n}}function hd(e,t){I(ri(e),()=>"The f passed in variableGrads(f) must be a function"),I(t==null||Array.isArray(t)&&t.every(c=>c instanceof ci),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const s=t!=null;if(!s){t=[];for(const c in v.registeredVariables)t.push(v.registeredVariables[c])}const n=s?t.filter(c=>!c.trainable):null,i=t.length;t=t.filter(c=>c.trainable),I(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const r=!0,{value:o,grads:a}=v.gradients(e,t,null,r);I(a.some(c=>c!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),I(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);const l={};return t.forEach((c,p)=>{a[p]!=null&&(l[c.name]=a[p])}),n!=null&&n.forEach(c=>l[c.name]=null),{value:o,grads:l}}function fs(e){return v.customGrad(e)}function ud(e){const t=e.filter(s=>s==null).length;if(t>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`)}function MF(e){const t=b(e,"x","neg"),s={x:t};return v.runKernelFunc(n=>n.neg(t),s,null,lp)}const ke=S({neg_:MF});function UF(e){const t=b(e,"x","softplus"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.softplus(t);return i([t]),r},s,null,zr)}const di=S({softplus_:UF});function $F(e){const t=b(e,"x","logSigmoid"),s=fs(n=>{const i=ke(di(ke(n))),r=o=>{const a=R(o,os(ke(n)));return a};return{value:i,gradFunc:r}});return s(t)}const LI=S({logSigmoid_:$F});function WF(e,t=null,s=!1){const n=b(e,"x","max"),i=(a,l)=>{const c=Ne(t,n.shape);let p=c;const u=dt(p,n.rank);let h=n;u!=null&&(h=se(n,u),p=qt(p.length,h.rank));const d=a.max(h,p);u!=null&&h.dispose();let m=d;if(s){const f=wt(m.shape,Ne(t,n.shape));m=O(m,f),d.dispose()}return l([n,m]),m},r={x:n},o={reductionIndices:t,keepDims:s};return v.runKernelFunc(i,r,null,Ri,o)}const Lt=S({max_:WF});function zF(e,t){let s=b(e,"a","sub"),n=b(t,"b","sub");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.subtract(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Br)}const X=S({sub_:zF});function PF(e,t=null,s=!1){let n=b(e,"x","sum");n.dtype==="bool"&&(n=G(n,"int32"));const i=(a,l)=>{l([n]);const c=Ne(t,n.shape),p=dt(c,n.rank);let u=c,h=n;p!=null&&(h=se(n,p),u=qt(u.length,n.rank));let d=a.sum(h,u);if(s){const m=wt(d.shape,c);d=O(d,m)}return d},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,Lp,o)}const te=S({sum_:PF});function BF(e,t=-1){const s=b(e,"logits","logSoftmax");if(t===-1&&(t=s.rank-1),t!==s.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${s.rank} and axis was ${t}`);const n=(o,a)=>{const l=!0,c=Lt(e,t,!0),p=X(e,c),u=X(G(p,"float32"),zt(te(ut(p),t,l)));return a([u]),u},i={logits:s},r={axis:t};return v.runKernelFunc(n,i,null,tp,r)}const Il=S({logSoftmax_:BF});function jF(e,t=null,s=!1){const n=b(e,"x","logSumExp"),i=Ne(t,n.shape),r=Lt(n,i,!0),o=X(n,r),a=ut(o),l=te(a,i),c=zt(l),p=$(O(r,c.shape),c);if(s){const u=wt(p.shape,i);return O(p,u)}return p}const dd=S({logSumExp_:jF});function VF(e,t){const s=b(e,"a","logicalAnd","bool"),n=b(t,"b","logicalAnd","bool");Ie(s.shape,n.shape);const i={a:s,b:n};return v.runKernelFunc(r=>r.logicalAnd(s,n),i,null,xy)}const Yt=S({logicalAnd_:VF});function GF(e){const t=b(e,"x","logicalNot","bool"),s={x:t};return v.runKernelFunc(n=>n.logicalNot(t),s,null,Ya)}const Jr=S({logicalNot_:GF});function qF(e,t){const s=b(e,"a","logicalOr","bool"),n=b(t,"b","logicalOr","bool");Ie(s.shape,n.shape);const i={a:s,b:n};return v.runKernelFunc(r=>r.logicalOr(s,n),i,null,Ly)}const vl=S({logicalOr_:qF});function HF(e,t){const s=b(e,"a","logicalXor","bool"),n=b(t,"b","logicalXor","bool");return Ie(s.shape,n.shape),Yt(vl(e,t),Jr(Yt(e,t)))}const SI=S({logicalXor_:HF});function YF(e,t,s,n,i){const r=b(e,"x","maxPool"),o=1;let a=r,l=!1;r.rank===3&&(l=!0,a=O(r,[1,r.shape[0],r.shape[1],r.shape[2]])),I(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),I(tt(s,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&I(De(n),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const c=(d,m)=>{const f=Wn(a.shape,t,s,1,n,i);let g;return f.filterWidth===1&&f.filterHeight===1&&Nt(f.inShape,f.outShape)?g=a.clone():g=d.maxPool(a,f),m([a,g]),g},p={x:a},u={filterSize:t,strides:s,pad:n,dimRoundingMode:i},h=v.runKernelFunc(c,p,null,Oi,u);return l?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const ft=S({maxPool_:YF});function KF(e,t=[1,1,1],s,n,i,r="NDHWC",o){o==null?o=[1,1,1]:It("dilations is deprecated, this field will be gone in v3.0.0.");const a=b(e,"x","maxPool3d");let l=a,c=!1;a.rank===4&&(c=!0,l=O(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),I(l.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${l.rank}.`),I(r==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),I(tt(s,o),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&I(De(n),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const p=(m,f)=>{o==null&&(o=[1,1,1]);const g=Fi(l.shape,t,s,o,n,i,r),y=m.maxPool3d(l,g);return f([l,y]),y},u={x:l},h={filterSize:t,strides:s,pad:n,dimRoundingMode:i,dataFormat:r,dilations:o},d=v.runKernelFunc(p,u,null,ip,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const Tl=S({maxPool3d_:KF});function XF(e,t,s,n,i=!1){const r=b(e,"x","maxPoolWithArgmax"),o={x:r},a={filterSize:t,strides:s,pad:n,includeBatchInIndex:i},l=v.runKernel(Wo,o,a);return{result:l[0],indexes:l[1]}}const md=S({maxPoolWithArgmax_:XF});function ye(e,t="float32"){if(t==="complex64"){const n=ye(e,"float32"),i=ye(e,"float32");return Gt(n,i)}const s=ai(We(e),t);return v.makeTensor(s,e,t)}function Kt(e,t="float32"){if(t==="complex64"){const n=Kt(e,"float32"),i=ye(e,"float32");return Gt(n,i)}const s=Ep(We(e),t);return v.makeTensor(s,e,t)}function JF(e,t=null,s=!1){const n=b(e,"x","mean"),i=Ne(t,n.shape),r=gb(n.shape,i),o=r[1],a=We(o),l=fs(c=>{const p=j(a),u=p.dtype===c.dtype?c:G(c,p.dtype),h=Z(u,p),d=te(h,t,s),m=f=>{const g=c.shape.slice();i.forEach(x=>{g[x]=1});const y=O(f,g),w=Z(R(y,Kt(c.shape,"float32")),a);return w};return{value:d,gradFunc:m}});return l(n)}const Xe=S({mean_:JF});function ZF(e,t=null,s=!1){const n=b(e,"x","min"),i=(a,l)=>{const c=Ne(t,n.shape);let p=c;const u=dt(p,n.rank);let h=n;u!=null&&(h=se(n,u),p=qt(p.length,n.rank));const d=a.min(h,p);u!=null&&h.dispose();let m=d;if(s){const f=wt(m.shape,c);m=O(d,f),d.dispose()}return l([n,m]),m},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,rp,o)}const Ui=S({min_:ZF});function QF(e,t){let s=b(e,"a","minimum"),n=b(t,"b","minimum");[s,n]=Ce(s,n),s.dtype==="bool"&&(s=G(s,"int32"),n=G(n,"int32")),Ie(s.shape,n.shape);const i=(o,a)=>{const l=o.minimum(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,op)}const bn=S({minimum_:QF});function eM(e,t){let s=b(e,"a","mod"),n=b(t,"b","mod");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.mod(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,ap)}const Al=S({mod_:eM});function tM(e){const t=b(e,"x","square"),s={},n=[t],i=[];return v.runKernelFunc((r,o)=>(o([t]),r.square(t)),{x:t},null,"Square",s,n,i)}const xe=S({square_:tM});function sM(e,t=null,s=!1){e=b(e,"x","moments");const n=Ne(t,e.shape),i=Xe(e,n,s);let r=i.shape;s||(r=wt(i.shape,n));const o=xe(X(G(e,"float32"),O(i,r))),a=Xe(o,n,s);return{mean:i,variance:a}}const na=S({moments_:sM});function nM(e,t,s,n){const i=b(t,"data","multiRNNCell"),r=Di(s,"c","multiRNNCell"),o=Di(n,"h","multiRNNCell");let a=i;const l=[];for(let u=0;u<e.length;u++){const h=e[u](a,r[u],o[u]);l.push(h[0]),l.push(h[1]),a=h[1]}const c=[],p=[];for(let u=0;u<l.length;u+=2)c.push(l[u]),p.push(l[u+1]);return[c,p]}const II=S({multiRNNCell_:nM});function iM(e,t,s,n=!1){const i=b(e,"logits","multinomial"),r=i.size,o=i.rank;if(r<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${r}.`);if(o>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);s=s||Math.random();const a=o===1?O(i,[1,-1]):i,l=v.runKernelFunc(c=>c.multinomial(a,n,t,s),{logits2D:a});return o===1?O(l,[l.size]):l}const fd=S({multinomial_:iM});function rM(e,t){let s=b(e,"a","notEqual"),n=b(t,"b","notEqual");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.notEqual(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,Ka)}const Js=S({notEqual_:rM});function oM(e){const t=b(e,"input","real"),s=i=>i.real(t),n={input:t};return v.runKernelFunc(s,n,null,mp)}const Zs=S({real_:oM});function aM(e){const t=b(e,"x","onesLike"),s=(i,r)=>{if(t.dtype==="complex64"){const o=Ot(Zs(t)),a=re(yn(t));return Gt(o,a)}return i.onesLike(t)},n={x:t};return v.runKernelFunc(s,n,null,pp)}const Ot=S({onesLike_:aM});function lM(e,t){const s=b(e,"v1","outerProduct"),n=b(t,"v2","outerProduct");I(s.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${s.rank} and ${n.rank}.`);const i=O(s,[-1,1]),r=O(n,[1,-1]);return Te(i,r)}const vI=S({outerProduct_:lM});function cM(e,t,s=0){const n=b(e,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const i=(a,l)=>(l([n]),a.pad(n,t,s)),r={paddings:t,constantValue:s},o={x:n};return v.runKernelFunc(i,o,null,Bo,r)}const Pt=S({pad_:cM});function pM(e,t,s=0){return I(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Pt(e,[t],s)}const TI=S({pad1d_:pM});function uM(e,t,s=0){return I(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pt(e,t,s)}const AI=S({pad2d_:uM});function hM(e,t,s=0){return I(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pt(e,t,s)}const NI=S({pad3d_:hM});function dM(e,t,s=0){return I(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pt(e,t,s)}const CI=S({pad4d_:dM});function mM(e,t,s){const n=b(e,"x","spaceToBatchND");I(n.rank>=1+t.length,()=>`input rank ${n.rank} should be > than [blockShape] ${t.length}`),I(s.length===t.length,()=>`paddings.shape[0] ${s.length} must be equal to [blockShape] ${t.length}`),I(n.shape.reduce((a,l,c)=>c>0&&c<=t.length?a&&(l+s[c-1][0]+s[c-1][1])%t[c-1]===0:a,!0),()=>`input spatial dimensions ${n.shape.slice(1)} with paddings ${s.toString()} must be divisible by blockShapes ${t.toString()}`);const i=a=>a.spaceToBatchND(n,t,s),r={x:n},o={blockShape:t,paddings:s};return v.runKernelFunc(i,r,null,Vo,o)}const Zr=S({spaceToBatchND_:mM});function yM(e,t,s,n,i,r){i==null&&(i=[1,1]),r==null&&(r=1),n===0&&(n="valid");const o=b(e,"x","maxPool");let a=o,l=!1;o.rank===3&&(l=!0,a=O(o,[1,o.shape[0],o.shape[1],o.shape[2]])),I(tt(r,i),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`);const c=Wn(a.shape,t,r,i,n),p=[c.dilationHeight,c.dilationWidth];let u;n==="same"?u=gM([c.filterHeight,c.filterWidth],p):u=[[0,0],[0,0]];const h=p[0]===1&&p[1]===1,[d,m]=fM([c.inHeight,c.inWidth],p,u),f=h?n:"valid",g=h?a:Zr(a,p,d),y=s==="avg"?()=>ds(g,t,r,f):()=>ft(g,t,r,f),w=y(),x=h?w:Yr(w,p,m);return l?O(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function fM(e,t,s){const n=s.map(p=>p[0]),i=s.map(p=>p[1]),r=e.concat(n,i),o=t.map((p,u)=>(p-r[u]%p)%p),a=i.map((p,u)=>p+o[u]),l=t.map((p,u)=>[n[u],a[u]]),c=t.map((p,u)=>[0,o[u]]);return[l,c]}function gM(e,t){const s=e.map((o,a)=>o+(o-1)*(t[a]-1)),n=s.map(o=>o-1),i=n.map(o=>Math.floor(o/2)),r=n.map((o,a)=>o-i[a]);return n.map((o,a)=>[i[a],r[a]])}const RI=S({pool_:yM});function bM(e,t){let s=b(e,"base","pow"),n=b(t,"exp","pow");[s,n]=Ce(s,n);const i={a:s,b:n},r=(o,a)=>{const l=o.pow(s,n);return a([s,n,l]),l};return v.runKernelFunc(r,i,null,hp)}const es=S({pow_:bM});function wM(e,t){const s=b(e,"x","prelu"),n=b(t,"alpha","prelu"),i=(o,a)=>{const l=o.prelu(s,n);return a([s,n]),l},r={x:s,alpha:n};return v.runKernelFunc(i,r,null,dp)}const Qr=S({prelu_:wM});function xM(e,t=null,s=!1){let n=b(e,"x","prod");const i=a=>{n.dtype==="bool"&&(n=G(n,"int32"));const l=Ne(t,n.shape),c=dt(l,n.rank);let p=l,u=n;c!=null&&(u=se(n,c),p=qt(p.length,n.rank));let h=a.prod(u,p);if(s){const d=wt(h.shape,l);h=O(h,d)}return h},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,vy,o)}const Nl=S({prod_:xM});function LM(e,t,s){const n=We(e);let i=null;if(s==null||s==="float32")i=new Float32Array(n);else if(s==="int32")i=new Int32Array(n);else if(s==="bool")i=new Uint8Array(n);else throw new Error(`Unknown data type ${s}`);for(let r=0;r<n;r++)i[r]=t();return v.makeTensor(i,e,s)}const OI=S({rand_:LM});const gd=vc(Tc());class Gp{constructor(e,t,s,n,i){this.mean=e,this.stdDev=t,this.dtype=s,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const r=i||Math.random();this.random=gd.alea(r.toString())}nextValue(){if(!isNaN(this.nextVal)){const n=this.nextVal;return this.nextVal=NaN,n}let e,t,s=!1;for(;!s;){let n,i,r;do n=2*this.random()-1,i=2*this.random()-1,r=n*n+i*i;while(r>=1||r===0);const o=Math.sqrt(-2*Math.log(r)/r);e=this.mean+this.stdDev*n*o,t=this.mean+this.stdDev*i*o,(!this.truncated||this.isValidTruncated(e))&&(s=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class EI{constructor(e,t,s,n){this.alpha=e,this.beta=1/t,this.dtype=s;const i=n||Math.random();this.randu=gd.alea(i.toString()),this.randn=new Gp(0,1,s,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,s,n,i,r;for(;;){do n=this.randn.nextValue(),r=1+this.c*n;while(r<=0);if(r*=r*r,e=n*n,t=1-.331*e*e,s=.5*e+this.d*(1-r+Math.log(r)),i=this.randu(),i<t||Math.log(i)<s)break}return r=1/this.beta*this.d*r,this.alpha<1&&(r*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(r)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}}class _I{constructor(e=0,t=1,s,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=s,n==null&&(n=Math.random()),typeof n=="number"&&(n=n.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=gd.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function SM(e,t,s=1,n="float32",i){if(s==null&&(s=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);const r=new EI(t,s,n,i),o=ge(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const kI=S({randomGamma_:SM});function IM(e,t=0,s=1,n,i){if(n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);const r=new Gp(t,s,n,!1,i),o=ge(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const qp=S({randomNormal_:IM});function vM(e,t=0,s=1,n="float32",i){const r=ge(e,n),o=new _I(t,s,null,i);for(let a=0;a<r.values.length;a++)r.values[a]=o.nextValue();return r.toTensor()}const wn=S({randomUniform_:vM});function Oe(e,t){Ys(e);const s=Qt(e,t);if(s.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const n=null;return hs(e,n,s,t)}function $i(e,t,s=1,n="float32"){if(s===0)throw new Error("Cannot have a step of zero");const i=()=>{const o=e===t,a=e<t&&s<0,l=t<e&&s>1;if(o||a||l)return ye([0],n);const c=Math.abs(Math.ceil((t-e)/s)),p=ai(c,n);t<e&&s===1&&(s=-1),p[0]=e;for(let u=1;u<p.length;u++)p[u]=p[u-1]+s;return Oe(p,n)},r={start:e,stop:t,step:s,dtype:n};return v.runKernelFunc(i,{},null,Ty,r)}function TM(e){const t=b(e,"x","reciprocal"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.reciprocal(t);return i([t]),r},s,null,kr)}const yd=S({reciprocal_:TM});function AM(e){const t=b(e,"x","relu"),s=(i,r)=>(r([t]),t.dtype==="bool"?G(t,"int32"):i.relu(t)),n={x:t};return v.runKernelFunc(s,n,null,fp)}const Fe=S({relu_:AM});function NM(e){const t=b(e,"x","relu6"),s=(i,r)=>(r([t]),t.dtype==="bool"?G(t,"int32"):i.relu6(t)),n={x:t};return v.runKernelFunc(s,n,null,bp)}const bd=S({relu6_:NM});function CM(e,t){const s=b(e,"x","reverse"),n=o=>{const a=Ne(t,s.shape);if(s.rank===0)return Fs(s);const l=o.reverse(s,a);return O(l,s.shape)},i={x:s},r={dims:t};return v.runKernelFunc(n,i,null,wp,r)}const Et=S({reverse_:CM});function RM(e){const t=b(e,"x","reverse");return I(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Et(t,0)}const DI=S({reverse1d_:RM});function OM(e,t){const s=b(e,"x","reverse");return I(s.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${s.rank}.`),Et(s,t)}const FI=S({reverse2d_:OM});function EM(e,t){const s=b(e,"x","reverse");return I(s.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${s.rank}.`),Et(s,t)}const MI=S({reverse3d_:EM});function _M(e,t){const s=b(e,"x","reverse");return I(s.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${s.rank}.`),Et(s,t)}const UI=S({reverse4d_:_M});function kM(e){const t=b(e,"x","round"),s={x:t};return v.runKernelFunc(n=>n.round(t),s,null,Dr)}const wd=S({round_:kM});function DM(e){const t=b(e,"x","rsqrt"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.rsqrt(t);return i([t]),r},s,null,Fr)}const Cl=S({rsqrt_:DM});function FM(e){const t=b(e,"x","selu"),s=(i,r)=>{const o=i.selu(t);return r([t]),o},n={x:t};return v.runKernelFunc(s,n,null,Mr)}const Rl=S({selu_:FM});function MM(e,t,s,n,i,r=[1,1],o="NHWC"){const a=b(e,"x","separableConv2d"),l=b(t,"depthwiseFilter","separableConv2d"),c=b(s,"pointwiseFilter","separableConv2d");let p=a,u=!1;if(a.rank===3&&(u=!0,p=O(a,[1,a.shape[0],a.shape[1],a.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");I(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.rank}.`),I(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),I(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),I(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),I(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);const h=l.shape[2],d=l.shape[3];I(c.shape[2]===h*d,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*d}, but got ${c.shape[2]}.`);const m=fn(p,l,n,i,o,r),f=1,g=rt(m,c,f,"valid",o);return u?O(g,[g.shape[1],g.shape[2],g.shape[3]]):g}const eo=S({separableConv2d_:MM});async function UM(e,t){const s=b(e,"x","setdiff1d"),n=b(t,"y","setdiff1d");I(s.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${s.dtype}) and y (${n.dtype}).`),I(s.rank===1,()=>`x should be 1D tensor, but got x (${s.shape}).`),I(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);const i=await s.data(),r=await n.data(),o=new Set(r);let a=0;for(let p=0;p<i.length;p++)o.has(i[p])||a++;const l=new dn([a],s.dtype),c=new dn([a],"int32");for(let p=0,u=0;p<i.length;p++)o.has(i[p])||(l.values[u]=i[p],c.values[u]=p,u++);return[l.toTensor(),c.toTensor()]}const xd=UM;function $M(e){const t=b(e,"x","sign"),s={x:t};return v.runKernelFunc(n=>n.sign(t),s,null,$r)}const Ld=S({sign_:$M});function WM(e){const t=b(e,"x","sin"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sin(t);return i([t]),r},s,null,ti)}const Ol=S({sin_:WM});function zM(e){const t=b(e,"x","sinh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sinh(t);return i([t]),r},s,null,Ur)}const El=S({sinh_:zM});function PM(e,t,s){const n=b(e,"x","slice1d");return I(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),he(n,[t],[s])}const _l=S({slice1d_:PM});function BM(e,t,s){const n=b(e,"x","slice2d");return I(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const Hp=S({slice2d_:BM});function jM(e,t,s){const n=b(e,"x","slice3d");return I(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const to=S({slice3d_:jM});function VM(e,t,s){const n=b(e,"x","slice4d");return I(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const ia=S({slice4d_:VM});function GM(e,t=-1){const s=b(e,"logits","softmax","float32");if(t===-1&&(t=s.rank-1),t!==s.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${s.rank} and dim was ${t}`);const n={logits:s},i={dim:t};return v.runKernelFunc((r,o)=>{const a=r.softmax(s,t);return o([a]),a},n,null,Ip,i)}const ts=S({softmax_:GM});function qM(e){I(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return v.runKernelFunc(s=>{const n=e.shape[e.shape.length-1],i=e.size/n,r=e.as2D(i,n),o=s.fft(r);return o.reshape(e.shape)},t,null,Kc)}const so=S({fft_:qM});function HM(e){I(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return v.runKernelFunc(s=>{const n=e.shape[e.shape.length-1],i=e.size/n,r=O(e,[i,n]),o=s.ifft(r);return O(o,e.shape)},t,null,Qc)}const Wi=S({ifft_:HM});function YM(e){const t=e.shape[e.shape.length-1],s=e.size/t;let n;if(t<=2){const i=O(e,[s,t]);n=Wi(i)}else{const i=[s,2*(t-1)],r=O(Zs(e),[s,t]),o=O(yn(e),[s,t]),a=Et(he(r,[0,1],[s,t-2]),1),l=R(Et(he(o,[0,1],[s,t-2]),1),j(-1)),c=be([r,a],1),p=be([o,l],1),u=O(Gt(c,p),[i[0],i[1]]);n=Wi(u)}if(n=Zs(n),e.rank===3&&e.shape[0]!==0){const i=n,r=e.shape[0];n=O(n,[r,n.shape[0]/r,n.shape[1]]),i.dispose()}return n}const kl=S({irfft_:YM});function Sb(e,t,s=0){let n=[];if(typeof t=="number")I(e.shape[s]%t===0,()=>"Number of splits must evenly divide the axis."),n=new Array(t).fill(e.shape[s]/t);else{const i=t.reduce((o,a)=>(a===-1&&(o+=1),o),0);I(i<=1,()=>"There should be only one negative value in split array.");const r=t.indexOf(-1);if(r!==-1){const o=t.reduce((a,l)=>l>0?a+l:a);t[r]=e.shape[s]-o}I(e.shape[s]===t.reduce((o,a)=>o+a),()=>"The sum of sizes must match the size of the axis dimension."),n=t}return n}function KM(e,t,s=0){const n=b(e,"x","split"),i=(a,l)=>{const c=Ne(s,n.shape)[0],p=Sb(n,t,c);return a.split(n,p,c)},r={x:n},o={numOrSizeSplits:t,axis:s};return v.runKernelFunc(i,r,null,Sp,o)}const Bt=S({split_:KM});function XM(e,t){I(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let s=e.shape[e.shape.length-1];const n=e.size/s;let i;if(t!=null&&t<s){const m=e.shape.map(g=>0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,i=he(e,m,f),s=t}else if(t!=null&&t>s){const m=e.shape.map(f=>f);m[e.shape.length-1]=t-s,i=be([e,ye(m)],e.shape.length-1),s=t}else i=e;const r=re(i),o=O(Gt(i,r),[n,s]),a=so(o),l=Math.floor(s/2)+1,c=Zs(a),p=yn(a),u=Bt(c,[l,s-l],c.shape.length-1),h=Bt(p,[l,s-l],p.shape.length-1),d=i.shape.slice();return d[i.shape.length-1]=l,O(Gt(u[0],h[0]),d)}const no=S({rfft_:XM});function JM(e){const t=b(e,"x","sqrt"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sqrt(t);return i([t]),r},s,null,Pr)}const Je=S({sqrt_:JM});function ZM(e,t){let s=b(e,"a","squaredDifference"),n=b(t,"b","squaredDifference");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=(a,l)=>{const c=a.squaredDifference(s,n);return l([s,n]),c},r={a:s,b:n},o={};return v.runKernelFunc(i,r,null,si,o)}const io=S({squaredDifference_:ZM});function QM(e,t){const s=b(e,"x","squeeze");return O(s,Fy(s.shape,t).newShape)}const Qs=S({squeeze_:QM});function eU(e,t=0){const s=Di(e,"tensors","stack");if(I(s.length>=1,()=>"Pass at least one tensor to tf.stack"),s.length===1)return Mt(s[0],t);const n=s[0].rank,i=s[0].shape,r=s[0].dtype;I(t<=n,()=>"Axis must be <= rank of the tensor"),s.forEach(a=>{Se(i,a.shape,"All tensors passed to stack must have matching shapes"),I(r===a.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=s.map(a=>Mt(a,t));return be(o,t)}const Ge=S({stack_:eU});function tU(e,t=0){const s=b(e,"x","step"),n={x:s},i={alpha:t};return v.runKernelFunc(r=>r.step(s,t),n,null,Vr,i)}const mi=S({step_:tU});function sU(e,t,s,n,i=0,r=0,o=0,a=0,l=0){let c=b(e,"x","stridedSlice");const p=d=>{n==null&&(n=new Array(t.length));const m=Bp(o);if(m.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(o!==0&&a!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(o!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const f=c.rank-t.length,g=Bp(a),y=c.shape.slice();g.forEach(M=>{t[M]=0,s[M]=1,y.splice(M,0,1)}),c=O(c,y);const{begin:w,end:x,strides:T}=lb(c.shape,m,f,t,s,n,i,r,o);t=w,s=x,n=T;const A=Bp(l);A.forEach(M=>{s[M]=t[M]+1,n[M]=1});const _=ab(t,s,n),E=_.filter((M,P)=>A.indexOf(P)===-1),F=n.every(M=>M===1);if(F)return O(he(c,t,_),E);const D=d.stridedSlice(c,t,s,n);return O(D,E)},u={x:c},h={begin:t,end:s,strides:n,beginMask:i,endMask:r,ellipsisMask:o,newAxisMask:a,shrinkAxisMask:l};return v.runKernelFunc(p,u,null,Oy,h)}const Sd=S({stridedSlice_:sU});function nU(e){const t=b(e,"x","tan"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.tan(t);return i([t]),r},s,null,ni)}const Id=S({tan_:nU});function ls(e,t,s){if(Ys(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const n=Qt(e,s);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return hs(e,t,n,s)}function ss(e,t,s){if(Ys(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const n=Qt(e,s);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return hs(e,t,n,s)}function $I(e,t,s){if(Ys(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const n=Qt(e,s);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return hs(e,t,n,s)}function WI(e,t,s){if(Ys(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const n=Qt(e,s);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||n,hs(e,t,n,s)}function iU(e,t=1,s=!0){const n=b(e,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const i=n.shape[n.shape.length-1];if(t>i)throw new Error(`'k' passed to topk() must be <= the last dimension (${i}) but got ${t}`);const r={x:n},o={k:t,sorted:s},[a,l]=v.runKernelFunc(c=>c.topk(n,t,s),r,null,Ey,o);return{values:a,indices:l}}const vd=S({topk_:iU});function rU(e,t=0,s=1,n,i){if(n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");const r=new Gp(t,s,n,!0,i),o=ge(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const ro=S({truncatedNormal_:rU});function oU(e,t=0){const s=b(e,"x","unique",null);I(s.rank>0,()=>"The input tensor must be at least 1D");const n={x:s},i={axis:t},[r,o]=v.runKernel(qo,n,i);return{values:r,indices:o}}const Yp=S({unique_:oU});function aU(e,t,s){const n=b(e,"x","unsortedSegmentSum"),i=b(t,"segmentIds","unsortedSegmentSum","int32");I(De(s),()=>"numSegments must be of dtype int");const r={x:n,segmentIds:i},o={numSegments:s},a=(l,c)=>{const p=l.unsortedSegmentSum(n,i,s);return c([i]),p};return v.runKernelFunc(a,r,null,Ap,o)}const Td=S({unsortedSegmentSum_:aU});function lU(e,t=0){const s=b(e,"x","unstack");I(t>=-s.shape.length&&t<s.shape.length,()=>`Axis = ${t} is not in [-${s.shape.length}, ${s.shape.length})`),t<0&&(t+=s.shape.length);const n={value:s},i={axis:t},r=o=>o.unstack(s,t);return v.runKernelFunc(r,n,null,Tp,i)}const qe=S({unstack_:lU});function Ad(e,t=!0,s,n){return v.makeVariable(e,t,s,n)}function Nd(e,t){const s=[];for(let r=0;r<t.length;r++)t[r]&&s.push(r);const n=ge(e,"int32"),i=ge([s.length,e.length],"int32");for(let r=0;r<s.length;r++){const o=n.indexToLoc(s[r]),a=r*e.length;i.values.set(o,a)}return i.toTensor()}async function cU(e){const t=b(e,"condition","whereAsync","bool"),s=await t.data(),n=Nd(t.shape,s);return e!==t&&t.dispose(),n}const Dl=cU;async function pU(e,t,s){const n=b(e,"tensor","boolMask"),i=b(t,"mask","boolMask","bool"),r=s??0,o=i.rank,a=n.shape;I(o>0,()=>"mask cannot be scalar"),Se(a.slice(r,r+o),i.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=r;f<r+o;f++)l*=a[f];const c=a.slice(0,r).concat([l],a.slice(r+o)),p=O(n,c),u=O(i,[-1]),h=await Dl(u),d=Qs(h,[1]),m=hi(p,d,r);return e!==n&&n.dispose(),t!==i&&i.dispose(),d.dispose(),p.dispose(),u.dispose(),h.dispose(),m}const uU=pU;function hU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","notEqualStrict"),n=b(t,"b","notEqualStrict");return Se(s.shape,n.shape,"Error in notEqualStrict: "),Js(s,n)}function dU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","lessStrict"),n=b(t,"b","lessStrict");return Se(s.shape,n.shape,"Error in lessStrict: "),Xr(s,n)}function mU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","equalStrict"),n=b(t,"b","equalStrict");return Se(s.shape,n.shape,"Error in equalStrict: "),as(s,n)}function fU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","lessEqualStrict"),n=b(t,"b","lessEqualStrict");return Se(s.shape,n.shape,"Error in lessEqualStrict: "),Ws(s,n)}function gU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","greaterStrict"),n=b(t,"b","greaterStrict");return Se(s.shape,n.shape,"Error in greaterStrict: "),Ut(s,n)}function yU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","greaterEqualStrict"),n=b(t,"b","greaterEqualStrict");return Se(s.shape,n.shape,"Error in greaterEqualStrict: "),ms(s,n)}const bU=S({equalStrict_:mU}),wU=S({greaterEqualStrict_:yU}),xU=S({greaterStrict_:gU}),LU=S({lessEqualStrict_:fU}),SU=S({lessStrict_:dU}),IU=S({notEqualStrict_:hU});function vU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","addStrict"),n=b(t,"b","addStrict");return Se(s.shape,n.shape,"Error in addStrict: "),$(s,n)}function TU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","subStrict"),n=b(t,"b","subStrict");return Se(s.shape,n.shape,"Error in subStrict: "),X(s,n)}function AU(e,t){return It("strict variants of ops have been deprecated and will be removed in future"),Se(e.shape,t.shape,"Error in powStrict: "),es(e,t)}function NU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","mul"),n=b(t,"b","mul");return Se(s.shape,n.shape,"Error in multiplyStrict: "),R(s,n)}function CU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","div"),n=b(t,"b","div");return Se(s.shape,n.shape,"Error in divideStrict: "),Z(s,n)}function RU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","modStrict"),n=b(t,"b","modStrict");return Se(s.shape,n.shape,"Error in modStrict: "),Al(s,n)}function OU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","minimumStrict"),n=b(t,"b","minimumStrict");return Se(s.shape,n.shape,"Error in minimumStrict: "),bn(s,n)}function EU(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","maximumStrict"),n=b(t,"b","maximumStrict");return Se(s.shape,n.shape,"Error in maximumStrict: "),Ht(s,n)}function _U(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","squaredDifferenceStrict"),n=b(t,"b","squaredDifferenceStrict");return Se(s.shape,n.shape,"Error in squaredDifferenceStrict: "),io(s,n)}const kU=S({addStrict_:vU}),DU=S({divStrict_:CU}),FU=S({maximumStrict_:EU}),MU=S({minimumStrict_:OU}),UU=S({modStrict_:RU}),$U=S({mulStrict_:NU}),WU=S({powStrict_:AU}),zU=S({squaredDifferenceStrict_:_U}),PU=S({subStrict_:TU});function BU(e,t="euclidean",s=null,n=!1){e=b(e,"x","norm");const i=zI(e,t,s);let r=i.shape;if(n){const o=Ne(s,e.shape);r=wt(i.shape,o)}return O(i,r)}function zI(e,t,s=null){if(e.rank===0)return et(e);if(e.rank!==1&&s===null)return zI(O(e,[-1]),t,s);if(e.rank===1||typeof s=="number"||Array.isArray(s)&&s.length===1){if(t===1)return te(et(e),s);if(t===Infinity)return Lt(et(e),s);if(t===-Infinity)return Ui(et(e),s);if(t==="euclidean"||t===2)return Je(te(es(et(e),j(2,"int32")),s));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(s)&&s.length===2){if(t===1)return Lt(te(et(e),s[0]),s[1]-1);if(t===Infinity)return Lt(te(et(e),s[1]),s[0]);if(t===-Infinity)return Ui(te(et(e),s[1]),s[0]);if(t==="fro"||t==="euclidean")return Je(te(xe(e),s));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${s}`)}const Kp=S({norm_:BU});function jU(e,t,s,n,i=!0){const r=b(e,"v","movingAverage"),o=b(t,"x","movingAverage"),a=b(s,"decay","movingAverage");Hy(r,o),I(Nt(r.shape,o.shape),()=>"Shape mismatch in v and x");const l=j(1),c=X(l,a);let p=R(X(o,r),c);if(i){I(n!=null,()=>"When using zeroDebias: true, step is required.");const u=b(n,"step","movingAverage");p=Z(p,X(l,es(a,u)))}return $(r,p)}const VU=S({movingAverage_:jU});function GU(e,t,s){const n=b(e,"indices","scatterND","int32"),i=b(t,"updates","scatterND");Mh(i,n,s);const r=l=>l.scatterND(n,i,s),o={indices:n,updates:i},a={shape:s};return v.runKernelFunc(r,o,null,Cy,a)}const Ib=S({scatterND_:GU});function PI(e,t,s,n){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const i=e.rank>0?e.shape[0]:1,r=e.rank>1?e.shape[1]:1;if(s.length!==r)throw new Error(`outputShape has incorrect number of elements:, ${s.length}, should be: ${r}.`);const o=t.size;if(!(t.rank===0||t.rank===1&&o===i))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${i}]`);if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function qU(e,t,s,n=0){const i=b(e,"sparseIndices","sparseToDense","int32"),r=b(t,"sparseValues","sparseToDense"),o=b(n,"defaultValue","sparseToDense",r.dtype);PI(i,r,s,o);const a={sparseIndices:i,sparseValues:r,defaultValue:o},l={outputShape:s};return v.runKernelFunc(c=>c.sparseToDense(i,r,s,o),a,null,Ry,l)}const Xp=S({sparseToDense_:qU});function HU(e,t){const s=b(t,"indices","gatherND","int32"),n=b(e,"x","gatherND"),i=o=>o.gatherND(n,s),r={params:n,indices:s};return v.runKernelFunc(i,r,null,fy)}const vb=S({gatherND_:HU});function BI(e,t){if(t==null)return e.shape.slice();if(Nt(e.shape,t))return t;if(e.shape.length===t.length){const s=[];for(let n=0;n<e.shape.length;n++)t[n]==null&&e.shape[n]!=null?s.push(e.shape[n]):s.push(t[n]);return s}return t}function YU(e,t,s,n){const i=b(e,"x","dropout");if(I(i.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${i.dtype} tensor instead.`),I(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof me?i.clone():i;const r=BI(i,s),o=1-t,a=Z(ui($(wn(r,0,1,"float32",n),o)),o);return R(i,a)}const Tb=S({dropout_:YU});function Ab(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Jp(e,t,s){const n=1-e%2,i=new Float32Array(e);for(let r=0;r<e;++r){const o=2*Math.PI*r/(e+n-1);i[r]=t-s*Math.cos(o)}return Oe(i,"float32")}async function KU(e,t,s=1){const n=b(e,"predictions","inTopK"),i=b(t,"targets","inTopK");I(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),I(n.rank-1===i.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${i.rank}`),Se(n.shape.slice(0,n.shape.length-1),i.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const r=n.shape[n.shape.length-1];I(s>0&&s<=r,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${r}), but got ${s}`);const o=await n.data(),a=await i.data(),[l,c]=[o.length/r,r],p=el("bool",l);for(let u=0;u<l;u++){const h=u*c,d=o.subarray(h,h+c),m=[];for(let f=0;f<d.length;f++)m.push({value:d[f],index:f});m.sort((f,g)=>g.value-f.value),p[u]=0;for(let f=0;f<s;f++)if(m[f].index===a[u]){p[u]=1;break}}return e!==n&&n.dispose(),t!==i&&i.dispose(),ze(p,i.shape,"bool")}const XU=KU;function JU(e,t,s,n,i,r="NHWC",o){let a=e;e.rank===3&&(a=O(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=O(t,[1,t.shape[0],t.shape[1],t.shape[2]])),I(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),I(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),I(s.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${s}.`);const c=r==="NHWC"?a.shape[3]:a.shape[1],p=r==="NHWC"?l.shape[3]:l.shape[1];I(c===s[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${s[2]}.`),I(p===s[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${s[3]}).`),o!=null&&I(De(i),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${i}.`);const u=m=>{const f=1,g=qr(r),y=rs(a.shape,s,n,f,i,o,!1,g);return m.conv2dDerFilter(a,l,y)},h={x:a,dy:l},d={strides:n,pad:i,dataFormat:r,dimRoundingMode:o};return v.runKernelFunc(u,h,null,iy,d)}const Fl=S({conv2DBackpropFilter_:JU});function ra(e,t,s){if(s==null||s==="linear")return e;if(s==="relu")return R(e,mi(t));throw new Error(`Cannot compute gradient for fused activation ${s}.`)}function oa(e,t){let s=t;const n=Ke(e.shape,t.shape);return n.length>0&&(s=te(s,n)),O(s,e.shape)}function aa(e,t,s){if(t==="linear")return e;if(t==="relu")return Fe(e);if(t==="elu")return gn(e);if(t==="relu6")return bd(e);if(t==="prelu")return Qr(e,s);throw new Error(`Unknown fused activation ${t}.`)}const la=(e,t)=>{const s=e>0;return!s||t==="linear"};function ZU({x:e,filter:t,strides:s,pad:n,dataFormat:i="NHWC",dilations:r=[1,1],dimRoundingMode:o,bias:a,activation:l="linear",preluActivationWeights:c}){if(l=l||"linear",la(v.state.gradientDepth,l)===!1){let A=rt(e,t,s,n,i,r,o);return a!=null&&(A=$(A,a)),aa(A,l,c)}const p=b(e,"x","conv2d"),u=b(t,"filter","conv2d");let h=p,d=!1;p.rank===3&&(d=!0,h=O(p,[1,p.shape[0],p.shape[1],p.shape[2]])),I(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),I(u.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${u.rank}.`),o!=null&&I(De(n),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`),I(h.shape[3]===u.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${u.shape[2]}.`),I(tt(s,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),I(i==="NHWC",()=>`Error in conv2d: got dataFormat of ${i} but only NHWC is currently supported.`);const m=rs(h.shape,u.shape,s,r,n,o);let f;a!=null&&(f=b(a,"bias","fused conv2d"),[f]=Ce(f,p),Ie(m.outShape,f.shape));let g;c!=null&&(g=b(c,"prelu weights","fused conv2d"));const y=(A,_)=>{const[E,F,D,M]=_,P=ra(A,D,l);I(Ks(r),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const B=gl(F.shape,P,E,s,n),Y=Fl(F,P,E.shape,s,n),q=[B,Y];if(M!=null){const K=oa(M,P);q.push(K)}return q},w=A=>{const _=A.fusedConv2d({input:h,filter:u,convInfo:m,bias:f,activation:l,preluActivationWeights:g});return _},x={x:h,filter:u,bias:f,preluActivationWeights:g},T={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o,activation:l};if(a==null){const A=fs((_,E,F)=>{let D=v.runKernelFunc(w,x,null,Ah,T);return F([E,_,D]),d&&(D=O(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:y}});return A(h,u)}else{const A=fs((_,E,F,D)=>{let M=v.runKernelFunc(w,x,null,Ah,T);return D([E,_,M,F]),d&&(M=O(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:y}});return A(h,u,f)}}const QU=S({fusedConv2d_:ZU});function e$(e,t,s,n){let i=e;e.rank===3&&(i=O(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let r=t;r.rank===3&&(r=O(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const o=l=>l.depthwiseConv2DDerFilter(i,r,n),a={x:i,dy:r};return v.runKernelFunc(o,a,null,cy)}const Cd=S({depthwiseConv2dNativeBackpropFilter_:e$});function t$(e,t,s,n){let i=t,r=!1;t.rank===3&&(r=!0,i=O(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const o=c=>c.depthwiseConv2DDerInput(i,s,n),a={dy:i},l=v.runKernelFunc(o,a,null,py);return r?O(l,[l.shape[1],l.shape[2],l.shape[3]]):l}const Rd=S({depthwiseConv2dNativeBackpropInput_:t$});function s$({x:e,filter:t,strides:s,pad:n,dataFormat:i="NHWC",dilations:r=[1,1],dimRoundingMode:o,bias:a,activation:l="linear",preluActivationWeights:c}){if(la(v.state.gradientDepth,l)===!1){let A=fn(e,t,s,n,i,r,o);return a!=null&&(A=$(A,a)),aa(A,l,c)}const p=b(e,"x","depthwiseConv2d"),u=b(t,"filter","depthwiseConv2d");let h=p,d=!1;p.rank===3&&(d=!0,h=O(p,[1,p.shape[0],p.shape[1],p.shape[2]])),I(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),I(u.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`),I(h.shape[3]===u.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),r==null&&(r=[1,1]),I(tt(s,r),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),o!=null&&I(De(n),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${n}.`);const m=rs(h.shape,u.shape,s,r,n,o,!0);let f;a!=null&&(f=b(a,"bias","fused conv2d"),[f]=Ce(f,p),Ie(m.outShape,f.shape));let g;c!=null&&(g=b(c,"prelu weights","fused depthwiseConv2d"));const y=(A,_)=>{I(Ks(r),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${r}'`);const[E,F,D,M]=_,P=ra(A,D,l),B=Rd(F.shape,P,E,m),Y=Cd(F,P,E.shape,m);if(M!=null){const q=oa(f,P);return[B,Y,q]}return[B,Y]},w=A=>{const _=A.fusedDepthwiseConv2D({input:h,filter:u,convInfo:m,bias:f,activation:l,preluActivationWeights:g});return _},x={x:h,filter:u,bias:f,preluActivationWeights:g},T={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o,activation:l};if(a==null){const A=fs((_,E,F)=>{let D=v.runKernelFunc(w,x,null,Nh,T);return F([E,_,D]),d&&(D=O(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:y}});return A(h,u)}else{const A=fs((_,E,F,D)=>{let M=v.runKernelFunc(w,x,null,Nh,T);return D([E,_,M,F]),d&&(M=O(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:y}});return A(h,u,f)}}const n$=S({fusedDepthwiseConv2d_:s$});function i$({a:e,b:t,transposeA:s=!1,transposeB:n=!1,bias:i,activation:r="linear",preluActivationWeights:o}){if(la(v.state.gradientDepth,r)===!1){let M=Te(e,t,s,n);return i!=null&&(M=$(M,i)),aa(M,r,o)}let a=b(e,"a","fused matMul"),l=b(t,"b","fused matMul");[a,l]=Ce(a,l);const c=s?a.shape[a.rank-2]:a.shape[a.rank-1],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],u=s?a.shape[a.rank-1]:a.shape[a.rank-2],h=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=a.shape.slice(0,-2),m=l.shape.slice(0,-2),f=We(d),g=We(m);I(a.rank>=2&&l.rank>=2&&a.rank===l.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${a.rank} and ${l.rank}.`),I(Nt(d,m),()=>`Error in fused matMul: outer dimensions (${d}) and (${m}) of Tensors with shapes ${a.shape} and ${l.shape} must match.`),I(c===p,()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${a.shape} and ${l.shape} and transposeA=${s} and transposeB=${n} must match.`);const y=a.shape.slice(0,-2).concat([u,h]),w=s?O(a,[f,c,u]):O(a,[f,u,c]),x=n?O(l,[g,h,p]):O(l,[g,p,h]);let T;i!=null&&(T=b(i,"bias","fused matMul"),[T]=Ce(T,a),Ie(y,T.shape));let A;o!=null&&(A=b(o,"prelu weights","fused matMul"));const _=(M,P)=>{const[B,Y,q,K]=P,H=ra(O(M,q.shape),q,r);let Q,J;if(!s&&!n?(Q=Te(H,Y,!1,!0),J=Te(B,H,!0,!1)):!s&&n?(Q=Te(H,Y,!1,!1),J=Te(H,B,!0,!1)):s&&!n?(Q=Te(Y,H,!1,!0),J=Te(B,H,!1,!1)):(Q=Te(Y,H,!0,!0),J=Te(H,B,!0,!0)),i!=null){const ie=oa(K,H);return[Q,J,ie]}else return[Q,J]},E=M=>{const P=M.fusedBatchMatMul({a:w,b:x,transposeA:s,transposeB:n,bias:T,activation:r,preluActivationWeights:A});return P},F={a:w,b:x,bias:T,preluActivationWeights:A},D={transposeA:s,transposeB:n,activation:r};if(i==null){const M=fs((P,B,Y)=>{const q=v.runKernelFunc(E,F,null,Th,D);return Y([P,B,q]),{value:O(q,y),gradFunc:_}});return M(w,x)}else{const M=fs((P,B,Y,q)=>{const K=v.runKernelFunc(E,F,null,Th,D);return q([P,B,K,Y]),{value:O(K,y),gradFunc:_}});return M(w,x,T)}}const r$=S({fusedMatMul_:i$});const xn={};Ee(xn,{conv2d:()=>QU,depthwiseConv2d:()=>n$,matMul:()=>r$});function o$(e){return Jp(e,.54,.46)}const jI=S({hammingWindow_:o$});function a$(e){return Jp(e,.5,.5)}const Od=S({hannWindow_:a$});function l$(e,t,s,n=!1,i=0){let r=0;const o=[];for(;r+t<=e.size;)o.push(he(e,r,t)),r+=s;if(n)for(;r<e.size;){const a=r+t-e.size,l=be([he(e,r,t-a),Wt([a],i)]);o.push(l),r+=s}return o.length===0?ls([],[0,t]):O(be(o),[o.length,t])}const Ed=S({frame_:l$});function c$(e,t,s,n,i=Od){n==null&&(n=Ab(t));const r=Ed(e,t,s),o=R(r,i(t)),a=[];for(let l=0;l<r.shape[0];l++)a.push(no(he(o,[l,0],[1,t]),n));return be(a)}const VI=S({stft_:c$});function p$(e,t,s,n,i,r){const o=b(e,"image","cropAndResize"),a=b(t,"boxes","cropAndResize","float32"),l=b(s,"boxInd","cropAndResize","int32");i=i||"bilinear",r=r||0;const c=a.shape[0];I(o.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),I(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${a.shape}.`),I(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${a.shape}.`),I(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),I(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),I(i==="bilinear"||i==="nearest",()=>`method must be bilinear or nearest, but was ${i}`);const p=m=>m.cropAndResize(o,a,l,n,i,r),u={image:o,boxes:a,boxInd:l},h={method:i,extrapolationValue:r,cropSize:n},d=v.runKernelFunc(p,u,null,ay,h);return d}const GI=S({cropAndResize_:p$});function u$(e){const t=b(e,"image","flipLeftRight","float32");I(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const s={image:t},n=v.runKernel(Uo,s,{});return n}const qI=S({flipLeftRight_:u$});function h$(e,t,s=0,n=.5){const i=b(e,"image","rotateWithOffset","float32");I(i.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${i.rank}.`);const r={image:i},o={radians:t,fillValue:s,center:n},a=v.runKernel(Ho,r,o);return a}const HI=S({rotateWithOffset_:h$});function Ln(e,t,s,n,i,r){n==null&&(n=.5),i==null&&(i=Number.NEGATIVE_INFINITY),r==null&&(r=0);const o=e.shape[0];return s=Math.min(s,o),I(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),I(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),I(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),I(t.rank===1,()=>"scores must be a 1D tensor"),I(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),I(0<=r&&r<=1,()=>`softNmsSigma must be in [0, 1], but was '${r}'`),{maxOutputSize:s,iouThreshold:n,scoreThreshold:i,softNmsSigma:r}}function d$(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY){const r=b(e,"boxes","nonMaxSuppression"),o=b(t,"scores","nonMaxSuppression"),a=Ln(r,o,s,n,i);s=a.maxOutputSize,n=a.iouThreshold,i=a.scoreThreshold;const l={maxOutputSize:s,iouThreshold:n,scoreThreshold:i};return v.runKernelFunc(c=>c.nonMaxSuppression(r,o,s,n,i),{boxes:r,scores:o},null,cp,l)}const YI=S({nonMaxSuppression_:d$});function KI(e,t,s){const n=m$(e,t,s),i=n<0?-(n+1):n;e.splice(i,0,t)}function m$(e,t,s){return g$(e,t,s||f$)}function f$(e,t){return e>t?1:e<t?-1:0}function g$(e,t,s){let n=0,i=e.length,r=0,o=!1;for(;n<i;){r=n+(i-n>>>1);const a=s(t,e[r]);a>0?n=r+1:(i=r,o=!a)}return o?n:-n-1}function _d(e,t,s,n,i){return Nb(e,t,s,n,i,0).selectedIndices}function kd(e,t,s,n,i,r){return Nb(e,t,s,n,i,0,!1,r,!0)}function Dd(e,t,s,n,i,r){return Nb(e,t,s,n,i,r,!0)}function Nb(e,t,s,n,i,r,o=!1,a=!1,l=!1){const c=[];for(let g=0;g<t.length;g++)t[g]>i&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(XI);const p=r>0?-.5/r:0,u=[],h=[];for(;u.length<s&&c.length>0;){const g=c.pop(),{score:y,boxIndex:w,suppressBeginIndex:x}=g;if(y<i)break;let T=!1;for(let A=u.length-1;A>=x;--A){const _=y$(e,w,u[A]);if(_>=n){T=!0;break}if(g.score=g.score*b$(n,p,_),g.score<=i)break}g.suppressBeginIndex=u.length,T||(g.score===y?(u.push(w),h.push(g.score)):g.score>i&&KI(c,g,XI))}const d=u.length,m=s-d;a&&m>0&&(u.push(...new Array(m).fill(0)),h.push(...new Array(m).fill(0)));const f={selectedIndices:Oe(u,"int32")};return o&&(f.selectedScores=Oe(h,"float32")),l&&(f.validOutputs=j(d,"int32")),f}function y$(e,t,s){const n=e.subarray(t*4,t*4+4),i=e.subarray(s*4,s*4+4),r=Math.min(n[0],n[2]),o=Math.min(n[1],n[3]),a=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),c=Math.min(i[0],i[2]),p=Math.min(i[1],i[3]),u=Math.max(i[0],i[2]),h=Math.max(i[1],i[3]),d=(a-r)*(l-o),m=(u-c)*(h-p);if(d<=0||m<=0)return 0;const f=Math.max(r,c),g=Math.max(o,p),y=Math.min(a,u),w=Math.min(l,h),x=Math.max(y-f,0)*Math.max(w-g,0);return x/(d+m-x)}function b$(e,t,s){const n=Math.exp(t*s*s);return s<=e?n:0}function XI(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function w$(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY){const r=b(e,"boxes","nonMaxSuppressionAsync"),o=b(t,"scores","nonMaxSuppressionAsync"),a=Ln(r,o,s,n,i);s=a.maxOutputSize,n=a.iouThreshold,i=a.scoreThreshold;const l=await Promise.all([r.data(),o.data()]),c=l[0],p=l[1],u=_d(c,p,s,n,i);return r!==e&&r.dispose(),o!==t&&o.dispose(),u}const JI=w$;function x$(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=0){const o=b(e,"boxes","nonMaxSuppression"),a=b(t,"scores","nonMaxSuppression"),l=Ln(o,a,s,n,i,r);s=l.maxOutputSize,n=l.iouThreshold,i=l.scoreThreshold,r=l.softNmsSigma;const c={boxes:o,scores:a},p={maxOutputSize:s,iouThreshold:n,scoreThreshold:i,softNmsSigma:r},u=v.runKernel(Po,c,p);return{selectedIndices:u[0],selectedScores:u[1]}}const ZI=S({nonMaxSuppressionWithScore_:x$});async function L$(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=0){const o=b(e,"boxes","nonMaxSuppressionAsync"),a=b(t,"scores","nonMaxSuppressionAsync"),l=Ln(o,a,s,n,i,r);s=l.maxOutputSize,n=l.iouThreshold,i=l.scoreThreshold,r=l.softNmsSigma;const c=await Promise.all([o.data(),a.data()]),p=c[0],u=c[1],h=Dd(p,u,s,n,i,r);return o!==e&&o.dispose(),a!==t&&a.dispose(),h}const QI=L$;function S$(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=!1){const o=b(e,"boxes","nonMaxSuppression"),a=b(t,"scores","nonMaxSuppression"),l=Ln(o,a,s,n,i,null),c=l.maxOutputSize,p=l.iouThreshold,u=l.scoreThreshold,h={boxes:o,scores:a},d={maxOutputSize:c,iouThreshold:p,scoreThreshold:u,padToMaxOutputSize:r},m=v.runKernel(zo,h,d);return{selectedIndices:m[0],validOutputs:m[1]}}const ev=S({nonMaxSuppressionPadded_:S$});async function I$(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=!1){const o=b(e,"boxes","nonMaxSuppressionAsync"),a=b(t,"scores","nonMaxSuppressionAsync"),l=Ln(o,a,s,n,i,null),c=l.maxOutputSize,p=l.iouThreshold,u=l.scoreThreshold,[h,d]=await Promise.all([o.data(),a.data()]),m=kd(h,d,c,p,u,r);return o!==e&&o.dispose(),a!==t&&a.dispose(),m}const tv=I$;function v$(e,t,s=!1){const n=b(e,"images","resizeBilinear");I(n.rank===3||n.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`),I(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`);let i=n,r=!1;n.rank===3&&(r=!0,i=O(n,[1,n.shape[0],n.shape[1],n.shape[2]]));const[o,a]=t,l=(h,d)=>(d([i]),h.resizeBilinear(i,o,a,s)),c={images:i},p={alignCorners:s,size:t},u=v.runKernelFunc(l,c,null,yp,p);return r?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const sv=S({resizeBilinear_:v$});function T$(e,t,s=!1){const n=b(e,"images","resizeNearestNeighbor");I(n.rank===3||n.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`),I(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),I(n.dtype==="float32"||n.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let i=n,r=!1;n.rank===3&&(r=!0,i=O(n,[1,n.shape[0],n.shape[1],n.shape[2]]));const[o,a]=t,l={images:i},c={alignCorners:s,size:t},p=(h,d)=>(d([i]),h.resizeNearestNeighbor(i,o,a,s)),u=v.runKernelFunc(p,l,null,gp,c);return r?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const nv=S({resizeNearestNeighbor_:T$});function A$(e,t,s){I(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),I(s%1===0,()=>`bandPart(): numUpper must be an integer, got ${s}.`);const n=b(e,"a","bandPart");I(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);const i=n.shape,[r,o]=n.shape.slice(-2);if(!(t<=r))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${r}).`);if(!(s<=o))throw new Error(`bandPart(): numUpper (${s}) must not be greater than the number of columns (${o}).`);t<0&&(t=r),s<0&&(s=o);const a=O($i(0,r,1,"int32"),[-1,1]),l=$i(0,o,1,"int32"),c=X(a,l),p=Yt(Ws(c,j(+t,"int32")),ms(c,j(-s,"int32"))),u=ye([r,o],n.dtype);return O(Ge(qe(O(n,[-1,r,o])).map(h=>mt(p,h,u))),i)}const iv=S({bandPart_:A$});function N$(e){let t;if(Array.isArray(e)){t=!1,I(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const i=e[0].shape[0];for(let r=1;r<e.length;++r)I(e[r].shape[0]===i,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[r].shape[0]} vs. ${i})`)}else t=!0,e=Bt(e,e.shape[0],0).map(i=>Qs(i,[0]));I(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const s=[],n=e;for(let i=0;i<e.length;++i)s.push(v.tidy(()=>{let r=n[i];if(i>0)for(let o=0;o<i;++o){const a=R(te(R(s[o],r)),s[o]);r=X(r,a)}return Z(r,Kp(r,"euclidean"))}));return t?Ge(s,0):s}const rv=S({gramSchmidt_:N$});function C$(e,t=!1){if(I(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return ov(e,t);{const s=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),n=qe(O(e,[s,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],r=[];n.forEach(l=>{const[c,p]=ov(l,t);i.push(c),r.push(p)});const o=O(Ge(i,0),e.shape),a=O(Ge(r,0),e.shape);return[o,a]}}function ov(e,t=!1){return v.tidy(()=>{I(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const s=e.shape[0],n=e.shape[1];let i=sa(s),r=Fs(e);const o=ls([[1]],[1,1]);let a=Fs(o);const l=s>=n?n:s;for(let c=0;c<l;++c){const p=r,u=a,h=i;[a,r,i]=v.tidy(()=>{const d=he(r,[c,c],[s-c,1]),m=Kp(d),f=he(r,[c,c],[1,1]),g=mt(Ut(f,0),ls([[-1]]),ls([[1]])),y=X(f,R(g,m)),w=Z(d,y);w.shape[0]===1?a=Fs(o):a=be([o,he(w,[1,0],[w.shape[0]-1,w.shape[1]])],0);const x=ke(Z(Te(g,y),m)),T=he(r,[c,0],[s-c,n]),A=R(x,a),_=se(a);if(c===0)r=X(T,Te(A,Te(_,T)));else{const D=X(T,Te(A,Te(_,T)));r=be([he(r,[0,0],[c,n]),D],0)}const E=se(A),F=he(i,[0,c],[s,i.shape[1]-c]);if(c===0)i=X(F,Te(Te(F,a),E));else{const D=X(F,Te(Te(F,a),E));i=be([he(i,[0,0],[s,c]),D],1)}return[a,r,i]}),ce([p,u,h])}return!t&&s>n&&(i=he(i,[0,0],[s,n]),r=he(r,[0,0],[n,n])),[i,r]})}const av=S({qr_:C$});var gt;(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(gt||(gt={}));function R$(e,t,s=gt.SUM_BY_NONZERO_WEIGHTS){const n=b(e,"losses","computeWeightedLoss");let i=null;t!=null&&(i=b(t,"weights","computeWeightedLoss"));const r=i==null?n:R(n,i);if(s===gt.NONE)return r;if(s===gt.SUM)return te(r);if(s===gt.MEAN){if(i==null)return Xe(r);{const o=n.size/i.size,a=Z(te(r),te(i));return o>1?Z(a,j(o)):a}}if(s===gt.SUM_BY_NONZERO_WEIGHTS){if(i==null)return Z(te(r),j(n.size));{const o=R(i,Kt(n.shape)),a=G(te(Js(o,j(0))),"float32");return Z(te(r),a)}}throw Error(`Unknown reduction: ${s}`)}const ns=S({computeWeightedLoss_:R$});function O$(e,t,s,n=gt.SUM_BY_NONZERO_WEIGHTS){const i=b(e,"labels","absoluteDifference"),r=b(t,"predictions","absoluteDifference");let o=null;s!=null&&(o=b(s,"weights","absoluteDifference")),Se(i.shape,r.shape,"Error in absoluteDifference: ");const a=et(X(i,r));return ns(a,o,n)}const lv=S({absoluteDifference_:O$});function E$(e,t,s,n,i=gt.SUM_BY_NONZERO_WEIGHTS){const r=b(e,"labels","cosineDistance"),o=b(t,"predictions","cosineDistance");let a=null;n!=null&&(a=b(n,"weights","cosineDistance")),Se(r.shape,o.shape,"Error in cosineDistance: ");const l=j(1),c=X(l,te(R(r,o),s,!0));return ns(c,a,i)}const cv=S({cosineDistance_:E$});function _$(e,t,s,n=gt.SUM_BY_NONZERO_WEIGHTS){let i=b(e,"labels","hingeLoss");const r=b(t,"predictions","hingeLoss");let o=null;s!=null&&(o=b(s,"weights","hingeLoss")),Se(i.shape,r.shape,"Error in hingeLoss: ");const a=j(1);i=X(R(j(2),i),a);const l=Fe(X(a,R(i,r)));return ns(l,o,n)}const pv=S({hingeLoss_:_$});function k$(e,t,s,n=1,i=gt.SUM_BY_NONZERO_WEIGHTS){const r=b(e,"labels","huberLoss"),o=b(t,"predictions","huberLoss");let a=null;s!=null&&(a=b(s,"weights","huberLoss")),Se(r.shape,o.shape,"Error in huberLoss: ");const l=j(n),c=et(X(o,r)),p=bn(c,l),u=X(c,p),h=$(R(j(.5),xe(p)),R(l,u));return ns(h,a,i)}const uv=S({huberLoss_:k$});function D$(e,t,s,n=1e-7,i=gt.SUM_BY_NONZERO_WEIGHTS){const r=b(e,"labels","logLoss"),o=b(t,"predictions","logLoss");let a=null;s!=null&&(a=b(s,"weights","logLoss")),Se(r.shape,o.shape,"Error in logLoss: ");const l=j(1),c=j(n),p=ke(R(r,zt($(o,c)))),u=R(X(l,r),zt($(X(l,o),c))),h=X(p,u);return ns(h,a,i)}const hv=S({logLoss_:D$});function F$(e,t,s,n=gt.SUM_BY_NONZERO_WEIGHTS){const i=b(e,"labels","meanSquaredError"),r=b(t,"predictions","meanSquaredError");let o=null;s!=null&&(o=b(s,"weights","meanSquaredError")),Se(i.shape,r.shape,"Error in meanSquaredError: ");const a=io(i,r);return ns(a,o,n)}const dv=S({meanSquaredError_:F$});function M$(e,t){const s=b(e,"labels","sigmoidCrossEntropyWithLogits"),n=b(t,"logits","sigmoidCrossEntropyWithLogits");Se(s.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");const i=Fe(n),r=R(n,s),o=Sl(ut(ke(et(n))));return $(X(i,r),o)}function U$(e,t,s,n=0,i=gt.SUM_BY_NONZERO_WEIGHTS){let r=b(e,"multiClassLabels","sigmoidCrossEntropy");const o=b(t,"logits","sigmoidCrossEntropy");let a=null;if(s!=null&&(a=b(s,"weights","sigmoidCrossEntropy")),Se(r.shape,o.shape,"Error in sigmoidCrossEntropy: "),n>0){const c=j(n),p=j(1),u=j(.5);r=$(R(r,X(p,c)),R(u,c))}const l=M$(r,o);return ns(l,a,i)}const mv=S({sigmoidCrossEntropy_:U$});function $$(e,t,s=-1){if(s===-1&&(s=t.rank-1),s!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${s}`);const n=fs((i,r,o)=>{const a=!0,l=dd(r,[s],a),c=X(G(r,"float32"),l);o([i,c]);const p=ke(R(c,i)),u=te(p,[s]),h=(d,m)=>{const[f,g]=m,y=wt(d.shape,[s]);return[R(O(d,y),X(G(f,"float32"),ut(g))),R(O(d,y),X(ut(g),G(f,"float32")))]};return{value:u,gradFunc:h}});return n(e,t)}function W$(e,t,s,n=0,i=gt.SUM_BY_NONZERO_WEIGHTS){let r=b(e,"onehotLabels","softmaxCrossEntropy");const o=b(t,"logits","softmaxCrossEntropy");let a=null;if(s!=null&&(a=b(s,"weights","softmaxCrossEntropy")),Se(r.shape,o.shape,"Error in softmaxCrossEntropy: "),n>0){const c=j(n),p=j(1),u=j(r.shape[1]);r=$(R(r,X(p,c)),Z(c,u))}const l=$$(r,o);return ns(l,a,i)}const fv=S({softmaxCrossEntropy_:W$});const z$={fft:so,ifft:Wi,rfft:no,irfft:kl},P$={hammingWindow:jI,hannWindow:Od,frame:Ed,stft:VI},en={flipLeftRight:qI,resizeNearestNeighbor:nv,resizeBilinear:sv,rotateWithOffset:HI,cropAndResize:GI,nonMaxSuppression:YI,nonMaxSuppressionAsync:JI,nonMaxSuppressionWithScore:ZI,nonMaxSuppressionWithScoreAsync:QI,nonMaxSuppressionPadded:ev,nonMaxSuppressionPaddedAsync:tv},Cb={bandPart:iv,gramSchmidt:rv,qr:av},B$={absoluteDifference:lv,computeWeightedLoss:ns,cosineDistance:cv,hingeLoss:pv,huberLoss:uv,logLoss:hv,meanSquaredError:dv,sigmoidCrossEntropy:mv,softmaxCrossEntropy:fv};class gs extends cb{minimize(e,t=!1,s){const{value:n,grads:i}=this.computeGradients(e,s);if(s!=null){const r=s.map(o=>({name:o.name,tensor:i[o.name]}));this.applyGradients(r)}else this.applyGradients(i);return ce(i),t?n:(n.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return hd(e,t)}dispose(){this.iterations_!=null&&ce(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:j(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(gs,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class ca extends gs{constructor(e,t,s=null){super();this.learningRate=e,this.rho=t,this.epsilon=s,this.accumulatedGrads=[],this.accumulatedUpdates=[],s==null&&(this.epsilon=v.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=v.registeredVariables[s],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${s}/accum_grad`,variable:C(()=>re(i).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${s}/accum_var`,variable:C(()=>re(i).variable(r))});const o=Array.isArray(e)?e[n].tensor:e[s];if(o==null)return;const a=this.accumulatedGrads[n].variable,l=this.accumulatedUpdates[n].variable;C(()=>{const c=$(R(a,this.rho),R(xe(o),1-this.rho)),p=R(Z(Je($(l,this.epsilon)),Je($(a,this.epsilon))),o),u=$(R(l,this.rho),R(xe(p),1-this.rho));a.assign(c),l.assign(u);const h=$(R(p,-this.learningRate),i);i.assign(h)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(ce(this.accumulatedGrads.map(e=>e.variable)),ce(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,s=!1;this.accumulatedGrads=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})),this.accumulatedUpdates=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}ca.className="Adadelta";As(ca);class pa extends gs{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=v.registeredVariables[s];if(this.accumulatedGrads[n]==null){const a=!1;this.accumulatedGrads[n]={originalName:`${s}/accumulator`,variable:C(()=>Wt(i.shape,this.initialAccumulatorValue).variable(a))}}const r=Array.isArray(e)?e[n].tensor:e[s];if(r==null)return;const o=this.accumulatedGrads[n].variable;C(()=>{const a=$(o,xe(r));o.assign(a);const l=$(R(Z(r,Je($(a,v.backend.epsilon()))),-this.learningRate),i);i.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&ce(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulatedGrads=e.map(s=>({originalName:s.name,variable:s.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}pa.className="Adagrad";As(pa);class ua extends gs{constructor(e,t,s,n=null){super();this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],C(()=>{this.accBeta1=j(t).variable(),this.accBeta2=j(s).variable()}),n==null&&(this.epsilon=v.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);C(()=>{const s=X(1,this.accBeta1),n=X(1,this.accBeta2);t.forEach((i,r)=>{const o=v.registeredVariables[i],a=!1;this.accumulatedFirstMoment[r]==null&&(this.accumulatedFirstMoment[r]={originalName:`${i}/m`,variable:C(()=>re(o).variable(a))}),this.accumulatedSecondMoment[r]==null&&(this.accumulatedSecondMoment[r]={originalName:`${i}/v`,variable:C(()=>re(o).variable(a))});const l=Array.isArray(e)?e[r].tensor:e[i];if(l==null)return;const c=this.accumulatedFirstMoment[r].variable,p=this.accumulatedSecondMoment[r].variable,u=$(R(c,this.beta1),R(l,1-this.beta1)),h=$(R(p,this.beta2),R(xe(l),1-this.beta2)),d=Z(u,s),m=Z(h,n);c.assign(u),p.assign(h);const f=$(R(Z(d,$(Je(m),this.epsilon)),-this.learningRate),o);o.assign(f)}),this.accBeta1.assign(R(this.accBeta1,this.beta1)),this.accBeta2.assign(R(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&ce(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&ce(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),C(()=>{this.accBeta1.assign(es(this.beta1,this.iterations_+1)),this.accBeta2.assign(es(this.beta2,this.iterations_+1))});const t=e.length/2,s=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}ua.className="Adam";As(ua);class ha extends gs{constructor(e,t,s,n=null,i=0){super();this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=n,this.decay=i,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],C(()=>{this.iteration=j(0).variable(),this.accBeta1=j(t).variable()}),n==null&&(this.epsilon=v.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);C(()=>{const s=X(1,this.accBeta1),n=Z(-this.learningRate,$(R(this.iteration,this.decay),1));t.forEach((i,r)=>{const o=v.registeredVariables[i],a=!1;this.accumulatedFirstMoment[r]==null&&(this.accumulatedFirstMoment[r]={originalName:`${i}/m`,variable:re(o).variable(a)}),this.accumulatedWeightedInfNorm[r]==null&&(this.accumulatedWeightedInfNorm[r]={originalName:`${i}/v`,variable:re(o).variable(a)});const l=Array.isArray(e)?e[r].tensor:e[i];if(l==null)return;const c=this.accumulatedFirstMoment[r].variable,p=this.accumulatedWeightedInfNorm[r].variable,u=$(R(c,this.beta1),R(l,1-this.beta1)),h=R(p,this.beta2),d=et(l),m=Ht(h,d);c.assign(u),p.assign(m);const f=$(R(Z(n,s),Z(u,$(m,this.epsilon))),o);o.assign(f)}),this.iteration.assign($(this.iteration,1)),this.accBeta1.assign(R(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&ce(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&ce(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}ha.className="Adamax";As(ha);class zi extends gs{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=Array.isArray(e)?e[n].tensor:e[s];if(i==null)return;const r=v.registeredVariables[s];C(()=>{const o=$(R(this.c,i),r);r.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=pt(j(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}zi.className="SGD";As(zi);class da extends zi{constructor(e,t,s=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=s,this.accumulations=[],this.m=j(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=v.registeredVariables[s];if(this.accumulations[n]==null){const a=!1;this.accumulations[n]={originalName:`${s}/momentum`,variable:C(()=>re(i).variable(a))}}const r=this.accumulations[n].variable,o=Array.isArray(e)?e[n].tensor:e[s];if(o==null)return;C(()=>{let a;const l=$(R(this.m,r),o);this.useNesterov?a=$(R(this.c,$(o,R(l,this.m))),i):a=$(R(this.c,l),i),r.assign(l),i.assign(a)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&ce(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=!1;this.accumulations=e.map(s=>({originalName:s.name,variable:s.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}da.className="Momentum";As(da);class ma extends gs{constructor(e,t=.9,s=0,n=null,i=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=s,this.epsilon=n,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=i,n==null&&(this.epsilon=v.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=v.registeredVariables[s],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${s}/rms`,variable:C(()=>re(i).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${s}/momentum`,variable:C(()=>re(i).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${s}/mg`,variable:C(()=>re(i).variable(r))});const o=Array.isArray(e)?e[n].tensor:e[s];if(o==null)return;const a=this.accumulatedMeanSquares[n].variable,l=this.accumulatedMoments[n].variable;C(()=>{const c=$(R(a,this.decay),R(xe(o),1-this.decay));if(this.centered){const p=this.accumulatedMeanGrads[n].variable,u=$(R(p,this.decay),R(o,1-this.decay)),h=Z(R(o,this.learningRate),Je(X(c,$(xe(u),this.epsilon)))),d=$(R(l,this.momentum),h);a.assign(c),p.assign(u),l.assign(d);const m=X(i,d);i.assign(m)}else{const p=$(R(a,this.decay),R(xe(o),1-this.decay)),u=$(R(l,this.momentum),Z(R(o,this.learningRate),Je($(p,this.epsilon))));a.assign(p),l.assign(u);const h=X(i,u);i.assign(h)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&ce(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&ce(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&ce(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,s=!1;this.accumulatedMeanSquares=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})),this.accumulatedMoments=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}ma.className="RMSProp";As(ma);class oo{static sgd(e){return new zi(e)}static momentum(e,t,s=!1){return new da(e,t,s)}static rmsprop(e,t=.9,s=0,n=null,i=!1){return new ma(e,t,s,n,i)}static adam(e=.001,t=.9,s=.999,n=null){return new ua(e,t,s,n)}static adadelta(e=.001,t=.95,s=null){return new ca(e,t,s)}static adamax(e=.002,t=.9,s=.999,n=null,i=0){return new ha(e,t,s,n,i)}static adagrad(e,t=.1){return new pa(e,t)}}da,zi,ca,pa,ma,ha,ua;const ao={sgd:oo.sgd,momentum:oo.momentum,adadelta:oo.adadelta,adagrad:oo.adagrad,rmsprop:oo.rmsprop,adamax:oo.adamax,adam:oo.adam};const j$=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Zp(){return new Promise(e=>j$(()=>e()))}function V$(e,t,s){const n=s*(typeof e=="number"?e:e[0]),i=t*(typeof e=="number"?e:e[1]);return[n,i]}function G$(e,t,s,n=!0){let i=[];if(n)i=i.concat(t.slice(0)),i.push(e[0]/s),i=i.concat(e.slice(1));else{i=i.concat(e[0]);const r=t.length;for(let o=0;o<r;++o)i=i.concat([e[o+1]/t[o],t[o]]);i=i.concat(e.slice(r+1))}return i}function q$(e,t,s=!0){const n=[];if(s){n.push(t);for(let i=t+1;i<e;++i)i<=2*t?(n.push(i),n.push(i-(t+1))):n.push(i)}else{const i=[],r=[];for(let o=1;o<e;++o)o>=t*2+1||o%2===1?r.push(o):i.push(o);n.push(...i),n.push(0),n.push(...r)}return n}function H$(e,t,s,n=!0){const i=[];n?i.push(e[0]/s):i.push(e[0]*s);for(let r=1;r<e.length;++r)r<=t.length?n?i.push(t[r-1]*e[r]):i.push(e[r]/t[r-1]):i.push(e[r]);return i}function Y$(e,t){const s=[0];for(let n=0;n<t;++n)s.push(e[n][0]);return s}function K$(e,t,s){const n=e.slice(0,1);for(let i=0;i<s;++i)n.push(e[i+1]-t[i][0]-t[i][1]);return n}const Rb=1.7580993408473768,Ob=1.0507009873554805;const X$=.3275911,J$=.254829592,Z$=-.284496736,Q$=1.421413741,eW=-1.453152027,tW=1.061405429;function sW(...e){W().getBool("IS_TEST")||console.warn(...e)}function nW(...e){W().getBool("IS_TEST")||console.log(...e)}function iW(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const s=new Float32Array(e.length*2);for(let n=0;n<s.length;n+=2)s[n]=e[n/2],s[n+1]=t[n/2];return s}function rW(e){const t=new Float32Array(e.length/2),s=new Float32Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=e[n],s[n/2]=e[n+1];return{real:t,imag:s}}function oW(e){const t=Math.ceil(e.length/4),s=new Float32Array(t),n=new Float32Array(t);for(let i=0;i<e.length;i+=4)s[Math.floor(i/4)]=e[i],n[Math.floor(i/4)]=e[i+1];return{real:s,imag:n}}function aW(e){const t=Math.floor(e.length/4),s=new Float32Array(t),n=new Float32Array(t);for(let i=2;i<e.length;i+=4)s[Math.floor(i/4)]=e[i],n[Math.floor(i/4)]=e[i+1];return{real:s,imag:n}}function lW(e,t){const s=e[t*2],n=e[t*2+1];return{real:s,imag:n}}function cW(e,t,s,n){e[n*2]=t,e[n*2+1]=s}function pW(e,t){const s=new Float32Array(e/2),n=new Float32Array(e/2);for(let i=0;i<Math.ceil(e/2);i++){const r=(t?2:-2)*Math.PI*(i/e);s[i]=Math.cos(r),n[i]=Math.sin(r)}return{real:s,imag:n}}function uW(e,t,s){const n=(s?2:-2)*Math.PI*(e/t),i=Math.cos(n),r=Math.sin(n);return{real:i,imag:r}}const U={};Ee(U,{ERF_A1:()=>J$,ERF_A2:()=>Z$,ERF_A3:()=>Q$,ERF_A4:()=>eW,ERF_A5:()=>tW,ERF_P:()=>X$,PARALLELIZE_THRESHOLD:()=>ld,SELU_SCALE:()=>Ob,SELU_SCALEALPHA:()=>Rb,applyActivation:()=>aa,assertAndGetBroadcastShape:()=>Ie,assertAxesAreInnerMostDims:()=>aD,assertParamsConsistent:()=>wb,assignToTypedArray:()=>cW,axesAreInnerMostDims:()=>fb,calculateShapes:()=>QS,castTensor:()=>hW,combineLocations:()=>uI,complexWithEvenIndex:()=>oW,complexWithOddIndex:()=>aW,computeConv2DInfo:()=>rs,computeConv3DInfo:()=>Hr,computeDefaultPad:()=>bb,computeDilation2DInfo:()=>yD,computeOptimalWindowSize:()=>fF,computeOutAndReduceShapes:()=>gb,computeOutShape:()=>xb,computePool2DInfo:()=>Wn,computePool3DInfo:()=>Fi,convertConv2DDataFormat:()=>qr,eitherStridesOrDilationsAreOne:()=>tt,expandShapeToKeepDim:()=>wt,exponent:()=>uW,exponents:()=>pW,getAxesPermutation:()=>dt,getBroadcastDims:()=>tF,getComplexWithIndex:()=>lW,getFusedBiasGradient:()=>oa,getFusedDyActivation:()=>ra,getImageCenter:()=>V$,getInnerMostAxes:()=>qt,getPermuted:()=>q$,getReductionAxes:()=>Ke,getReshaped:()=>G$,getReshapedPermuted:()=>H$,getSliceBeginCoords:()=>Y$,getSliceSize:()=>K$,getUndoAxesPermutation:()=>Jo,linspaceImpl:()=>mW,log:()=>nW,mergeRealAndImagArrays:()=>iW,prepareAndValidate:()=>JS,prepareSplitSize:()=>Sb,reshapeTensor:()=>dW,segment_util:()=>yI,shouldFuse:()=>la,slice_util:()=>Ms,splitRealAndImagArrays:()=>rW,tupleValuesAreOne:()=>Ks,upcastType:()=>Ft,validateInput:()=>Mh,validateUpdateShape:()=>rb,warn:()=>sW});function hW(e,t,s){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const n=ye(e.shape),i=G(e,"float32"),r=s.complex(i,n);return n.dispose(),i.dispose(),r}if(!$y(e.dtype,t))return v.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const n=s.real(e),i=G(n,t);return n.dispose(),i}if(t==="int32")return s.int(e);if(t==="bool"){const n=j(0,e.dtype),i=s.notEqual(e,n);return n.dispose(),i}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function dW(e,t){return v.makeTensorFromDataId(e.dataId,t,e.dtype)}function mW(e,t,s){const n=(t-e)/(s-1),i=ai(s,"float32");i[0]=e;for(let r=1;r<i.length;r++)i[r]=i[r-1]+n;return Oe(i,"float32")}function gv(e,t,s){const n=new Array(e.rank).fill(0),i=e.shape.slice();return t.map(r=>{const o=[...i];o[s]=r;const a=he(e,n,o);return n[s]+=r,a})}function yv(e,t){const s=new Array(e.rank);for(let i=0;i<s.length;i++)s[i]=e.shape[i]*t[i];const n=ge(s,e.dtype);for(let i=0;i<n.values.length;++i){const r=n.indexToLoc(i),o=new Array(e.rank);for(let l=0;l<o.length;l++)o[l]=r[l]%e.shape[l];const a=e.locToIndex(o);n.values[i]=e.values[a]}return n.toTensor()}function bv(e,t,s,n,i){const r=t[t.length-1],[o,a]=[e.length/r,r],l=el(s,o*n),c=el("int32",o*n);for(let u=0;u<o;u++){const h=u*a,d=e.subarray(h,h+a),m=[];for(let w=0;w<d.length;w++)m.push({value:d[w],index:w});m.sort((w,x)=>x.value-w.value);const f=u*n,g=l.subarray(f,f+n),y=c.subarray(f,f+n);for(let w=0;w<n;w++)g[w]=m[w].value,y[w]=m[w].index}const p=t.slice();return p[p.length-1]=n,[ze(l,p,s),ze(c,p,"int32")]}const vt={};Ee(vt,{nonMaxSuppressionV3Impl:()=>_d,nonMaxSuppressionV4Impl:()=>kd,nonMaxSuppressionV5Impl:()=>Dd,split:()=>gv,tile:()=>yv,topkImpl:()=>bv,whereImpl:()=>Nd});const wv={kernelName:_o,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,mi(G(s,"float32"),-1))}}};const xv={kernelName:dr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=xe(G(s,"float32")),i=Je(X(j(1),n));return ke(Z(e,i))}}}};const Lv={kernelName:mr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=Je(X(xe(G(s,"float32")),1));return Z(e,n)}}}};const Sv={kernelName:Zn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{let a=e;const l=Ke(s.shape,i);return l.length>0&&(a=te(a,l)),O(a,s.shape)},o=()=>{let a=e;const l=Ke(n.shape,i);return l.length>0&&(a=te(a,l)),O(a,n.shape)};return{a:r,b:o}}};const Iv={kernelName:Mc,saveAllInputs:!0,gradFunc:(e,t)=>{const s={};return t.forEach((n,i)=>{s[i]=()=>e.clone()}),s}};const vv={kernelName:Uc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>re(s)}}};const Tv={kernelName:$c,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>re(s)}}};const Av={kernelName:fr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,Je(X(j(1),xe(G(s,"float32")))))}}};const Nv={kernelName:gr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=Je($(j(1),xe(G(s,"float32"))));return Z(e,n)}}}};const Cv={kernelName:ko,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=$(xe(s),xe(n));let l=R(e,Z(n,a));const c=Ke(s.shape,i);return c.length>0&&(l=te(l,c)),O(l,s.shape)},o=()=>{const a=$(xe(s),xe(n));let l=ke(R(e,Z(s,a)));const c=Ke(n.shape,i);return c.length>0&&(l=te(l,c)),O(l,n.shape)};return{a:r,b:o}}};const Rv={kernelName:yr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,$(xe(G(s,"float32")),1))}}};const Ov={kernelName:br,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,X(j(1),xe(G(s,"float32"))))}}};function fW(e,t,s,n,i=[1,1,1],r,o){const a=b(e,"dy","avgPool3dBackprop"),l=b(t,"input","avgPool3dBackprop");let c=a,p=l,u=!1;l.rank===4&&(u=!0,c=O(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),p=O(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),I(c.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${c.rank}.`),I(p.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${p.rank}.`),I(tt(n,i),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),o!=null&&I(De(r),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const h=g=>{const y=Fi(p.shape,s,n,i,r,o);return g.avgPool3dBackprop(c,p,y)},d={dy:c,input:p},m={filterSize:s,strides:n,dilations:i,pad:r,dimRoundingMode:o},f=v.runKernelFunc(h,d,null,ny,m);return u?O(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}const Ev=S({avgPool3dBackprop_:fW});const _v={kernelName:Wc,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{filterSize:i,strides:r,dilations:o,pad:a,dimRoundingMode:l}=s,c=o??[1,1,1];return{x:()=>Ev(e,n,i,r,c,a,l)}}};function gW(e,t,s,n,i){const r=b(e,"dy","avgPoolBackprop"),o=b(t,"input","avgPoolBackprop");I(o.rank===r.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${r.rank})`);let a=o,l=r,c=!1;o.rank===3&&(c=!0,a=O(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=O(r,[1,r.shape[0],r.shape[1],r.shape[2]])),I(l.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${l.rank}.`),I(a.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${a.rank}.`);const p=m=>{const f=Wn(a.shape,s,n,1,i);return m.avgPoolBackprop(l,a,f)},u={dy:l,input:a},h={filterSize:s,strides:n,pad:i},d=v.runKernelFunc(p,u,null,Do,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const kv=S({avgPoolBackprop_:gW});const Dv={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{filterSize:i,strides:r,pad:o}=s;return{x:()=>kv(e,n,i,r,o)}}};const Fv={kernelName:zc,inputsToSave:["a","b"],gradFunc:(e,t,s)=>{const[n,i]=t,{transposeA:r,transposeB:o}=s;return!r&&!o?{a:()=>Te(e,i,!1,!0),b:()=>Te(n,e,!0,!1)}:!r&&o?{a:()=>Te(e,i,!1,!1),b:()=>Te(e,n,!0,!1)}:r&&!o?{a:()=>Te(i,e,!1,!0),b:()=>Te(n,e,!1,!1)}:{a:()=>Te(i,e,!0,!0),b:()=>Te(e,n,!0,!0)}}};const Mv={kernelName:Pc,gradFunc:(e,t,s)=>{const{blockShape:n,crops:i}=s;return{x:()=>Zr(e,n,i)}}};const Uv={kernelName:Bc,gradFunc:(e,t,s)=>{const n=s,i=n.inputShape,r=n.shape,o=Array.from(r);for(let l=i.length-1;l>=0;l--)if(i[l]===r[l])o[l]=1;else if(i[l]!==1)throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${r}].`);const a=[];for(let l=0;l<o.length;l++)o[l]>1&&a.push(l);return{x:()=>te(e,a,!0)}}};const $v={kernelName:Ai,gradFunc:e=>({x:()=>e.clone()})};const Wv={kernelName:wr,gradFunc:e=>({x:()=>re(e)})};const zv={kernelName:xr,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{clipValueMin:i,clipValueMax:r}=s;return{x:()=>mt(Yt(ms(n,i),Ws(n,r)),e,re(e))}}};const Pv={kernelName:Fo,saveAllInputs:!0,gradFunc:(e,t,s)=>{const n=t.map(l=>l.shape),{axis:i}=s,r=Ne(i,t[0].shape)[0],o=n.map(l=>l[r]),a=Bt(e,o,r);return a.map(l=>()=>l)}};const Bv={kernelName:Vc,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const[n,i]=t,{dilations:r,strides:o,pad:a,dataFormat:l}=s;return I(Ks(r),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`),{x:()=>gl(n.shape,e,i,o,a,l),filter:()=>Fl(n,e,i.shape,o,a,l)}}};const jv={kernelName:Gc,inputsToSave:["dy","filter"],gradFunc:(e,t,s)=>{const[n,i]=t,{strides:r,pad:o,dataFormat:a,dimRoundingMode:l}=s;return{dy:()=>rt(e,i,r,o,a,1,l),filter:()=>Fl(e,n,i.shape,r,o,a,l)}}};function yW(e,t,s,n,i){let r=e;e.rank===4&&(r=O(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=O(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),I(r.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${r.shape}.`),I(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),I(s.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${s}.`),I(r.shape[4]===s[3],()=>`Error in conv3dDerFilter: depth of input ${r.shape[4]}) must match input depth in filter (${s[3]}.`),I(o.shape[4]===s[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${s[4]}).`);const a=p=>{const u=1,h=Hr(r.shape,s,n,u,i);return p.conv3dDerFilter(r,o,h)},l={x:r,y:o},c={strides:n,pad:i};return v.runKernelFunc(a,l,null,ry,c)}const Vv=S({conv3DBackpropFilter_:yW});const Gv={kernelName:qc,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const{dilations:n,strides:i,pad:r}=s;I(Ks(n),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);const[o,a]=t;return{x:()=>sd(o.shape,e,a,i,r),filter:()=>Vv(o,e,a.shape,i,r)}}};const qv={kernelName:Qn,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(ke(Ol(G(s,"float32"))),e)}}};const Hv={kernelName:Lr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(El(G(s,"float32")),e)}}};const Yv={kernelName:Hc,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{axis:i,exclusive:r,reverse:o}=s;return{x:()=>{const a=dt([i],n.rank);let l=xl(e,i,r,!o);return a!=null&&(l=se(l,a)),l}}}};const Kv={kernelName:Yc,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const{dilations:n,strides:i,pad:r,dimRoundingMode:o}=s,a=n??[1,1];I(Ks(a),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[l,c]=t;I(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),I(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),I(l.shape[3]===c.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),I(tt(i,a),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${a}'.`),o!=null&&I(De(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=rs(l.shape,c.shape,i,a,r,o,!0);return{x:()=>Rd(l.shape,e,c,p),filter:()=>Cd(l,e,c.shape,p)}}};const Xv={kernelName:Mo,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const[n,i]=t,r={x:n,filter:i,dy:e},o={x:n,filter:i,dy:e};return{x:()=>v.runKernel(qa,r,s),filter:()=>v.runKernel(Ha,o,s)}}};const Jv={kernelName:ei,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=Z(e,G(n,"float32")),l=Ke(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{let a=R(e,G(s,"float32"));const l=Ke(n.shape,i);l.length>0&&(a=O(te(a,l),n.shape));const c=xe(n);return ke(Z(a,G(c,"float32")))};return{a:r,b:o}}};const Zv={kernelName:Sr,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t,n=r=>r.eluDer(e,s),i={dy:e,y:s};return{x:()=>v.runKernelFunc(n,i,null,hy)}}};const Qv={kernelName:Ir,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t,n=R(ut(ke(xe(s))),2/Math.sqrt(Math.PI));return{x:()=>R(e,n)}}};const eT={kernelName:vr,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,s)}}};const tT={kernelName:Tr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,ut(s))}}};const sT={kernelName:Ar,gradFunc:e=>({x:()=>re(e)})};const nT={kernelName:Xc,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=Z(e,G(n,"float32")),l=Ke(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{let a=R(e,G(s,"float32"));const l=Ke(n.shape,i);l.length>0&&(a=O(te(a,l),n.shape));const c=xe(n);return ke(Z(a,G(c,"float32")))};return{a:r,b:o}}};const iT={kernelName:Ni,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,s)=>{const{varianceEpsilon:n}=s,[i,r,o,a]=t,l=a??j(1),c=Ke(r.shape,i.shape),p=[];if(r.rank===1){for(let T=0;T<i.shape.length-1;++T)p.push(i.shape[T]);p.push(1)}const u=X(i,r),h=R(e,l),d=Cl($(o,j(n))),m=R(R(R(d,d),d),j(-.5)),f=()=>r.rank===1?O(R(R(e,$s(O(d,[1,1,1,r.shape[0]]),p)),l),i.shape):O(R(R(e,d),l),i.shape),g=()=>{let T=R(R(d,j(-1)),h);return r.rank===1&&(T=te(T,c)),O(T,r.shape)},y=()=>{let T=R(R(m,u),h);return r.rank===1&&(T=te(T,c)),O(T,r.shape)},w=()=>{const T=R(u,d);let A=R(e,T);return r.rank===1&&(A=te(A,c)),O(A,r.shape)},x=()=>{let T=e;return r.rank===1&&(T=te(T,c)),O(T,r.shape)};return{x:f,mean:g,variance:y,scale:w,offset:x}}};const aT={kernelName:Jc,inputsToSave:["x","indices"],gradFunc:(e,t,s)=>{const[n,i]=t,{axis:r}=s,o=Ne(r,n.shape)[0],a=()=>{const l=n.shape,c=i.size,p=l.slice(0,o),u=p.length,h=l.slice(r,l.length).slice(1),d=h.length,m=rT(0,u),f=rT(u+1,u+1+d),g=oT([p,[c],h]),y=O(e,g),w=O(i,[c]),x=oT([[u],m,f]),T=se(y,x);let A=Td(T,w,n.shape[o]);const _=Jo(x);return A=se(A,_),A};return{x:a,indices:()=>i}}};function rT(e,t){const s=[];for(let n=e;n<t;++n)s.push(n);return s}function oT(e){const t=[];for(let s=0;s<e.length;++s)for(let n=0;n<e[s].length;++n)t.push(e[s][n]);return t}const lT={kernelName:Zc,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t;return{a:()=>re(s),b:()=>re(n)}}};const cT={kernelName:Ci,gradFunc:e=>({x:()=>G(e,"float32")})};const pT={kernelName:Nr,gradFunc:e=>({x:()=>re(e)})};const uT={kernelName:Cr,gradFunc:e=>({x:()=>re(e)})};const hT={kernelName:Rr,gradFunc:e=>({x:()=>re(e)})};const dT={kernelName:Er,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,$(s,1))}}};const mT={kernelName:Or,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,G(s,"float32"))}}};const fT={kernelName:tp,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n]=t,{axis:i}=s;return{logits:()=>{const r=!0,o=ut(n);return X(e,R(te(e,i,r),o))}}}};function bW(e,t,s,n=5,i=1,r=1,o=.5){const a=p=>p.LRNGrad(s,e,t,n,i,r,o),l={x:e,y:t,dy:s},c={depthRadius:n,bias:i,alpha:r,beta:o};return v.runKernelFunc(a,l,null,Sy,c)}const gT=S({localResponseNormalizationBackprop_:bW});const yT={kernelName:sp,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n,i]=t,{depthRadius:r,bias:o,alpha:a,beta:l}=s;return{x:()=>gT(n,i,e,r,o,a,l)}}};function Fd(e,t,s,n,i){return t.rank<s.rank&&(t=O(t,wt(t.shape,n))),e.rank<s.rank&&(e=O(e,wt(e.shape,n))),{x:()=>{const r=R(e,G(as(s,t),e.dtype));return i==null?r:se(r,i)}}}const Eb={kernelName:Ri,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const n=s,{reductionIndices:i}=n,[r,o]=t,a=Ne(i,r.shape),l=dt(a,r.rank),c=Fd(e,o,r,a,l);return{x:()=>{let p=c.x();return l!=null&&(p=se(p)),p}}}};const bT={kernelName:np,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=()=>R(e,G(ms(s,n),"float32")),r=()=>R(e,G(Xr(s,n),"float32"));return{a:i,b:r}}};function wW(e,t,s,n,i,r=[1,1,1],o,a){const l=b(e,"dy","maxPool3dBackprop"),c=b(t,"input","maxPool3dBackprop"),p=b(s,"output","maxPool3dBackprop");let u=l,h=c,d=p,m=!1;c.rank===4&&(m=!0,u=O(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),h=O(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),d=O(p,[1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]])),I(u.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${u.rank}.`),I(h.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${h.rank}.`),I(d.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${d.rank}.`),I(tt(i,r),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${i} and dilations '${r}'`),a!=null&&I(De(o),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const f=x=>{const T=Fi(h.shape,n,i,r,o,a);return x.maxPool3dBackprop(u,h,d,T)},g={dy:u,input:h,output:d},y={filterSize:n,strides:i,dilations:r,pad:o,dimRoundingMode:a},w=v.runKernelFunc(f,g,null,Iy,y);return m?O(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const wT=S({maxPool3dBackprop_:wW});const xT={kernelName:ip,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n,i]=t,{filterSize:r,strides:o,dilations:a,pad:l,dimRoundingMode:c}=s,p=a??[1,1,1];return{x:()=>wT(e,n,i,r,o,p,l,c)}}};function xW(e,t,s,n,i,r,o){const a=b(e,"dy","maxPoolBackprop"),l=b(t,"input","maxPoolBackprop"),c=b(s,"output","maxPoolBackprop");I(l.rank===a.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${a.rank})`),I(a.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${a.rank}.`),I(l.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${l.rank}.`),o!=null&&I(De(r),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=d=>{const m=Wn(l.shape,n,i,1,r,o);return d.maxPoolBackprop(a,l,c,m)},u={dy:a,input:l,output:c},h={filterSize:n,strides:i,pad:r,dimRoundingMode:o};return v.runKernelFunc(p,u,null,$o,h)}const LT=S({maxPoolBackprop_:xW});const ST={kernelName:Oi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n,i]=t,{filterSize:r,strides:o,pad:a}=s;return{x:()=>LT(e,n,i,r,o,a)}}};const IT={kernelName:rp,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const n=s,{axis:i}=n,[r,o]=t,a=Ne(i,r.shape),l=dt(a,r.rank),c=Fd(e,o,r,a,l);return{x:()=>{let p=c.x();return l!=null&&(p=se(p)),p}}}};const vT={kernelName:op,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=()=>R(e,G(Ws(s,n),"float32")),r=()=>R(e,G(Ut(s,n),"float32"));return{a:i,b:r}}};const TT={kernelName:ap,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=Ke(s.shape,i);return a.length>0?O(te(e,a),s.shape):e},o=()=>{const a=R(e,ke(ui(Z(s,n)))),l=Ke(n.shape,i);return l.length>0?O(te(a,l),n.shape):a};return{a:r,b:o}}};const AT={kernelName:_r,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=R(e,G(n,"float32")),l=Ke(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{const a=R(e,G(s,"float32")),l=Ke(n.shape,i);return l.length>0?O(te(a,l),n.shape):a};return{a:r,b:o}}};const NT={kernelName:lp,gradFunc:e=>({x:()=>ke(e)})};const CT={kernelName:up,inputsToSave:["indices"],gradFunc:(e,t)=>{const s=t[0];return{indices:()=>ye(s.shape,"float32")}}};const RT={kernelName:pp,gradFunc:e=>({x:()=>re(e)})};const _b={kernelName:Bo,inputsToSave:["x"],gradFunc:(e,t,s)=>{const n=t[0],{paddings:i}=s,r=i.map(o=>o[0]);return{x:()=>he(e,r,n.shape)}}};const OT={kernelName:hp,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[s,n,i]=t,r=s,o=n,a=Ie(r.shape,o.shape),l=()=>{const p=G(o,"float32");let u=R(e,R(p,es(r,X(p,j(1)))));const h=Ke(r.shape,a);return h.length>0&&(u=te(u,h)),O(u,r.shape)},c=()=>{const p=Ut(r,0),u=mt(p,zt(r),re(r));let h=R(e,R(i,u));const d=Ke(o.shape,a);return d.length>0&&(h=te(h,d)),O(h,o.shape)};return{a:l,b:c}}};const ET={kernelName:dp,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[s,n]=t,i=Ut(s,0);return{x:()=>mt(i,e,R(e,n)),alpha:()=>{let r=mt(i,re(e),R(e,s));const o=Ke(n.shape,e.shape);return o.length>0&&(r=te(r,o)),O(r,n.shape)}}}};const _T={kernelName:kr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,ke(xe(s)))}}};const kT={kernelName:bp,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t,n=R(Ws(s,6),mi(s));return{x:()=>R(e,G(n,"float32"))}}};const DT={kernelName:fp,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,G(mi(s),"float32"))}}};const FT={kernelName:Ei,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>O(e,s.shape)}}};const MT={kernelName:yp,inputsToSave:["images"],gradFunc:(e,t,s)=>{const[n]=t,i=a=>{const{alignCorners:l}=s;return a.resizeBilinearBackprop(e,n,l)},r={images:n},o=()=>v.runKernelFunc(i,r,null,Ny,s);return{images:o}}};const UT={kernelName:gp,inputsToSave:["images"],gradFunc:(e,t,s)=>{const[n]=t,i=a=>{const{alignCorners:l}=s;return a.resizeNearestNeighborBackprop(e,n,l)},r={images:n},o=()=>v.runKernelFunc(i,r,null,Ay,s);return{images:o}}};const $T={kernelName:wp,gradFunc:(e,t,s)=>{const{dims:n}=s,i=Ne(n,e.shape);return{x:()=>Et(e,i)}}};const WT={kernelName:Dr,gradFunc:e=>({x:()=>re(e)})};const zT={kernelName:Fr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>ke(Z(e,R(es(s,1.5),2)))}}};const PT={kernelName:xp,inputsToSave:["condition"],gradFunc:(e,t)=>{const[s]=t;return{condition:()=>G(re(s),"float32"),t:()=>R(e,G(s,e.dtype)),e:()=>R(e,G(Jr(s),e.dtype))}}};const BT={kernelName:Mr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=Ut(s,j(0)),i=j(Rb),r=j(Ob),o=R(e,r),a=R(R(e,i),ut(G(s,"float32")));return mt(n,o,a)}}}};const jT={kernelName:Wr,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,R(s,X(j(1),s)))}}};const VT={kernelName:$r,gradFunc:e=>({x:()=>re(e)})};const GT={kernelName:ti,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(Kr(G(s,"float32")),e)}}};const qT={kernelName:Ur,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(wl(G(s,"float32")),e)}}};const HT={kernelName:jo,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{begin:i,size:r}=s,o=n.shape,[a,l]=jp(n,i,r),c=[];for(let p=0;p<e.rank;p++)c.push([a[p],o[p]-a[p]-l[p]]);return{x:()=>Pt(e,c)}}};const YT={kernelName:Ip,outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n]=t,{dim:i}=s,r=!0,o=R(e,n);return{logits:()=>X(o,R(te(o,[i],r),n))}}};const KT={kernelName:zr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,os(s))}}};const kb={kernelName:Vo,gradFunc:(e,t,s)=>{const{blockShape:n,paddings:i}=s;return{x:()=>Yr(e,n,i)}}};const Db={kernelName:Sp,gradFunc:(e,t,s)=>{const{axis:n}=s;return{x:()=>be(e,n)}}};const XT={kernelName:Pr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,R(Je(G(s,"float32")),2))}}};const JT={kernelName:Go,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,R(G(s,"float32"),2))}}};const ZT={kernelName:si,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=j(2),r=()=>R(e,R(i,X(s,n))),o=()=>R(e,R(i,X(n,s)));return{a:r,b:o}}};const QT={kernelName:Vr,gradFunc:e=>({x:()=>re(e)})};const eA={kernelName:Br,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{let a=e;const l=Ke(s.shape,i);return l.length>0&&(a=te(a,l)),O(a,s.shape)},o=()=>{let a=e;const l=Ke(n.shape,i);return l.length>0&&(a=te(a,l)),O(ke(a),n.shape)};return{a:r,b:o}}};const tA={kernelName:Lp,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,i=n.shape.slice(),{axis:r}=s,o=Ne(r,n.shape);o.forEach(c=>{i[c]=1});const a=O(e,i),l=R(a,Kt(n.shape,"float32"));return{x:()=>l}}};const sA={kernelName:ni,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,xe(Kr(s)))}}};const nA={kernelName:jr,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(X(j(1),xe(s)),e)}}};const iA={kernelName:vp,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{reps:i}=s,r=()=>{let o=re(n);if(n.rank===1)for(let a=0;a<i[0];++a)o=$(o,he(e,[a*n.shape[0]],[n.shape[0]]));else if(n.rank===2)for(let a=0;a<i[0];++a)for(let l=0;l<i[1];++l)o=$(o,he(e,[a*n.shape[0],l*n.shape[1]],[n.shape[0],n.shape[1]]));else if(n.rank===3)for(let a=0;a<i[0];++a)for(let l=0;l<i[1];++l)for(let c=0;c<i[2];++c)o=$(o,he(e,[a*n.shape[0],l*n.shape[1],c*n.shape[2]],[n.shape[0],n.shape[1],n.shape[2]]));else if(n.rank===4)for(let a=0;a<i[0];++a)for(let l=0;l<i[1];++l)for(let c=0;c<i[2];++c)for(let p=0;p<i[3];++p)o=$(o,he(e,[a*n.shape[0],l*n.shape[1],c*n.shape[2],p*n.shape[3]],[n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${n.rank} tensors yet.`);return o};return{x:r}}};const rA={kernelName:_i,gradFunc:(e,t,s)=>{const n=s,{perm:i}=n,r=Jo(i);return{x:()=>se(e,r)}}};const oA={kernelName:Tp,gradFunc:(e,t,s)=>{const n=s,{axis:i}=n;return{value:()=>Ge(e,i)}}};const aA={kernelName:Ap,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[s]=t,n=()=>LW(e,s);return{x:n}}};function LW(e,t){const s=Ht(t,re(t)),n=hi(e,s);let i=ms(t,j(0,"int32"));const r=n.rank-i.rank;for(let a=0;a<r;++a)i=Mt(i,a+1);i=Yt(i,Kt(n.shape,"bool"));const o=re(n);return mt(i,n,o)}const lA={kernelName:Np,gradFunc:e=>({x:()=>re(e)})};const SW=[wv,xv,Lv,Sv,Iv,vv,Tv,Av,Nv,Cv,Rv,Ov,_v,Dv,Fv,Mv,Uv,$v,Wv,zv,Pv,jv,Bv,Gv,qv,Hv,Yv,Kv,Xv,Jv,Zv,Qv,eT,tT,nT,sT,iT,aT,lT,cT,pT,uT,hT,dT,mT,fT,yT,Eb,Eb,bT,xT,ST,IT,vT,TT,AT,NT,CT,RT,_b,_b,OT,ET,_T,kT,DT,FT,MT,UT,$T,WT,zT,PT,BT,jT,VT,GT,qT,HT,YT,KT,kb,kb,Db,Db,XT,ZT,JT,QT,eA,tA,sA,nA,iA,rA,oA,aA,lA];for(const e of SW)ky(e);let Fb;function Tt(){return Fb==null&&(Fb=mb().epsilon()),Fb}function ys(){return"channelsLast"}class Sn extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Sn.prototype)}}class Ns extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ns.prototype)}}class k extends Error{constructor(e){super(e);Object.setPrototypeOf(this,k.prototype)}}class ae extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ae.prototype)}}class Mb extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Mb.prototype)}}class IW extends Error{constructor(e){super(e);Object.setPrototypeOf(this,IW.prototype)}}function In(e,t){if(Array.isArray(e)){let s=[];for(let n=0;n<t;n++)s=s.concat(e);return s}else{const s=new Array(t);return s.fill(e),s}}function tn(e,t){if(!e)throw new Mb(t)}function Ub(e,t){let s=0;for(const n of e)n===t&&s++;return s}function jt(e){return e.length===1?e[0]:e}function He(e){return Array.isArray(e)?e:[e]}function vn(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2"),s=t.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return s[0]!=="_"?s:"private"+s}function Pi(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,s)=>s.toUpperCase())}let Tn={};function Ml(e){if(e==null)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function $b(e){if(e==null||typeof e!="object")return;if(Array.isArray(e))e.forEach(t=>$b(t));else{const t=Object.keys(e);for(const s of t){const n=e[s];n!=null&&typeof n=="object"&&(!Array.isArray(n)&&n.type==="ndarray"&&typeof n.value=="number"?e[s]=n.value:$b(n))}}}function fi(e,t={},s={},n="object",i=!1){if(typeof e=="string"){const r=e;let o;if(r in s)o=s[r];else if(r in Tn)o=Tn[r];else if(o=t[r],o==null)throw new k(`Unknown ${n}: ${e}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{const r=e;if(r.className==null||r.config==null)throw new k(`${n}: Improper config format: ${JSON.stringify(r)}.
'className' and 'config' must set.`);const o=r.className;let a,l;if(o in s?[a,l]=s[o]:o in Tn?[a,l]=Tn.className:o in t&&([a,l]=t[o]),a==null)throw new k(`Unknown ${n}: ${o}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){const c={};for(const d of Object.keys(Tn))c[d]=Tn[d];for(const d of Object.keys(s))c[d]=s[d];const p=r.config;p.customObjects=c;const u=Object.assign({},Tn);for(const d of Object.keys(s))Tn[d]=s[d];$b(r.config);const h=l(a,r.config,s,i);return Tn=Object.assign({},u),h}else{const c=Object.assign({},Tn);for(const u of Object.keys(s))Tn[u]=s[u];const p=new a(r.config);return Tn=Object.assign({},c),p}}}function vW(e,t){return e<t?-1:e>t?1:0}function Qp(e,t){return-1*vW(e,t)}function An(e){if(e==null)return e;const t=[];for(const s of e)t.indexOf(s)===-1&&t.push(s);return t}function cA(e){if(e==null)throw new k(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Bi(e,t,s){if(s==null)return;if(e.indexOf(s)<0)throw new k(`${s} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function Md(e,t,s=0,n=Infinity){return tn(s>=0),tn(n>=s),Array.isArray(e)&&e.length>=s&&e.length<=n&&e.every(i=>typeof i===t)}function yt(e,t){Array.isArray(e)?(N.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((s,n)=>yt(s,`element ${n+1} of ${t}`))):N.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${pA(e)}.`)}function pA(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>pA(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function uA(e,t){let s=N.now(),n;const i=(...r)=>{const o=N.now();return o-s<t||(s=o,n=e(...r)),n};return i}function Ud(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Wb(e,t){return C(()=>Je(te(R(e,e),t,!0)))}class eu extends V.Serializable{getConfig(){return{}}}class $d extends eu{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return C(()=>{const t=Wb(e,this.axis),s=xt(t,0,this.maxValue);return R(e,Z(s,$(Tt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}$d.className="MaxNorm";V.registerClass($d);class Wd extends eu{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return C(()=>Z(e,$(Tt(),Wb(e,this.axis))))}getConfig(){return{axis:this.axis}}}Wd.className="UnitNorm";V.registerClass(Wd);class zd extends eu{apply(e){return Fe(e)}}zd.className="NonNeg";V.registerClass(zd);class Pd extends eu{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return C(()=>{const t=Wb(e,this.axis),s=$(R(this.rate,xt(t,this.minValue,this.maxValue)),R(1-this.rate,t));return R(e,Z(s,$(Tt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Pd.className="MinMaxNorm";V.registerClass(Pd);const hA={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ot(e){return Ml(e)}function dA(e,t={}){return fi(e,V.SerializationMap.getMap().classNameMap,t,"constraint")}function at(e){if(e==null)return null;if(typeof e=="string"){const t=e in hA?hA[e]:e,s={className:t,config:{}};return dA(s)}else return e instanceof eu?e:dA(e)}const zb={};Ee(zb,{maxNorm:()=>TW,minMaxNorm:()=>CW,nonNeg:()=>NW,unitNorm:()=>AW});function TW(e){return new $d(e)}function AW(e){return new Wd(e)}function NW(){return new zd}function CW(e){return new Pd(e)}const mA=["channelsFirst","channelsLast"],fA=["valid","same","causal"],gA=["max","avg"],yA=["sum","mul","concat","ave"];const Ul=new Map;function lt(e){Bi(mA,"DataFormat",e)}function bs(e){Bi(fA,"PaddingMode",e)}function Pb(e){Bi(gA,"PoolMode",e)}const tu=[],bA="/";function zn(e,t){tu.push(e);try{const s=t();return tu.pop(),s}catch(s){throw tu.pop(),s}}function RW(){return tu.length===0?"":tu.join(bA)+bA}function Bd(e){if(!wA(e))throw new Error("Not a valid tensor name: '"+e+"'");return RW()+e}function jd(e){if(!wA(e))throw new Error("Not a valid tensor name: '"+e+"'");Ul.has(e)||Ul.set(e,0);const t=Ul.get(e);if(Ul.set(e,Ul.get(e)+1),t>0){const s=`${e}_${t}`;return Ul.set(s,1),s}else return e}const OW=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function wA(e){return!!e.match(OW)}function xA(e){return e===parseInt(e.toString(),10)}function Nn(e,t,s){t==null&&(t=0),s==null&&(s=e.length);let n=1;for(let i=t;i<s;++i)n*=e[i];return n}function LA(e){return e=Array.isArray(e)?new Float32Array(e):e,Oe(e)}function fa(e){return Ui(LA(e)).dataSync()[0]}function Pn(e){return Lt(LA(e)).dataSync()[0]}function cs(e,t){if(t<e)throw new k(`end (${t}) < begin (${e}) is forbidden.`);const s=[];for(let n=e;n<t;++n)s.push(n);return s}function ji(e,t){return e.asType(t)}function Vi(e,t=-1){const s=e.shape.slice();return t<0&&(t=s.length+t+1),s.splice(t,0,1),e.reshape(s)}function SA(e,t){return C(()=>{if(e.shape.length!==2)throw new k(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);const s=Vi(e,1);return Vd(s,[1,t,1])})}function IA(e){const t=[Nn(e.shape)];return e.reshape(t)}function vA(e){if(e.rank<=1)throw new k(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Nn(e.shape,1)];return e.reshape(t)}function Gi(e,t,s){return C(()=>{switch(e.rank){case 1:return _l(e,t,s);case 2:return Hp(e,[t,0],[s,e.shape[1]]);case 3:return to(e,[t,0,0],[s,e.shape[1],e.shape[2]]);case 4:return ia(e,[t,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3]]);case 5:return he(e,[t,0,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return he(e,[t,0,0,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new k(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Bb(e,t,s){return C(()=>{switch(e.rank){case 1:return _l(e,t,s);case 2:return Hp(e,[0,t],[e.shape[0],s]);case 3:return to(e,[0,0,t],[e.shape[0],e.shape[1],s]);case 4:return ia(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],s]);default:throw new k(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function su(e,t,s,n){return C(()=>{switch(e.rank){case 1:return _l(e,t,s);case 2:switch(n){case 1:return Gi(e,t,s);case 2:return Bb(e,t,s);default:throw new k(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return Gi(e,t,s);case 2:return to(e,[0,t,0],[e.shape[0],s,e.shape[2]]);case 3:return Bb(e,t,s);default:throw new k(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return Gi(e,t,s);case 2:return ia(e,[0,t,0,0],[e.shape[0],s,e.shape[2],e.shape[3]]);case 3:return ia(e,[0,0,t,0],[e.shape[0],e.shape[1],s,e.shape[3]]);case 4:return Bb(e,t,s);default:throw new k(`The axis is not within the rank of the tensor ${n}`)}default:throw new k(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function $l(e,t=-1){let s;return t<0&&(s=e[0].rank,s!==0?t=s:t=0),t===e[0].rank&&(t=-1),be(e,t)}function jb(e,t){switch(e.rank){case 1:return Zh([e,t]);case 2:return Qh([e,t],0);case 3:return ed([e,t],0);case 4:return td([e,t],0);default:throw new k(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Vd(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new k(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return $s(e,t)}function Wl(e,t=0,s=1,n,i){return qp(e,t,s,n,i)}function Cn(e,t,s,n){if(e.rank<2||t.rank<2)throw new ae(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){const i=e.shape.slice(-1)[0],r=t.shape.slice(-2)[0];if(i!==r)throw new ae(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2){const i=!1,r=!1;return xn.matMul({a:e,b:t,transposeA:i,transposeB:r,bias:n?Vb(e.rank,n,ys()):null,activation:s})}else{const i=e.shape.slice(),r=i.pop();e=e.reshape([-1,r]);const o=t.shape.slice(),a=o.pop(),l=o.pop(),c=[...o,a],p=Array.from({length:t.rank},(m,f)=>f===0?t.rank-2:f<=t.rank-2?f-1:f);t=t.transpose(p).reshape([l,-1]);const u=[...i,...c],h=!1,d=!1;return xn.matMul({a:e,b:t,transposeA:h,transposeB:d,bias:n?Vb(e.rank,n,ys()):null,activation:s}).reshape(u)}}function Gd(e,t,s){return C(()=>(Array.isArray(t)?t=Oe(t,"int32"):t=t.toInt(),hi(e,t,s)))}function ga(e){return R(e,e)}function Vb(e,t,s){const n=t.shape;if(t.rank!==1&&t.rank!==e)throw new k(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(s==="channelsFirst")return n.length===1?t.reshape([1,n[0],1,1,1]):t.reshape([1,n[3],n[0],n[1],n[2]]);if(s==="channelsLast")return n.length===1?t.reshape([1,1,1,1,n[0]]):t.reshape([1].concat(n))}else if(e===4){if(s==="channelsFirst")return n.length===1?t.reshape([1,n[0],1,1]):t.reshape([1,n[2],n[0],n[1]]);if(s==="channelsLast")return n.length===1?t.reshape([1,1,1,n[0]]):t.reshape([1].concat(n))}else if(e===3){if(s==="channelsFirst")return n.length===1?t.reshape([1,n[0],1]):t.reshape([1,n[1],n[0]]);if(s==="channelsLast")return n.length===1?t.reshape([1,1,n[0]]):t.reshape([1].concat(n))}else if(e<3)return t;throw new k(`Unsupported input rank by biasAdd: ${t.rank}`)}function Cs(e,t,s){return C(()=>(s==null&&(s=ys()),lt(s),e.add(Vb(e.rank,t,s))))}function TA(e,t=1){if(t!==1)throw new ae(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return gn(e)}function AA(e){return C(()=>Z(e,et(e).add(1)))}function qd(e,t,s,n){return C(()=>Tb(e,t,s,n))}function NA(e){return C(()=>{const t=$(.5,R(.2,e));return xt(t,0,1)})}function lo(e,t,s=!1){return s?e():t()}const CA=["fanIn","fanOut","fanAvg"],RA=["normal","uniform","truncatedNormal"];function EW(e){Bi(CA,"FanMode",e)}function _W(e){Bi(RA,"Distribution",e)}class zs extends V.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Hd extends zs{apply(e,t){return ye(e,t)}}Hd.className="Zeros";V.registerClass(Hd);class zl extends zs{apply(e,t){return Kt(e,t)}}zl.className="Ones";V.registerClass(zl);class Yd extends zs{constructor(e){super();if(typeof e!="object")throw new k(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new k(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return C(()=>R(j(this.value),Kt(e,t)))}getConfig(){return{value:this.value}}}Yd.className="Constant";V.registerClass(Yd);class Kd extends zs{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return wn(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Kd.className="RandomUniform";V.registerClass(Kd);class Xd extends zs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ae(`randomNormal does not support dType ${t}.`);return Wl(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Xd.className="RandomNormal";V.registerClass(Xd);class Jd extends zs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ae(`truncatedNormal does not support dType ${t}.`);return ro(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Jd.className="TruncatedNormal";V.registerClass(Jd);class Zd extends zs{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return C(()=>{if(e.length!==2||e[0]!==e[1])throw new k("Identity matrix initializer can only be used for 2D square matrices.");return R(this.gain,sa(e[0]))})}getConfig(){return{gain:this.gain}}}Zd.className="Identity";V.registerClass(Zd);function kW(e,t="channelsLast"){let s,n;if(lt(t),e.length===2)s=e[0],n=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){const i=Nn(e,2);s=e[1]*i,n=e[0]*i}else if(t==="channelsLast"){const i=Nn(e,0,e.length-2);s=e[e.length-2]*i,n=e[e.length-1]*i}}else{const i=Nn(e);s=Math.sqrt(i),n=Math.sqrt(i)}return[s,n]}class ws extends zs{constructor(e){super();if(e.scale<0)throw new k(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,EW(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,_W(this.distribution),this.seed=e.seed}apply(e,t){const s=kW(e),n=s[0],i=s[1];let r=this.scale;if(this.mode==="fanIn"?r/=Math.max(1,n):this.mode==="fanOut"?r/=Math.max(1,i):r/=Math.max(1,(n+i)/2),this.distribution==="normal"){const o=Math.sqrt(r);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ae(`${this.getClassName()} does not support dType ${t}.`);return ro(e,0,o,t,this.seed)}else{const o=Math.sqrt(3*r);return wn(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}ws.className="VarianceScaling";V.registerClass(ws);class nu extends ws{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ws.className}}nu.className="GlorotUniform";V.registerClass(nu);class iu extends ws{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ws.className}}iu.className="GlorotNormal";V.registerClass(iu);class ru extends ws{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ws.className}}ru.className="HeNormal";V.registerClass(ru);class ou extends ws{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ws.className}}ou.className="HeUniform";V.registerClass(ou);class au extends ws{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ws.className}}au.className="LeCunNormal";V.registerClass(au);class lu extends ws{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ws.className}}lu.className="LeCunNormal";V.registerClass(lu);class Qd extends zs{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new ae("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return C(()=>{if(e.length<2)throw new ae("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);const s=e[0]>e[1]?[e[1],e[0]]:e,n=Wl(s,0,1,"float32");let i=Cb.gramSchmidt(n);return e[0]>e[1]&&(i=i.transpose()),R(this.gain,i)})}getConfig(){return{gain:this.gain,seed:this.seed}}}Qd.className="Orthogonal";V.registerClass(Qd);const OA={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function EA(e,t={}){return fi(e,V.SerializationMap.getMap().classNameMap,t,"initializer")}function Ze(e){return Ml(e)}function je(e){if(typeof e=="string"){const t=e in OA?OA[e]:e;if(t==="GlorotNormal")return new iu;if(t==="GlorotUniform")return new nu;if(t==="HeNormal")return new ru;if(t==="HeUniform")return new ou;if(t==="LeCunNormal")return new au;if(t==="LeCunUniform")return new lu;{const s={};return s.className=t,s.config={},EA(s)}}else return e instanceof zs?e:EA(e)}const Gb={};Ee(Gb,{constant:()=>MW,glorotNormal:()=>jW,glorotUniform:()=>BW,heNormal:()=>VW,heUniform:()=>GW,identity:()=>zW,leCunNormal:()=>qW,leCunUniform:()=>HW,ones:()=>FW,orthogonal:()=>YW,randomNormal:()=>$W,randomUniform:()=>UW,truncatedNormal:()=>WW,varianceScaling:()=>PW,zeros:()=>DW});function DW(){return new Hd}function FW(){return new zl}function MW(e){return new Yd(e)}function UW(e){return new Kd(e)}function $W(e){return new Xd(e)}function WW(e){return new Jd(e)}function zW(e){return new Zd(e)}function PW(e){return new ws(e)}function BW(e){return new nu(e)}function jW(e){return new iu(e)}function VW(e){return new ru(e)}function GW(e){return new ou(e)}function qW(e){return new au(e)}function HW(e){return new lu(e)}function YW(e){return new Qd(e)}let KW=0;function em(){return KW++}const tm={};function co(e=""){return e in tm||(tm[e]=0),tm[e]+=1,e+tm[e].toString()}function sm(e){return Array.isArray(e)&&Array.isArray(e[0])}function Pl(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function we(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new k(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function Ue(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new k(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Bl(e){let t=0;for(const s of e)s.shape.length===0?t+=1:t+=s.shape.reduce((n,i)=>n*i);return t}const _A="Variable";class nm{constructor(e,t="float32",s=_A,n=!0,i=null){this.dtype=t??"float32",this.shape=e.shape,this.id=em(),s=s??_A,this.originalName=Bd(s),this.name=jd(this.originalName),this.trainable_=n,this.constraint=i,this.val=Ad(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),XW(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function XW(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function cu(e){return e.map(t=>t.read())}function jl(e){e.forEach(t=>{const s=t[0];s.write(t[1])})}class st{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class xs{constructor(e,t,s,n,i,r,o){this.dtype=e,this.shape=t,this.sourceLayer=s,this.inputs=n,this.callArgs=i,this.outputTensorIndex=o,this.id=em(),r!=null&&(this.originalName=Bd(r),this.name=jd(this.originalName)),this.rank=t.length}}let JW=0;class ya{constructor(e,t){this.callArgs=t,this.id=JW++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const s of e.inboundLayers)s!=null&&s.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let ZW=0;class Le extends V.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=ZW++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const s=this.getClassName();t=vn(s)+"_"+co(s)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let s;if(e.batchInputShape!=null)s=e.batchInputShape;else if(e.inputShape!=null){let i=null;e.batchSize!=null&&(i=e.batchSize),s=[i].concat(e.inputShape)}this.batchInputShape=s;let n=e.dtype;n==null&&(n=e.inputDType),n==null&&(n="float32"),this.dtype=n}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new Ns(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new k(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return jt(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return jt(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Sn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new Sn(`Layer ${this.name} is not connected, no input to return.`);return jt(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Sn(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Sn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return jt(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=He(e),this.inputSpec==null||this.inputSpec.length===0)return;const t=He(this.inputSpec);if(e.length!==t.length)throw new k(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let s=0;s<e.length;s++){const n=e[s],i=t[s];if(i==null)continue;const r=n.rank;if(i.ndim!=null&&r!==i.ndim)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${r}`);if(i.maxNDim!=null&&r>i.maxNDim)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${r}`);if(i.minNDim!=null&&r<i.minNDim)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected min_ndim=${i.minNDim}, found ndim=${r}.`);if(i.dtype!=null&&n.dtype!==i.dtype)throw new k(`Input ${s} is incompatible with layer ${this.name} : expected dtype=${i.dtype}, found dtype=${n.dtype}.`);if(i.axes){const o=n.shape;for(const a in i.axes){const l=Number(a),c=i.axes[a],p=l>=0?o[l]:o[o.length+l];if(c!=null&&[c,null].indexOf(p)===-1)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${o}.`)}}if(i.shape!=null)for(let o=0;o<i.shape.length;++o){const a=i.shape[o],l=n.shape[o];if(a!=null&&l!=null&&a!==l)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected shape=${i.shape}, found shape=${n.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const s=He(e);let n=!0;for(const r of s)if(!(r instanceof xs)){n=!1;break}let i=!0;for(const r of s)if(r instanceof xs){i=!1;break}if(n===i)throw new k("Arguments to apply() must be all SymbolicTensors or all Tensors");return zn(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const r=[];for(const o of He(e))r.push(o.shape);this.build(jt(r)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&i&&(this._refCount=1)}if(this.assertInputCompatibility(e),i){let r=this.call(e,t);const o=He(r),a=[];for(let l of o)s.indexOf(l)!==-1&&(l=l.clone()),a.push(l);if(r=jt(a),this.activityRegularizer!=null)throw new ae("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}else{const r=QW(e),o=this.computeOutputShape(r);let a;const l=ez(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?r[0]:r),o!=null&&o.length>0&&Array.isArray(o[0])?a=o.map((c,p)=>new xs(l,c,this,He(e),t,this.name,p)):a=new xs(l,o,this,He(e),t,this.name),this.addInboundNode(e,a,null,null,r,o,t),this._refCount++,this.activityRegularizer!=null)throw new ae("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape==null)return;if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((s,n)=>{s!=null&&e[n]!=null&&e[n]!==s&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new Sn(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const s=JSON.stringify(t.outputShapes);e.indexOf(s)===-1&&e.push(s)}if(e.length===1){const t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new Sn(`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 Ns(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Bl(this.weights)}build(e){this.built=!0}getWeights(e=!1){return cu(e?this.trainableWeights:this.weights)}setWeights(e){C(()=>{const t=this.weights;if(t.length!==e.length)throw new k(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;const s=[],n=cu(t);for(let i=0;i<n.length;++i){const r=n[i],o=t[i],a=e[i];if(!N.arraysEqual(r.shape,a.shape))throw new k(`Layer weight shape ${r.shape} not compatible with provided weight shape ${a.shape}`);s.push([o,a])}jl(s)})}addWeight(e,t,s,n,i,r,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new k(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),s==null&&(s="float32"),this.fastWeightInitDuringBuild&&(n=je("zeros"));const a=n.apply(t,s),l=new nm(a,s,e,r,o);return a.dispose(),i!=null&&this.addLoss(()=>i.apply(l.read())),r==null&&(r=!0),r?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){if(e==null||Array.isArray(e)&&e.length===0)return;e=He(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e)}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(s=>{if(s!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,s,n,i,r,o=null){const a=He(e);t=He(t),s=He(s),n=He(n),i=Pl(i),r=Pl(r);const l=[],c=[],p=[];for(const u of a)l.push(u.sourceLayer),c.push(u.nodeIndex),p.push(u.tensorIndex);new ya({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:p,inputTensors:a,outputTensors:t,inputMasks:s,outputMasks:n,inputShapes:i,outputShapes:r},o);for(let u=0;u<t.length;u++)t[u].sourceLayer=this,t[u].nodeIndex=this.inboundNodes.length-1,t[u].tensorIndex=u}getConfig(){const e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)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(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function QW(e){e=He(e);const t=[];for(const s of e)t.push(s.shape);return jt(t)}function ez(e){return"float32"}function qb(e,t,s){if((t==null||s!=null&&s>0)&&(t=e.sourceLayer,s=e.nodeIndex),t.inboundNodes.length===0)return[e];{const n=t.inboundNodes[s];if(n.inboundLayers.length===0)return n.inputTensors;{const i=[];for(let r=0;r<n.inboundLayers.length;r++){const o=n.inputTensors[r],a=n.inboundLayers[r],l=n.nodeIndices[r],c=qb(o,a,l);for(const p of c)i.indexOf(p)===-1&&i.push(p)}return i}}}class qi extends Le{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:co("input").toString()});if(e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new k("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new k("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new k("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const s=e.dtype||"float32";this.batchInputShape=t,this.dtype=s,this.inputSpec=[{shape:t}];const n=new xs(this.dtype,this.batchInputShape,this,[],{},this.name);n.nodeIndex=0,n.tensorIndex=0,new ya({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[n],outputTensors:[n],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new k(`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}}}qi.className="InputLayer";V.registerClass(qi);function im(e){if(e.batchShape==null&&e.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(e.batchShape!=null&&e.shape!=null)throw new k("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let s=e.dtype;s==null&&(s="float32");const n=new qi({batchInputShape:t,name:e.name,dtype:s,sparse:e.sparse}),i=n.inboundNodes[0].outputTensors;return i[0]}async function gi(e){if(e==null)return;const t=[],s=[],n=[];for(const i in e){const r=e[i];if(typeof r!="number"){const o=r;t.push(o.data()),s.push(i),n.push(o)}}if(t.length>0){const i=await Promise.all(t);for(let r=0;r<i.length;++r)e[s[r]]=i[r][0];ce(n)}}function rm(e){if(e==null)return;for(const t in e){const s=e[t];typeof s!="number"&&s.dispose()}}var kA;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(kA||(kA={}));const tz=125;class ba{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class Hb{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(const s of this.callbacks)await s.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(const s of this.callbacks)await s.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(const s of this.callbacks)await s.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(const s of this.callbacks)await s.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class sz extends ba{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});const s=t.size==null?0:t.size;this.seen+=s;for(const n in t){const i=t[n];if(typeof i=="number")this.totals.hasOwnProperty(n)||(this.totals[n]=0),this.totals[n]=this.totals[n]+i*s;else{let r;n in this.totals?r=this.totals[n]:this.totals[n]=0;const o=C(()=>$(this.totals[n],R(i,s)));this.totals[n]=o,r!=null&&r.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(const s of this.params.metrics){if(this.totals[s]==null)continue;typeof this.totals[s]=="number"?t[s]=this.totals[s]/this.seen:C(()=>{const n=R(Z(1,this.seen),this.totals[s]);t[s]=n,this.totals[s].dispose(),pt(t[s])})}}}class Yb extends ba{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(const s in t)this.history[s]==null&&(this.history[s]=[]),this.history[s].push(t[s])}async syncData(){const e=[],t=[],s=[];for(const i in this.history){const r=this.history[i];for(let o=0;o<r.length;++o)if(typeof r[o]!="number"){const a=r[o];e.push(a.data()),t.push(i),s.push(o)}}const n=await Promise.all(e);for(let i=0;i<n.length;++i){const r=this.history[t[i]][s[i]];r.dispose(),this.history[t[i]][s[i]]=n[i][0]}}}class Kb extends ba{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=tz),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");N.isNumber(this.yieldEvery)&&(this.maybeWait=uA(this.maybeWait.bind(this),this.yieldEvery)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,s){const n=[];this.yield!=null&&(await gi(s),n.push(this.yield(e,t,s))),n.push(Zp()),await Promise.all(n)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await gi(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const s=[];this.epochEnd!=null&&(await gi(t),s.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&s.push(Zp()),await Promise.all(s)}async onBatchBegin(e,t){this.batchBegin!=null&&(await gi(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const s=[];this.batchEnd!=null&&(await gi(t),s.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?s.push(Zp()):N.isNumber(this.yieldEvery)&&s.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(s)}async onTrainBegin(e){this.trainBegin!=null&&(await gi(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await gi(e),await this.trainEnd(e))}}function om(e,t){if(e==null&&(e={}),e instanceof ba)return[e];if(Array.isArray(e)&&e[0]instanceof ba)return e;const s=He(e);return s.map(n=>new Kb(n,t))}class sn{constructor(){}static registerCallbackConstructor(e,t){N.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),sn.checkForDuplicate(t),sn.constructors[e]==null&&(sn.constructors[e]=[]),sn.constructors[e].push(t)}static checkForDuplicate(e){for(const t in sn.constructors){const s=sn.constructors[+t];s.forEach(n=>{if(n===e)throw new k("Duplicate callback constructor.")})}}static clear(){sn.constructors={}}static createCallbacks(e){const t=[];for(const s in sn.constructors){const n=+s;e>=n&&t.push(...sn.constructors[n])}return t.map(s=>new s)}}sn.constructors={};function am(e,t,s,n,i,r,o,a,l){const c=new Yb,p=[new sz,...sn.createCallbacks(t)];e!=null&&p.push(...e),p.push(c);const u=new Hb(p);return u.setParams({epochs:s,initialEpoch:n,samples:i,steps:r,batchSize:o,verbose:t,doValidation:a,metrics:l}),{callbackList:u,history:c}}function Ls(e,t={},s=!1){return fi(e,V.SerializationMap.getMap().classNameMap,t,"layer",s)}function pu(e,t){return C(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));const s=te(ga(e),t,!0),n=Wt(s.shape,Tt()),i=Je(Ht(s,n));return Z(e,i)})}function yi(e,t){return C(()=>Xe(ga(X(t,e)),-1))}function Vl(e,t){return C(()=>Xe(et(X(t,e)),-1))}function po(e,t){return C(()=>{const s=X(e,t),n=xt(et(e),Tt(),Number.MAX_VALUE),i=et(Z(s,n));return R(100,Xe(i,-1))})}function nz(e,t){return C(()=>{const s=xt(t,Tt(),Number.MAX_VALUE),n=zt($(1,s)),i=xt(e,Tt(),Number.MAX_VALUE),r=zt($(1,i));return Xe(ga(X(n,r)),-1)})}function iz(e,t){return C(()=>{const s=Ht(0,X(1,R(e,t)));return Xe(ga(s),-1)})}function rz(e,t){return C(()=>{const s=Ht(0,X(1,R(e,t)));return Xe(s,-1)})}function oz(e,t){return C(()=>{const s=te(R(e,t),-1),n=Lt(R(X(1,e),t),-1);return Ht(0,$(1,X(n,s)))})}function az(e,t){return C(()=>{const s=Math.log(2),n=X(t,e),i=X($(n,di(R(-2,n))),s);return Xe(i,-1)})}function wa(e,t,s=!1){return C(()=>{if(s)t=ts(t);else{const n=te(t,t.shape.length-1,!0);t=Z(t,n)}return t=xt(t,Tt(),1-Tt()),ke(te(R(e.toFloat(),zt(t)),t.shape.length-1))})}function Gl(e,t,s=!1){return C(()=>{const n=ui(IA(e)).toInt();t=xt(t,Tt(),1-Tt());const i=t.shape,r=pi(n,i[i.length-1]).reshape(i);return wa(r,t,s)})}function lz(e,t){if(!N.arraysEqual(e.shape,t.shape))throw new k(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return C(()=>{const s=t.relu(),n=t.abs().neg();return s.sub(t.mul(e)).add(n.exp().log1p())})}function ql(e,t){return C(()=>{let s;return s=xt(t,Tt(),1-Tt()),s=zt(Z(s,X(1,s))),Xe(lz(e,s),-1)})}function cz(e,t){return C(()=>{const s=xt(e,Tt(),1),n=xt(t,Tt(),1);return te(R(e,zt(Z(s,n))),-1)})}function pz(e,t){return C(()=>{const s=zt($(Tt(),t));return Xe(X(t,R(e,s)),-1)})}function uu(e,t){return C(()=>{const s=pu(e,-1),n=pu(t,-1),i=R(s,n);return ke(te(i,-1))})}const hu={meanSquaredError:yi,meanAbsoluteError:Vl,meanAbsolutePercentageError:po,meanSquaredLogarithmicError:nz,squaredHinge:iz,hinge:rz,categoricalHinge:oz,logcosh:az,categoricalCrossentropy:wa,sparseCategoricalCrossentropy:Gl,binaryCrossentropy:ql,kullbackLeiblerDivergence:cz,poisson:pz,cosineProximity:uu};function lm(e){if(typeof e=="string"){if(e in hu)return hu[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new k(t)}else return e}function du(e,t){return C(()=>{const s=R(.5,Ot(t)),n=ji(Ut(t,s),e.dtype);return Xe(as(e,n),-1)})}function mu(e,t){return C(()=>ji(as(Qo(e,-1),Qo(t,-1)),"float32"))}function DA(e,t){return C(()=>Yt(e.equal(1),t.equal(1)).sum().cast("float32"))}function uz(e,t){return C(()=>Yt(e.equal(1),t.equal(0)).sum().cast("float32"))}function hz(e,t){return C(()=>Yt(e.equal(0),t.equal(1)).sum().cast("float32"))}function Xb(e,t){return C(()=>{const s=DA(e,t),n=hz(e,t),i=s.add(n);return mt(Ut(i,0),s.div(i),0).cast("float32")})}function FA(e,t){return C(()=>{const s=DA(e,t),n=uz(e,t),i=s.add(n);return mt(Ut(i,0),s.div(i),0).cast("float32")})}function cm(e,t){return ql(e,t)}function pm(e,t){return e.rank===t.rank&&(e=e.squeeze([e.rank-1])),t=t.argMax(-1),t.dtype!==e.dtype&&(t=t.asType(e.dtype)),as(e,t).asType("float32")}const dz=yi,mz=yi,fz=Vl,gz=Vl,yz=po,bz=po,fu=wa,wz=uu,Jb=Gl,um={binaryAccuracy:du,categoricalAccuracy:mu,precision:Xb,categoricalCrossentropy:fu,sparseCategoricalCrossentropy:Jb,mse:dz,MSE:mz,mae:fz,MAE:gz,mape:yz,MAPE:bz,cosine:wz};function MA(e){if(typeof e=="string"&&e in um)return um[e];if(typeof e!="string"&&e!=null)return e;throw new k(`Unknown metric ${e}`)}function gu(e){if(tn(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(const s of Object.keys(hu))if(hu[s]===e){t=s;break}if(t!==void 0)return t;for(const s of Object.keys(um))if(um[s]===e){t=s;break}return t!==void 0?t:e.name}}function UA(e){const t={Adagrad:()=>ao.adagrad(.01),Adadelta:()=>ao.adadelta(1,.95,Tt()),Adam:()=>ao.adam(.001,.9,.999,Tt()),Adamax:()=>ao.adamax(.002,.9,.999,Tt(),0),RMSProp:()=>ao.rmsprop(.001,.9,0,Tt()),SGD:()=>ao.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new k(`Unknown Optimizer ${e}`)}const $A=1*1024*1024;function Qb(e,t,s=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Zb(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(s){const n=JSON.stringify(e);n.length>$A&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${$A}.`)}}function Zb(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const s of t){if(typeof s!="string")return!1;if(!Zb(e[s]))return!1}return!0}else if(Array.isArray(e)){for(const t of e)if(!Zb(t))return!1;return!0}else return!1;else{const t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function WA(e,t,s,n=console.log){const i=Lz(e),r=["Layer (type)","Output shape","Param #"];i?(t=t||65,s=s||[.45,.85,1]):(t=t||98,s=s||[.33,.55,.67,1]),s[s.length-1]<=1&&(s=s.map(p=>Math.floor(t*p)));let o;if(!i){r.push("Receives inputs"),o=[];for(const p in e.nodesByDepth)o.push(...e.nodesByDepth[p])}n("_".repeat(t)),hm(r,s,n),n("=".repeat(t));const a=e.layers;for(let p=0;p<a.length;++p)i?Sz(a[p],s,n):Iz(a[p],s,o,n),n((p===a.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const l=xz(e),c=Bl(e.nonTrainableWeights);n(`Total params: ${l+c}`),n(`Trainable params: ${l}`),n(`Non-trainable params: ${c}`),n("_".repeat(t))}function xz(e){let t;return e.collectedTrainableWeights!=null?t=Bl(e.collectedTrainableWeights):t=Bl(e.trainableWeights),t}function Lz(e){let t=!0;const s=[],n=[];for(const i in e.nodesByDepth)s.push(e.nodesByDepth[i]);for(const i of s){if(i.length>1||i.length===1&&i[0].inboundLayers.length>1){t=!1;break}n.push(...i)}if(t)for(const i of e.layers){let r=!1;for(const o of i.inboundNodes)if(n.indexOf(o)!==-1)if(r){t=!1;break}else r=!0;if(!t)break}return t}function hm(e,t,s=console.log){let n="";for(let i=0;i<e.length;++i)i>0&&(n=n.slice(0,n.length-1)+" "),n+=e[i],n=n.slice(0,t[i]),n+=" ".repeat(t[i]-n.length);s(n)}function Sz(e,t,s){let n;try{n=JSON.stringify(e.outputShape)}catch(a){n="multiple"}const i=e.name,r=e.getClassName(),o=[`${i} (${r})`,n,e.countParams().toString()];hm(o,t,s)}function Iz(e,t,s,n){let i;try{i=JSON.stringify(e.outputShape)}catch(p){i="multiple"}const r=[];for(const p of e.inboundNodes){if(s!=null&&s.length>0&&s.indexOf(p)===-1)continue;for(let u=0;u<p.inboundLayers.length;++u){const h=p.inboundLayers[u].name,d=p.nodeIndices[u],m=p.tensorIndices[u];r.push(`${h}[${d}][${m}]`)}}const o=e.name,a=e.getClassName(),l=r.length===0?"":r[0],c=[`${o} (${a})`,i,e.countParams().toString(),l];hm(c,t,n);for(let p=1;p<r.length;++p)hm(["","","",r[p]],t,n)}function zA(e,t,s){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof s=="string"}function xa(e,t){if(e===null)return null;if(typeof e=="string")return Pi(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){const s=[],n=e.length;for(let i=0;i<n;++i){const r=e[i];zA(t,i,r)?s.push(r):s.push(xa(r,t))}return s}else{const s={};for(const n of Object.keys(e)){const i=e[n];if(n==="name"&&typeof i=="string")s[n]=i;else{const r=Pi(n);s[r]=xa(i,r)}}return s}}function dm(e,t){if(e==null)return null;if(typeof e=="string")return vn(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){const s=[],n=e.length;for(let i=0;i<n;++i){const r=e[i];zA(t,i,r)?s.push(r):s.push(dm(r,t))}return s}else{const s={};for(const n of Object.keys(e)){const i=e[n],r=vn(n);(n==="name"||n==="className")&&typeof i=="string"?s[r]=i:s[r]=dm(i,n)}return s}}const uo="2.6.0";function vz(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return G(t,e.dtype)}catch(s){throw new k(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}class Hi{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Hi)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,s){if(this.id2Value[e.id]==null)this.id2Value[e.id]=vz(e,t),this.name2Id[e.name]=e.id,s!=null&&(this.id2Mask[e.id]=s);else throw new k(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof xs){if(this.id2Value[e.id]==null)throw new k(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{const t=this.name2Id[e];if(t==null)throw new k(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof xs){if(this.id2Value[e.id]==null)throw new k(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{const t=this.name2Id[e];if(t==null)throw new k(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&ce(this.id2Mask)}}const ew={},PA={};function La(e,t,s,n){const i=s==null?!1:s.training,r=Array.isArray(e),o=r?e:[e],a=o.map(m=>m.name),l=[],c=t.names();for(const m of a)c.indexOf(m)!==-1?l.push(t.getValue(m)):l.push(null);n!=null&&(n.maxNumTensors=-Infinity,n.minNumTensors=Infinity);const p=a.join(",")+"|"+t.names().join(",");let u,h;if(ew[p]==null){const m=Tz(o,t);u=m.sorted,h=m.recipientCounts,ew[p]=u,PA[p]=h}u=ew[p],h={},i||Object.assign(h,PA[p]);const d=new Hi(t);for(let m=0;m<u.length;++m){if(n!=null){const D=pl().numTensors;D>n.maxNumTensors&&(n.maxNumTensors=D),D<n.minNumTensors&&(n.minNumTensors=D)}const f=u[m],g=f.sourceLayer;if(g instanceof qi)continue;const y=[],w=[],x=[];let T=!1;for(const D of f.inputs){const M=d.getValue(D),P=d.getMask(D);y.push(M),w.push(P),P!=null&&(T=!0),i||(h[D.name]--,h[D.name]===0&&!t.hasKey(D)&&a.indexOf(D.name)===-1&&!M.isDisposed&&D.sourceLayer.stateful!==!0&&x.push(M))}T&&(s=s||{},s.mask=w[0]);const A=He(g.apply(y,s));let _=null;g.supportsMasking&&(_=g.computeMask(y,w));const E=Az(f),F=Array.isArray(E)?E:[E];for(let D=0;D<F.length;++D){d.hasKey(F[D])||d.add(F[D],A[D],Array.isArray(_)?_[0]:_);const M=a.indexOf(F[D].name);M!==-1&&(l[M]=A[D])}i||ce(x)}return d.disposeMasks(),r?l:l[0]}function Tz(e,t){N.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let s=[],n={};if(e.length===1){const i=BA(e[0],t);s=i.sorted,n=i.recipientMap}else{const i=new Set;for(const r of e){const{sorted:o,recipientMap:a}=BA(r,t);for(const l of o)i.has(l.name)||(s.push(l),i.add(l.name));for(const l in a)n[l]==null&&(n[l]=new Set),a[l].forEach(c=>n[l].add(c))}}return{sorted:s,recipientCounts:Nz(n)}}function Nz(e){const t={};for(const s in e)t[s]=e[s].size;return t}function BA(e,t){const s=new Set,n=[],i={};for(const a of t.names())s.add(a);const r=[],o=[];for(r.push(e);r.length>0;){const a=r[r.length-1];if(s.has(a.name)){r.pop();continue}const l=o[o.length-1]===r.length-1;if(a.inputs.length===0||l)r.pop(),n.push(a),s.add(a.name),l&&o.pop();else{o.push(r.length-1);for(const c of a.inputs){if(i[c.name]==null&&(i[c.name]=new Set),i[c.name].add(a.name),s.has(c.name))continue;r.push(c)}}}return{sorted:n,recipientMap:i}}function Az(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let s=null;for(let n=0;n<e.sourceLayer.inboundNodes.length;++n)for(const i of e.sourceLayer.inboundNodes[n].outputTensors)if(i.id===e.id){s=n;break}t=e.sourceLayer.getOutputAt(s)}return t}class Bn extends Le{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){const y=this.getClassName().toLowerCase();this.name=co(y)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],An(this.inputs).length!==this.inputs.length)throw new k(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);An(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 w=y.sourceLayer,x=y.nodeIndex,T=y.tensorIndex;this.outputLayers.push(w),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(T)}for(const y of this.inputs){const w=y.sourceLayer,x=y.nodeIndex,T=y.tensorIndex;tn(x===0,"input layer has >1 nodes"),tn(T===0,"input layer has >1 tensors"),this.inputLayers.push(w),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(T)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){const w=this.inputLayers[y];if(!(w instanceof qi))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${w.getClassName()}.`);this.inputNames.push(w.name),this.feedInputShapes.push(w.batchInputShape),this.feedInputNames.push(w.name)}for(const y of this.outputLayers)this.outputNames.push(y.name);this.internalInputShapes=this.inputs.map(y=>y.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);const t={},s={},n={},i={},r={},o=[],a=(y,w,x,T,A,_)=>{(T==null||A==null||_==null)&&(T=y.sourceLayer,A=y.nodeIndex,_=y.tensorIndex);const E=T.inboundNodes[A];if(x.indexOf(E)!==-1)throw new Ns(`The tensor ${y.name} at layer "${T.name}" is part of a cycle.`);if(w.indexOf(E)!==-1)return;this.containerNodes.add(Bn.nodeKey(T,A)),T.id in r||(r[T.id]=Object.keys(r).length),x.indexOf(E)===-1&&x.push(E);const F=E.inboundLayers.length;for(let D=0;D<F;D++){const M=E.inputTensors[D],P=E.inboundLayers[D],B=E.nodeIndices[D],Y=E.tensorIndices[D];a(M,w,x,P,B,Y)}for(w.push(E);x.indexOf(E)>=0;)x.splice(x.indexOf(E),1);o.push(E)},l=[],c=[];for(const y of this.outputs)a(y,l,c);const p=o.slice().reverse();for(const y of p){s[y.id]=y,y.id in t||(t[y.id]=0);let w=t[y.id];const x=n[y.outboundLayer.id]==null?0:n[y.outboundLayer.id];w=Math.max(w,x),n[y.outboundLayer.id]=w,i[y.outboundLayer.id]=y.outboundLayer,t[y.id]=w;for(let T=0;T<y.inboundLayers.length;T++){const A=y.inboundLayers[T],_=y.nodeIndices[T],E=A.inboundNodes[_],F=t[E.id]==null?0:t[E.id];t[E.id]=Math.max(w+1,F),s[E.id]=E}}const u={};for(const y in t){const w=t[y];w in u||(u[w]=[]),u[w].push(s[y])}const h={};for(const y in n){const w=n[y];w in h||(h[w]=[]),h[w].push(i[y])}let d=Object.keys(h).map(y=>parseInt(y,10)).sort(Qp);this.layers=[];for(const y of d){const w=h[y];w.sort((x,T)=>{const A=r[x.id],_=r[T.id];return A<_?-1:A>_?1:0});for(const x of w)x instanceof Bn&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=h,d=Object.keys(u).map(y=>parseInt(y,10)).sort(Qp);const m=this.inputs.slice(),f=[];for(const y of d)for(const w of u[y]){const x=w.outboundLayer;if(x!=null){for(const T of w.inputTensors)if(m.indexOf(T)===-1)throw new Ns(`Graph disconnected: cannot obtain value for tensor ${T} at layer "${x.name}". The following previous layers were accessed without issue: ${f}`);for(const T of w.outputTensors)m.push(T);f.push(x.name)}}this.nodesByDepth=u;const g=this.layers.map(y=>y.name);for(const y of g){const w=g.filter(x=>x===y).length;if(w!==1)throw new Ns(`The name "${y}" is used ${w} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new ya({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(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(s=>s.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new k("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const s of this.layers)t.push(...s.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const s={};let n=0;for(const r of this.layers)for(const o of r.weights){if(s[o.originalName]!=null)throw new k(`Duplicate weight name: ${o.originalName}`);s[o.originalName]=o,n++}const i=[];for(const r in e){let o=r;if(s[r]==null){const a=r.split("/"),l=a.slice(0,-2).concat([a[a.length-1]]);o=l.join("/")}if(s[o]!=null)i.push([s[o],e[r]]);else if(t)throw new k(`Provided weight data has no target variable: ${r}`);delete s[o]}if(t){const r=[];for(const o in s)r.push(o);if(r.length>0)throw new k(`${r.length} of ${n} weights are not set: ${r}`)}jl(i)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${uo}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const s=dm(this.updatedConfig());return t?JSON.stringify(s):s}call(e,t){return C(()=>{e=He(e);const s=new Hi;for(let n=0;n<this.inputs.length;++n)s.add(this.inputs[n],e[n]);return La(this.outputs,s,t)})}computeMask(e,t){return C(()=>{e=He(e);let s;return t==null?s=In(null,e.length):s=He(t),this.runInternalGraph(e,s)[1]})}computeOutputShape(e){const t=Pl(e);if(t.length!==this.inputLayers.length)throw new k(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const s={};for(let o=0;o<t.length;o++){const a=this.inputLayers[o],l=t[o],c=a.name+"_0_0";s[c]=l}const n=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(Qp);if(n.length>1)for(const o of n){const a=this.nodesByDepth[o];for(const l of a){const c=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(c.id)!==-1)continue;const p=[];for(let m=0;m<l.inboundLayers.length;m++){const f=l.inboundLayers[m],g=l.nodeIndices[m],y=l.tensorIndices[m],w=`${f.name}_${g}_${y}`,x=s[w];p.push(x)}const u=c.computeOutputShape(jt(p)),h=Pl(u),d=c.inboundNodes.indexOf(l);for(let m=0;m<h.length;m++){const f=`${c.name}_${d}_${m}`;s[f]=h[m]}}}const i=[],r=[];for(let o=0;o<this.outputLayers.length;o++){const a=this.outputLayers[o],l=this.outputLayersNodeIndices[o],c=this.outputLayersTensorIndices[o],p=`${a.name}_${l}_${c}`;r.push(p)}for(let o=0;o<r.length;o++){const a=r[o];tn(a in s),i.push(s[a])}return jt(i)}runInternalGraph(e,t){t==null&&(t=In(null,e.length));const s={};for(let a=0;a<this.inputs.length;++a){const l=this.inputs[a],c=e[a],p=t[a];s[l.id]=[c,p]}const n=Object.keys(this.nodesByDepth).map(a=>parseInt(a,10)).sort(Qp);for(const a of n){const l=this.nodesByDepth[a];for(const c of l){const p=c.outboundLayer,u=c.inputTensors,h=c.outputTensors,d=new Array;for(const m of u)m.id in s&&d.push(s[m.id]);if(d.length===u.length){let m={},f,g,y,w;if(c.callArgs!=null&&(m=c.callArgs),d.length===1){const[x,T]=d[0];m.mask==null&&(m.mask=T),y=He(p.call(x,m)),w=He(p.computeMask(x,T)),f=[x],g=[T]}else f=d.map(x=>x[0]),g=d.map(x=>x[1]),m.mask==null&&(m.mask=g),y=He(p.call(f,m)),w=He(p.computeMask(f,g));if(p.activityRegularizer)throw new ae("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x<h.length;++x){const T=h[x],A=y[x],_=w[x];s[T.id]=[A,_]}}}}const i=[],r=[],o=[];for(const a of this.outputs){tn(a.id in s,`Could not compute output ${a.name} : ${a.id}`);const[l,c]=s[a.id];o.push(l.shape),i.push(l),r.push(c)}return[i,r,o]}buildNodeConversionMap(e){const t={};let s;for(const n of this.layers){s=n instanceof Bn?1:0;for(let i=0;i<n.inboundNodes.length;i++){const r=Bn.nodeKey(n,i);this.containerNodes.has(r)&&(t[r]=s,s+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new k(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}else if(e==null)throw new k("Provide either a layer name or layer index");for(const s of this.layers)if(s.name===e)return s;throw new k(`No such layer: ${e}`)}calculateLosses(){return C(()=>{const e=[];for(const t of this.layers)for(let s=0;s<t.inboundNodes.length;++s){const n=Bn.nodeKey(t,s);this.containerNodes.has(n)&&e.push(...t.calculateLosses())}return e})}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),s=[];for(const r of this.layers){const o=r.getClassName(),a=r.getConfig(),l=[];for(let p=0;p<r.inboundNodes.length;p++){const u=r.inboundNodes[p],h=Bn.nodeKey(r,p);let d={};if(this.containerNodes.has(h)){if(u.callArgs)try{JSON.stringify(u.callArgs),d=u.callArgs}catch(m){console.warn(`Layer ${r.name} was passed non-serializable keyword arguments: ${u.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),d={}}if(u.inboundLayers.length>0){const m=[];for(let f=0;f<u.inboundLayers.length;f++){const g=u.inboundLayers[f],y=u.nodeIndices[f],w=u.tensorIndices[f],x=Bn.nodeKey(g,y);let T=t[x];T==null&&(T=0),m.push([g.name,T,w,d])}l.push(m)}}}const c={};c.name=r.name,c.className=o,c.config=a,c.inboundNodes=l,s.push(c)}e.layers=s;const n=[];for(let r=0;r<this.inputLayers.length;r++){const o=this.inputLayers[r],a=this.inputLayersNodeIndices[r],l=Bn.nodeKey(o,a);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);const p=this.inputLayersTensorIndices[r];n.push([o.name,c,p])}e.inputLayers=n;const i=[];for(let r=0;r<this.outputLayers.length;r++){const o=this.outputLayers[r],a=this.outputLayersNodeIndices[r],l=Bn.nodeKey(o,a);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);const p=this.outputLayersTensorIndices[r];i.push([o.name,c,p])}return e.outputLayers=i,e}static fromConfig(e,t,s={},n=!1){const i={},r={};function o(f,g){f.name in r?r[f.name].push(g):r[f.name]=[g]}function a(f,g){const y=[];let w;for(const x of g){const T=x[0],A=x[1],_=x[2];if(w=x[3]==null?{}:x[3],!(T in i)){o(f,g);return}const E=i[T];if(E.inboundNodes.length<=A){o(f,g);return}const F=E.inboundNodes[A];y.push(F.outputTensors[_])}y.length>0&&f.apply(jt(y),w)}function l(f){const g=f.name,y=Ls(f,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(n),i[g]=y;const w=f.inboundNodes;w.forEach(x=>{if(!(x instanceof Array))throw new k(`Corrupted configuration, expected array for nodeData: ${x}`);o(y,x)})}const c=t.name,p=t.layers;for(const f of p)l(f);for(;!cA(r);)for(const f of p){const g=i[f.name];if(g.name in r){const y=r[g.name];delete r[g.name];for(const w of y)a(g,w)}}const u=[],h=[],d=t.inputLayers;for(const f of d){const g=f[0],y=f[1],w=f[2];tn(g in i);const x=i[g],T=x.inboundNodes[y].outputTensors;u.push(T[w])}const m=t.outputLayers;for(const f of m){const g=f[0],y=f[1],w=f[2];tn(g in i);const x=i[g],T=x.inboundNodes[y].outputTensors;h.push(T[w])}return new e({inputs:u,outputs:h,name:c})}get stateful(){if(this._stateful)throw new k("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){C(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}function Cz(e,t,s){const n=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(i=>null);if(n===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==n)throw new Error(`Provided ${s} is an array of ${e.length} element(s), but the model has ${n} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){const i=[];return t.forEach(r=>{r in e?i.push(e[r]):i.push(null)}),i}else throw new Error(`The model has multiple (${n}) outputs, so ${s} must be either an array with ${n} elements or an object with ${t} keys. Provided ${s} not understood: ${JSON.stringify(e)}`)}function mm(e,t){return Cz(e,t,"classWeight")}async function fm(e,t,s,n){if(t!=null||n!=null)throw new Error("Support sampleWeight is not implemented yet");if(s!=null){const i=C(()=>{if(e.shape.length===1)return e.clone();if(e.shape.length===2)if(e.shape[1]>1){const a=1;return e.argMax(a)}else{if(e.shape[1]===1)return e.reshape([e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),r=Array.from(await i.data());ce(i);const o=[];return r.forEach(a=>{if(s[a]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${a} exists in the data but not in classWeight`);o.push(s[a])}),Oe(o,"float32")}else return null}function jA(e,t){return R(e,t)}const Rz=32;function GA(e,t){let s,n;const i=t;s=i.xs,n=i.ys,N.assert(s!=null&&n!=null,()=>`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 r=VA("input",e.inputNames,s),o=VA("output",e.outputNames,n),a=r[0].shape[0];N.assert(r.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${r.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),N.assert(o.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<r.length;l++)N.assert(r[l].shape[0]===a,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${r[l].shape[0]}; expected ${a} based on input ${e.inputNames[0]}.`);for(let l=0;l<o.length;l++)N.assert(o[l].shape[0]===a,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${o[l].shape[0]}; expected ${a} based on input ${e.inputNames[0]}.`);return{xs:r,ys:o}}function VA(e,t,s){if(s instanceof me)return[s];if(Array.isArray(s))return N.assert(s.length===t.length,()=>`Received an array of ${s.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),s;{const n=[];for(const i of t){if(s[i]==null)throw new k(`The feature data generated by the dataset lacks the required ${e} key '${i}'.`);n.push(s[i])}return n}}function Oz(e){if(e.length===3)throw new ae("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function HA(e,t,s){const n=s.batchesPerEpoch!=null;if(N.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),N.assert(s!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),N.assert(s.epochs!=null&&s.epochs>0&&Number.isInteger(s.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${s.epochs}`),N.assert(!n||s.batchesPerEpoch>0&&Number.isInteger(s.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${s.batchesPerEpoch}`),N.assert(s.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const i=s.validationData!=null;let r,o;if(i)if(qA(s.validationData))N.assert(s.validationBatches==null||s.validationBatches>0&&Number.isInteger(s.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${s.validationBatches}`);else{const g=Oz(s.validationData);r=g.xs,o=g.ys}const a=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let c;i?c=l.slice().concat(l.map(g=>"val_"+g)):c=l.slice();const p=om(s.callbacks,s.yieldEvery),u=s.verbose==null?1:s.verbose,{callbackList:h,history:d}=am(p,u,s.epochs,null,null,Ez(t,s),null,i,c);h.setModel(e),e.history=d,await h.onTrainBegin(),e.stopTraining_=!1;let m=s.initialEpoch==null?0:s.initialEpoch,f=await t.iterator();for(;m<s.epochs;){const g={};await h.onEpochBegin(m);let y=0,w=0;for(n||(f=await t.iterator());n?y<s.batchesPerEpoch:!0;){const x=await f.next();if(n&&x.done){console.warn(`You provided \`batchesPerEpoch\` as ${s.batchesPerEpoch}, but your dataset iterator ran out of data after ${y} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${s.batchesPerEpoch*s.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(x.value!=null){const{xs:T,ys:A}=GA(e,x.value),_={};_.batch=w,_.size=T[0].shape[0],await h.onBatchBegin(w,_);const E=[];if(s.classWeight!=null){const M=mm(s.classWeight,e.outputNames);for(let P=0;P<M.length;++P)E.push(await fm(A[P],null,M[P]))}const F=T.concat(A).concat(E),D=a(F);ce(F);for(let M=0;M<l.length;++M){const P=l[M],B=D[M];_[P]=B,pt(B)}await h.onBatchEnd(w,_),rm(_),w++,y++}if(n?y>=s.batchesPerEpoch:x.done){if(i){let T;qA(s.validationData)?T=He(await e.evaluateDataset(s.validationData,{batches:s.validationBatches})):T=He(e.evaluate(r,o,{batchSize:s.validationBatchSize==null?Rz:s.validationBatchSize,verbose:0}));for(let A=0;A<e.metricsNames.length;++A)g[`val_${e.metricsNames[A]}`]=T[A]}break}if(e.stopTraining_)break}if(await h.onEpochEnd(m,g),m++,e.stopTraining_)break}return await h.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function Ez(e,t){let s=null;return t.batchesPerEpoch!=null?s=t.batchesPerEpoch:Number.isFinite(e.size)&&(s=e.size),s}function qA(e){return typeof e.iterator=="function"}function _z(e){return typeof e.next=="function"}async function YA(e,t,s){s=s||{};const n=s.batches!=null,i=e.testFunction;let r=[];if(s.verbose>0)throw new ae("Verbose mode is not implemented yet.");N.assert(!n||s.batches>0&&Number.isInteger(s.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(s.batches)}`);const o=_z(t)?t:await t.iterator();let a=0,l=0;for(;n?l<s.batches:!0;){const c=await o.next();if(r=C(()=>{if(c.value){const{xs:p,ys:u}=GA(e,c.value),h=p.concat(u),d=C(()=>i(h));if(ce(h),l===0)for(let f=0;f<d.length;++f)r.push(j(0));const m=h[0].shape[0];for(let f=0;f<d.length;++f){const g=d[f],y=r[f];r[f]=C(()=>$(r[f],R(m,g))),l>0&&ce(y)}ce(d),a+=m,++l}return r}),c.done){n&&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, ${s.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let c=0;c<r.length;++c){const p=r[c];r[c]=Z(r[c],a),ce(p)}return jt(r)}function gm(e){N.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Hl(e,t,s){return e==null?[null]:Array.isArray(e)?e.map(n=>Gi(n,t,s-t)):Gi(e,t,s-t)}function ym(e,t){return C(()=>e==null?null:Array.isArray(e)?e.map(s=>ym(s,t)):Gd(e,t.dtype==="int32"?t:t.toInt()))}function bm(e,t){const s=[];let n=0,i=null;for(;n<e;)i=n+t,i>=e&&(i=e),s.push([n,i]),n=i;return s}async function kz(e,t,s,n,i,r,o,a,l,c,p,u,h,d,m){i==null&&(i=32),r==null&&(r=1),p==null&&(p=!0),h==null&&(h=0);let f=!1;if(l!=null&&c!=null&&(f=!0),m!=null&&(f=!0,d==null))throw new k("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const g=e.checkNumSamples(s,i,d,"steps_per_epoch");let y;g!=null&&(y=cs(0,g)),o==null&&(o=1);const{callbackList:w,history:x}=am(a,o,r,h,g,d,i,f,u);w.setModel(e),e.history=x,await w.onTrainBegin(),e.stopTraining_=!1;for(let T=h;T<r;++T){await w.onEpochBegin(T);const A={};if(d!=null)throw new ae("stepsPerEpoch mode is not implemented yet.");{if(p==="batch")throw new ae("batch shuffling is not implemneted yet");p&&N.shuffle(y);const _=Oe(y),E=bm(g,i);for(let F=0;F<E.length;++F){const D={};if(await w.onBatchBegin(F,D),C(()=>{const M=E[F][0],P=E[F][1],B=Gi(_,M,P-M);D.batch=F,D.size=P-M;const Y=ym(s,B),q=t(Y);for(let K=0;K<n.length;++K){const H=n[K],Q=q[K];D[H]=Q,pt(Q)}if(F===E.length-1&&f){const K=e.testLoop(l,c,i);for(let H=0;H<n.length;++H){const Q=n[H],J=K[H];pt(J),A["val_"+Q]=J}}}),await w.onBatchEnd(F,D),rm(D),e.stopTraining_)break}_.dispose()}if(await w.onEpochEnd(T,A),e.stopTraining_)break}return await w.onTrainEnd(),await e.history.syncData(),e.history}async function KA(e,t,s,n={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let i,r,o,a,l,c,p;try{const u=n.batchSize==null?32:n.batchSize;gm(u);const h=!1,d=await e.standardizeUserData(t,s,n.sampleWeight,n.classWeight,h,u);i=d[0],r=d[1],p=d[2];let m=!1,f;if(n.validationData!=null&&n.validationData.length>0){if(m=!0,n.validationData.length===2)o=n.validationData[0],a=n.validationData[1];else throw n.validationData.length===3?new ae("validationData including sample weights is not supported yet."):new k(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);const E=!0,F=await e.standardizeUserData(o,a,null,null,E,u);l=F[0],c=F[1],f=l.concat(c)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){m=!0;const E=Math.floor(i[0].shape[0]*(1-n.validationSplit)),F=i[0].shape[0];l=Hl(i,E,F),i=Hl(i,0,E),c=Hl(r,E,F),r=Hl(r,0,E),f=l.concat(c)}else n.validationSteps!=null&&(m=!0);const g=i.concat(r).concat(p);e.checkTrainableWeightsConsistency();const y=e.makeTrainFunction(),w=e.getDedupedMetricsNames();let x,T;m?(e.makeTestFunction(),x=e.testFunction,T=w.slice().concat(w.map(E=>"val_"+E))):(x=null,f=[],T=w.slice());const A=om(n.callbacks,n.yieldEvery),_=await kz(e,y,g,w,u,n.epochs,n.verbose,A,x,f,n.shuffle,T,n.initialEpoch,null,null);return _}finally{e.isTraining=!1,ho(i,t),ho(r,s),ho(l,o),ho(c,a),p!=null&&ce(p)}}function tw(e){const t=[];e instanceof me&&(e=[e]);for(let s=0;s<e.length;++s){const n=e[s];if(n.rank===1)t.push(Vi(n,1));else{if(n.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(n)}}return t}function ho(e,t){if(e==null)return;const s=[];if(t instanceof me)s.push(t.id);else if(Array.isArray(t))t.forEach(i=>s.push(i.id));else if(t!=null)for(const i in t){const r=t[i];s.push(r.id)}const n=[];if(e instanceof me)s.indexOf(e.id)===-1&&n.push(e);else if(Array.isArray(e))e.forEach(i=>{s.indexOf(i.id)===-1&&n.push(i)});else if(e!=null)for(const i in e){const r=e[i];s.indexOf(r.id)===-1&&n.push(r)}n.forEach(i=>{i.isDisposed||i.dispose()})}function Dz(e){return e instanceof me}function sw(e){return Array.isArray(e)}function XA(e){return!Dz(e)&&!sw(e)}function JA(e,t,s,n=!0,i=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(sw(e)&&e.length>0)o=!0;else if(XA(e)){for(const a in e)if(e.hasOwnProperty(a)){o=!0;break}}else o=!0;if(o)throw new k(`Error when checking model ${i} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let r;if(XA(e)){e=e,r=[];for(const o of t){if(e[o]==null)throw new k(`No data provided for "${o}". Need data for each key in: ${t}`);r.push(e[o])}}else if(sw(e)){if(e=e,e.length!==t.length)throw new k(`Error when checking model ${i}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);r=e}else{if(e=e,t.length>1)throw new k(`The model ${i} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);r=[e]}if(r=tw(r),s!=null)for(let o=0;o<t.length;++o){if(s[o]==null)continue;const a=r[o];if(a.shape.length!==s[o].length)throw new k(`Error when checking ${i}: expected ${t[o]} to have ${s[o].length} dimension(s). but got array with shape ${a.shape}`);for(let l=0;l<s[o].length;++l){if(l===0&&!n)continue;const c=a.shape[l],p=s[o][l];if(p!=null&&p>=0&&c!==p)throw new k(`Error when checking ${i}: expected ${t[o]} to have shape [${s[o]}], but got array with shape [${a.shape}].`)}}return r}function Fz(e,t,s){const n=An(e.map(r=>r.shape[0]));n.sort();const i=An(t.map(r=>r.shape[0]));if(i.sort(),n.length>1)throw new k(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(r=>r.shape))}`);if(i.length>1)throw new k(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(r=>r.shape))}`);if(n.length>0&&i.length>0&&!N.arraysEqual(n,i))throw new k(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${i[0]} target sample(s).`)}function Mz(e,t,s){const n=[yi,ql,wa];for(let i=0;i<e.length;++i){const r=e[i],o=t[i],a=s[i];if(o==null)continue;if(o===wa&&r.shape[r.shape.length-1]===1)throw new k(`You are passing a target array of shape ${r.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(n.indexOf(o)!==-1){const l=r.shape.slice(1),c=a.slice(1);for(let p=0;p<l.length;++p){const u=l[p],h=c[p];if(h!=null&&u!==h)throw new k(`A target Tensor with shape ${r.shape} was passed for an output of shape ${a}, while using a loss function that expects targets to have the same shape as the output.`)}}}}function ZA(e,t,s,n=!0,i=""){let r;if(Array.isArray(e)){if(e.length!==t.length)throw new k(`Error when checking model ${i}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);r=e}else{if(t.length>1)throw new k(`The model expects ${t.length} ${i} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);r=[e]}if(s!=null)for(let o=0;o<t.length;++o){if(s[o]==null)continue;const a=r[o];if(a.shape.length!==s[o].length)throw new k(`Error when checking ${i}: expected ${t[o]} to have ${s[o].length} dimension(s), but got array with shape ${JSON.stringify(a.shape)}`);for(let l=0;l<s[o].length;++l){if(l===0&&!n)continue;const c=a.shape[l],p=s[o][l];if(p!=null&&p!==c)throw new k(`Error when checking ${i}: expected ${t[o]} to have shape ${JSON.stringify(s[o])} but got array with shape ${JSON.stringify(a.shape)}.`)}}}function Uz(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(n=>[]);let s;if(typeof e=="string"||typeof e=="function")s=[e];else if(Array.isArray(e)||typeof e=="object")s=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(s))return t.map(n=>s);{const n=[];for(const i of t){let r=s.hasOwnProperty(i)?s[i]:[];Array.isArray(r)||(r=[r]),n.push(r)}return n}}const $z="layers-model";class nn extends Bn{constructor(e){super(e);this.isTraining=!1}summary(e,t,s=console.log){if(!this.built)throw new k("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).");WA(this,e,t,s)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=UA(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof gs))throw new k("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(const r in e.loss)if(this.outputNames.indexOf(r)===-1)throw new k(`Unknown entry in loss dictionary: "${r}". Only expected the following keys: ${this.outputNames}`);for(const r of this.outputNames)e.loss[r]==null&&console.warn(`Output "${r}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${r} during training`),t.push(lm(e.loss[r]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new k(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const r=e.loss;t=r.map(o=>lm(o))}else{const r=lm(e.loss);this.outputs.forEach(o=>{t.push(r)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let r=0;r<this.outputs.length;++r){const o=this.internalOutputShapes[r],a=this.outputNames[r];this.feedOutputNames.push(a),this.feedOutputShapes.push(o),this.feedLossFns.push(this.lossFunctions[r])}const s=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],zn("loss",()=>{for(let r=0;r<this.outputs.length;++r){if(s.indexOf(r)!==-1)continue;const o=this.lossFunctions[r];this.outputs.length>1&&(this.metricsTensors.push([o,r]),this.metricsNames.push(this.outputNames[r]+"_loss"))}});const n=Uz(e.metrics,this.outputNames),i=(r,o,a)=>{this.outputNames.length>1&&(o=this.outputNames[r]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([a,r])};zn("metric",()=>{for(let r=0;r<this.outputs.length;++r){if(s.indexOf(r)!==-1)continue;const o=n[r],a=l=>{const c="";let p,u,h;for(const d of l){if(typeof d=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(d)!==-1){const f=this.internalOutputShapes[r];f[f.length-1]===1||this.lossFunctions[r]===ql?["accuracy","acc"].indexOf(d)!==-1?u=du:["crossentropy","ce"].indexOf(d)!==-1&&(u=cm):this.lossFunctions[r]===Gl?["accuracy","acc"].indexOf(d)!==-1?u=pm:["crossentropy","ce"].indexOf(d)!==-1&&(u=Jb):["accuracy","acc"].indexOf(d)!==-1?u=mu:["crossentropy","ce"].indexOf(d)!==-1&&(u=fu);let g;["accuracy","acc"].indexOf(d)!==-1?g="acc":["crossentropy","ce"].indexOf(d)!==-1&&(g="ce"),h=u,p=c+g}else{const f=MA(d);h=f,p=c+gu(d)}let m;zn(p,()=>{m=h}),i(r,p,m)}};a(o)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){if(this.collectedTrainableWeights==null)return;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,t,s={}){const n=s.batchSize==null?32:s.batchSize;gm(n);const i=!0,r=this.standardizeUserDataXY(e,t,i,n);try{const o=r[0].concat(r[1]);this.makeTestFunction();const a=this.testFunction,l=this.testLoop(a,o,n,s.verbose,s.steps);return jt(l)}finally{ho(r[0],e),ho(r[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),YA(this,e,t)}checkNumSamples(e,t,s,n="steps"){let i;if(s!=null){if(i=null,t!=null)throw new k(`If ${n} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?i=e[0].shape[0]:i=e.shape[0];else throw new k(`Either the input data should have a defined shape, or ${n} shoud be specified.`);return i}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new k("`outputs` is an empty Array, which is not allowed.");const s=Array.isArray(t),n=s?t:[t],i=this.retrieveSymbolicTensors(n),r=new Hi;if(e instanceof me&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new k(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let a=0;a<this.inputs.length;++a)r.add(this.inputs[a],e[a])}else for(const a of this.inputs){const l=e[a.name];if(l==null)throw new k(`No value is provided for the model's input ${a.name}`);r.add(a,l)}const o=La(i,r);return s?o:o[0]}retrieveSymbolicTensors(e){const t=In(null,e.length);let s=e.length;for(const n of this.layers){const i=Array.isArray(n.output)?n.output:[n.output],r=i.map(o=>o.name);for(let o=0;o<e.length;++o){const a=r.indexOf(e[o]);if(a!==-1&&(t[o]=i[a],s--),s===0)break}if(s===0)break}if(s>0){const n=[];throw t.forEach((i,r)=>{i==null&&n.push(e[r])}),new k(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,s=!1){return C(()=>{const n=this.checkNumSamples(e);if(s)throw new ae("Verbose predictLoop() is not implemented yet.");const i=bm(n,t),r=this.outputs.map(o=>[]);for(let o=0;o<i.length;++o){const a=C(()=>{const l=i[o][0],c=i[o][1],p=Hl(e,l,c),u=[];if(Array.isArray(p))for(let d=0;d<p.length;++d)u.push({key:this.inputs[d],value:p[d]});else u.push({key:this.inputs[0],value:p});const h=new Hi(u);return La(this.outputs,h)});a.forEach((l,c)=>r[c].push(l))}return jt(r.map(o=>be(o,0)))})}predict(e,t={}){const s=tw(e);ZA(s,this.inputNames,this.feedInputShapes,!1);try{const n=t.batchSize==null?32:t.batchSize;return gm(n),this.predictLoop(s,n)}finally{ho(s,e)}}predictOnBatch(e){ZA(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,s=!0,n){if(this.optimizer_==null)throw new Ns("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const i=[];for(let r=0;r<this.feedOutputShapes.length;++r){const o=this.feedOutputShapes[r],a=this.feedLossFns[r];a===Gl?i.push(o.slice(0,o.length-1).concat([1])):i.push(o)}if(e=JA(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=JA(t,this.feedOutputNames,i,!1,"target"),Fz(e,t,null),Mz(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&n!=null&&n>0&&e[0].shape[0]%n!==0)throw new k(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${n}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,s,n,i=!0,r){const[o,a]=this.standardizeUserDataXY(e,t,i,r);if(s!=null)throw new Error("sample weight is not supported yet.");let l=null;if(n!=null){const c=mm(n,this.outputNames);l=[];for(let p=0;p<c.length;++p)l.push(await fm(a[p],null,c[p]))}return[o,a,l]}testLoop(e,t,s,n=0,i){return C(()=>{const r=this.checkNumSamples(t,s,i,"steps"),o=[];if(n>0)throw new ae("Verbose mode is not implemented yet.");if(i!=null)throw new ae("steps mode in testLoop() is not implemented yet");{const a=bm(r,s),l=Oe(cs(0,r));for(let c=0;c<a.length;++c){const p=a[c][0],u=a[c][1],h=Gi(l,p,u-p),d=ym(t,h),m=e(d);if(c===0)for(let f=0;f<m.length;++f)o.push(j(0));for(let f=0;f<m.length;++f){const g=m[f];o[f]=$(o[f],R(u-p,g))}}for(let c=0;c<o.length;++c)o[c]=Z(o[c],r)}return o})}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let s=0;s<e.length;++s){const n=e[s];let i=n;if(Ub(e,n)>1){const r=Ub(e.slice(0,s),n);i+=`_${r}`}t.push(i)}return t}makeTrainFunction(){return e=>{const t=[],s=e.slice(0,this.inputs.length),n=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),r=[],o=()=>{const p=[];for(let m=0;m<this.inputs.length;++m)p.push({key:this.inputs[m],value:s[m]});const u=new Hi(p),h=La(this.outputs,u,{training:!0});let d;for(let m=0;m<this.lossFunctions.length;++m){const f=this.lossFunctions[m];let g=f(n[m],h[m]);i[m]!=null&&(g=jA(g,i[m]));const y=Xe(g);t.push(y),m===0?d=g:d=$(d,g)}for(let m=0;m<this.metricsTensors.length;++m){let f;if(this.outputs.length>1&&m<this.outputs.length)f=t[m];else{const g=this.metricsTensors[m][0],y=this.metricsTensors[m][1];f=Xe(g(n[y],h[y]))}pt(f),r.push(f)}return d=Xe(d),this.calculateLosses().forEach(m=>{d=$(d,m)}),d},a=this.collectedTrainableWeights.map(p=>p.read()),l=!0,c=this.optimizer_.minimize(o,l,a);return[c].concat(r)}}makeTestFunction(){this.testFunction=e=>C(()=>{const t=[];let s;const n=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=[];for(let l=0;l<this.inputs.length;++l)r.push({key:this.inputs[l],value:n[l]});const o=new Hi(r),a=La(this.outputs,o);for(let l=0;l<this.lossFunctions.length;++l){const c=this.lossFunctions[l],p=Xe(c(i[l],a[l]));l===0?s=p:s=$(s,p),t.push(s)}for(let l=0;l<this.metricsTensors.length;++l){const c=this.metricsTensors[l][0],p=this.metricsTensors[l][1],u=Xe(c(i[p],a[p]));t.push(u)}return t})}async fit(e,t,s={}){return KA(this,e,t,s)}async fitDataset(e,t){return HA(this,e,t)}async trainOnBatch(e,t){const s=await this.standardizeUserData(e,t),n=s[0],i=s[1],r=this.makeTrainFunction(),o=r(n.concat(i)),a=[];for(const l of o){const c=await l.data();a.push(c[0])}return ce(o),jt(a)}getNamedWeights(e){const t=[],s=e!=null&&e.trainableOnly,n=s?this.trainableWeights:this.weights,i=this.getWeights(s);for(let r=0;r<n.length;++r){if(s&&!n[r].trainable)continue;t.push({name:n[r].originalName,tensor:i[r]})}return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){const t=pl().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-pl().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=vn(this.loss);else if(Array.isArray(this.loss)){for(const t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>vn(t))}else{const t=Object.keys(this.loss);e={};const s=this.loss;for(const n of t)if(typeof s[n]=="string")e[n]=vn(s[n]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[vn(gu(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>vn(gu(e)));{const e={};for(const t in this.metrics)e[t]=vn(gu(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");const t=xa(e.optimizer_config),s=Ls(t);let n;if(typeof e.loss=="string")n=Pi(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(r=>Pi(r));else if(e.loss!=null){n={};for(const r in e.loss)n[r]=Pi(e.loss[r])}let i;if(Array.isArray(e.metrics))i=e.metrics.map(r=>Pi(r));else if(e.metrics!=null){i={};for(const r in e.metrics)i[r]=Pi(e.metrics[r])}this.compile({loss:n,metrics:i,optimizer:s})}async save(e,t){if(typeof e=="string"){const l=Rt.getSaveHandlers(e);if(l.length===0)throw new k(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new k(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new k("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const s=await Rt.encodeWeights(this.getNamedWeights(t)),n=!1,i=null,r=this.toJSON(i,n),o={modelTopology:r,format:$z,generatedBy:`TensorFlow.js tfjs-layers v${uo}`,convertedBy:null},a=t==null?!1:t.includeOptimizer;if(a&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();const l="optimizer",{data:c,specs:p}=await Rt.encodeWeights(await this.optimizer.getWeights(),l);s.specs.push(...p),s.data=Rt.concatenateArrayBuffers([s.data,c])}if(this.userDefinedMetadata!=null){const l=!0;Qb(this.userDefinedMetadata,this.name,l),o.userDefinedMetadata=this.userDefinedMetadata}return o.weightData=s.data,o.weightSpecs=s.specs,e.save(o)}setUserDefinedMetadata(e){Qb(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}nn.className="Model";V.registerClass(nn);class QA extends nn{}QA.className="Functional";V.registerClass(QA);async function eN(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let s=e.modelTopology;s.model_config!=null&&(s=s.model_config);const n=xa(s),i=Ls(n,t);if(e.weightsManifest!=null){const r=await Rt.loadWeights(e.weightsManifest,e.pathPrefix,i.weights.map(a=>a.originalName)),o={};for(const a of i.weights)o[a.originalName]=r[a.originalName];i.loadWeights(o),ce(r)}return i}async function tN(e,t){if(t==null&&(t={}),typeof e=="string"){const s=Rt.getLoadHandlers(e,t);if(s.length===0)s.push(Rt.browserHTTPRequest(e,t));else if(s.length>1)throw new k(`Found more than one (${s.length}) load handlers for URL '${e}'`);e=s[0]}return Wz(e,void 0,t)}async function Wz(e,t,s){if(s==null&&(s={}),e.load==null)throw new k("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const n=await e.load();let i=n.modelTopology;i.model_config!=null&&(i=i.model_config);const r=s.strict==null?!0:s.strict,o=n.weightData!=null&&n.weightSpecs!=null&&r,a=Ls(xa(i),t,o),l=n.trainingConfig;if(l!=null&&a.loadTrainingConfig(l),n.userDefinedMetadata!=null&&a.setUserDefinedMetadata(n.userDefinedMetadata),n.weightData!=null){if(n.weightSpecs==null)throw new k("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:c,optimizerWeights:p}=zz(n.weightData,n.weightSpecs);a.loadWeights(c,r),a.optimizer!=null&&p.length>0&&await a.optimizer.setWeights(p),ce(c),ce(p.map(u=>u.tensor))}return a}function zz(e,t){const s=Rt.decodeWeights(e,t),n={},i=[];return t.forEach(r=>{r.group==="optimizer"?i.push({name:r.name,tensor:s[r.name]}):n[r.name]=s[r.name]}),{modelWeights:n,optimizerWeights:i}}class mo extends nn{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:co("sequential_"),e.layers!=null)for(const t of e.layers)this.add(t)}checkShape(e){const t=e.inboundNodes[0].outputTensors[0].shape;if(t.some(s=>s<0))throw new k(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof mo||e instanceof nn;let s;if(t){if(s=e,s.outputs.length!==1)throw new k("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(s.inputs.length!==1)throw new k("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new k("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const n=im({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(n)}if(t)this.outputs=s.outputs,this.inputs=s.inputs;else{if(e.inboundNodes.length!==1)throw new k(`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(e.inboundNodes[0].outputTensors.length!==1)throw new k("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 ya({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:In(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(n=>n.shape),outputShapes:this.outputs[0].shape})}else{const n=e.apply(this.outputs[0]);if(Array.isArray(n))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=[n],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(Ue(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new nn({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,s=console.log){this.built||this.build(),super.summary(e,t,s)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,s={}){if(!this.built)throw new Ns("The model needs to be compiled before being used.");return this.model.evaluate(e,t,s)}async evaluateDataset(e,t){if(!this.built)throw new Ns("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&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 this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,s={}){if(!this.built)throw new Ns("The model needs to be compiled before being used.");return this.model.fit(e,t,s)}async fitDataset(e,t){if(!this.built)throw new Ns("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,s={},n=!1){let i,r={};if(t instanceof Array){if(!(t[0].className!=null)||t[0].className==="Merge")throw new k("Legacy serialization format not supported yet.");i=t}else N.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),i=t.layers,delete t.layers,r=t;const o=new e(r);if(!(o instanceof mo))throw new ae(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(const a of i){const l=void 0,c=Ls(a,l,n);n&&c.setFastWeightInitDuringBuild(!0),o.add(c)}return o}set stopTraining(e){if(this.model==null)throw new k("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new k("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const s={};s.className=t.getClassName(),s.config=t.getConfig(),e.push(s)}return{name:this.name,layers:e}}}mo.className="Sequential";V.registerClass(mo);function sN(e){return new nn(e)}function nN(e){return new mo(e)}function iN(e,t){return t==null&&(t={}),tN(e,t)}function wm(e){return im(e)}function rN(e,t){sn.registerCallbackConstructor(e,t)}class Ps extends V.Serializable{getConfig(){return{}}}class oN extends Ps{apply(e,t=1){return TA(e,t)}}oN.className="elu";V.registerClass(oN);class aN extends Ps{apply(e){return Rl(e)}}aN.className="selu";V.registerClass(aN);class lN extends Ps{apply(e){return Fe(e)}}lN.className="relu";V.registerClass(lN);class cN extends Ps{apply(e){return C(()=>bn(6,Fe(e)))}}cN.className="relu6";V.registerClass(cN);class pN extends Ps{apply(e){return e}}pN.className="linear";V.registerClass(pN);class uN extends Ps{apply(e){return os(e)}}uN.className="sigmoid";V.registerClass(uN);class hN extends Ps{apply(e){return NA(e)}}hN.className="hardSigmoid";V.registerClass(hN);class dN extends Ps{apply(e){return di(e)}}dN.className="softplus";V.registerClass(dN);class mN extends Ps{apply(e){return AA(e)}}mN.className="softsign";V.registerClass(mN);class fN extends Ps{apply(e){return Mi(e)}}fN.className="tanh";V.registerClass(fN);class xm extends Ps{apply(e,t=-1){return ts(e,t)}}xm.className="softmax";V.registerClass(xm);class gN extends Ps{apply(e,t=-1){return Il(e,t)}}gN.className="logSoftmax";V.registerClass(gN);class yN extends Ps{apply(e,t=1){return C(()=>os(e.mul(t)).mul(e))}}yN.className="swish";V.registerClass(yN);function jn(e){return e.getClassName()}function nw(e,t={}){return fi(e,V.SerializationMap.getMap().classNameMap,t,"activation")}function Vn(e){if(e==null){const t={};return t.className="linear",t.config={},nw(t)}if(typeof e=="string"){const t={};return t.className=e,t.config={},nw(t)}else return e instanceof Ps?e:nw(e)}function iw(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}class bN extends V.Serializable{}class Yl extends bN{constructor(e){super();iw(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return C(()=>{let t=ye([1]);return this.hasL1&&(t=$(t,te(R(this.l1,et(e))))),this.hasL2&&(t=$(t,te(R(this.l2,ga(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Yl.className="L1L2";V.registerClass(Yl);function wN(e){return iw(e),new Yl({l1:e!=null?e.l1:null,l2:0})}function xN(e){return iw(e),new Yl({l2:e!=null?e.l2:null,l1:0})}const LN={l1l2:"L1L2"};function Pe(e){return Ml(e)}function SN(e,t={}){return fi(e,V.SerializationMap.getMap().classNameMap,t,"regularizer")}function Ye(e){if(e==null)return null;if(typeof e=="string"){const t=e in LN?LN[e]:e,s={className:t,config:{}};return SN(s)}else return e instanceof bN?e:SN(e)}class Lm extends Le{constructor(e){super(e??{});this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=we(e);let s=Fe(e);return this.maxValue!=null&&(s=xt(s,0,this.maxValue)),s}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Lm.className="ReLU";V.registerClass(Lm);class Sm extends Le{constructor(e){super(e??{});this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const s=we(e);return Ll(s,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Sm.className="LeakyReLU";V.registerClass(Sm);class Im extends Le{constructor(e){super(e??{});if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=je(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Ye(e.alphaRegularizer),this.alphaConstraint=at(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new k(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Ue(e);const t=e.slice(1);if(this.sharedAxes!=null)for(const n of this.sharedAxes)t[n-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const s={};if(this.sharedAxes!=null)for(let n=1;n<e.length;++n)s[n]=e[n];this.inputSpec=[new st({ndim:e.length,axes:s})],this.built=!0}call(e,t){return e=we(e),Qr(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Ze(this.alphaInitializer),alphaRegularizer:Pe(this.alphaRegularizer),alphaConstraint:ot(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Im.className="PReLU";V.registerClass(Im);class vm extends Le{constructor(e){super(e??{});if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new ae(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const s=we(e);return gn(s)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}vm.className="ELU";V.registerClass(vm);class Tm extends Le{constructor(e){super(e??{});this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){const s=we(e);return s.mul(ji(s.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Tm.className="ThresholdedReLU";V.registerClass(Tm);class Am extends Le{constructor(e){super(e??{});this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new xm().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){const s=we(e);return this.softmax(s,this.axis)}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}Am.className="Softmax";V.registerClass(Am);function fo(e,t,s){if(typeof e=="number")return In(e,t);if(e.length!==t)throw new k(`The ${s} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let n=0;n<t;++n){const i=e[n];if(!xA(i))throw new k(`The ${s} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${i}`)}return e}function Rs(e,t,s,n,i=1){if(e==null)return e;const r=t+(t-1)*(i-1);let o;return s==="same"?o=e:o=e-r+1,Math.floor((o+n-1)/n)}function yu(e,t,s,n){if(e==null)return null;if(n==="valid")e=e*t+Pn([s-t,0]);else if(n==="same")e=e*t;else throw new k(`Unsupport padding mode: ${n}.`);return e}function bu(e,t){return C(()=>(lt(t),t==="channelsFirst"?se(e,[0,2,3,1]):e))}function rw(e,t){return C(()=>(lt(t),t==="channelsFirst"?se(e,[0,2,3,4,1]):e))}function Pz(e,t,s,n=1,i="valid",r,o=1){return C(()=>{if(r==null&&(r=ys()),lt(r),e.shape.length!==3)throw new k(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new k(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(s!=null&&s.shape.length!==1)throw new k(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(r==="channelsFirst"&&(e=se(e,[0,2,1])),i==="causal")throw new ae("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let a=fl(e,t,n,i==="same"?"same":"valid","NWC",o);return s!=null&&(a=Cs(a,s)),a})}function IN(e,t,s,n=[1,1],i="valid",r,o,a=null){return C(()=>{if(r==null&&(r=ys()),lt(r),e.rank!==3&&e.rank!==4)throw new k(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new k(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=bu(e,r);if(i==="causal")throw new ae("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=xn.conv2d({x:l,filter:t,strides:n,pad:i==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:s,activation:a}),r==="channelsFirst"&&(l=se(l,[0,3,1,2])),l})}function Bz(e,t,s,n=[1,1,1],i="valid",r,o){return C(()=>{if(r==null&&(r=ys()),lt(r),e.rank!==4&&e.rank!==5)throw new k(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new k(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let a=rw(e,r);if(i==="causal")throw new ae("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=bl(a,t,n,i==="same"?"same":"valid","NDHWC",o),s!=null&&(a=Cs(a,s)),r==="channelsFirst"&&(a=se(a,[0,4,1,2,3])),a})}class Nm extends Le{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Nm.verifyArgs(t),this.rank=e,yt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new ae(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=fo(t.kernelSize,e,"kernelSize"),this.strides=fo(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,bs(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,lt(this.dataFormat),this.activation=Vn(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=je(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=at(t.biasConstraint),this.biasRegularizer=Ye(t.biasRegularizer),this.activityRegularizer=Ye(t.activityRegularizer),this.dilationRate=fo(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new k(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new k(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new k(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(tn("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!Md(e.kernelSize,"number",1,3))throw new k(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:jn(this.activation),useBias:this.useBias,biasInitializer:Ze(this.biasInitializer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),biasConstraint:ot(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class wu extends Nm{constructor(e,t){super(e,t);this.kernel=null,wu.verifyArgs(t),this.filters=t.filters,yt(this.filters,"filters"),this.kernelInitializer=je(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=at(t.kernelConstraint),this.kernelRegularizer=Ye(t.kernelRegularizer)}build(e){e=Ue(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new k(`The channel dimension of the input should be defined. Found ${e[t]}`);const s=e[t],n=this.kernelSize.concat([s,this.filters]);this.kernel=this.addWeight("kernel",n,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:s}}],this.built=!0}call(e,t){return C(()=>{e=we(e);let s;const n=this.bias==null?null:this.bias.read(),i=Ud(this.activation.getClassName());if(i!=null&&this.rank===2)s=IN(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(this.rank===1)s=Pz(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)s=IN(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)s=Bz(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new ae("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(s=this.activation.apply(s))}return s})}computeOutputShape(e){e=Ue(e);const t=[],s=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let i=0;i<s.length;++i){const r=Rs(s[i],this.kernelSize[i],this.padding,this.strides[i],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[i]);t.push(r)}let n=[e[0]];return this.dataFormat==="channelsLast"?(n=n.concat(t),n.push(this.filters)):(n.push(this.filters),n=n.concat(t)),n}getConfig(){const e={filters:this.filters,kernelInitializer:Ze(this.kernelInitializer),kernelRegularizer:Pe(this.kernelRegularizer),kernelConstraint:ot(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new k(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class Kl extends wu{constructor(e){super(2,e);Kl.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!Md(e.kernelSize,"number",1,2))throw new k(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Kl.className="Conv2D";V.registerClass(Kl);class xu extends wu{constructor(e){super(3,e);xu.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new k(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}xu.className="Conv3D";V.registerClass(xu);class Cm extends Kl{constructor(e){super(e);if(this.inputSpec=[new st({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new k(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Ue(e),e.length!==4)throw new k("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new k("The channel dimension of the inputs should be defined. Found `None`.");const s=e[t],n=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",n,"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 st({ndim:4,axes:{[t]:s}})],this.built=!0}call(e,t){return C(()=>{let s=we(e);if(s.shape.length!==4)throw new k(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const n=s.shape,i=n[0];let r,o;this.dataFormat==="channelsFirst"?(r=2,o=3):(r=1,o=2);const a=n[r],l=n[o],c=this.kernelSize[0],p=this.kernelSize[1],u=this.strides[0],h=this.strides[1],d=yu(a,u,c,this.padding),m=yu(l,h,p,this.padding),f=[i,d,m,this.filters];this.dataFormat!=="channelsLast"&&(s=se(s,[0,2,3,1]));let g=yl(s,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=se(g,[0,3,1,2])),this.bias!=null&&(g=Cs(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=Ue(e);const t=e.slice();let s,n,i;this.dataFormat==="channelsFirst"?(s=1,n=2,i=3):(s=3,n=1,i=2);const r=this.kernelSize[0],o=this.kernelSize[1],a=this.strides[0],l=this.strides[1];return t[s]=this.filters,t[n]=yu(t[n],a,r,this.padding),t[i]=yu(t[i],l,o,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Cm.className="Conv2DTranspose";V.registerClass(Cm);class vN extends wu{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new k("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new k("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new k(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=je(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Ye(t.depthwiseRegularizer),this.depthwiseConstraint=at(t.depthwiseConstraint),this.pointwiseInitializer=je(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Ye(t.pointwiseRegularizer),this.pointwiseConstraint=at(t.pointwiseConstraint)}build(e){if(e=Ue(e),e.length<this.rank+2)throw new k(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new k(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const s=e[t],n=this.kernelSize.concat([s,this.depthMultiplier]),i=[];for(let o=0;o<this.rank;++o)i.push(1);i.push(s*this.depthMultiplier,this.filters);const r=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",n,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,r,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",i,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,r,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,r,this.biasConstraint):this.bias=null,this.inputSpec=[new st({ndim:this.rank+2,axes:{[t]:s}})],this.built=!0}call(e,t){return C(()=>{e=we(e);let s;if(this.rank===1)throw new ae("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=se(e,[0,2,3,1])),s=eo(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(s=Cs(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),this.dataFormat==="channelsFirst"&&(s=se(s,[0,3,1,2])),s})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Ze(this.depthwiseInitializer),e.pointwiseInitializer=Ze(this.pointwiseInitializer),e.depthwiseRegularizer=Pe(this.depthwiseRegularizer),e.pointwiseRegularizer=Pe(this.pointwiseRegularizer),e.depthwiseConstraint=ot(this.depthwiseConstraint),e.pointwiseConstraint=ot(this.pointwiseConstraint),e}}vN.className="SeparableConv";class Rm extends vN{constructor(e){super(2,e)}}Rm.className="SeparableConv2D";V.registerClass(Rm);class Lu extends wu{constructor(e){super(1,e);Lu.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!Md(e.kernelSize,"number",1,1))throw new k(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Lu.className="Conv1D";V.registerClass(Lu);class Om extends Le{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return C(()=>{if(e=we(e),this.dataFormat==="channelsLast"){const s=su(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return su(s,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const s=su(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return su(s,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Om.className="Cropping2D";V.registerClass(Om);class Em extends Le{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){const t=e[2]==null?null:this.size[0]*e[2],s=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,s]}else{const t=e[1]==null?null:this.size[0]*e[1],s=e[2]==null?null:this.size[1]*e[2];return[e[0],t,s,e[3]]}}call(e,t){return C(()=>{let s=we(e);const n=s.shape;if(this.dataFormat==="channelsFirst"){s=se(s,[0,2,3,1]);const i=this.size[0]*n[2],r=this.size[1]*n[3],o=s.resizeNearestNeighbor([i,r]);return se(o,[0,3,1,2])}else{const i=this.size[0]*n[1],r=this.size[1]*n[2];return s.resizeNearestNeighbor([i,r])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Em.className="UpSampling2D";V.registerClass(Em);function jz(e,t,s=[1,1],n="valid",i,r){return C(()=>{i==null&&(i=ys()),lt(i);let o=bu(e,i);if(e.rank!==4)throw new k(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new k(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=fn(o,t,s,n==="same"?"same":"valid","NHWC",r),i==="channelsFirst"&&(o=se(o,[0,3,1,2])),o})}class _m extends Nm{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=je(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=at(e.depthwiseConstraint),this.depthwiseRegularizer=Ye(e.depthwiseRegularizer)}build(e){if(e=Ue(e),e.length<4)throw new k(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new k(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const s=e[t],n=[this.kernelSize[0],this.kernelSize[1],s,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",n,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[s*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return C(()=>{e=we(e);let s=jz(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(s=Cs(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),s})}computeOutputShape(e){e=Ue(e);const t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,i=Rs(t,this.kernelSize[0],this.padding,this.strides[0]),r=Rs(s,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],n,i,r]:[e[0],i,r,n]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Ze(this.depthwiseInitializer),e.depthwiseRegularizer=Pe(this.depthwiseRegularizer),e.depthwiseConstraint=ot(this.depthwiseRegularizer),e}}_m.className="DepthwiseConv2D";V.registerClass(_m);function ow(e,t,s,n){if(Array.isArray(e)){if(t!=null||s!=null)throw new k("When inputs is an array, neither initialState or constants should be provided");n!=null&&(s=e.slice(e.length-n,e.length),e=e.slice(0,e.length-n)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function i(r){return r==null||Array.isArray(r)?r:[r]}return t=i(t),s=i(s),{inputs:e,initialState:t,constants:s}}function aw(e,t,s,n=!1,i,r,o=!1,a=!1){return C(()=>{const l=t.shape.length;if(l<3)throw new k(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(cs(2,l));if(t=se(t,c),r!=null)throw new ae("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),i!=null&&(i=i.asType("bool").asType("float32"),i.rank===l-1&&(i=Mt(i,-1)),i=se(i,c)),n&&(t=Et(t,0),i!=null&&(i=Et(i,0)));const p=[];let u,h=s;const d=t.shape[0],m=qe(t);let f;i!=null&&(f=qe(i));for(let y=0;y<d;++y){const w=m[y],x=C(()=>e(w,h));if(i==null)u=x[0],h=x[1];else{const T=C(()=>{const A=f[y],_=Ot(A).sub(A),E=x[0].mul(A).add(h[0].mul(_)),F=h.map((D,M)=>x[1][M].mul(A).add(D.mul(_)));return{output:E,newStates:F}});u=T.output,h=T.newStates}a&&p.push(u)}let g;if(a){const y=1;g=Ge(p,y)}return[u,g,h]})}class rn extends Le{constructor(e){super(e);let t;if(e.cell==null)throw new k("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Su({cells:e.cell}):t=e.cell,t.stateSize==null)throw new k("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new st({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return cs(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){sm(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const s=t[0];let n;if(this.returnSequences?n=[e[0],e[1],s]:n=[e[0],s],this.returnState){const i=[];for(const r of t)i.push([e[0],r]);return[n].concat(i)}else return n}computeMask(e,t){return C(()=>{Array.isArray(t)&&(t=t[0]);const s=this.returnSequences?t:null;if(this.returnState){const n=this.states.map(i=>null);return[s].concat(n)}else return s})}get states(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let s=0;s<e;++s)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){const t=null;if(this.numConstants!=null)throw new ae("Constants support is not implemented in RNN yet.");sm(e)&&(e=e[0]),e=e;const s=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new st({shape:[s,null,...n]});const i=[e[0]].concat(e.slice(2));if(t!=null)throw new ae("Constants support is not implemented in RNN yet.");this.cell.build(i);let r;if(Array.isArray(this.cell.stateSize)?r=this.cell.stateSize:r=[this.cell.stateSize],this.stateSpec!=null){if(!N.arraysEqual(this.stateSpec.map(o=>o.shape[o.shape.length-1]),r))throw new k(`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=r.map(o=>new st({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){C(()=>{if(!this.stateful)throw new Sn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape[0];if(s==null)throw new k("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(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(n=>ye([s,n])):this.states_=[ye([s,this.cell.stateSize])];else if(e==null)ce(this.states_),this.keptStates!=null&&(ce(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(n=>ye([s,n])):this.states_[0]=ye([s,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new k(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):ce(this.states_);for(let n=0;n<this.states_.length;++n){const i=e[n],r=Array.isArray(this.cell.stateSize)?this.cell.stateSize[n]:this.cell.stateSize,o=[s,r];if(!N.arraysEqual(i.shape,o))throw new k(`State ${n} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[n]=i}}this.states_=this.states_.map(n=>pt(n.clone()))})}apply(e,t){let s=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});const i=ow(e,s,n,this.numConstants);e=i.inputs,s=i.initialState,n=i.constants;let r=[],o=[];if(s!=null){t.initialState=s,r=r.concat(s),this.stateSpec=[];for(const l of s)this.stateSpec.push(new st({shape:l.shape}));o=o.concat(this.stateSpec)}n!=null&&(t.constants=n,r=r.concat(n),this.numConstants=n.length);const a=r[0]instanceof xs;if(a){const l=[e].concat(r),c=this.inputSpec.concat(o),p=this.inputSpec;this.inputSpec=c;const u=super.apply(l,t);return this.inputSpec=p,u}else return super.apply(e,t)}call(e,t){return C(()=>{const s=t==null?null:t.mask,n=t==null?null:t.training;let i=t==null?null:t.initialState;e=we(e),i==null&&(this.stateful?i=this.states_:i=this.getInitialState(e));const r=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(i.length!==r)throw new k(`RNN Layer has ${r} state(s) but was passed ${i.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const o={training:n},a=(d,m)=>{const f=this.cell.call([d].concat(m),o);return[f[0],f.slice(1)]},l=aw(a,e,i,this.goBackwards,s,null,this.unroll,this.returnSequences),c=l[0],p=l[1],u=l[2];this.stateful&&this.resetStates(u,n);const h=this.returnSequences?p:c;return this.returnState?[h].concat(u):h})}getInitialState(e){return C(()=>{let t=ye(e.shape);return t=te(t,[1,2]),t=Vi(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(s=>s>1?Vd(t,[1,s]):t):this.cell.stateSize>1?[Vd(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);const s=this.cell.getConfig();return this.getClassName()===rn.className&&(t.cell={className:this.cell.getClassName(),config:s}),Object.assign({},s,e,t)}static fromConfig(e,t,s={}){const n=t.cell,i=Ls(n,s);return new e(Object.assign(t,{cell:i}))}}rn.className="RNN";V.registerClass(rn);class go extends Le{}class Iu extends go{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,yt(this.units,"units"),this.activation=Vn(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=je(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=je(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=je(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ye(e.kernelRegularizer),this.recurrentRegularizer=Ye(e.recurrentRegularizer),this.biasRegularizer=Ye(e.biasRegularizer),this.kernelConstraint=at(e.kernelConstraint),this.recurrentConstraint=at(e.recurrentConstraint),this.biasConstraint=at(e.biasConstraint),this.dropout=fa([1,Pn([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=fa([1,Pn([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Ue(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return C(()=>{if(e=e,e.length!==2)throw new k(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let s=e[1];e=e[0];const n=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Yi({ones:()=>Ot(e),rate:this.dropout,training:n})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Yi({ones:()=>Ot(s),rate:this.recurrentDropout,training:n}));let i;const r=this.dropoutMask,o=this.recurrentDropoutMask;r!=null?i=Cn(R(e,r),this.kernel.read()):i=Cn(e,this.kernel.read()),this.bias!=null&&(i=Cs(i,this.bias.read())),o!=null&&(s=R(s,o));let a=$(i,Cn(s,this.recurrentKernel.read()));return this.activation!=null&&(a=this.activation.apply(a)),[a,a]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:jn(this.activation),useBias:this.useBias,kernelInitializer:Ze(this.kernelInitializer),recurrentInitializer:Ze(this.recurrentInitializer),biasInitializer:Ze(this.biasInitializer),kernelRegularizer:Pe(this.kernelRegularizer),recurrentRegularizer:Pe(this.recurrentRegularizer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),kernelConstraint:ot(this.kernelConstraint),recurrentConstraint:ot(this.recurrentConstraint),biasConstraint:ot(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}Iu.className="SimpleRNNCell";V.registerClass(Iu);class km extends rn{constructor(e){e.cell=new Iu(e),super(e)}call(e,t){return C(()=>{this.cell.dropoutMask!=null&&(ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,n=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:n,initialState:i})})}static fromConfig(e,t){return new e(t)}}km.className="SimpleRNN";V.registerClass(km);class vu extends go{constructor(e){super(e);if(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 k("GRUCell does not support reset_after parameter set to true.");this.units=e.units,yt(this.units,"units"),this.activation=Vn(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vn(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=je(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=je(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=je(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ye(e.kernelRegularizer),this.recurrentRegularizer=Ye(e.recurrentRegularizer),this.biasRegularizer=Ye(e.biasRegularizer),this.kernelConstraint=at(e.kernelConstraint),this.recurrentConstraint=at(e.recurrentConstraint),this.biasConstraint=at(e.biasConstraint),this.dropout=fa([1,Pn([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=fa([1,Pn([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Ue(e);const t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return C(()=>{if(e=e,e.length!==2)throw new k(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const s=t.training==null?!1:t.training;let n=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Yi({ones:()=>Ot(e),rate:this.dropout,training:s,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Yi({ones:()=>Ot(n),rate:this.recurrentDropout,training:s,count:3}));const i=this.dropoutMask,r=this.recurrentDropoutMask;let o,a,l;0<this.dropout&&this.dropout<1&&(e=R(e,i[0]));let c=Cn(e,this.kernel.read());this.useBias&&(c=Cs(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(n=R(n,r[0]));const p=this.recurrentKernel.read(),[u,h]=Bt(p,[2*this.units,this.units],p.rank-1),d=Cn(n,u),[m,f,g]=Bt(c,3,c.rank-1),[y,w]=Bt(d,2,d.rank-1);o=this.recurrentActivation.apply($(m,y)),a=this.recurrentActivation.apply($(f,w));const x=Cn(R(a,n),h);l=this.activation.apply($(g,x));const T=$(R(o,n),R($(1,ke(o)),l));return[T,T]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:jn(this.activation),recurrentActivation:jn(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ze(this.kernelInitializer),recurrentInitializer:Ze(this.recurrentInitializer),biasInitializer:Ze(this.biasInitializer),kernelRegularizer:Pe(this.kernelRegularizer),recurrentRegularizer:Pe(this.recurrentRegularizer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),kernelConstraint:ot(this.kernelConstraint),recurrentConstraint:ot(this.recurrentConstraint),biasConstraint:ot(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}}vu.className="GRUCell";V.registerClass(vu);class Dm extends rn{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new vu(e),super(e)}call(e,t){return C(()=>{this.cell.dropoutMask!=null&&(ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,n=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:n,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}Dm.className="GRU";V.registerClass(Dm);class Sa extends go{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,yt(this.units,"units"),this.activation=Vn(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vn(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=je(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=je(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=je(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Ye(e.kernelRegularizer),this.recurrentRegularizer=Ye(e.recurrentRegularizer),this.biasRegularizer=Ye(e.biasRegularizer),this.kernelConstraint=at(e.kernelConstraint),this.recurrentConstraint=at(e.recurrentConstraint),this.biasConstraint=at(e.biasConstraint),this.dropout=fa([1,Pn([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=fa([1,Pn([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=Ue(e);const s=e[e.length-1];this.kernel=this.addWeight("kernel",[s,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let n;if(this.useBias){if(this.unitForgetBias){const i=this.biasInitializer,r=this.units;n=new(t=class extends zs{apply(a,l){const c=i.apply([r]),p=new zl().apply([r]),u=i.apply([r*2]);return jb(jb(c,p),u)}},t.className="CustomInit",t)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return C(()=>{const s=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new k(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=e[1];const i=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Yi({ones:()=>Ot(e),rate:this.dropout,training:s,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Yi({ones:()=>Ot(n),rate:this.recurrentDropout,training:s,count:4}));const r=this.dropoutMask,o=this.recurrentDropoutMask;let a,l,c,p;0<this.dropout&&this.dropout<1&&(e=R(e,r[0]));let u=Cn(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=R(n,o[0])),u=$(u,Cn(n,this.recurrentKernel.read())),this.useBias&&(u=Cs(u,this.bias.read()));const[h,d,m,f]=Bt(u,4,u.rank-1);a=this.recurrentActivation.apply(h),l=this.recurrentActivation.apply(d),c=$(R(l,i),R(a,this.activation.apply(m))),p=this.recurrentActivation.apply(f);const g=R(p,this.activation.apply(c));return[g,g,c]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:jn(this.activation),recurrentActivation:jn(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ze(this.kernelInitializer),recurrentInitializer:Ze(this.recurrentInitializer),biasInitializer:Ze(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Pe(this.kernelRegularizer),recurrentRegularizer:Pe(this.recurrentRegularizer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),kernelConstraint:ot(this.kernelConstraint),recurrentConstraint:ot(this.recurrentConstraint),biasConstraint:ot(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}}Sa.className="LSTMCell";V.registerClass(Sa);class Fm extends rn{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Sa(e),super(e)}call(e,t){return C(()=>{this.cell.dropoutMask!=null&&(ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,n=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:n,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}Fm.className="LSTM";V.registerClass(Fm);class Su extends go{constructor(e){super(e);this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return C(()=>{e=e;let s=e.slice(1);const n=[];for(const o of this.cells.slice().reverse())Array.isArray(o.stateSize)?n.push(s.splice(0,o.stateSize.length)):n.push(s.splice(0,1));n.reverse();const i=[];let r;for(let o=0;o<this.cells.length;++o){const a=this.cells[o];s=n[o],o===0?r=[e[0]].concat(s):r=[r[0]].concat(s),r=a.call(r,t),i.push(r.slice(1))}s=[];for(const o of i.slice().reverse())s.push(...o);return[r[0]].concat(s)})}build(e){sm(e)&&(e=e[0]),e=e;let t;this.cells.forEach((s,n)=>{zn(`RNNCell_${n}`,()=>{s.build(e),Array.isArray(s.stateSize)?t=s.stateSize[0]:t=s.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){const e=super.getConfig(),t=i=>({className:i.getClassName(),config:i.getConfig()}),s=this.cells.map(t),n={cells:s};return Object.assign({},e,n)}static fromConfig(e,t,s={}){const n=[];for(const i of t.cells)n.push(Ls(i,s));return new e({cells:n})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const s of this.cells)t.push(...s.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return cu(e)}setWeights(e){const t=[];for(const s of this.cells){const n=s.weights.length,i=e.splice(n);for(let r=0;r<s.weights.length;++r)t.push([s.weights[r],i[r]])}jl(t)}}Su.className="StackedRNNCells";V.registerClass(Su);function Yi(e){const{ones:t,rate:s,training:n=!1,count:i=1}=e,r=()=>qd(t(),s),o=()=>lo(r,t,n);if(!i||i<=1)return pt(o().clone());const a=Array(i).fill(void 0).map(o);return a.map(l=>pt(l.clone()))}var Vz=function(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(s[n[i]]=e[n[i]]);return s};class gMe extends go{}class TN extends rn{constructor(e){if(e.unroll)throw new ae("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new ae("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new st({ndim:5})]}call(e,t){return C(()=>{if(this.cell.dropoutMask!=null&&(ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new k("ConvRNN2D cell does not support constants");const s=t==null?null:t.mask,n=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:n,initialState:i})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return C(()=>{const{stateSize:t}=this.cell,s=e.shape,n=this.computeSingleOutputShape(s),i=[n[0],...n.slice(2)],r=ye(i);return Array.isArray(t)?Array(t.length).fill(r):[r]})}resetStates(e,t=!1){C(()=>{if(!this.stateful)throw new Sn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape,n=this.computeSingleOutputShape(s),i=[n[0],...n.slice(2)],r=s[0];if(r==null)throw new k("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(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ye(i)):this.states_=[ye(i)];else if(e==null)ce(this.states_),this.keptStates!=null&&(ce(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ye(i)):this.states_[0]=ye(i);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new k(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):ce(this.states_);for(let o=0;o<this.states_.length;++o){const a=e[o],l=i;if(!N.arraysEqual(a.shape,l))throw new k(`State ${o} is incompatible with layer ${this.name}: expected shape=${l}, received shape=${a.shape}`);this.states_[o]=a}}this.states_=this.states_.map(o=>pt(o.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:s,kernelSize:n,padding:i,strides:r,dilationRate:o}=this.cell,a=t==="channelsFirst",l=e[a?3:2],c=e[a?4:3],p=Rs(l,n[0],i,r[0],o[0]),u=Rs(c,n[1],i,r[1],o[1]),h=[...e.slice(0,2),...a?[s,p,u]:[p,u,s]];return h}}TN.className="ConvRNN2D";class Tu extends Sa{constructor(e){const{filters:t,kernelSize:s,strides:n,padding:i,dataFormat:r,dilationRate:o}=e;super(Object.assign({},e,{units:t}));this.filters=t,yt(this.filters,"filters"),this.kernelSize=fo(s,2,"kernelSize"),this.kernelSize.forEach(a=>yt(a,"kernelSize")),this.strides=fo(n||1,2,"strides"),this.strides.forEach(a=>yt(a,"strides")),this.padding=i||"valid",bs(this.padding),this.dataFormat=r||"channelsLast",lt(this.dataFormat),this.dilationRate=fo(o||1,2,"dilationRate"),this.dilationRate.forEach(a=>yt(a,"dilationRate"))}build(e){var t;e=Ue(e);const s=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[s]==null)throw new k(`The channel dimension of the input should be defined. Found ${e[s]}`);const n=e[s],i=4,r=this.kernelSize.concat([n,this.filters*i]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const o=this.kernelSize.concat([this.filters,this.filters*i]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",o,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let a;if(this.unitForgetBias){const l=this.biasInitializer,c=this.filters;a=new(t=class extends zs{apply(u,h){const d=l.apply([c]),m=Kt([c]),f=l.apply([c*2]);return $l([d,m,f])}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*i],null,a,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return C(()=>{if(e.length!==3)throw new k(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const s=t.training||!1,n=e[0],i=e[1],r=e[2],o=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Yi({ones:()=>Ot(n),rate:this.dropout,training:s,count:o}));const a=this.dropoutMask,l=(ie,ne,le)=>!ne||!ne[le]?ie:R(ne[le],ie);let c=l(n,a,0),p=l(n,a,1),u=l(n,a,2),h=l(n,a,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Yi({ones:()=>Ot(i),rate:this.recurrentDropout,training:s,count:o}));const d=this.recurrentDropoutMask;let m=l(i,d,0),f=l(i,d,1),g=l(i,d,2),y=l(i,d,3);const w=3,[x,T,A,_]=Bt(this.kernel.read(),o,w),[E,F,D,M]=this.useBias?Bt(this.bias.read(),o):[null,null,null,null];c=this.inputConv(c,x,E,this.padding),p=this.inputConv(p,T,F,this.padding),u=this.inputConv(u,A,D,this.padding),h=this.inputConv(h,_,M,this.padding);const[P,B,Y,q]=Bt(this.recurrentKernel.read(),o,w);m=this.recurrentConv(m,P),f=this.recurrentConv(f,B),g=this.recurrentConv(g,Y),y=this.recurrentConv(y,q);const K=this.recurrentActivation.apply($(c,m)),H=this.recurrentActivation.apply($(p,f)),Q=$(R(H,r),R(K,this.activation.apply($(u,g)))),J=R(this.recurrentActivation.apply($(h,y)),this.activation.apply(Q));return[J,J,Q]})}getConfig(){const e=super.getConfig(),{units:t}=e,s=Vz(e,["units"]),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},s,n)}inputConv(e,t,s,n){const i=rt(e,t,this.strides,n||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return s?Cs(i,s,this.dataFormat):i}recurrentConv(e,t){const s=1;return rt(e,t,s,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}Tu.className="ConvLSTM2DCell";V.registerClass(Tu);class Mm extends TN{constructor(e){const t=new Tu(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}}Mm.className="ConvLSTM2D";V.registerClass(Mm);class Au extends Le{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(this.noiseShape==null)return this.noiseShape;const t=e.shape,s=[];for(let n=0;n<this.noiseShape.length;++n)s.push(this.noiseShape[n]==null?t[n]:this.noiseShape[n]);return s}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e);if(0<this.rate&&this.rate<1){const n=t.training==null?!1:t.training,i=this.getNoiseShape(s),r=lo(()=>qd(s,this.rate,i,this.seed),()=>s,n);return r}return e})}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Au.className="Dropout";V.registerClass(Au);class Um extends Au{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Um.className="SpatialDropout1D";V.registerClass(Um);class $m extends Le{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,yt(this.units,"units"),this.activation=Vn(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=je(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=je(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=at(e.kernelConstraint),this.biasConstraint=at(e.biasConstraint),this.kernelRegularizer=Ye(e.kernelRegularizer),this.biasRegularizer=Ye(e.biasRegularizer),this.activityRegularizer=Ye(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Ue(e);const t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=Ue(e);const t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e),n=Ud(this.activation.getClassName());let i;return n!=null?i=Cn(s,this.kernel.read(),n,this.bias?this.bias.read():null):(i=Cn(s,this.kernel.read()),this.bias!=null&&(i=Cs(i,this.bias.read())),this.activation!=null&&(i=this.activation.apply(i))),i})}getConfig(){const e={units:this.units,activation:jn(this.activation),useBias:this.useBias,kernelInitializer:Ze(this.kernelInitializer),biasInitializer:Ze(this.biasInitializer),kernelRegularizer:Pe(this.kernelRegularizer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),kernelConstraint:ot(this.kernelConstraint),biasConstraint:ot(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}$m.className="Dense";V.registerClass($m);class Wm extends Le{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Ue(e);for(const t of e.slice(1))if(t==null)throw new k(`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],Nn(e,1)]}call(e,t){return C(()=>{this.invokeCallHook(e,t);let s=we(e);if(this.dataFormat==="channelsFirst"&&s.rank>1){const n=[0];for(let i=2;i<s.rank;++i)n.push(i);n.push(1),s=s.transpose(n)}return vA(s)})}getConfig(){const e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Wm.className="Flatten";V.registerClass(Wm);class zm extends Le{constructor(e){super(e);this.supportsMasking=!0,this.activation=Vn(e.activation)}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e);return this.activation.apply(s)})}getConfig(){const e={activation:jn(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}zm.className="Activation";V.registerClass(zm);class Pm extends Le{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return C(()=>(e=we(e),SA(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Pm.className="RepeatVector";V.registerClass(Pm);class Bm extends Le{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){const s="Total size of new array must be unchanged.",n=t.slice();let i=1,r=null;for(let a=0;a<n.length;++a){const l=n[a];if(this.isUnknown(l))if(r===null)r=a;else throw new k("Can only specifiy one unknown dimension.");else i*=l}const o=Nn(e);if(r!==null){if(i===0||o%i!==0)throw new k(s);n[r]=o/i}else if(o!==i)throw new k(s);return n}computeOutputShape(e){let t=!1;for(let s=0;s<e.length;++s)if(this.isUnknown(e[s])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e),n=s.shape,i=n.slice(0,1).concat(this.fixUnknownDimension(n.slice(1),this.targetShape));return s.reshape(i)})}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Bm.className="Reshape";V.registerClass(Bm);class jm extends Le{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=cs(1,e.dims.length+1);if(!N.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new st({ndim:this.dims.length+1})]}computeOutputShape(e){e=Ue(e);const t=e.slice();return this.dims.forEach((s,n)=>{t[n+1]=e[s]}),t}call(e,t){return se(we(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}jm.className="Permute";V.registerClass(jm);class Vm extends Le{constructor(e){super(e??{});this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const s=we(e),n=-1;return Zo(Js(s,this.maskValue),n)}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e),n=-1,i=!0,r=Zo(Js(s,this.maskValue),n,i),o=s.mul(r.asType(s.dtype));return o})}}Vm.className="Masking";V.registerClass(Vm);class Gm extends Le{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(He(e.inputLength))}this.inputDim=e.inputDim,yt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,yt(this.outputDim,"outputDim"),this.embeddingsInitializer=je(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Ye(e.embeddingsRegularizer),this.activityRegularizer=Ye(e.activityRegularizer),this.embeddingsConstraint=at(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return C(()=>this.maskZero?(e=we(e),Js(e,re(e))):null)}computeOutputShape(e){if(e=Ue(e),this.inputLength==null)return[...e,this.outputDim];const t=He(this.inputLength);if(t.length!==e.length-1)throw new k(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let s=0;for(let n=0;n<t.length;++n){const i=t[n],r=e[n+1];if(i!=null&&r!=null&&i!==r)throw new k(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);i==null&&(t[s]=r),s++}}return[e[0],...t,this.outputDim]}call(e,t){return C(()=>{this.invokeCallHook(e,t);let s=we(e);s.dtype!=="int32"&&(s=ji(s,"int32"));const n=Gd(this.embeddings.read(),s.as1D());return n.reshape(Ue(this.computeOutputShape(s.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ze(this.embeddingsInitializer),embeddingsRegularizer:Pe(this.embeddingsRegularizer),activityRegularizer:Pe(this.activityRegularizer),embeddingsConstraint:ot(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Gm.className="Embedding";V.registerClass(Gm);class Ia extends Le{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new ae}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;const s=e.slice(0,e.length-t.length);for(let n=0;n<t.length;++n){const i=e[e.length-t.length+n],r=t[n];if(i==null||r==null||i<0||r<0)s.push(null);else if(i===1)s.push(r);else if(r===1)s.push(i);else{if(i!==r)throw new k("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));s.push(i)}}return s}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Ue(e)]),e=e,e.length<2)throw new k(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const i of e)i!=null&&i[0]!==null&&t.push(i[0]);if(t=An(t),t.length>1)throw new k(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let s=e[0]==null?null:e[0].slice(1);for(let i=1;i<e.length;++i){const r=e[i]==null?null:e[i].slice(1);s=this.computeElementwiseOpOutputShape(s,r)}const n=e.map(i=>i.length);e.indexOf(null)===-1&&An(n).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return C(()=>{if(e=e,this.reshapeRequired){const s=[],n=e.map(i=>i.rank);if(n.indexOf(null)===-1){const i=Pn(n);for(let r of e){const o=r.rank;for(let a=0;a<i-o;++a)r=Vi(r,1);s.push(r)}return this.mergeFunction(s)}else{let i=!1;for(const a of e){const l=a.rank;if(l==null){const c=a.shape,p=c[0],u=c.slice(1).concat([p]);let h=a.reshape([p].concat(Nn(c.slice(1))));h=se(h,[1,0]),h=h.reshape(u),s.push(h),i=!0}else if(l>1){const c=cs(1,l).concat([0]);s.push(se(a,c)),i=!0}else s.push(a)}let r=this.mergeFunction(s);const o=r.rank;if(i){if(o==null){const a=r.shape,l=a.length,c=a[l-1],p=[c].concat(a.slice(0,a.length-1));r=se(r.reshape([-1,c]),[1,0]).reshape(p)}else if(o>1){const a=[o-1].concat(cs(0,o-1));r=se(r,a)}}return r}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let n=1;n<e.length;++n){const i=e[n]==null?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,i)}let s=[];for(const n of e)n!=null&&n[0]!==null&&s.push(n[0]);return s=An(s),s.length===1?t=s.concat(t):t=[null].concat(t),t}computeMask(e,t){return C(()=>{if(t==null)return null;if(!Array.isArray(t))throw new k("`mask` should be an Array");if(!Array.isArray(e))throw new k("`inputs` should be an Array");if(t.length!==e.length)throw new k(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(n=>n==null))return null;t=t.map(n=>n==null?n:Mt(n,0));let s=t[0];for(let n=1;n<t.length-1;++n)s=Yt(s,t[n]);return s})}}class qm extends Ia{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=$(t,e[s]);return t})}}qm.className="Add";V.registerClass(qm);class Hm extends Ia{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=R(t,e[s]);return t})}}Hm.className="Multiply";V.registerClass(Hm);class Ym extends Ia{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=$(t,e[s]);return R(1/e.length,t)})}}Ym.className="Average";V.registerClass(Ym);class Km extends Ia{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0];for(let s=1;s<e.length;++s)t=Ht(t,e[s]);return t})}}Km.className="Maximum";V.registerClass(Km);class Xm extends Ia{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0];for(let s=1;s<e.length;++s)t=bn(t,e[s]);return t})}}Xm.className="Minimum";V.registerClass(Xm);class Jm extends Ia{constructor(e){super(e);this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!(Array.isArray(e)&&Array.isArray(e[0]))||e.length===1)throw new k("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(const n of e)if(n!=null){t=!1;break}if(t)return;const s=[];for(let n=0;n<e.length;++n){const i=e[n].slice();i.splice(this.axis,1);let r=!1;for(const o of s)if(N.arraysEqual(o,i)){r=!0;break}r||s.push(i)}if(s.length>1)throw new k("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return C(()=>$l(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new k("A `Concatenate` layer should be called on a list of inputs.");const t=e,s=t[0].slice(),n=this.axis<0?s.length+this.axis:this.axis;for(const i of t.slice(1)){if(s[n]==null||i[n]==null){s[n]=null;break}s[n]+=i[n]}return s}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new k("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new k("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new k(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return C(()=>{let s=!0;if(t.forEach(r=>{if(r!=null){s=!1;return}}),s)return null;const n=[];for(let r=0;r<e.length;++r)t[r]==null?n.push(Ot(e[r]).asType("bool")):t[r].rank<e[r].rank?n.push(Mt(t[r],-1)):n.push(t[r]);const i=be(n,this.axis);return hl(i,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}Jm.className="Concatenate";V.registerClass(Jm);function Nu(e,t){for(;e<0;)e+=t;return e}function Gz(e,t,s){if(e.shape.length>3||t.shape.length>3)throw new ae("batchDot is not implemented for tensors of 4D or higher rank yet");if(N.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),N.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof s=="number"&&(s=[s,s]),e.dtype==="complex64"||t.dtype==="complex64")throw new ae("batchDot is not implemented for complex64-type Tensors yet.");const n=e.shape.length,i=t.shape.length;s==null&&(s=[n-1,i-2]);const r=s;return C(()=>{let o;if(n>i){o=n-i;const l=[];for(let c=0;c<o;++c)l.push(1);t=t.reshape(t.shape.concat(l))}else if(i>n){o=i-n;const l=[];for(let c=0;c<o;++c)l.push(1);e=e.reshape(e.shape.concat(l))}else o=0;let a;if(e.shape.length===2&&t.shape.length===2)r[0]===r[1]?a=e.mul(t).sum(r[0]):a=e.transpose([1,0]).mul(t).sum(r[1]);else{const l=r[0]!==e.shape.length-1,c=r[1]===t.shape.length-1;a=e.matMul(t,l,c)}if(o>0){let l;n>i?l=n+i-3:l=n-1;const c=[];for(let p=l;p<l+o;++p)c.push(p);a=a.squeeze(c)}return a.shape.length===1&&(a=a.expandDims(1)),a})}class Zm extends Ia{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){N.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0],s=e[1];if(t.length>3||s.length>3)throw new ae("Dot layer does not support tensors of 4D or higher rank yet.");const n=this.interpretAxes(t,s);if(t[n[0]]!==s[n[1]])throw new k(`Dimension incompatibility: ${t[n[0]]} !== ${s[n[1]]}`)}mergeFunction(e){if(e.length!==2)throw new k(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],s=e[1],n;return Array.isArray(this.axes)?n=this.axes.map((i,r)=>Nu(i,e[r].shape.length)):n=[Nu(this.axes,t.shape.length),Nu(this.axes,s.shape.length)],this.normalize&&(t=pu(t,n[0]),s=pu(s,n[1])),Gz(t,s,n)}interpretAxes(e,t){let s;return Array.isArray(this.axes)?s=this.axes:s=[Nu(this.axes,e.length),Nu(this.axes,t.length)],s}computeOutputShape(e){N.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0].slice(),s=e[1].slice();if(t.length>3||s.length>3)throw new ae("Dot layer does not support tensors of 4D or higher rank yet.");const n=this.interpretAxes(t,s);t.splice(n[0],1),s.splice(n[1],1),s.splice(0,1);const i=t.concat(s);return i.length===1&&i.push(1),i}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}Zm.className="Dot";V.registerClass(Zm);class Qm extends Le{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e),n=()=>Wl(s.shape,0,this.stddev).add(s),i=lo(n,()=>s,t.training||!1);return i})}}Qm.className="GaussianNoise";V.registerClass(Qm);class ef extends Le{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e);if(this.rate>0&&this.rate<1){const n=()=>{const i=Math.sqrt(this.rate/(1-this.rate));return s.mul(Wl(s.shape,1,i))};return lo(n,()=>s,t.training||!1)}return s})}}ef.className="GaussianDropout";V.registerClass(ef);class tf extends Le{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||we(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return C(()=>{if(this.rate<1&&this.rate>0){const s=this._getNoiseShape(e),n=()=>{const i=we(e),r=1.6732632423543772,o=1.0507009873554805,a=-r*o;let l=ms(wn(s),this.rate);l=ji(l,"float32");const c=((1-this.rate)*(1+this.rate*a**2))**-.5,p=-c*a*this.rate,u=i.mul(l).add(l.add(-1).mul(a));return u.mul(c).add(p)};return lo(n,()=>we(e),t.training||!1)}return e})}}tf.className="AlphaDropout";V.registerClass(tf);function Cu(e,t,s,n,i,r=.001){let o;if(e.rank===2)o=Yh(e,t,s,n,i,r);else if(e.rank===3)o=Kh(e,t,s,n,i,r);else if(e.rank===4)o=Xh(e,t,s,n,i,r);else throw new ae(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function qz(e,t,s,n,i=.001){return C(()=>{const r=na(e,n),o=r.mean,a=r.variance,l=Cu(e,o,a,s,t,i);return[l,o,a]})}function Hz(e,t,s,n,i=.001){return C(()=>{const r=na(e,n),o=r.mean,a=r.variance,l=[];for(const m of cs(0,e.rank))n.indexOf(m)!==-1?l.push(1):l.push(e.shape[m]);const c=o.reshape(l),p=a.reshape(l),u=t==null?null:t.reshape(l),h=s==null?null:s.reshape(l),d=Cu(e,c,p,h,u,i);return[d,o,a]})}function Yz(e,t,s,n,i=.001){return N.arraysEqual(n.slice().sort(),cs(0,e.rank-1))?qz(e,t,s,n,i):Hz(e,t,s,n,i)}class sf extends Le{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=je(e.betaInitializer||"zeros"),this.gammaInitializer=je(e.gammaInitializer||"ones"),this.movingMeanInitializer=je(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=je(e.movingVarianceInitializer||"ones"),this.betaConstraint=at(e.betaConstraint),this.gammaConstraint=at(e.gammaConstraint),this.betaRegularizer=Ye(e.betaRegularizer),this.gammaRegularizer=Ye(e.gammaRegularizer)}build(e){e=Ue(e);const t=this.axis>=0?this.axis:this.axis+e.length,s=e[t];if(s==null)throw new k(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new st({ndim:e.length,axes:{[t]:s}})];const n=[s];this.scale&&(this.gamma=this.addWeight("gamma",n,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",n,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",n,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",n,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return C(()=>{const s=t.training==null?!1:t.training,n=we(e),i=n.shape,r=i.length,o=cs(0,r),a=this.axis>=0?this.axis:this.axis+r;o.splice(a,1);const l=In(1,r);l[a]=i[a];const c=o.slice();c.sort();const p=!N.arraysEqual(c,cs(0,r).slice(0,r-1)),u=()=>{if(p){const y=this.movingMean.read().reshape(l),w=this.movingVariance.read().reshape(l),x=this.center?this.beta.read().reshape(l):null,T=this.scale?this.gamma.read().reshape(l):null;return Cu(n,y,w,x,T,this.epsilon)}else return Cu(n,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!s)return u();const[h,d,m]=Yz(n,this.gamma.read(),this.beta.read(),o,this.epsilon),f=(y,w,x)=>{C(()=>{const T=1-x,A=y.read(),_=A.sub(w).mul(T);y.write(A.sub(_))})},g=()=>{f(this.movingMean,d,this.momentum),f(this.movingVariance,m,this.momentum)};return g(),h})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ze(this.betaInitializer),gammaInitializer:Ze(this.gammaInitializer),movingMeanInitializer:Ze(this.movingMeanInitializer),movingVarianceInitializer:Ze(this.movingVarianceInitializer),betaRegularizer:Pe(this.betaRegularizer),gammaRegularizer:Pe(this.gammaRegularizer),betaConstraint:ot(this.betaConstraint),gammaConstraint:ot(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}sf.className="BatchNormalization";V.registerClass(sf);class nf extends Le{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(const t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=je(e.betaInitializer||"zeros"),this.gammaInitializer=je(e.gammaInitializer||"ones"),this.betaRegularizer=Ye(e.betaRegularizer),this.gammaRegularizer=Ye(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Ue(e);const t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let i=0;i<this.axis.length;++i)this.axis[i]<0&&(this.axis[i]+=t);for(const i of this.axis)if(i<0||i>=t)throw new Error(`Invalid axis: ${i}`);if(this.axis.length!==An(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const s=this.axis.map(i=>e[i]),n=!0;this.scale?this.gamma=this.addWeight("gamma",s,"float32",this.gammaInitializer,this.gammaRegularizer,n):this.gamma=null,this.center?this.beta=this.addWeight("beta",s,"float32",this.betaInitializer,this.betaRegularizer,n):this.beta=null,this.built=!0}call(e,t){const s=we(e),n=s.shape,i=n.length;return C(()=>{const r=!0;let{mean:o,variance:a}=na(s,this.axis,r);const l=In(1,i);for(const m of this.axis)l[m]=n[m];const c=m=>m!=null&&m.shape.length!==i&&this.axis!==[i-1]?m.reshape(l):m;let p=c(this.gamma.read()),u=c(this.beta.read());const h=[],d=[];for(let m=0;m<i;++m)this.axis.indexOf(m)!==-1?(h.push(n[m]),d.push(1)):(h.push(1),d.push(n[m]));return o=o.tile(h),a=a.tile(h),p=p.tile(d),u=u.tile(d),Cu(s,o,a,u,p,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ze(this.betaInitializer),gammaInitializer:Ze(this.gammaInitializer),betaRegularizer:Pe(this.betaRegularizer),gammaRegularizer:Pe(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}nf.className="LayerNormalization";V.registerClass(nf);function Kz(e,t,s){return C(()=>{if(e.rank!==4)throw new k(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new k("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(s==null&&(s=ys()),s!=="channelsLast"&&s!=="channelsFirst")throw new k(`Unknown data format: ${s}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let n;return s==="channelsFirst"?n=[[0,0],[0,0],t[0],t[1]]:n=[[0,0],t[0],t[1],[0,0]],Pt(e,n)})}class rf extends Le{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?ys():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new k(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,s;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],s=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new k(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new k(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);s=e.padding[1]}this.padding=[t,s]}this.inputSpec=[new st({ndim:4})]}computeOutputShape(e){e=Ue(e);let t,s;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?s=e[3]+this.padding[1][0]+this.padding[1][1]:s=null,[e[0],e[1],t,s]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?s=e[2]+this.padding[1][0]+this.padding[1][1]:s=null,[e[0],t,s,e[3]])}call(e,t){return C(()=>Kz(we(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}rf.className="ZeroPadding2D";V.registerClass(rf);function of(e,t,s,n,i,r){return C(()=>{lt(i),Pb(r),bs(n),s==null&&(s=[1,1]),n==null&&(n="valid"),i==null&&(i=ys()),r==null&&(r="max"),e=bu(e,i);let o;const a=n==="same"?"same":"valid";return r==="max"?o=ft(e,t,s,a):o=ds(e,t,s,a),i==="channelsFirst"&&(o=se(o,[0,3,1,2])),o})}function AN(e,t,s,n,i,r){return C(()=>{lt(i),Pb(r),bs(n),s==null&&(s=[1,1,1]),n==null&&(n="valid"),i==null&&(i=ys()),r==null&&(r="max"),e=rw(e,i);let o;const a=n==="same"?"same":"valid";return r==="max"?o=Tl(e,t,s,a):o=ml(e,t,s,a),i==="channelsFirst"&&(o=se(o,[0,4,1,2,3])),o})}class NN extends Le{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new k(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(yt(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new k(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);yt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,bs(this.padding),this.inputSpec=[new st({ndim:3})]}computeOutputShape(e){e=Ue(e);const t=Rs(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return C(()=>{this.invokeCallHook(e,t),e=Vi(we(e),2);const s=this.poolingFunction(we(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Qs(s,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class af extends NN{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return lt(i),bs(n),of(e,t,s,n,i,"max")}}af.className="MaxPooling1D";V.registerClass(af);class lf extends NN{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return lt(i),bs(n),of(e,t,s,n,i,"avg")}}lf.className="AveragePooling1D";V.registerClass(lf);class CN extends Le{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new k(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];yt(this.poolSize,"poolSize"),yt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,lt(this.dataFormat),bs(this.padding),this.inputSpec=[new st({ndim:4})]}computeOutputShape(e){e=Ue(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Rs(t,this.poolSize[0],this.padding,this.strides[0]),s=Rs(s,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,s]:[e[0],t,s,e[3]]}call(e,t){return C(()=>(this.invokeCallHook(e,t),this.poolingFunction(we(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class cf extends CN{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return lt(i),bs(n),of(e,t,s,n,i,"max")}}cf.className="MaxPooling2D";V.registerClass(cf);class pf extends CN{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return lt(i),bs(n),of(e,t,s,n,i,"avg")}}pf.className="AveragePooling2D";V.registerClass(pf);class RN extends Le{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new k(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];yt(this.poolSize,"poolSize"),yt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,lt(this.dataFormat),bs(this.padding),this.inputSpec=[new st({ndim:5})]}computeOutputShape(e){e=Ue(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Rs(t,this.poolSize[0],this.padding,this.strides[0]),s=Rs(s,this.poolSize[1],this.padding,this.strides[1]),n=Rs(n,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,s,n]:[e[0],t,s,n,e[4]]}call(e,t){return C(()=>(this.invokeCallHook(e,t),this.poolingFunction(we(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class uf extends RN{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return lt(i),bs(n),AN(e,t,s,n,i,"max")}}uf.className="MaxPooling3D";V.registerClass(uf);class hf extends RN{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return lt(i),bs(n),AN(e,t,s,n,i,"avg")}}hf.className="AveragePooling3D";V.registerClass(hf);class ON extends Le{constructor(e){super(e);this.inputSpec=[new st({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new ae}}class df extends ON{constructor(e){super(e||{})}call(e,t){return C(()=>{const s=we(e);return Xe(s,1)})}}df.className="GlobalAveragePooling1D";V.registerClass(df);class mf extends ON{constructor(e){super(e||{})}call(e,t){return C(()=>{const s=we(e);return Lt(s,1)})}}mf.className="GlobalMaxPooling1D";V.registerClass(mf);class EN extends Le{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,lt(this.dataFormat),this.inputSpec=[new st({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new ae}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class ff extends EN{call(e,t){return C(()=>{const s=we(e);return this.dataFormat==="channelsLast"?Xe(s,[1,2]):Xe(s,[2,3])})}}ff.className="GlobalAveragePooling2D";V.registerClass(ff);class gf extends EN{call(e,t){return C(()=>{const s=we(e);return this.dataFormat==="channelsLast"?Lt(s,[1,2]):Lt(s,[2,3])})}}gf.className="GlobalMaxPooling2D";V.registerClass(gf);class _N extends Le{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,s={}){const n=t.layer,i=Ls(n,s);delete t.layer;const r={layer:i};return Object.assign(r,t),new e(r)}}class yf extends _N{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=Ue(e),e.length<3)throw new k(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=Ue(e);const t=[e[0]].concat(e.slice(2)),s=this.layer.computeOutputShape(t),n=e[1];return[s[0],n].concat(s.slice(1))}call(e,t){return C(()=>{e=we(e);const s=(r,o)=>{const a=we(this.layer.call(r,t));return[a,[]]},n=aw(s,e,[],!1,null,null,!1,!0),i=n[1];return i})}}yf.className="TimeDistributed";V.registerClass(yf);function Xz(e){Bi(yA,"BidirectionalMergeMode",e)}const Jz="concat";class bf extends _N{constructor(e){super(e);const t=e.layer.getConfig(),s={};s.className=e.layer.getClassName(),s.config=t,this.forwardLayer=Ls(s),t.goBackwards=!(t.goBackwards===!0);const n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=Ls(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?Jz:e.mergeMode,Xz(this.mergeMode),e.weights)throw new ae("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,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,s=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,s)),this.backwardLayer.setWeights(e.slice(s))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let s,n,i;return this.returnState&&(i=t.slice(1)),s=t[0],s=s,this.mergeMode==="concat"?(s[s.length-1]*=2,n=[s]):this.mergeMode==null?n=[s,s.slice()]:n=[s],this.returnState?this.mergeMode==null?n.concat(i).concat(i.slice()):[s].concat(i).concat(i.slice()):jt(n)}apply(e,t){let s=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});const i=ow(e,s,n,this.numConstants);if(e=i.inputs,s=i.initialState,n=i.constants,Array.isArray(e)&&(s=e.slice(1),e=e[0]),(s==null||s.length===0)&&n==null)return super.apply(e,t);const r=[],o=[];if(s!=null){const l=s.length;if(l%2>0)throw new k("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=s,r.push(...s);const c=s.map(p=>new st({shape:p.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),o.push(...c)}if(n!=null)throw new ae("Support for constants in Bidirectional layers is not implemented yet.");const a=r[0]instanceof xs;for(const l of r)if(l instanceof xs!==a)throw new k("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(a){const l=[e].concat(r),c=this.inputSpec.concat(o),p=this.inputSpec;this.inputSpec=c;const u=super.apply(l,t);return this.inputSpec=p,u}else return super.apply(e,t)}call(e,t){return C(()=>{const s=t.initialState;let n,i;if(s==null)n=this.forwardLayer.call(e,t),i=this.backwardLayer.call(e,t);else{const a=s.slice(0,s.length/2),l=s.slice(s.length/2);n=this.forwardLayer.call(e,Object.assign(t,{initialState:a})),i=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let r;this.returnState&&(Array.isArray(n)&&(r=n.slice(1).concat(i.slice(1))),n=n[0],i=i[0]),this.returnSequences&&(i=Et(i,1));let o;return this.mergeMode==="concat"?o=$l([n,i]):this.mergeMode==="sum"?o=$(n,i):this.mergeMode==="ave"?o=R(.5,$(n,i)):this.mergeMode==="mul"?o=R(n,i):this.mergeMode==null&&(o=[n,i]),this.returnState?this.mergeMode==null?o.concat(r):[o].concat(r):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){zn(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),zn(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let s;if(this.returnSequences?this.mergeMode==null?s=[t,t]:s=t:this.mergeMode==null?s=[null,null]:s=null,this.returnState){const n=this.forwardLayer.states,i=n.map(r=>null);return Array.isArray(s)?s.concat(i).concat(i):[s].concat(i).concat(i)}else return s}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),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const s=Ls(t.layer);if(delete t.layer,t.numConstants!=null)throw new ae("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const n=t;return n.layer=s,new e(n)}}bf.className="Bidirectional";V.registerClass(bf);const lw={};Ee(lw,{Layer:()=>Le,RNN:()=>rn,RNNCell:()=>go,activation:()=>dP,add:()=>SP,alphaDropout:()=>rB,average:()=>IP,averagePooling1d:()=>cw,averagePooling2d:()=>pw,averagePooling3d:()=>uw,avgPool1d:()=>_P,avgPool2d:()=>DP,avgPool3d:()=>MP,avgPooling1d:()=>kP,avgPooling2d:()=>FP,avgPooling3d:()=>UP,batchNormalization:()=>RP,bidirectional:()=>JP,concatenate:()=>vP,conv1d:()=>rP,conv2d:()=>oP,conv2dTranspose:()=>aP,conv3d:()=>lP,convLstm2d:()=>HP,convLstm2dCell:()=>YP,cropping2D:()=>pP,dense:()=>mP,depthwiseConv2d:()=>hP,dot:()=>CP,dropout:()=>fP,elu:()=>Qz,embedding:()=>LP,flatten:()=>yP,gaussianDropout:()=>iB,gaussianNoise:()=>nB,globalAveragePooling1d:()=>$P,globalAveragePooling2d:()=>WP,globalMaxPool1d:()=>QP,globalMaxPool2d:()=>eB,globalMaxPooling1d:()=>kN,globalMaxPooling2d:()=>DN,gru:()=>PP,gruCell:()=>BP,input:()=>wm,inputLayer:()=>Zz,layerNormalization:()=>OP,leakyReLU:()=>tP,lstm:()=>jP,lstmCell:()=>VP,masking:()=>oB,maxPool1d:()=>tB,maxPool2d:()=>sB,maxPooling1d:()=>FN,maxPooling2d:()=>MN,maxPooling3d:()=>zP,maximum:()=>TP,minimum:()=>AP,multiply:()=>NP,permute:()=>xP,prelu:()=>sP,reLU:()=>eP,repeatVector:()=>bP,reshape:()=>wP,rnn:()=>KP,separableConv2d:()=>cP,simpleRNN:()=>GP,simpleRNNCell:()=>qP,softmax:()=>nP,spatialDropout1d:()=>gP,stackedRNNCells:()=>XP,thresholdedReLU:()=>iP,timeDistributed:()=>ZP,upSampling2d:()=>uP,zeroPadding2d:()=>EP});function Zz(e){return new qi(e)}function Qz(e){return new vm(e)}function eP(e){return new Lm(e)}function tP(e){return new Sm(e)}function sP(e){return new Im(e)}function nP(e){return new Am(e)}function iP(e){return new Tm(e)}function rP(e){return new Lu(e)}function oP(e){return new Kl(e)}function aP(e){return new Cm(e)}function lP(e){return new xu(e)}function cP(e){return new Rm(e)}function pP(e){return new Om(e)}function uP(e){return new Em(e)}function hP(e){return new _m(e)}function dP(e){return new zm(e)}function mP(e){return new $m(e)}function fP(e){return new Au(e)}function gP(e){return new Um(e)}function yP(e){return new Wm(e)}function bP(e){return new Pm(e)}function wP(e){return new Bm(e)}function xP(e){return new jm(e)}function LP(e){return new Gm(e)}function SP(e){return new qm(e)}function IP(e){return new Ym(e)}function vP(e){return new Jm(e)}function TP(e){return new Km(e)}function AP(e){return new Xm(e)}function NP(e){return new Hm(e)}function CP(e){return new Zm(e)}function RP(e){return new sf(e)}function OP(e){return new nf(e)}function EP(e){return new rf(e)}function cw(e){return new lf(e)}function _P(e){return cw(e)}function kP(e){return cw(e)}function pw(e){return new pf(e)}function DP(e){return pw(e)}function FP(e){return pw(e)}function uw(e){return new hf(e)}function MP(e){return uw(e)}function UP(e){return uw(e)}function $P(e){return new df(e)}function WP(e){return new ff(e)}function kN(e){return new mf(e)}function DN(e){return new gf(e)}function FN(e){return new af(e)}function MN(e){return new cf(e)}function zP(e){return new uf(e)}function PP(e){return new Dm(e)}function BP(e){return new vu(e)}function jP(e){return new Fm(e)}function VP(e){return new Sa(e)}function GP(e){return new km(e)}function qP(e){return new Iu(e)}function HP(e){return new Mm(e)}function YP(e){return new Tu(e)}function KP(e){return new rn(e)}function XP(e){return new Su(e)}function JP(e){return new bf(e)}function ZP(e){return new yf(e)}const QP=kN,eB=DN,tB=FN,sB=MN;function nB(e){return new Qm(e)}function iB(e){return new ef(e)}function rB(e){return new tf(e)}function oB(e){return new Vm(e)}const hw={};Ee(hw,{MAPE:()=>yB,MSE:()=>xB,binaryAccuracy:()=>aB,binaryCrossentropy:()=>lB,categoricalAccuracy:()=>pB,categoricalCrossentropy:()=>uB,cosineProximity:()=>mB,mape:()=>bB,meanAbsoluteError:()=>fB,meanAbsolutePercentageError:()=>gB,meanSquaredError:()=>wB,mse:()=>LB,precision:()=>hB,recall:()=>dB,sparseCategoricalAccuracy:()=>cB});function aB(e,t){return du(e,t)}function lB(e,t){return cm(e,t)}function cB(e,t){return pm(e,t)}function pB(e,t){return mu(e,t)}function uB(e,t){return fu(e,t)}function hB(e,t){return Xb(e,t)}function dB(e,t){return FA(e,t)}function mB(e,t){return uu(e,t)}function fB(e,t){return Vl(e,t)}function gB(e,t){return po(e,t)}function yB(e,t){return po(e,t)}function bB(e,t){return po(e,t)}function wB(e,t){return yi(e,t)}function xB(e,t){return yi(e,t)}function LB(e,t){return yi(e,t)}const dw={};Ee(dw,{modelFromJSON:()=>eN});const mw={};Ee(mw,{l1:()=>IB,l1l2:()=>SB,l2:()=>vB});function SB(e){return new Yl(e)}function IB(e){return wN(e)}function vB(e){return xN(e)}class fw extends ba{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof nn))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function wf(e,t){return e<t}function UN(e,t){return e>t}class gw extends fw{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new ae("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=wf:this.mode==="max"?this.monitorFunc=UN:this.monitor.indexOf("acc")!==-1?this.monitorFunc=UN:this.monitorFunc=wf,this.monitorFunc===wf&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===wf?Infinity:-Infinity}async onEpochEnd(e,t){await gi(t);const s=this.getMonitorValue(t);if(s==null)return;this.monitorFunc(s-this.minDelta,this.best)?(this.best=s,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});const t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}function TB(e){return new gw(e)}const $N={earlyStopping:TB};var Rn;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(Rn||(Rn={}));var WN;(function(e){let t;(function(s){s[s.LEGACY=0]="LEGACY",s[s.V1=1]="V1",s[s.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(WN||(WN={}));const yw={};function zN(e,t){const s={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};yw[e]=s}function xf(e){return yw[e]}function PN(e){delete yw[e]}function L(e,t,s,n){const i=t.inputParams[e];if(i&&i.inputIndexStart!==void 0){const o=i.inputIndexStart,a=i.inputIndexEnd===0?void 0:i.inputIndexEnd===void 0?o+1:i.inputIndexEnd;if(i.type==="tensor")return Vt(t.inputNames[i.inputIndexStart],s,n);if(i.type==="tensors"){const p=t.inputNames.slice(o,a);return p.map(u=>Vt(u,s,n))}const l=Vt(t.inputNames.slice(o)[0],s,n),c=l.dataSync();return i.type==="number"?c[0]:N.toNestedArray(l.shape,c)}const r=t.attrParams[e];return r&&r.value}function Vt(e,t,s){const[n,i]=Ss(e),r=s.currentContextIds.find(o=>!!t[Lf(n,o)]);return r!==void 0?t[Lf(n,r)][i]:void 0}function BN(e,t,s){return t[Lf(e,s.currentContextId)]}function Gn(e,t){const[s,n]=Ss(e);return[Lf(s,t&&t.currentContextId),n]}function Lf(e,t){return t?`${e}-${t}`:e}function Ss(e){const t=e.split(":");if(t.length===1)return[e,0];const s=t[0];return[s,Number(t[t.length-1])]}function Ru(e,t,s){let n=L("pad",e,t,s);if(n==="explicit"){n=L("explicitPaddings",e,t,s);const i=[[0,0],[0,0],[0,0],[0,0]];for(let r=0;r<4;r++)i[r][0]=n[r*2],i[r][1]=n[r*2+1];return i}return n}function qn(e){return e.kept?e:Fs(e)}const bw={};Ee(bw,{json:()=>AB});const AB=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];const ww={};Ee(ww,{json:()=>NB});const NB=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"clip_value_min",name:"clipValueMin",type:"number"},{tfName:"clip_value_max",name:"clipValueMax",type:"number"}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"clipValueMin",name:"clipValueMin",type:"number",defaultValue:0},{tfName:"clipValueMax",name:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];const xw={};Ee(xw,{json:()=>CB});const CB=[{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}];const Lw={};Ee(Lw,{json:()=>RB});const RB=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}];const Sw={};Ee(Sw,{json:()=>OB});const OB=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}];const Iw={};Ee(Iw,{json:()=>EB});const EB=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];const vw={};Ee(vw,{json:()=>_B});const _B=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}];const Tw={};Ee(Tw,{json:()=>kB});const kB=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}];const Aw={};Ee(Aw,{json:()=>DB});const DB=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}];const Nw={};Ee(Nw,{json:()=>FB});const FB=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];const Cw={};Ee(Cw,{json:()=>MB});const MB=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];const Rw={};Ee(Rw,{json:()=>UB});const UB=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}];const Ow={};Ee(Ow,{json:()=>$B});const $B=[{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}];const Ew={};Ee(Ew,{json:()=>WB});const WB=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}];const _w={};Ee(_w,{json:()=>zB});const zB=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}];const kw={};Ee(kw,{json:()=>PB});const PB=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]}];class Fw{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[bw,ww,xw,Lw,Sw,Iw,vw,Nw,Aw,Tw,Cw,Rw,Ow,Ew,_w,kw],t=[].concat(...e.map(s=>s.json));this.opMappers=t.reduce((s,n)=>(s[n.tfOpName]=n,s),{})}transformGraph(e,t={}){const s=e.node,n=[],i=[],r=[],o=s.reduce((m,f)=>(m[f.name]=this.mapNode(f),f.op.startsWith("Placeholder")?n.push(m[f.name]):f.op==="Const"?i.push(m[f.name]):(f.input==null||f.input.length===0)&&r.push(m[f.name]),m),{});let a=[];const l=[];let c={},p={};t!=null&&(c=this.mapSignatureEntries(t.inputs),p=this.mapSignatureEntries(t.outputs));const u=Object.keys(o);u.forEach(m=>{const f=o[m];f.inputNames.forEach(g=>{const[y]=Gn(g);f.inputs.push(o[y]),o[y].children.push(f)})}),Object.keys(p).length===0?u.forEach(m=>{const f=o[m];f.children.length===0&&l.push(f)}):Object.keys(p).forEach(m=>{const[f]=Gn(m),g=o[f];g!=null&&(g.signatureKey=p[m],l.push(g))}),Object.keys(c).length>0?Object.keys(c).forEach(m=>{const[f]=Gn(m),g=o[f];g&&(g.signatureKey=c[m],a.push(g))}):a=n;let h={};e.library!=null&&e.library.function!=null&&(h=e.library.function.reduce((m,f)=>(m[f.signature.name]=this.mapFunction(f),m),{}));const d={nodes:o,inputs:a,outputs:l,weights:i,placeholders:n,signature:t,functions:h};return r.length>0&&(d.initNodes=r),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,s)=>(t[e[s].name]=s,t),{})}mapNode(e){const t=xf(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});const s={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(n=>n.startsWith("^")?n.substr(1):n),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr};return t.inputs!=null&&(s.inputParams=t.inputs.reduce((n,i)=>(n[i.name]={type:i.type,inputIndexStart:i.start,inputIndexEnd:i.end},n),{})),t.attrs!=null&&(s.attrParams=t.attrs.reduce((n,i)=>{const r=i.type;let o;switch(i.type){case"string":o=Sf(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Sf(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"string[]":o=Rf(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Rf(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number":o=vf(e.attr,i.tfName,i.defaultValue||0),o===void 0&&!!i.tfDeprecatedName&&(o=vf(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number[]":o=Cf(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Cf(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool":o=If(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=If(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool[]":o=Ef(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Ef(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape":o=Nf(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Nf(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape[]":o=Of(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Of(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype":o=Tf(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Tf(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype[]":o=Af(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Af(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"func":o=jN(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=jN(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${i.type} for op: ${e.op}`)}return n[i.name]={value:o,type:r},n},{})),s}mapFunction(e){const t=e.nodeDef,s=[],n=[];let i={};t!=null&&(i=t.reduce((p,u)=>(p[u.name]=this.mapNode(u),u.op==="Const"&&n.push(p[u.name]),p),{}));const r=[],o=[];e.signature.inputArg.forEach(p=>{const[u]=Gn(p.name),h={name:u,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Dw(p.type),type:"dtype"}},children:[]};h.signatureKey=p.name,r.push(h),i[u]=h});const a=Object.keys(i);a.forEach(p=>{const u=i[p];u.inputNames.forEach(h=>{const[d]=Gn(h);u.inputs.push(i[d]),i[d].children.push(u)})});const l=e.ret;e.signature.outputArg.forEach(p=>{const[u,h]=Gn(l[p.name]),d=i[u];d!=null&&(d.defaultOutput=h,o.push(d))});const c=this.mapArgsToSignature(e);return{nodes:i,inputs:r,outputs:o,weights:n,placeholders:s,signature:c}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,s)=>(t[s.name]=this.mapArgToTensorInfo(s),t),{}),outputs:e.signature.outputArg.reduce((t,s)=>(t[s.name]=this.mapArgToTensorInfo(s,e.ret),t),{})}}mapArgToTensorInfo(e,t){let s=e.name;return t!=null&&(s=t[s]),{name:s,dtype:e.type}}}function BB(e){const t=W().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function VN(e,t){const s=Array.isArray(e)?String.fromCharCode.apply(null,e):BB(e);return t?s:s.toLowerCase()}function Sf(e,t,s,n=!1){const i=e[t];return i!=null?VN(i.s,n):s}function If(e,t,s){const n=e[t];return n?n.b:s}function vf(e,t,s){const n=e[t]||{},i=n.i!=null?n.i:n.f!=null?n.f:s;return typeof i=="number"?i:parseInt(i,10)}function Dw(e){typeof e=="string"&&(e=Rn[e]);switch(e){case Rn.DT_FLOAT:return"float32";case Rn.DT_INT32:case Rn.DT_INT64:case Rn.DT_INT8:case Rn.DT_UINT8:return"int32";case Rn.DT_BOOL:return"bool";case Rn.DT_DOUBLE:return"float32";case Rn.DT_STRING:return"string";default:return null}}function jN(e,t,s){const n=e[t];return n&&n.func?n.func.name:s}function Tf(e,t,s){const n=e[t];return n&&n.type?Dw(n.type):s}function Af(e,t,s){const n=e[t];return n&&n.list&&n.list.type?n.list.type.map(i=>Dw(i)):s}function GN(e){return e.unknownRank?void 0:e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function Nf(e,t,s){const n=e[t];return n&&n.shape?GN(n.shape):s}function Cf(e,t,s){const n=e[t];return n?((n.list.f&&n.list.f.length?n.list.f:n.list.i)||[]).map(i=>typeof i=="number"?i:parseInt(i,10)):s}function Rf(e,t,s,n=!1){const i=e[t];return i&&i.list&&i.list.s?i.list.s.map(r=>VN(r,n)):s}function Of(e,t,s){const n=e[t];return n&&n.list&&n.list.shape?n.list.shape.map(i=>GN(i)):s}function Ef(e,t,s){const n=e[t];return n&&n.list&&n.list.b?n.list.b:s}class qN{constructor(e,t,s){this.node=e,this.tensorMap=t,this.context=s,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(n=>this.getInput(n)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((n,i)=>(n[i]=this.getAttr(i),n),{}))}getInput(e){return Vt(e,this.tensorMap,this.context)}getAttr(e,t){const s=this.node.rawAttrs[e];if(s.tensor!=null)return Vt(e,this.tensorMap,this.context);if(s.i!=null||s.f!=null)return vf(this.node.rawAttrs,e,t);if(s.s!=null)return Sf(this.node.rawAttrs,e,t);if(s.b!=null)return If(this.node.rawAttrs,e,t);if(s.shape!=null)return Nf(this.node.rawAttrs,e,t);if(s.type!=null)return Tf(this.node.rawAttrs,e,t);if(s.list!=null){if(s.list.i!=null||s.list.f!=null)return Cf(this.node.rawAttrs,e,t);if(s.list.s!=null)return Rf(this.node.rawAttrs,e,t);if(s.list.shape!=null)return Of(this.node.rawAttrs,e,t);if(s.list.b!=null)return Ef(this.node.rawAttrs,e,t);if(s.list.type!=null)return Af(this.node.rawAttrs,e,t)}return t}}const HN=(e,t,s)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[$(L("a",e,t,s),L("b",e,t,s))];case"AddN":return[Wh(L("tensors",e,t,s))];case"FloorMod":case"Mod":return[Al(L("a",e,t,s),L("b",e,t,s))];case"Mul":return[R(L("a",e,t,s),L("b",e,t,s))];case"RealDiv":case"Div":return[Z(L("a",e,t,s),L("b",e,t,s))];case"DivNoNan":return[rd(L("a",e,t,s),L("b",e,t,s))];case"FloorDiv":return[ul(L("a",e,t,s),L("b",e,t,s))];case"Sub":return[X(L("a",e,t,s),L("b",e,t,s))];case"Minimum":return[bn(L("a",e,t,s),L("b",e,t,s))];case"Maximum":return[Ht(L("a",e,t,s),L("b",e,t,s))];case"Pow":return[es(L("a",e,t,s),L("b",e,t,s))];case"SquaredDifference":return[io(L("a",e,t,s),L("b",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const YN=(e,t,s)=>{switch(e.op){case"Abs":case"ComplexAbs":return[et(L("x",e,t,s))];case"Acos":return[Uh(L("x",e,t,s))];case"Acosh":return[$h(L("x",e,t,s))];case"Asin":return[Ph(L("x",e,t,s))];case"Asinh":return[Bh(L("x",e,t,s))];case"Atan":return[jh(L("x",e,t,s))];case"Atan2":return[Vh(L("x",e,t,s),L("y",e,t,s))];case"Atanh":return[Gh(L("x",e,t,s))];case"Ceil":return[Jh(L("x",e,t,s))];case"Complex":return[Gt(L("real",e,t,s),L("imag",e,t,s))];case"Cos":return[Kr(L("x",e,t,s))];case"Cosh":return[wl(L("x",e,t,s))];case"Elu":return[gn(L("x",e,t,s))];case"Erf":return[od(L("x",e,t,s))];case"Exp":return[ut(L("x",e,t,s))];case"Expm1":return[ad(L("x",e,t,s))];case"Floor":return[ui(L("x",e,t,s))];case"Log":return[zt(L("x",e,t,s))];case"Log1p":return[Sl(L("x",e,t,s))];case"Imag":return[yn(L("x",e,t,s))];case"Neg":return[ke(L("x",e,t,s))];case"Reciprocal":return[yd(L("x",e,t,s))];case"Real":return[Zs(L("x",e,t,s))];case"Relu":return[Fe(L("x",e,t,s))];case"Round":return[wd(L("x",e,t,s))];case"Selu":return[Rl(L("x",e,t,s))];case"Sigmoid":return[os(L("x",e,t,s))];case"Sin":return[Ol(L("x",e,t,s))];case"Sign":return[Ld(L("x",e,t,s))];case"Sinh":return[El(L("x",e,t,s))];case"Softplus":return[di(L("x",e,t,s))];case"Sqrt":return[Je(L("x",e,t,s))];case"Square":return[xe(L("x",e,t,s))];case"Tanh":return[Mi(L("x",e,t,s))];case"Tan":return[Id(L("x",e,t,s))];case"Relu6":case"ClipByValue":return[xt(L("x",e,t,s),L("clipValueMin",e,t,s),L("clipValueMax",e,t,s))];case"Rsqrt":return[Cl(Vt(e.inputNames[0],t,s))];case"Prod":return[Nl(L("x",e,t,s),L("axes",e,t,s))];case"LeakyRelu":return[Ll(L("x",e,t,s),L("alpha",e,t,s))];case"Prelu":return[Qr(L("x",e,t,s),L("alpha",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Bs(e,t,s=""){N.assert(jB(e,t),()=>s+` Shapes ${e} and ${t} must match`)}function jB(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==-1&&t[s]!==-1&&e[s]!==t[s])return!1;return!0}class KN{constructor(e,t,s,n,i,r,o){this.name=e,this.dtype=t,this.maxSize=s,this.elementShape=n,this.identicalElementShapes=i,this.dynamicSize=r,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=j(0),pt(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const s=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Bs(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),s.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(s.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);s.tensor=t,pt(t),s.written=!0,this.tensors[e]=s}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((s,n)=>this.write(s,t[n]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let n=0;n<this.size();n++)e.push(n)}if(e.length===0)return ze([],[0].concat(this.elementShape));const s=this.readMany(e);return Bs(this.elementShape,s[0].shape,"TensorArray shape mismatch: "),Ge(s,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return ze([],[0].concat(this.elementShape));const t=[];for(let n=0;n<this.size();n++)t.push(n);const s=this.readMany(t);return Bs(this.elementShape,s[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${s[0].shape})`),be(s,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const s=Math.max(...e);if(!this.dynamicSize&&s>=this.maxSize)throw new Error(`Max index must be < array size (${s} vs. ${this.maxSize})`);this.writeMany(e,qe(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let s=0;const n=e.map(a=>(s+=a,s));if(s!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${s}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const i=s===0?0:t.size/s,r=[];C(()=>{t=O(t,[1,s,i]);for(let a=0;a<e.length;++a){const l=a===0?0:n[a-1],c=[0,l,0],p=[1,e[a],i];r[a]=O(he(t,c,p),this.elementShape)}return r});const o=[];for(let a=0;a<e.length;a++)o[a]=a;this.writeMany(o,r)}}class Ou{constructor(e,t,s,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=s,e!=null&&e.forEach(i=>{if(s!==i.dtype)throw new Error(`Invalid data types; op elements ${s}, but list elements ${i.dtype}`);Bs(t,i.shape,"TensorList shape mismatch: "),pt(i)}),this.idTensor=j(0),this.maxNumElements=n,pt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Ou([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,s=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(s!==-1&&this.tensors.length!==s)throw new Error(`Operation expected a list with ${s} elements but got a list with ${this.tensors.length} elements.`);return Bs(e,this.elementShape,"TensorList shape mismatch: "),C(()=>{const n=this.tensors.map(i=>O(i,e));return Ge(n,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");const s=this.tensors.pop();return Bs(s.shape,e,"TensorList shape mismatch: "),O(s,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Bs(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");pt(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,s){if(s!==this.elementDtype)throw new Error(`Invalid data types; op elements ${s}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);return Bs(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Bs(this.elementShape,t.shape,"TensorList shape mismatch: "),pt(t),this.tensors[e]=t}gather(e,t,s){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);return Bs(this.elementShape,s,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?ze([],[0].concat(this.elementShape)):C(()=>{const n=e.map(i=>O(this.tensors[i],s));return Ge(n,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Bs(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?ze([],[0].concat(this.elementShape)):C(()=>{const s=this.tensors.map(n=>O(n,t));return be(s,0)})}}function XN(e,t,s){const n=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==s)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${s}`);const i=e.shape.slice(1);Bs(i,t,"TensorList shape mismatch: ");const r=qe(e);return new Ou(r,t,n)}function JN(e,t,s){return new Ou([],e,t,s)}function ZN(e,t,s,n){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const i=Math.max(...t);if(n!=null&&n!==-1&&i>=n)throw new Error(`Max index must be < array size (${i} vs. ${n})`);const r=new Ou([],s,e.dtype,n),o=qe(e,0);return t.forEach((a,l)=>{r.setItem(a,o[l])}),r}function QN(e,t,s){let n=0;const i=t.map(l=>(n+=l,n));if(n!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${e.shape}`);const r=n===0?0:e.size/n,o=C(()=>{const l=[];e=O(e,[1,n,r]);for(let c=0;c<t.length;++c){const p=c===0?0:i[c-1],u=[0,p,0],h=[1,t[c],r];l[c]=O(he(e,u,h),s)}return e.dispose(),l}),a=new Ou([],s,e.dtype,t.length);for(let l=0;l<o.length;l++)a.setItem(l,o[l]);return a}const eC=async(e,t,s)=>{switch(e.op){case"If":case"StatelessIf":{const n=L("thenBranch",e,t,s),i=L("elseBranch",e,t,s),r=L("cond",e,t,s),o=L("args",e,t,s),a=await r.data();return a[0]?s.functionMap[n].executeFunctionAsync(o,s.tensorArrayMap,s.tensorListMap):s.functionMap[i].executeFunctionAsync(o,s.tensorArrayMap,s.tensorListMap)}case"While":case"StatelessWhile":{const n=L("body",e,t,s),i=L("cond",e,t,s),r=L("args",e,t,s),o=await s.functionMap[i].executeFunctionAsync(r,s.tensorArrayMap,s.tensorListMap),a=r.map(p=>p.id);let l=await o[0].data();o.forEach(p=>{!p.kept&&a.indexOf(p.id)===-1&&p.dispose()});let c=r;for(;l[0];){const p=c;c=await s.functionMap[n].executeFunctionAsync(c,s.tensorArrayMap,s.tensorListMap);const u=c.map(d=>d.id);p.forEach(d=>{!d.kept&&a.indexOf(d.id)===-1&&u.indexOf(d.id)===-1&&d.dispose()});const h=await s.functionMap[i].executeFunctionAsync(c,s.tensorArrayMap,s.tensorListMap);l=await h[0].data(),h.forEach(d=>{!d.kept&&a.indexOf(d.id)===-1&&u.indexOf(d.id)===-1&&d.dispose()})}return c}case"LoopCond":{const n=L("pred",e,t,s);return[qn(n)]}case"Switch":{const n=L("pred",e,t,s);let i=L("data",e,t,s);return i.kept||(i=qn(i)),(await n.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const n=e.inputNames.find(i=>Vt(i,t,s)!==void 0);if(n){const i=Vt(n,t,s);return[qn(i)]}return}case"Enter":{const n=L("frameName",e,t,s),i=L("tensor",e,t,s);return s.enterFrame(n),[qn(i)]}case"Exit":{const n=L("tensor",e,t,s);return s.exitFrame(),[qn(n)]}case"NextIteration":{const n=L("tensor",e,t,s);return s.nextIteration(),[qn(n)]}case"TensorArrayV3":{const n=L("size",e,t,s),i=L("dtype",e,t,s),r=L("elementShape",e,t,s),o=L("dynamicSize",e,t,s),a=L("clearAfterRead",e,t,s),l=L("identicalElementShapes",e,t,s),c=L("name",e,t,s),p=new KN(c,i,n,r,l,o,a);return s.addTensorArray(p),[p.idTensor,j(1)]}case"TensorArrayWriteV3":{const n=L("tensorArrayId",e,t,s),i=L("index",e,t,s),r=L("tensor",e,t,s),o=s.getTensorArray(n.id);return o.write(i,r),[o.idTensor]}case"TensorArrayReadV3":{const n=L("tensorArrayId",e,t,s),i=L("index",e,t,s),r=s.getTensorArray(n.id);return[r.read(i)]}case"TensorArrayGatherV3":{const n=L("tensorArrayId",e,t,s),i=L("indices",e,t,s),r=L("dtype",e,t,s),o=s.getTensorArray(n.id);return[o.gather(i,r)]}case"TensorArrayScatterV3":{const n=L("tensorArrayId",e,t,s),i=L("indices",e,t,s),r=L("tensor",e,t,s),o=s.getTensorArray(n.id);return o.scatter(i,r),[o.idTensor]}case"TensorArrayConcatV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id),r=L("dtype",e,t,s);return[i.concat(r)]}case"TensorArraySplitV3":{const n=L("tensorArrayId",e,t,s),i=L("tensor",e,t,s),r=L("lengths",e,t,s),o=s.getTensorArray(n.id);return o.split(r,i),[o.idTensor]}case"TensorArraySizeV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id);return[j(i.size(),"int32")]}case"TensorArrayCloseV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const n=L("tensorListId",e,t,s),i=L("index",e,t,s),r=L("tensor",e,t,s),o=s.getTensorList(n.id);return o.setItem(i,r),[o.idTensor]}case"TensorListGetItem":{const n=L("tensorListId",e,t,s),i=L("index",e,t,s),r=L("elementShape",e,t,s),o=L("elementDType",e,t,s),a=s.getTensorList(n.id);return[a.getItem(i,r,o)]}case"TensorListScatterV2":case"TensorListScatter":{const n=L("indices",e,t,s),i=L("tensor",e,t,s),r=L("elementShape",e,t,s),o=L("numElements",e,t,s),a=ZN(i,n,r,o);return s.addTensorList(a),[a.idTensor]}case"TensorListReserve":{const n=L("elementShape",e,t,s),i=L("elementDType",e,t,s),r=L("numElements",e,t,s),o=JN(n,i,r);return s.addTensorList(o),[o.idTensor]}case"TensorListGather":{const n=L("tensorListId",e,t,s),i=L("indices",e,t,s),r=L("elementShape",e,t,s),o=L("elementDType",e,t,s),a=s.getTensorList(n.id);return[a.gather(i,o,r)]}case"TensorListStack":{const n=L("tensorListId",e,t,s),i=L("elementShape",e,t,s),r=L("elementDType",e,t,s),o=L("numElements",e,t,s),a=s.getTensorList(n.id);return[a.stack(i,r,o)]}case"TensorListFromTensor":{const n=L("tensor",e,t,s),i=L("elementShape",e,t,s),r=L("elementDType",e,t,s),o=XN(n,i,r);return s.addTensorList(o),[o.idTensor]}case"TensorListConcat":{const n=L("tensorListId",e,t,s),i=s.getTensorList(n.id),r=L("dtype",e,t,s),o=L("elementShape",e,t,s);return[i.concat(r,o)]}case"TensorListPushBack":{const n=L("tensorListId",e,t,s),i=L("tensor",e,t,s),r=s.getTensorList(n.id);return r.pushBack(i),[r.idTensor]}case"TensorListPopBack":{const n=L("tensorListId",e,t,s),i=L("elementShape",e,t,s),r=L("elementDType",e,t,s),o=s.getTensorList(n.id);return[o.popBack(i,r)]}case"TensorListSplit":{const n=L("tensor",e,t,s),i=L("elementShape",e,t,s),r=L("lengths",e,t,s),o=QN(n,r,i);return s.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function tC(e,t,s){const[n,i]=L("fusedOps",e,t,s),r=n==="biasadd",o=i==="prelu",a=n==="fusedbatchnorm",l=L("numArgs",e,t,s);if(r){if(o&&l!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&l!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(a)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");const c=L("strides",e,t,s),p=Ru(e,t,s),u=L("dataFormat",e,t,s).toUpperCase(),h=L("dilations",e,t,s),[d,m]=L("args",e,t,s);return{stride:c,pad:p,dataFormat:u,dilations:h,biasArg:d,preluArg:m,activationFunc:i}}const sC=(e,t,s)=>{switch(e.op){case"Conv1D":{const n=L("stride",e,t,s),i=L("pad",e,t,s),r=L("dataFormat",e,t,s).toUpperCase(),o=L("dilation",e,t,s);return[fl(L("x",e,t,s),L("filter",e,t,s),n,i,r,o)]}case"Conv2D":{const n=L("strides",e,t,s),i=Ru(e,t,s),r=L("dataFormat",e,t,s).toUpperCase(),o=L("dilations",e,t,s);return[rt(L("x",e,t,s),L("filter",e,t,s),[n[1],n[2]],i,r,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:n,pad:i,dataFormat:r,dilations:o,biasArg:a,preluArg:l,activationFunc:c}=tC(e,t,s);return[xn.conv2d({x:L("x",e,t,s),filter:L("filter",e,t,s),strides:[n[1],n[2]],pad:i,dataFormat:r,dilations:[o[1],o[2]],bias:a,activation:c,preluActivationWeights:l})]}case"FusedDepthwiseConv2dNative":{const{stride:n,pad:i,dataFormat:r,dilations:o,biasArg:a,preluArg:l,activationFunc:c}=tC(e,t,s);return[xn.depthwiseConv2d({x:L("x",e,t,s),filter:L("filter",e,t,s),strides:[n[1],n[2]],pad:i,dataFormat:r,dilations:[o[1],o[2]],bias:a,activation:c,preluActivationWeights:l})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const n=L("outputShape",e,t,s),i=L("strides",e,t,s),r=Ru(e,t,s);return[yl(L("x",e,t,s),L("filter",e,t,s),n,[i[1],i[2]],r)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const n=L("strides",e,t,s),i=Ru(e,t,s),r=L("dilations",e,t,s),o=L("dataFormat",e,t,s).toUpperCase();return[fn(L("input",e,t,s),L("filter",e,t,s),[n[1],n[2]],i,o,[r[1],r[2]])]}case"Conv3D":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("dataFormat",e,t,s).toUpperCase(),o=L("dilations",e,t,s);return[bl(L("x",e,t,s),L("filter",e,t,s),[n[1],n[2],n[3]],i,r,[o[1],o[2],o[3]])]}case"AvgPool":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s);return[ds(L("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i)]}case"MaxPool":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s);return[ft(L("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i)]}case"MaxPoolWithArgmax":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s),o=L("includeBatchInIndex",e,t,s),{result:a,indexes:l}=md(L("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i,o);return[a,l]}case"AvgPool3D":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s);return[ml(L("x",e,t,s),[r[1],r[2],r[3]],[n[1],n[2],n[3]],i)]}case"MaxPool3D":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s);return[Tl(L("x",e,t,s),[r[1],r[2],r[3]],[n[1],n[2],n[3]],i)]}case"Dilation2D":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("dilations",e,t,s),o=n[1],a=n[2],l=r[1],c=r[2];return[id(L("x",e,t,s),L("filter",e,t,s),[o,a],i,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const nC=(e,t,s)=>{switch(e.op){case"Fill":{const n=L("shape",e,t,s),i=L("dtype",e,t,s),r=L("value",e,t,s);return[Wt(n,r,i)]}case"LinSpace":{const n=L("start",e,t,s),i=L("stop",e,t,s),r=L("num",e,t,s);return[cd(n,i,r)]}case"Multinomial":{const n=L("logits",e,t,s),i=L("numSamples",e,t,s),r=L("seed",e,t,s);return[fd(n,i,r)]}case"OneHot":{const n=L("indices",e,t,s),i=L("depth",e,t,s),r=L("onValue",e,t,s),o=L("offValue",e,t,s);return[pi(n,i,r,o)]}case"Ones":return[Kt(L("shape",e,t,s),L("dtype",e,t,s))];case"OnesLike":return[Ot(L("x",e,t,s))];case"RandomUniform":return[wn(L("shape",e,t,s),L("minval",e,t,s),L("maxval",e,t,s),L("dtype",e,t,s))];case"Range":{const n=L("start",e,t,s),i=L("stop",e,t,s),r=L("step",e,t,s);return[$i(n,i,r,L("dtype",e,t,s))]}case"TruncatedNormal":{const n=L("shape",e,t,s),i=L("mean",e,t,s),r=L("stdDev",e,t,s),o=L("seed",e,t,s);return[ro(n,i,r,L("dtype",e,t,s),o)]}case"Zeros":return[ye(L("shape",e,t,s),L("dtype",e,t,s))];case"ZerosLike":return[re(L("x",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Mw(e,t,s){const n=L("boxes",e,t,s),i=L("scores",e,t,s),r=L("maxOutputSize",e,t,s),o=L("iouThreshold",e,t,s),a=L("scoreThreshold",e,t,s),l=L("softNmsSigma",e,t,s);return{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}}const iC=async(e,t,s)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}=Mw(e,t,s),c=await en.nonMaxSuppressionWithScoreAsync(n,i,r,o,a,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a}=Mw(e,t,s),l=L("padToMaxOutputSize",e,t,s),c=await en.nonMaxSuppressionPaddedAsync(n,i,r,o,a,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a}=Mw(e,t,s);return[await en.nonMaxSuppressionAsync(n,i,r,o,a)]}case"Where":{const n=G(L("condition",e,t,s),"bool"),i=[await Dl(n)];return n.dispose(),i}case"ListDiff":return xd(L("x",e,t,s),L("y",e,t,s));default:throw TypeError(`Node type ${e.op} is not implemented`)}};const rC=(e,t,s)=>{switch(e.op){case"TopKV2":{const n=L("x",e,t,s),i=L("k",e,t,s),r=L("sorted",e,t,s),o=vd(n,i,r);return[o.values,o.indices]}case"Unique":{const n=L("x",e,t,s),i=Yp(n);return[i.values,i.indices]}case"UniqueV2":{const n=L("x",e,t,s),i=L("axis",e,t,s),r=Yp(n,i);return[r.values,r.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const oC=(e,t,s)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const n=L("default",e,t,s);return[Vt(e.name,t,s)||n];case"Placeholder":return[Vt(e.name,t,s)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const c=L("x",e,t,s);return[qn(c)]}case"IdentityN":return L("x",e,t,s).map(c=>qn(c));case"Snapshot":const i=L("x",e,t,s);return[qn(i)];case"Shape":return[Oe(L("x",e,t,s).shape,"int32")];case"ShapeN":return L("x",e,t,s).map(c=>Oe(c.shape));case"Size":return[j(L("x",e,t,s).size,"int32")];case"Rank":return[j(L("x",e,t,s).rank,"int32")];case"NoOp":return[j(1)];case"Print":const r=L("x",e,t,s),o=L("data",e,t,s),a=L("message",e,t,s),l=L("summarize",e,t,s);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(a);for(let c=0;c<o.length;c++)console.log(Array.prototype.slice.call(o[c].dataSync()).slice(0,l));return[r];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const aC=(e,t,s)=>{switch(e.op){case"ResizeBilinear":{const n=L("images",e,t,s),i=L("size",e,t,s),r=L("alignCorners",e,t,s);return[en.resizeBilinear(n,[i[0],i[1]],r)]}case"ResizeNearestNeighbor":{const n=L("images",e,t,s),i=L("size",e,t,s),r=L("alignCorners",e,t,s);return[en.resizeNearestNeighbor(n,[i[0],i[1]],r)]}case"CropAndResize":{const n=L("image",e,t,s),i=L("boxes",e,t,s),r=L("boxInd",e,t,s),o=L("cropSize",e,t,s),a=L("method",e,t,s),l=L("extrapolationValue",e,t,s);return[en.cropAndResize(n,i,r,o,a,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const lC=(e,t,s)=>{switch(e.op){case"Equal":return[as(L("a",e,t,s),L("b",e,t,s))];case"NotEqual":return[Js(L("a",e,t,s),L("b",e,t,s))];case"Greater":return[Ut(L("a",e,t,s),L("b",e,t,s))];case"GreaterEqual":return[ms(L("a",e,t,s),L("b",e,t,s))];case"Less":return[Xr(L("a",e,t,s),L("b",e,t,s))];case"LessEqual":return[Ws(L("a",e,t,s),L("b",e,t,s))];case"LogicalAnd":return[Yt(L("a",e,t,s),L("b",e,t,s))];case"LogicalNot":return[Jr(L("a",e,t,s))];case"LogicalOr":return[vl(L("a",e,t,s),L("b",e,t,s))];case"Select":case"SelectV2":return[mt(L("condition",e,t,s),L("a",e,t,s),L("b",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const cC=(e,t,s)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Te(L("a",e,t,s),L("b",e,t,s),L("transposeA",e,t,s),L("transposeB",e,t,s))];case"Transpose":return[se(L("x",e,t,s),L("perm",e,t,s))];case"_FusedMatMul":const[n,i]=L("fusedOps",e,t,s),r=n==="biasadd",o=i==="prelu",a=L("numArgs",e,t,s);if(r){if(o&&a!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[l,c]=L("args",e,t,s);return[xn.matMul({a:L("a",e,t,s),b:L("b",e,t,s),transposeA:L("transposeA",e,t,s),transposeB:L("transposeB",e,t,s),bias:l,activation:i,preluActivationWeights:c})];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const pC=(e,t,s)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Xs(L("x",e,t,s),L("mean",e,t,s),L("variance",e,t,s),L("offset",e,t,s),L("scale",e,t,s),L("epsilon",e,t,s))];case"FusedBatchNormV3":return[Xs(L("x",e,t,s),L("mean",e,t,s),L("variance",e,t,s),L("offset",e,t,s),L("scale",e,t,s),L("epsilon",e,t,s))];case"LRN":return[pd(L("x",e,t,s),L("radius",e,t,s),L("bias",e,t,s),L("alpha",e,t,s),L("beta",e,t,s))];case"Softmax":return[ts(L("x",e,t,s))];case"LogSoftmax":return[Il(L("x",e,t,s))];case"SparseToDense":return[Xp(L("sparseIndices",e,t,s),L("outputShape",e,t,s),L("sparseValues",e,t,s),L("defaultValue",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const uC=(e,t,s)=>{switch(e.op){case"Max":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Lt(L("x",e,t,s),n,i)]}case"Mean":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Xe(L("x",e,t,s),n,i)]}case"Min":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Ui(L("x",e,t,s),n,i)]}case"Sum":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[te(L("x",e,t,s),n,i)]}case"All":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[hl(L("x",e,t,s),n,i)]}case"Any":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Zo(L("x",e,t,s),n,i)]}case"ArgMax":{const n=L("axis",e,t,s);return[Qo(L("x",e,t,s),n)]}case"ArgMin":{const n=L("axis",e,t,s);return[zh(L("x",e,t,s),n)]}case"Prod":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Nl(L("x",e,t,s),n,i)]}case"Cumsum":{const n=L("axis",e,t,s),i=L("exclusive",e,t,s),r=L("reverse",e,t,s);return[xl(L("x",e,t,s),n,i,r)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const hC=(e,t,s)=>{switch(e.op){case"ConcatV2":case"Concat":{const n=L("n",e,t,s),i=L("axis",e,t,s);let r=L("tensors",e,t,s);return r=r.slice(0,n),[be(r,i)]}case"GatherV2":case"Gather":{const n=L("axis",e,t,s),i=L("x",e,t,s),r=L("indices",e,t,s);return[hi(i,G(r,"int32"),n)]}case"ReverseV2":case"Reverse":{const n=L("axis",e,t,s),i=L("x",e,t,s);return[Et(i,n)]}case"Slice":{const n=L("begin",e,t,s),i=L("size",e,t,s);return[he(L("x",e,t,s),n,i)]}case"StridedSlice":{const n=L("begin",e,t,s),i=L("end",e,t,s),r=L("strides",e,t,s),o=L("beginMask",e,t,s),a=L("endMask",e,t,s),l=L("ellipsisMask",e,t,s),c=L("newAxisMask",e,t,s),p=L("shrinkAxisMask",e,t,s),u=L("x",e,t,s);return[Sd(u,n,i,r,o,a,l,c,p)]}case"Pack":return C(()=>{const n=L("axis",e,t,s),i=L("tensors",e,t,s),r=i[0].shape,o=Qs(i[0]).shape,a=i.map(l=>{const c=N.arraysEqual(l.shape,r);if(!c&&!N.arraysEqual(Qs(l).shape,o))throw new Error("the input tensors shape does not match");return c?l:O(l,r)});return[Ge(a,n)]});case"Unpack":{const n=L("axis",e,t,s),i=L("tensor",e,t,s);return qe(i,n)}case"Tile":{const n=L("reps",e,t,s);return[$s(L("x",e,t,s),n)]}case"Split":case"SplitV":{const n=L("axis",e,t,s),i=L("numOrSizeSplits",e,t,s),r=L("x",e,t,s);return Bt(r,i,n)}case"ScatterNd":{const n=L("indices",e,t,s),i=L("values",e,t,s),r=L("shape",e,t,s);return[Ib(n,i,r)]}case"GatherNd":{const n=L("x",e,t,s),i=L("indices",e,t,s);return[vb(n,i)]}case"SparseToDense":{const n=L("sparseIndices",e,t,s),i=L("outputShape",e,t,s),r=L("sparseValues",e,t,s),o=L("defaultValue",e,t,s);return[Xp(n,r,i,r.dtype===o.dtype?o:G(o,r.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const dC=(e,t,s)=>{switch(e.op){case"FFT":return[so(L("x",e,t,s))];case"IFFT":return[Wi(L("x",e,t,s))];case"RFFT":return[no(L("x",e,t,s))];case"IRFFT":return[kl(L("x",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const mC=(e,t,s)=>{switch(e.op){case"Cast":return[G(L("x",e,t,s),L("dtype",e,t,s))];case"ExpandDims":{const n=L("axis",e,t,s);return[Mt(L("x",e,t,s),n)]}case"Squeeze":{const n=L("axis",e,t,s);return[Qs(L("x",e,t,s),n)]}case"Reshape":return[O(L("x",e,t,s),L("shape",e,t,s))];case"PadV2":case"Pad":return[Pt(L("x",e,t,s),L("padding",e,t,s),L("constantValue",e,t,s))];case"SpaceToBatchND":{const n=L("blockShape",e,t,s),i=L("paddings",e,t,s);return[Zr(L("x",e,t,s),n,i)]}case"BatchToSpaceND":{const n=L("blockShape",e,t,s),i=L("crops",e,t,s);return[Yr(L("x",e,t,s),n,i)]}case"DepthToSpace":{const n=L("blockSize",e,t,s),i=L("dataFormat",e,t,s).toUpperCase();return[nd(L("x",e,t,s),n,i)]}case"BroadcastTo":return[ta(L("x",e,t,s),L("shape",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Uw(e,t,s){const n=((i,r,o)=>{switch(i.category){case"arithmetic":return C(()=>HN(i,r,o));case"basic_math":return C(()=>YN(i,r,o));case"control":return eC(i,r,o);case"convolution":return C(()=>sC(i,r,o));case"creation":return C(()=>nC(i,r,o));case"dynamic":return iC(i,r,o);case"evaluation":return C(()=>rC(i,r,o));case"image":return C(()=>aC(i,r,o));case"graph":return C(()=>oC(i,r,o));case"logical":return C(()=>lC(i,r,o));case"matrices":return C(()=>cC(i,r,o));case"normalization":return C(()=>pC(i,r,o));case"reduction":return C(()=>uC(i,r,o));case"slice_join":return C(()=>hC(i,r,o));case"spectral":return C(()=>dC(i,r,o));case"transformation":return C(()=>mC(i,r,o));case"custom":const a=xf(i.op);if(a&&a.customExecutor)return a.customExecutor(new qN(i,r,o));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,s);return n instanceof Promise?n.then(i=>[].concat(i)):[].concat(n)}class $w{constructor(e={},t={},s={},n={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=s,this.functionMap=n,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const s=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(s))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function zw(e,t,s,n){const i=new Set,r=[];let o=null,a=null;const l=new Set,c=Object.keys(e).map(h=>Ss(h)[0]);let p=[];n!=null&&(p=n.map(h=>Ss(h.name)[0]));const u=[...t];for(;u.length>0;){const h=u.pop();if((Ww(h)||VB(h))&&(o==null&&(o=h,a=o.children.map(d=>d.name).filter(d=>i.has(d)))),i.add(h.name),s[h.name]!=null)continue;if(c.indexOf(h.name)!==-1)continue;if(p.indexOf(h.name)!==-1)continue;if(h.inputs.length===0){r.push(h.name);continue}h.inputs.forEach(d=>{if(l.has(d.name))return;l.add(d.name),u.push(d)})}return{inputs:e,outputs:t,usedNodes:i,missingInputs:r,dynamicNode:o,syncInputs:a}}function fC(e,t,s){const{usedNodes:n,inputs:i}=s,r=[],o=Object.keys(i).map(p=>Ss(p)[0]).map(p=>e.nodes[p]),a=e.initNodes;o.forEach(p=>{n.has(p.name)&&r.push(p)}),e.weights.forEach(p=>{n.has(p.name)&&r.push(p)}),a!=null&&a.forEach(p=>{n.has(p.name)&&r.push(p)});const l=new Set,c=[];for(;r.length>0;){const p=r.pop();l.add(p.name),t[p.name]||c.push(p),p.children.forEach(u=>{!l.has(u.name)&&n.has(u.name)&&u.inputs.every(h=>l.has(h.name))&&r.push(u)})}return c}const GB=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],qB=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function Ww(e){return GB.indexOf(e.op)>=0}function VB(e){return qB.indexOf(e.op)>=0}class _f{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(s=>{this._functionExecutorMap[s]=new _f(e.functions[s],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map(s=>e[s].map(n=>n.id));this._weightIds=[].concat(...t),this._weightMap=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){const s=e.map(i=>i.name).sort(),n=t.map(i=>i.name).sort();return s.join(this.SEPERATOR)+"--"+n.join(this.SEPERATOR)}compile(e,t){const s=zw(e,t,this.weightMap,this._initNodes),{missingInputs:n,dynamicNode:i,syncInputs:r}=s;if(i!=null)throw new Error(`This execution contains the node '${i.name}', which has the dynamic op '${i.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${r}]`);if(n.length>0){const o=t.map(l=>l.name),a=Object.keys(e);throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${a}]. Missing the following inputs: [${n}]`)}return fC(this.graph,this.weightMap,s)}execute(e,t){e=this.mapInputs(e);const s=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const n=s.map(p=>this.graph.nodes[Ss(p)[0]]),i=t.map(p=>Ss(p)[0]);let r=i.map(p=>this.graph.nodes[p]);r.length===0&&(r=this._outputs);const o=this.getCompilationKey(n,r);let a=this.compiledMap.get(o);a==null&&(a=this.compile(e,r),this.compiledMap.set(o,a));const l={},c={};return C(()=>{const p=new $w(this.weightMap,l,c,this.functionExecutorMap),u=Object.assign({},this.weightMap);Object.keys(e).forEach(m=>{const[f,g]=Ss(m),y=[];y[g]=e[m],u[f]=y});const h=this.getFrozenTensorIds(u),d={};for(let m=0;m<a.length;m++){const f=a[m];if(!u[f.name]){const g=Uw(f,u,p);if(g instanceof Promise)throw new Error(`The execution of the op '${f.op}' returned a promise. Please use model.executeAsync() instead.`);u[f.name]=g,this.checkTensorForDisposal(f.name,f,u,p,h,i,d)}}return this.parent==null&&p.dispose(h),t.map(m=>Vt(m,u,p))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(s=>e[s]).map(s=>s.map(n=>n.id)));return new Set(t)}checkTensorForDisposal(e,t,s,n,i,r,o){if(t.category==="control"||r.indexOf(e)!==-1)return;s[e].forEach(a=>{a!=null&&(o[a.id]=(o[a.id]||0)+t.children.length)}),t.inputs.forEach(a=>{if(a.category!=="control"){const l=BN(a.name,s,n);l!=null&&l.forEach(c=>{if(c&&!i.has(c.id)){const p=o[c.id];p===1?(c.dispose(),delete o[c.id]):p!=null&&o[c.id]--}})}})}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,s=!1,n={},i={}){s||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));const r=new $w(this.weightMap,n,i,this.functionExecutorMap),o=await this.executeWithControlFlow(e,r,t,s),a=t.map(u=>Vt(u,o,r)),l=a.map(u=>u.id),c=Object.keys(e).map(u=>e[u].id),p=new Set([...l,...c,...this.weightIds]);return Object.keys(o).forEach(u=>{const h=o[u];h.forEach(d=>{d&&!d.isDisposed&&!p.has(d.id)&&d.dispose()})}),this.parent==null&&r.dispose(p),a}async executeFunctionAsync(e,t,s){const n=e.reduce((i,r,o)=>(i[this.inputs[o].name]=r,i),{});return this._executeAsync(n,this.outputNodes,!0,t,s)}async executeWithControlFlow(e,t,s,n){const i=Object.keys(e),r=i.map(w=>this.graph.nodes[Ss(w)[0]]),o=s.map(w=>Ss(w)[0]),a=o.map(w=>this.graph.nodes[w]),{usedNodes:l,missingInputs:c,dynamicNode:p,syncInputs:u}=zw(e,a,this.weightMap),h=[...r,...this.graph.weights].map(w=>({node:w,contexts:t.currentContext})),d=Object.assign({},this.weightMap);Object.keys(e).forEach(w=>{const[x,T]=Ss(w),A=[];A[T]=e[w],d[x]=A});const m={},f=this.getFrozenTensorIds(d),g={};for(;h.length>0;){const w=this.processStack(r,h,t,d,g,f,o,m,l);await Promise.all(w)}p==null&&!n&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const y=a.filter(w=>!Ww(w)&&!Vt(w.name,d,t)).map(w=>w.name);if(y.length>0){let w="";throw p!=null&&(w=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${u}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${i}]. Consider providing the following inputs: [${c}]. ${w}`)}return d}processStack(e,t,s,n,i,r,o,a,l){const c=[];for(;t.length>0;){const p=t.pop();s.currentContext=p.contexts;let u="";if(p.node.op==="Enter"&&L("isConstant",p.node,n,s)&&([u]=Gn(p.node.name,s)),e.indexOf(p.node)===-1){const h=Uw(p.node,n,s);u||([u]=Gn(p.node.name,s));const d=s.currentContext;h instanceof Promise?c.push(h.then(m=>(n[u]=m,s.currentContext=d,this.checkTensorForDisposal(u,p.node,n,s,r,o,a),this.processChildNodes(p.node,t,s,n,i,l),m))):(n[u]=h,this.checkTensorForDisposal(u,p.node,n,s,r,o,a),this.processChildNodes(p.node,t,s,n,i,l))}else this.processChildNodes(p.node,t,s,n,i,l)}return c}processChildNodes(e,t,s,n,i,r){e.children.forEach(o=>{const[a]=Gn(o.name,s);if(i[a]||!r.has(o.name))return;o.op==="Merge"?o.inputNames.some(l=>!!Vt(l,n,s))&&(i[a]=!0,t.push({contexts:s.currentContext,node:o})):o.inputNames.every(l=>!!Vt(l,n,s))&&(i[a]=!0,t.push({contexts:s.currentContext,node:o}))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const s=e[t],[n]=Ss(t),i=this.graph.nodes[n];if(i.attrParams.shape&&i.attrParams.shape.value){const r=i.attrParams.shape.value,o=r.length===s.shape.length&&s.shape.every((a,l)=>r[l]===-1||r[l]===a);N.assert(o,()=>`The shape of dict['${i.name}'] provided in model.execute(dict) must be [${r}], but was [${s.shape}]`)}i.attrParams.dtype&&i.attrParams.dtype.value&&N.assert(s.dtype===i.attrParams.dtype.value,()=>`The dtype of dict['${i.name}'] provided in model.execute(dict) must be ${i.attrParams.dtype.value}, but was ${s.dtype}`)})}mapInputs(e){const t={};for(const s in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[s]!=null){const n=this._signature.inputs[s];t[n.name]=e[s]}else t[s]=e[s];return t}checkInputs(e){const t=Object.keys(e).filter(s=>{const[n]=Ss(s);return this.graph.nodes[n]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>{if(this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null){const s=this._signature.outputs[t];return s.name}return t},{})}checkOutputs(e){e.forEach(t=>{const[s]=Ss(t);if(!this.graph.nodes[s])throw new Error(`The output '${t}' is not found in the graph`)})}}const HB="?tfjs-format=file",YB="model.json";class Pw{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={})}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}findIOHandler(){const e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=Rt.browserHTTPRequest(e,this.loadOptions);else{const t=Rt.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Rt.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let s={};this.artifacts.userDefinedMetadata!=null&&(s=this.artifacts.userDefinedMetadata.signature),this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const n=Rt.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new _f(Fw.Instance.transformGraph(t,s)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),e.modelInitializer!=null){const i=Fw.Instance.transformGraph(e.modelInitializer);this.initializer=new _f(i),this.initializer.weightMap=this.executor.weightMap,this.initializer.execute({},[])}return!0}async save(e,t){if(typeof e=="string"){const s=Rt.getSaveHandlers(e);if(s.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(s.length>1)throw new Error(`Found more than one (${s.length}) save handlers for URL '${e}'`);e=s[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof me)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,s,n)=>(t[s]=e[n],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const s=this.executor.execute(e,t);return s.length>1?s:s[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const s=await this.executor.executeAsync(e,t);return s.length>1?s:s[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,s)=>(t[s]=[e[s]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose()}}async function gC(e,t={}){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&(e.load==null&&(e.endsWith("/")||(e=e+"/"),e=`${e}${YB}${HB}`));const s=new Pw(e,t);return await s.load(),s}const kf="2.6.0";function yC(e,t){return Df(e,t)}function Df(e,t,s=new Map,n=new Set){if(e==null)return null;if(n.has(e))throw new Error("Circular references are not supported.");if(s.has(e))return s.get(e);const i=t(e);if(i.recurse&&i.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(i.recurse)if(yo(e)){const r=Array.isArray(e)?[]:{};n.add(e);for(const o in e){const a=e[o],l=Df(a,t,s,n);r[o]=l}return n.delete(e),r}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return s.set(e,i.value),i.value}function wC(e,t=Bw){return bC(e,t)}function bC(e,t,s=new Set){const n=e[0];if(s.has(n))throw new Error("Circular references are not supported.");const i=t(e);if(i.recurse&&i.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(i.recurse)if(yo(n)){const r=Array.isArray(n)?[]:{};s.add(n);for(const o in n){const a=e.map(c=>c[o]),l=bC(a,t,s);r[o]=l}return s.delete(n),r}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return i.value}function Bw(e){return e===null?null:yo(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function Ff(e,t){const s=new Map;Df(e,t,s);for(const i of Array.from(s.keys())){const r=s.get(i);if(r instanceof Promise){const o=await r;s.set(i,o)}}const n=Df(e,t,s);return n}function yo(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof me))}function xC(e){return e==null||KB(e)||Array.isArray(e)||typeof e=="object"&&e instanceof me||N.isTypedArray(e)}function KB(e){return e===null||typeof e!="object"&&typeof e!="function"}function LC(e){return yC(e,XB)}function XB(e){return e instanceof me?{value:e.clone(),recurse:!1}:yo(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class Mf{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),s=this.get(t);return this.set(t,this.pop()),s}}class Uf extends Mf{constructor(){super(Uf.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=this.capacity*2,t=new Array(e),s=this.length();for(let n=0;n<s;n++)t[n]=this.get(this.wrap(this.begin+n));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=s}}Uf.INITIAL_CAPACITY=32;const SC=vc(Tc());function jw(e){return new JB(e)}function Eu(e){return new ZB(e)}function vC(e,t){return new IC(e,t)}function TC(e,t=Ki.FAIL){return new QB(e,t)}class At{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let s=await e.next();for(;!s.done;)t.push(s.value),s=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),s=e(t.value);for(;!t.done&&s;)t=await this.next(),s=e(t.value)}handleErrors(e){return new oj(this,e)}filter(e){return new ij(this,e)}map(e){return new rj(this,e)}mapAsync(e){return new AC(this,e)}serialMapAsync(e){return new AC(this,e).serial()}flatmap(e){return new aj(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new nj(this,e,t)}columnMajorBatch(e,t=!0,s=Bw){const n=this.rowMajorBatch(e,t);return n.map(i=>wC(i,s))}concatenate(e,t){return new IC(jw([this,e]),t)}take(e){return e<0||e==null?this:new sj(this,e)}skip(e){return e<0||e==null?this:new tj(this,e)}prefetch(e){return new NC(this,e)}shuffle(e,t){return new lj(this,e,t)}serial(){return new ej(this)}}class JB extends At{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:LC(e),done:!1}}}class ZB extends At{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class ej extends At{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}}class tj extends At{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){const e=await this.upstream.next();if(e.done)return e;ce(e.value)}return this.upstream.next()}}class sj extends At{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class nj extends At{constructor(e,t,s=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=s,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){const e=[];for(;e.length<this.batchSize;){const t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class ij extends At{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;ce(e.value)}}}class rj extends At{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=mn.getTensorsInContainer(e.value),s=this.transform(e.value),n=mn.getTensorsInContainer(s);for(const i of t)mn.isTensorInList(i,n)||i.dispose();return{value:s,done:!1}}}class oj extends At{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class AC extends At{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=mn.getTensorsInContainer(e.value),s=await this.transform(e.value),n=mn.getTensorsInContainer(s);for(const i of t)mn.isTensorInList(i,n)||i.dispose();return{value:s,done:!1}}}class _u extends At{constructor(){super();this.outputQueue=new Uf,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class aj extends _u{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=mn.getTensorsInContainer(e.value),s=this.transform(e.value),n=mn.getTensorsInContainer(s);this.outputQueue.pushAll(s);for(const i of t)mn.isTensorInList(i,n)||i.dispose();return!0}}class IC extends At{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){const e="TODO: fill in upstream of chained summaries";return`${e} -> Chained`}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){const s=await this.moreIterators.next();if(s.done)return{value:null,done:!0};this.iterator=s.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var Ki;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(Ki||(Ki={}));class QB extends At{constructor(e,t=Ki.FAIL){super();this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){const e="TODO: fill in upstream of zip summaries";return`{${e}} -> Zip`}async nextState(e){await e;let t=0,s=0;function n(r){if(r instanceof At){const o=r.next();return{value:o.then(a=>(t++,a.done&&s++,a.value)),recurse:!1}}else return{value:null,recurse:!0}}const i=await Ff(this.iterators,n);if(t===s)return{value:null,done:!0};if(s>0)switch(this.mismatchMode){case Ki.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Ki.SHORTEST:return{value:null,done:!0};case Ki.LONGEST:default:}return this.count++,{value:i,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class NC extends At{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new Mf(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class lj extends NC{constructor(e,t,s){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=SC.alea(s||N.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}}const CC=vc(Tc());class Xi{constructor(){this.size=null}batch(e,t=!0){const s=this;N.assert(e>0,()=>`batchSize needs to be positive, but it is
${e}`);let n;return this.size===Infinity||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),Os(async()=>(await s.iterator()).columnMajorBatch(e,t,cj),n)}concatenate(e){const t=this;let s;return this.size===Infinity||e.size===Infinity?s=Infinity:this.size!=null&&e.size!=null?s=this.size+e.size:s=null,Os(async()=>(await t.iterator()).concatenate(await e.iterator()),s)}filter(e){const t=this;let s;return this.size===Infinity?s=Infinity:s=null,Os(async()=>(await t.iterator()).filter(n=>C(()=>e(n))),s)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return Os(async()=>(await t.iterator()).map(s=>C(()=>e(s))),this.size)}mapAsync(e){const t=this;return Os(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return Os(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let s;return this.size!=null&&e>0?s=this.size*e:e===0?s=0:this.size!=null&&(e===void 0||e<0)?s=Infinity:s=null,Os(async()=>{const n=Eu(async()=>({value:await t.iterator(),done:!1}));return vC(n.take(e))},s)}skip(e){const t=this;let s;return this.size!=null&&e>=0&&this.size>=e?s=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?s=0:s=null,Os(async()=>(await t.iterator()).skip(e),s)}shuffle(e,t,s=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const n=this,i=CC.alea(t||N.now().toString());return Os(async()=>{let r=i.int32();return s&&(r+=i.int32()),(await n.iterator()).shuffle(e,r.toString())},this.size)}take(e){const t=this;let s;return this.size!=null&&this.size>e?s=e:this.size!=null&&this.size<=e?s=this.size:s=null,Os(async()=>(await t.iterator()).take(e),s)}async toArray(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}Xi.MAX_BUFFER_SIZE=1e4;function Os(e,t=null){return new class extends Xi{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function RC(e){return Os(async()=>jw(e),e.length)}function OC(e){if(!yo(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let s=0;s<e.length;s++)t=t==null?e[s].size:Math.min(t,e[s].size);else if(e instanceof Object)for(const s in e)t=t==null?e[s].size:Math.min(t,e[s].size);return Os(async()=>{const s=await Ff(e,n=>{if(n instanceof Xi)return{value:n.iterator(),recurse:!1};if(yo(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return TC(s,Ki.SHORTEST)},t)}function cj(e){if(e===null)return null;const t=e[0];if(xC(t)){const s=pj(e);return{value:s,recurse:!1}}return{value:null,recurse:!0}}function pj(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof me?Ge(e):ze(e)}class $f extends Xi{constructor(e){super();this.input=e}async iterator(){const e=await this.input.iterator(),t=e.decodeUTF8(),s=t.split(`
`).map(n=>(n.endsWith("\r")&&(n=n.slice(0,-1)),n));return s}}const Wf='"',ku=Symbol("out"),EC=Symbol("field"),zf=Symbol("quote"),Vw=Symbol("quoteafterquote"),_C=Symbol("quoteinquote");class Pf extends Xi{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new $f(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(N.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&N.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((n,i)=>(n[i]=n[i]+1||1,n),{}),s=Object.keys(t).filter(n=>t[n]>1);if(N.assert(s.length===0,()=>"Duplicate column names found: "+s.toString()),this.columnConfigs)for(const n of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(n);if(i===-1)throw new Error('The key "'+n+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const s=t.value,n=this.parseRow(s,!1);return n}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),s={},n={};for(let i=0;i<this.fullColumnNames.length;i++){const r=this.fullColumnNames[i],o=this.columnConfigs?this.columnConfigs[r]:null;if(this.configuredColumnsOnly&&!o)continue;{const a=t[i];let l=null;if(a==="")if(o&&o.default!==void 0)l=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${r} is empty in this line: ${e}`);l=void 0}else{const c=Number(a);if(isNaN(c))o&&o.dtype==="bool"?l=this.getBoolean(a):l=a;else if(!o||!o.dtype)l=c;else switch(o.dtype){case"float32":l=c;break;case"int32":l=Math.floor(c);break;case"bool":l=this.getBoolean(a);break;default:l=c}}o&&o.isLabel?n[r]=l:s[r]=l}}return Object.keys(n).length===0?s:{xs:s,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){const s=[];let n=0;const i=e.length;let r=ku;for(let o=0;o<i;o++)switch(r){case ku:switch(e.charAt(o)){case Wf:n=o+1,r=zf;break;case this.delimiter:if(n=o+1,this.delimiter===" "&&this.delimWhitespace)break;s.push(""),r=ku;break;default:r=EC,n=o;break}break;case EC:switch(e.charAt(o)){case this.delimiter:s.push(e.substring(n,o)),r=ku,n=o+1;break;default:}break;case zf:switch(e.charAt(o)){case Wf:r=Vw;break;default:}break;case Vw:switch(e.charAt(o)){case this.delimiter:s.push(e.substring(n,o-1)),r=ku,n=o+1;break;case Wf:r=zf;break;default:r=_C;break}break;case _C:switch(e.charAt(o)){case Wf:r=zf;break;default:}break;default:}if(r===Vw?s.push(e.substring(n,i-1)):s.push(e.substring(n)),t&&s.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${s}`);return s}}class Gw extends At{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!(e.includeSpectrogram===!1),this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(W().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");const t=new Gw(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(s){throw new Error(`Error thrown while initializing video stream: ${s.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize);return}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const s=await this.getAudioData();if(this.includeSpectrogram){const n=this.flattenQueue(s.freqDataQueue);e=this.getTensorFromAudioDataArray(n,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const n=this.flattenQueue(s.timeDataQueue);t=this.getTensorFromAudioDataArray(n,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let s=0;return new Promise(n=>{const i=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-Infinity&&n({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++s===this.numFrames&&(clearInterval(i),n({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,s=new Float32Array(e.length*t);return e.forEach((n,i)=>s.set(n,i*t)),s}getTensorFromAudioDataArray(e,t){const s=new Float32Array(N.sizeFromShape(t));return s.set(e,s.length-e.length),ze(s,t)}}class qw extends At{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Oe([0],"int32"),this.webcamConfig.centerCrop){const s=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,n=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,i=(1-s)/2,r=(1-n)/2,o=i+s,a=n+r;this.cropBox=ls([r,i,a,o],[1,4])}else this.cropBox=ls([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(W().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const s=new qw(e,t);return await s.start(),s}async start(){this.webcamConfig.facingMode&&N.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Gr.fromPixels(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return C(()=>{const t=e.toFloat().expandDims(0);let s;s=en.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const n=s.shape;return s.reshape(n.slice(1))})}async capture(){return(await this.next()).value}stop(){const e=this.stream.getTracks();e.forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class Bf{}class Hw extends At{split(e){return new uj(this,e)}}class uj extends Hw{constructor(e,t){super();this.upstream=e,this.impl=new hj(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class hj extends _u{constructor(e,t){super();this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const s of t.slice(0,-1))this.outputQueue.push(s);return this.carryover=t[t.length-1],!0}}class kC extends At{decodeUTF8(){return new dj(this)}}class dj extends Hw{constructor(e){super();this.upstream=e,this.impl=new mj(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class mj extends _u{constructor(e){super();if(this.upstream=e,W().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:t}=kL();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t;if(e.done)return!1;t=e.value;let s;return W().get("IS_BROWSER")?s=this.decoder.decode(t,{stream:!0}):s=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(s),!0}}class jf extends kC{constructor(e,t={}){super();this.file=e,this.options=t,N.assert(e instanceof Uint8Array||(W().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise((t,s)=>{const n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,n)));else{const i=new FileReader;i.onload=o=>{let a=i.result;if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),!(a instanceof Uint8Array))return s(new TypeError("FileReader returned unknown type."));t(a)},i.onabort=o=>s(new Error("Aborted")),i.onerror=o=>s(new Error(o.type));const r=this.file.slice(this.offset,n);i.readAsArrayBuffer(r)}this.offset=n});return{value:await e,done:!1}}}async function DC(e,t={}){let s,n;typeof e=="string"?s=e:(s=e.url,n=fj(e));const i=await N.fetch(s,n);if(i.ok){const r=new Uint8Array(await i.arrayBuffer());return new jf(r,t)}else throw new Error(i.statusText)}const fj=e=>{const t={method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity};return t};function Vf(e){return typeof e=="string"&&e.substr(0,7)==="file://"}class Gf extends Bf{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(Vf(this.input)&&W().get("IS_NODE")){const e=DL();this.input=e.readFileSync(this.input.substr(7))}return new jf(this.input,this.options)}}class qf extends Bf{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return Vf(this.url)?new Gf(this.url,this.fileOptions).iterator():DC(this.url,this.fileOptions)}}function FC(e,t={}){return new Pf(new qf(e),t)}function MC(e){const t=Eu(e);return Os(async()=>t)}function UC(e){return Os(async()=>{const t=await e();return Eu(()=>t.next())})}async function $C(e,t){return qw.create(e,t)}async function WC(e){return Gw.create(e)}const Hf="2.6.0";const Yw={};Ee(Yw,{CSVDataset:()=>Pf,Dataset:()=>Xi,FileDataSource:()=>Gf,TextLineDataset:()=>$f,URLDataSource:()=>qf,array:()=>RC,csv:()=>FC,func:()=>MC,generator:()=>UC,microphone:()=>WC,version_data:()=>Hf,webcam:()=>$C,zip:()=>OC});function ee(e,t){Array.isArray(e)||(e=[e]),e.forEach(s=>{s!=null&&N.assert(s.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}const zC=vc(Tc());const gj=vt.nonMaxSuppressionV3Impl,yj=vt.split,bj=vt.tile,wj=vt.topkImpl,xj=vt.whereImpl;function Kw(e,t,s,n){if(s==="linear")return e.linear(t);if(s==="relu")return e.relu(t);if(s==="elu")return gn(t);if(s==="relu6")return e.relu6(t);if(s==="prelu")return e.prelu(t,n);throw new Error(`Activation ${s} has not been implemented for the CPU backend.`)}class Xw extends Eo{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Fc(this,Us())}write(e,t,s){this.firstUse&&(this.firstUse=!1,W().get("IS_NODE")&&U.warn(`
============================
Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
============================`));const n={};return this.data.set(n,{values:e,dtype:s,refCount:1}),n}makeTensorInfo(e,t,s){const n=this.write(s,e,t);return{dataId:n,shape:e,dtype:t}}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,s,n){this.data.set(e,{values:t,dtype:n,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:s}=this.data.get(e);if(t==="complex64"){const n=this.readSync(s.real.dataId),i=this.readSync(s.imag.dataId);return U.mergeRealAndImagArrays(n,i)}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let s=t;if(e.dtype==="string")try{s=t.map(n=>N.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ge(e.shape,e.dtype,s)}makeOutput(e,t,s){const n=this.write(e,t,s);return Us().makeTensorFromDataId(n,t,s,this)}disposeData(e){if(this.data.has(e)){const{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.data.has(t)){const s=this.data.get(t);s.refCount--,s.refCount<1&&this.disposeData(t)}}async time(e){const t=N.now();e();const s=N.now()-t;return{kernelMs: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."]}}stridedSlice(e,t,s,n){ee(e,"stridedSlice");const i=Ms.computeOutShape(t,s,n);if(i.some(a=>a===0))return ze([],i);const r=ge(i,e.dtype),o=this.bufferSync(e);for(let a=0;a<r.size;a++){const l=r.indexToLoc(a),c=new Array(l.length);for(let p=0;p<c.length;p++)c[p]=l[p]*n[p]+t[p];r.set(o.get(...c),...l)}return r.toTensor()}diag(e){const t=this.readSync(e.dataId),s=ge([e.size,e.size],e.dtype),n=s.values;for(let i=0;i<t.length;i++)n[i*e.size+i]=t[i];return s.toTensor()}unstack(e,t){const s=e.shape[t],n=new Array(e.rank-1);let i=0;for(let l=0;l<e.rank;l++)l!==t&&(n[i++]=e.shape[l]);const r=new Array(e.rank).fill(0),o=e.shape.slice();o[t]=1;const a=new Array(s);for(let l=0;l<a.length;l++)r[t]=l,a[l]=he(e,r,o).reshape(n);return a}reverse(e,t){ee(e,"reverse");const s=ge(e.shape,e.dtype),n=this.bufferSync(e);for(let i=0;i<s.size;i++){const r=s.indexToLoc(i),o=r.slice();t.forEach(a=>o[a]=e.shape[a]-1-o[a]),s.set(n.get(...o),...r)}return s.toTensor()}neg(e){return ee(e,"neg"),R(j(-1),e)}addN(e){ee(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),s=ge(e[0].shape,e[0].dtype),n=s.values;for(let i=0;i<e.length;i++){const r=t[i];for(let o=0;o<n.length;o++)n[o]+=r[o]}return s.toTensor()}softmax(e,t){const s=N.parseAxisParam([t],e.shape),n=Lt(e,s),i=U.expandShapeToKeepDim(n.shape,s),r=X(e,n.reshape(i)),o=ut(r),a=this.sum(o,s).reshape(i);return Z(o,a)}pow(e,t){return ee([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.pow(s,n))}batchMatMul(e,t,s,n){ee([e,t],"matMul");const i=s?e.shape[1]:e.shape[2],r=s?e.shape[2]:e.shape[1],o=n?t.shape[1]:t.shape[2],a=e.shape[0],l=this.readSync(e.dataId),c=this.readSync(t.dataId),[p,u,h]=s?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],[d,m,f]=n?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],g=r*o,y=ge([a,r,o],e.dtype),w=y.values,x=this.blockSize;for(let T=0;T<a;T++)for(let A=0;A<r;A+=x)for(let _=0;_<o;_+=x)for(let E=0;E<i;E+=x){const F=Math.min(A+x,r),D=Math.min(_+x,o),M=Math.min(E+x,i);for(let P=A;P<F;P++)for(let B=_;B<D;B++){let Y=0;for(let q=E;q<M;q++)Y+=l[T*p+P*u+q*h]*c[q*d+B*m+T*f];w[T*g+(P*o+B)]+=Y}}return y.toTensor()}fusedBatchMatMul({a:e,b:t,transposeA:s,transposeB:n,bias:i,activation:r,preluActivationWeights:o}){let a=this.batchMatMul(e,t,s,n);return i&&(a=$(a,i)),r&&(a=Kw(this,a,r,o)),a}floorDiv(e,t){ee([e,t],"floorDiv");const s=(i,r)=>Math.floor(i/r),n="int32";return this.broadcastedBinaryOp(e,t,n,s)}sum(e,t){ee(e,"sum"),U.assertAxesAreInnerMostDims("sum",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=Ft(e.dtype,"int32"),r=ye(s,i),o=N.sizeFromShape(n),a=this.readSync(r.dataId),l=this.readSync(e.dataId);for(let c=0;c<a.length;++c){const p=c*o;let u=0;for(let h=0;h<o;++h)u+=l[p+h];a[c]=u}return r}prod(e,t){ee(e,"sum");const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=Ft(e.dtype,"int32"),r=ye(s,i),o=N.sizeFromShape(n),a=this.readSync(r.dataId),l=this.readSync(e.dataId);for(let c=0;c<a.length;++c){const p=c*o;let u=1;for(let h=0;h<o;++h)u*=l[p+h];a[c]=u}return r}unsortedSegmentSum(e,t,s){ee(e,"unsortedSegmentSum");const n=[],i=e.rank-t.rank;for(let r=0;r<i;++r)t=t.expandDims(r+1);for(let r=0;r<s;++r){const o=j(r,"int32"),a=as(o,t).asType("float32"),l=a.mul(e).sum(0);n.push(l)}return Ge(n)}argMin(e,t){ee(e,"argMin");const s=[t];U.assertAxesAreInnerMostDims("argMin",s,e.rank);const[n,i]=U.computeOutAndReduceShapes(e.shape,s),r=ye(n,"int32"),o=N.sizeFromShape(i),a=this.readSync(r.dataId),l=this.readSync(e.dataId);for(let c=0;c<a.length;++c){const p=c*o;let u=l[p],h=0;for(let d=0;d<o;++d){const m=l[p+d];m<u&&(u=m,h=d)}a[c]=h}return r}argMax(e,t){ee(e,"argMax");const s=[t];U.assertAxesAreInnerMostDims("argMax",s,e.rank);const[n,i]=U.computeOutAndReduceShapes(e.shape,s),r=ye(n,"int32"),o=N.sizeFromShape(i),a=this.readSync(r.dataId),l=this.readSync(e.dataId);for(let c=0;c<a.length;++c){const p=c*o;let u=l[p],h=0;for(let d=0;d<o;++d){const m=l[p+d];m>u&&(u=m,h=d)}a[c]=h}return r}cumsum(e,t,s,n){if(ee(e,"cumsum"),t!==e.rank-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${e.rank-1} but got axis=${t}`);const i=Ft(e.dtype,"int32"),r=ye(e.shape,i),o=this.readSync(r.dataId),a=this.readSync(e.dataId),l=e.shape[e.rank-1],c=n?(p,u)=>p+l-u-1:(p,u)=>p+u;for(let p=0;p<a.length;p+=l)for(let u=0;u<l;u++){const h=c(p,u);if(u===0)o[h]=s?0:a[h];else{const d=c(p,u-1);o[h]=s?a[d]+o[d]:a[h]+o[d]}}return r}equal(e,t){return ee([e,t],"equal"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s===n?1:0)}notEqual(e,t){return ee([e,t],"notEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s!==n?1:0)}less(e,t){return ee([e,t],"less"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s<n?1:0)}lessEqual(e,t){return ee([e,t],"lessEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s<=n?1:0)}greater(e,t){return ee([e,t],"greater"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s>n?1:0)}greaterEqual(e,t){return ee([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s>=n?1:0)}logicalAnd(e,t){return ee([e,t],"logicalAnd"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s&&n)}logicalOr(e,t){return ee([e,t],"logicalOr"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s||n)}select(e,t,s){ee([e,t,s],"select");const n=this.readSync(e.dataId),i=this.readSync(t.dataId),r=this.readSync(s.dataId),o=ye(t.shape,Ft(t.dtype,s.dtype)),a=this.readSync(o.dataId);let l=0;const c=e.rank===0||e.rank>1||t.rank===1?1:N.sizeFromShape(t.shape.slice(1));for(let p=0;p<n.length;p++)for(let u=0;u<c;u++)n[p]===1?a[l++]=i[p]:a[l++]=r[p];return o}where(e){ee([e],"where");const t=this.readSync(e.dataId);return xj(e.shape,t)}topk(e,t,s){ee(e,"topk");const n=this.readSync(e.dataId);return wj(n,e.shape,e.dtype,t,s)}min(e,t){ee(e,"min"),U.assertAxesAreInnerMostDims("min",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=ye(s,e.dtype),r=N.sizeFromShape(n),o=this.readSync(i.dataId),a=this.readSync(e.dataId);for(let l=0;l<o.length;++l){const c=l*r;let p=a[c];for(let u=0;u<r;++u){const h=a[c+u];h<p&&(p=h)}o[l]=p}return i}minimum(e,t){return ee([e,t],"minimum"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.min(s,n))}mod(e,t){return ee([e,t],"mod"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>{const i=s%n;return s<0&&n<0||s>=0&&n>=0?i:(i+n)%n})}maximum(e,t){return ee([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.max(s,n))}all(e,t){ee(e,"all"),U.assertAxesAreInnerMostDims("all",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=ye(s,e.dtype),r=N.sizeFromShape(n),o=this.readSync(i.dataId),a=this.readSync(e.dataId);for(let l=0;l<o.length;++l){const c=l*r;let p=a[c];for(let u=0;u<r;++u){const h=a[c+u];p=p&&h}o[l]=p}return i}any(e,t){ee(e,"any"),U.assertAxesAreInnerMostDims("any",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=ye(s,e.dtype),r=N.sizeFromShape(n),o=this.readSync(i.dataId),a=this.readSync(e.dataId);for(let l=0;l<o.length;++l){const c=l*r;let p=a[c];for(let u=0;u<r;++u){const h=a[c+u];p=p||h}o[l]=p}return i}squaredDifference(e,t){return ee([e,t],"squaredDifference"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>{const i=s-n;return i*i})}linear(e){return e}relu(e){ee(e,"relu");const t=ye(e.shape,e.dtype),s=this.readSync(t.dataId),n=this.readSync(e.dataId);for(let i=0;i<n.length;++i)s[i]=Math.max(0,n[i]);return t}relu6(e){ee(e,"relu");const t=ye(e.shape,e.dtype),s=this.readSync(t.dataId),n=this.readSync(e.dataId);for(let i=0;i<n.length;++i)s[i]=Math.min(Math.max(0,n[i]),6);return t}prelu(e,t){return ee([e,t],"prelu"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>s<0?n*s:s)}eluDer(e,t){ee([e,t],"eluDer");const s=new Float32Array(t.size),n=this.readSync(t.dataId),i=this.readSync(e.dataId);for(let r=0;r<n.length;++r){const o=n[r];o>=1?s[r]=i[r]:s[r]=i[r]*(o+1)}return this.makeOutput(s,t.shape,"float32")}atan2(e,t){return ee([e,t],"atan2"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.atan2(s,n))}fusedConv2d({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){let o=this.conv2d(e,t,s);return n&&(o=$(o,n)),i&&(o=Kw(this,o,i,r)),o}conv2d(e,t,s){ee([e,t],"conv2d");const n=s.filterHeight,i=s.filterWidth,r=s.dilationHeight,o=s.dilationWidth,a=s.padInfo.left,l=s.padInfo.top,c=s.dataFormat==="channelsLast",p=ge(s.outShape,e.dtype),u=e.strides[0],h=c?e.strides[1]:e.strides[2],d=c?e.strides[2]:1,m=c?1:e.strides[1],f=p.strides[0],g=c?p.strides[1]:p.strides[2],y=c?p.strides[2]:1,w=c?1:p.strides[1],x=this.readSync(e.dataId),T=this.readSync(t.dataId),A=p.values;for(let _=0;_<s.batchSize;++_){const E=_*u,F=_*f;for(let D=0;D<s.outHeight;++D){const M=F+D*g,P=D*s.strideHeight-l;for(let B=0;B<n;B++){const Y=P+B*r;if(Y<0||Y>=s.inHeight)continue;const q=B*t.strides[0],K=E+Y*h;for(let H=0;H<s.outWidth;++H){const Q=M+H*y,J=H*s.strideWidth-a;for(let ie=0;ie<i;ie++){const ne=J+ie*o;if(ne<0||ne>=s.inWidth)continue;const le=q+ie*t.strides[1],ue=K+ne*d;let oe=le;for(let de=0;de<s.inChannels;++de){const Ae=x[ue+de*m];for(let Me=0;Me<s.outChannels;++Me)A[Q+Me*w]+=Ae*T[oe+Me];oe+=s.outChannels}}}}}}return p.toTensor()}conv3d(e,t,s){const n=s.filterDepth,i=s.filterHeight,r=s.filterWidth,o=s.dilationDepth,a=s.dilationHeight,l=s.dilationWidth,c=s.padInfo.front,p=s.padInfo.left,u=s.padInfo.top,h=ge(s.outShape,e.dtype),d=this.readSync(e.dataId),m=this.readSync(t.dataId),f=h.values;for(let g=0;g<s.batchSize;++g){const y=g*e.strides[0],w=g*h.strides[0];for(let x=0;x<s.outDepth;++x){const T=w+x*h.strides[1],A=x*s.strideDepth-c;for(let _=0;_<n;_++){const E=A+_*o;if(E<0||E>=s.inDepth)continue;const F=_*t.strides[0],D=y+E*e.strides[1];for(let M=0;M<s.outHeight;++M){const P=T+M*h.strides[2],B=M*s.strideHeight-u;for(let Y=0;Y<i;Y++){const q=B+Y*a;if(q<0||q>=s.inHeight)continue;const K=F+Y*t.strides[1],H=D+q*e.strides[2];for(let Q=0;Q<s.outWidth;++Q){const J=P+Q*s.outChannels,ie=Q*s.strideWidth-p;for(let ne=0;ne<r;ne++){const le=ie+ne*l;if(le<0||le>=s.inWidth)continue;const ue=K+ne*t.strides[2],oe=H+le*s.inChannels;let de=ue;for(let Ae=0;Ae<s.inChannels;++Ae){const Me=d[oe+Ae];for(let Qe=0;Qe<s.outChannels;++Qe)f[J+Qe]+=Me*m[de+Qe];de+=s.outChannels}}}}}}}}return h.toTensor()}conv2dDerInput(e,t,s){ee([e,t],"conv2dDerInput");const n=ge(s.inShape,"float32"),i=n.values,r=this.readSync(e.dataId),o=this.readSync(t.dataId),[a,l,c]=t.strides,{batchSize:p,filterHeight:u,filterWidth:h,inChannels:d,inHeight:m,inWidth:f,outChannels:g,outHeight:y,outWidth:w,strideHeight:x,strideWidth:T,dataFormat:A}=s,_=u-1-s.padInfo.top,E=h-1-s.padInfo.left,F=A==="channelsLast",D=n.strides[0],M=F?n.strides[1]:n.strides[2],P=F?n.strides[2]:1,B=F?1:n.strides[1],Y=e.strides[0],q=F?e.strides[1]:e.strides[2],K=F?e.strides[2]:1,H=F?1:e.strides[1];for(let Q=0;Q<p;++Q)for(let J=0;J<d;++J)for(let ie=0;ie<m;++ie){const ne=ie-_,le=Math.max(0,Math.ceil(ne/x)),ue=Math.min(y,(u+ne)/x);for(let oe=0;oe<f;++oe){const de=oe-E,Ae=Math.max(0,Math.ceil(de/T)),Me=Math.min(w,(h+de)/T);let Qe=0;for(let $t=le;$t<ue;++$t){const ks=$t*x-ne;for(let bt=Ae;bt<Me;++bt){const ps=bt*T-de,Fn=Y*Q+q*$t+K*bt,Gs=a*(u-1-ks)+l*(h-1-ps)+c*J;for(let Ds=0;Ds<g;++Ds){const cn=r[Fn+H*Ds],Ic=o[Gs+Ds];Qe+=cn*Ic}}}const St=D*Q+M*ie+P*oe+B*J;i[St]=Qe}}return n.toTensor()}conv3dDerInput(e,t,s){const n=ge(s.inShape,"float32"),i=n.values,[r,o,a,l]=n.strides,c=this.readSync(e.dataId),[p,u,h,d]=e.strides,m=this.readSync(t.dataId),[f,g,y,w]=t.strides,{batchSize:x,filterDepth:T,filterHeight:A,filterWidth:_,inChannels:E,inDepth:F,inHeight:D,inWidth:M,outChannels:P,outDepth:B,outHeight:Y,outWidth:q,strideDepth:K,strideHeight:H,strideWidth:Q}=s,J=T-1-s.padInfo.front,ie=A-1-s.padInfo.top,ne=_-1-s.padInfo.left;for(let le=0;le<x;++le)for(let ue=0;ue<E;++ue)for(let oe=0;oe<F;++oe){const de=oe-J,Ae=Math.max(0,Math.ceil(de/K)),Me=Math.min(B,(T+de)/K);for(let Qe=0;Qe<D;++Qe){const St=Qe-ie,$t=Math.max(0,Math.ceil(St/H)),ks=Math.min(Y,(A+St)/H);for(let bt=0;bt<M;++bt){const ps=bt-ne,Fn=Math.max(0,Math.ceil(ps/Q)),Gs=Math.min(q,(_+ps)/Q);let Ds=0;for(let cn=Ae;cn<Me;++cn){const Ic=cn*K-de;for(let ka=$t;ka<ks;++ka){const Da=ka*H-St;for(let Fa=Fn;Fa<Gs;++Fa){const Fg=Fa*Q-ps,Mg=p*le+u*cn+h*ka+d*Fa,YE=f*(T-1-Ic)+g*(A-1-Da)+y*(_-1-Fg)+w*ue;for(let Yu=0;Yu<P;++Yu){const KE=c[Mg+Yu],XE=m[YE+Yu];Ds+=KE*XE}}}}i[r*le+o*oe+a*Qe+l*bt+ue]=Ds}}}return n.toTensor()}conv2dDerFilter(e,t,s){ee([e,t],"conv2dDerFilter");const n=s.strideHeight,i=s.strideWidth,r=s.filterHeight,o=s.filterWidth,a=s.dataFormat==="channelsLast",l=ge(s.filterShape,"float32"),c=s.padInfo.left,p=s.padInfo.top,u=this.bufferSync(e),h=this.bufferSync(t);for(let d=0;d<r;++d){const m=Math.max(0,Math.ceil((p-d)/n)),f=Math.min(s.outHeight,(s.inHeight+p-d)/n);for(let g=0;g<o;++g){const y=Math.max(0,Math.ceil((c-g)/i)),w=Math.min(s.outWidth,(s.inWidth+c-g)/i);for(let x=0;x<s.inChannels;++x)for(let T=0;T<s.outChannels;++T){let A=0;for(let _=0;_<s.batchSize;++_)for(let E=m;E<f;++E){const F=d+E*n-p;for(let D=y;D<w;++D){const M=g+D*i-c;a?A+=u.get(_,F,M,x)*h.get(_,E,D,T):A+=u.get(_,x,F,M)*h.get(_,T,E,D)}}l.set(A,d,g,x,T)}}}return l.toTensor()}conv3dDerFilter(e,t,s){const n=s.strideDepth,i=s.strideHeight,r=s.strideWidth,o=s.filterDepth,a=s.filterHeight,l=s.filterWidth,c=ge(s.filterShape,"float32"),p=c.values,[u,h,d,m]=c.strides,f=this.readSync(t.dataId),[g,y,w,x]=t.strides,T=this.readSync(e.dataId),[A,_,E,F]=e.strides,D=s.padInfo.front,M=s.padInfo.left,P=s.padInfo.top;for(let B=0;B<o;++B){const Y=Math.max(0,Math.ceil((D-B)/n)),q=Math.min(s.outDepth,(s.inDepth+D-B)/n),K=B*u;for(let H=0;H<a;++H){const Q=Math.max(0,Math.ceil((P-H)/i)),J=Math.min(s.outHeight,(s.inHeight+P-H)/i),ie=H*h+K;for(let ne=0;ne<l;++ne){const le=Math.max(0,Math.ceil((M-ne)/r)),ue=Math.min(s.outWidth,(s.inWidth+M-ne)/r),oe=ne*d+ie;for(let de=0;de<s.inChannels;++de){const Ae=de*m+oe;for(let Me=0;Me<s.outChannels;++Me){let Qe=0;for(let St=0;St<s.batchSize;++St){const $t=St*A,ks=St*g;for(let bt=Y;bt<q;++bt){const ps=B+bt*n-D,Fn=ps*_+$t,Gs=bt*y+ks;for(let Ds=Q;Ds<J;++Ds){const cn=H+Ds*i-P,Ic=cn*E+Fn,ka=Ds*w+Gs;for(let Da=le;Da<ue;++Da){const Fa=ne+Da*r-M,Fg=Fa*F+Ic,Mg=Da*x+ka;Qe+=T[Fg+de]*f[Mg+Me]}}}}p[Ae+Me]=Qe}}}}}return c.toTensor()}fusedDepthwiseConv2D({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){let o=this.depthwiseConv2D(e,t,s);return n&&(o=$(o,n)),i&&(o=Kw(this,o,i,r)),o}depthwiseConv2D(e,t,s){ee([e,t],"depthwiseConv2D");const n=s.filterHeight,i=s.filterWidth,r=s.dilationHeight,o=s.dilationWidth,a=s.padInfo.left,l=s.padInfo.top,c=s.outChannels/s.inChannels,p=ge(s.outShape,e.dtype),u=this.readSync(e.dataId),h=this.readSync(t.dataId),d=p.values;for(let m=0;m<s.batchSize;++m){const f=m*e.strides[0],g=m*p.strides[0];for(let y=0;y<s.outHeight;++y){const w=g+y*p.strides[1],x=y*s.strideHeight-a;for(let T=0;T<n;++T){const A=x+T*r;if(A<0||A>=s.inHeight)continue;const _=T*t.strides[0],E=f+A*e.strides[1];for(let F=0;F<s.outWidth;++F){const D=w+F*p.strides[2],M=F*s.strideWidth-l;for(let P=0;P<i;++P){const B=M+P*o;if(B<0||B>=s.inWidth)continue;const Y=_+P*t.strides[1],q=E+B*s.inChannels;let K=D,H=Y;for(let Q=0;Q<s.inChannels;++Q){const J=u[q+Q];for(let ie=0;ie<c;++ie)d[K+ie]+=J*h[H+ie];K+=c,H+=c}}}}}}return p.toTensor()}depthwiseConv2DDerInput(e,t,s){ee([e,t],"depthwiseConv2DDerInput");const n=ge(s.inShape,"float32"),i=n.values,[r,o,a]=n.strides,l=this.readSync(e.dataId),[c,p,u]=e.strides,h=this.readSync(t.dataId),[d,m,f]=t.strides,{batchSize:g,filterHeight:y,filterWidth:w,inChannels:x,inHeight:T,inWidth:A,outChannels:_,outHeight:E,outWidth:F,strideHeight:D,strideWidth:M}=s,P=y-1-s.padInfo.top,B=w-1-s.padInfo.left,Y=_/x;for(let q=0;q<g;++q)for(let K=0;K<x;++K)for(let H=0;H<T;++H){const Q=H-P,J=Math.max(0,Math.ceil(Q/D)),ie=Math.min(E,(y+Q)/D);for(let ne=0;ne<A;++ne){const le=ne-B,ue=Math.max(0,Math.ceil(le/M)),oe=Math.min(F,(w+le)/M);let de=0;for(let Ae=J;Ae<ie;++Ae){const Me=Ae*D-Q;for(let Qe=ue;Qe<oe;++Qe){const St=Qe*M-le,$t=c*q+p*Ae+u*Qe,ks=d*(y-1-Me)+m*(w-1-St)+f*K;for(let bt=0;bt<Y;++bt){const ps=K*Y+bt,Fn=l[$t+ps],Gs=h[ks+bt];de+=Fn*Gs}}}i[r*q+o*H+a*ne+K]=de}}return n.toTensor()}depthwiseConv2DDerFilter(e,t,s){ee([e,t],"depthwiseConv2DDerFilter");const n=s.strideHeight,i=s.strideWidth,r=s.filterHeight,o=s.filterWidth,a=ge(s.filterShape,"float32"),l=s.padInfo.left,c=s.padInfo.top,p=s.outChannels/s.inChannels,u=this.bufferSync(e),h=this.bufferSync(t);for(let d=0;d<r;++d){const m=Math.max(0,Math.ceil((c-d)/n)),f=Math.min(s.outHeight,(s.inHeight+c-d)/n);for(let g=0;g<o;++g){const y=Math.max(0,Math.ceil((l-g)/i)),w=Math.min(s.outWidth,(s.inWidth+l-g)/i);for(let x=0;x<s.outChannels;++x){const T=Math.trunc(x/p),A=x%p;let _=0;for(let E=0;E<s.batchSize;++E)for(let F=m;F<f;++F){const D=d+F*n-c;for(let M=y;M<w;++M){const P=g+M*i-l;_+=u.get(E,D,P,T)*h.get(E,F,M,x)}}a.set(_,d,g,T,A)}}}return a.toTensor()}tile(e,t){return ee(e,"tile"),bj(this.bufferSync(e),t)}gather(e,t,s){ee([e,t],"gather");const n=e.shape.slice(),i=this.readSync(t.dataId);n[s]=i.length;const r=ge(n,e.dtype),o=this.bufferSync(e);for(let a=0;a<r.size;++a){const l=r.indexToLoc(a),c=l.slice();c[s]=i[l[s]];const p=o.locToIndex(c);r.values[a]=o.values[p]}return r.toTensor()}batchToSpaceND(e,t,s){ee([e],"batchToSpaceND");const n=t.reduce((c,p)=>c*p),i=U.getReshaped(e.shape,t,n),r=U.getPermuted(i.length,t.length),o=U.getReshapedPermuted(e.shape,t,n),a=U.getSliceBeginCoords(s,t.length),l=U.getSliceSize(o,s,t.length);return se(e.reshape(i),r).reshape(o).slice(a,l)}pool3d(e,t,s){ee(e,"pool3d");const n=t.strideDepth,i=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,u=t.effectiveFilterWidth,h=t.padInfo.front,d=t.padInfo.top,m=t.padInfo.left,f=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(e.dataId),y=ge(t.outShape,e.dtype),w=y.values,x=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],T=t.outShape[2]*t.outShape[3]*t.outShape[4],A=t.outShape[3]*t.outShape[4],_=t.outShape[4];for(let E=0;E<t.batchSize;++E){const F=E*x,D=E*e.strides[0];for(let M=0;M<t.inChannels;++M)for(let P=0;P<t.outDepth;++P){const B=P*n-h;let Y=B;for(;Y<0;)Y+=o;const q=Math.min(t.inDepth,c+B),K=F+P*T;for(let H=0;H<t.outHeight;++H){const Q=H*i-d;let J=Q;for(;J<0;)J+=a;const ie=Math.min(t.inHeight,p+Q),ne=K+H*A;for(let le=0;le<t.outWidth;++le){const ue=le*r-m;let oe=ue;for(;oe<0;)oe+=l;const de=Math.min(t.inWidth,u+ue),Ae=ne+le*_;let Me=f,Qe=0,St=0;for(let ks=Y;ks<q;ks+=o){const bt=D+ks*e.strides[1];for(let ps=J;ps<ie;ps+=a){const Fn=bt+ps*e.strides[2];for(let Gs=oe;Gs<de;Gs+=l){const Ds=Fn+Gs*e.strides[3],cn=g[Ds+M];if(s==="max"&&cn>Me?Me=cn:s==="avg"&&(Qe+=cn,St++),isNaN(Me))break}if(isNaN(Me))break}if(isNaN(Me))break}const $t=Ae+M;w[$t]=s==="avg"?Qe/St:Me}}}}return y.toTensor()}avgPool3d(e,t){return ee(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()}avgPool3dBackprop(e,t,s){ee([e,t],"avgPool3dBackprop");const n=s.strideDepth,i=s.strideHeight,r=s.strideWidth,o=s.filterDepth,a=s.filterHeight,l=s.filterWidth,c=s.dilationDepth,p=s.dilationHeight,u=s.dilationWidth,h=s.effectiveFilterDepth,d=s.effectiveFilterHeight,m=s.effectiveFilterWidth,f=h-1-s.padInfo.front,g=m-1-s.padInfo.left,y=d-1-s.padInfo.top,w=ge(t.shape,"float32"),x=1/(o*a*l),T=this.bufferSync(e);for(let A=0;A<s.batchSize;++A)for(let _=0;_<s.inChannels;++_)for(let E=0;E<s.inDepth;++E)for(let F=0;F<s.inHeight;++F)for(let D=0;D<s.inWidth;++D){const M=E-f,P=F-y,B=D-g;let Y=0;for(let q=0;q<h;q+=c){const K=(M+q)/n;if(K<0||K>=s.outDepth||Math.floor(K)!==K)continue;for(let H=0;H<d;H+=p){const Q=(P+H)/i;if(Q<0||Q>=s.outHeight||Math.floor(Q)!==Q)continue;for(let J=0;J<m;J+=u){const ie=(B+J)/r;if(ie<0||ie>=s.outWidth||Math.floor(ie)!==ie)continue;const ne=T.get(A,K,Q,ie,_);Y+=ne}}}w.set(Y*x,A,E,F,D,_)}return w.toTensor()}maxPool3d(e,t){return ee(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()}maxPool3dPositions(e,t){const s=ge(t.outShape,"int32"),n=t.strideDepth,i=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,u=t.effectiveFilterWidth,h=t.padInfo.front,d=t.padInfo.top,m=t.padInfo.left,f=this.bufferSync(e);for(let g=0;g<t.batchSize;++g)for(let y=0;y<t.inChannels;++y)for(let w=0;w<t.outDepth;++w){const x=w*n-h;let T=x;for(;T<0;)T+=o;const A=Math.min(t.inDepth,c+x);for(let _=0;_<t.outHeight;++_){const E=_*i-d;let F=E;for(;F<0;)F+=a;const D=Math.min(t.inHeight,p+E);for(let M=0;M<t.outWidth;++M){const P=M*r-m;let B=P;for(;B<0;)B+=l;const Y=Math.min(t.inWidth,u+P);let q=Number.NEGATIVE_INFINITY,K=-1;for(let H=T;H<A;H+=o){const Q=H-x;for(let J=F;J<D;J+=a){const ie=J-E;for(let ne=B;ne<Y;ne+=l){const le=ne-P,ue=f.get(g,H,J,ne,y);ue>=q&&(q=ue,K=Q*p*u+ie*p+le)}}}s.set(K,g,w,_,M,y)}}}return s.toTensor()}maxPool3dBackprop(e,t,s,n){ee([t,s],"maxPool3dBackprop");const i=this.maxPool3dPositions(t,n),r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,l=n.dilationDepth,c=n.dilationHeight,p=n.dilationWidth,u=n.effectiveFilterDepth,h=n.effectiveFilterHeight,d=n.effectiveFilterWidth,m=u-1-n.padInfo.front,f=d-1-n.padInfo.left,g=h-1-n.padInfo.top,y=ge(t.shape,"float32"),w=this.bufferSync(i),x=this.bufferSync(e);for(let T=0;T<n.batchSize;++T)for(let A=0;A<n.inChannels;++A)for(let _=0;_<n.inDepth;++_)for(let E=0;E<n.inHeight;++E)for(let F=0;F<n.inWidth;++F){const D=_-m,M=E-g,P=F-f;let B=0;for(let Y=0;Y<u;Y+=l){const q=(D+Y)/r;if(q<0||q>=n.outDepth||Math.floor(q)!==q)continue;for(let K=0;K<h;K+=c){const H=(M+K)/o;if(H<0||H>=n.outHeight||Math.floor(H)!==H)continue;for(let Q=0;Q<d;Q+=p){const J=(P+Q)/a;if(J<0||J>=n.outWidth||Math.floor(J)!==J)continue;const ie=u*h*d-1-w.get(T,q,H,J,A),ne=Y*h*d+K*d+Q,le=ie===ne?1:0;if(le===0)continue;const ue=x.get(T,q,H,J,A);B+=ue*le}}}y.set(B,T,_,E,F,A)}return y.toTensor()}resizeBilinear(e,t,s,n){ee(e,"resizeBilinear");const[i,r,o,a]=e.shape,l=this.readSync(e.dataId),c=new Float32Array(N.sizeFromShape([i,t,s,a])),p=[n&&t>1?r-1:r,n&&s>1?o-1:o],u=[n&&t>1?t-1:t,n&&s>1?s-1:s];let h=0;const d=p[0]/u[0],m=p[1]/u[1];for(let f=0;f<i;f++)for(let g=0;g<t;g++){const y=d*g,w=Math.floor(y),x=y-w,T=Math.min(r-1,Math.ceil(y)),A=f*e.strides[0]+w*e.strides[1],_=f*e.strides[0]+T*e.strides[1];for(let E=0;E<s;E++){const F=m*E,D=Math.floor(F),M=F-D,P=Math.min(o-1,Math.ceil(F)),B=A+D*e.strides[2],Y=_+D*e.strides[2],q=A+P*e.strides[2],K=_+P*e.strides[2];for(let H=0;H<a;H++){const Q=l[B+H],J=l[Y+H],ie=l[q+H],ne=l[K+H],le=Q+(ie-Q)*M,ue=J+(ne-J)*M,oe=le+(ue-le)*x;c[h++]=oe}}}return ze(c,[i,t,s,a])}resizeBilinearBackprop(e,t,s){ee([e,t],"resizeBilinearBackprop");const[n,i,r,o]=t.shape,[,a,l]=e.shape,c=new Float32Array(n*i*r*o),p=[s&&a>1?i-1:i,s&&l>1?r-1:r],u=[s&&a>1?a-1:a,s&&l>1?l-1:l],h=p[0]/u[0],d=p[1]/u[1],m=this.readSync(e.dataId);let f=0;for(let g=0;g<n;g++){const y=g*t.strides[0];for(let w=0;w<a;w++){const x=w*h,T=Math.floor(x),A=Math.min(Math.ceil(x),i-1),_=y+T*t.strides[1],E=y+A*t.strides[1],F=x-T,D=1-F;for(let M=0;M<l;M++){const P=M*d,B=Math.floor(P),Y=Math.min(Math.ceil(P),r-1),q=P-B,K=1-q,H=_+B*t.strides[2],Q=_+Y*t.strides[2],J=E+B*t.strides[2],ie=E+Y*t.strides[2],ne=D*K,le=D*q,ue=F*K,oe=F*q;for(let de=0;de<o;de++){const Ae=m[f++];c[H+de]+=Ae*ne,c[Q+de]+=Ae*le,c[J+de]+=Ae*ue,c[ie+de]+=Ae*oe}}}}return ss(c,[n,r,i,o],t.dtype)}resizeNearestNeighbor(e,t,s,n){ee(e,"resizeNearestNeighbor");const[i,r,o,a]=e.shape,l=this.readSync(e.dataId),c=new Float32Array(i*t*s*a),p=[n&&t>1?r-1:r,n&&s>1?o-1:o],u=[n&&t>1?t-1:t,n&&s>1?s-1:s],h=p[0]/u[0],d=p[1]/u[1];let m=0;for(let f=0;f<i;f++){const g=f*e.strides[0];for(let y=0;y<t;y++){const w=h*y,x=Math.min(r-1,n?Math.round(w):Math.floor(w)),T=g+x*e.strides[1];for(let A=0;A<s;A++){const _=d*A,E=Math.min(o-1,n?Math.round(_):Math.floor(_)),F=T+E*e.strides[2];for(let D=0;D<a;D++){const M=l[F+D];c[m++]=M}}}}return ze(c,[i,t,s,a],e.dtype)}resizeNearestNeighborBackprop(e,t,s){ee([e,t],"resizeNearestNeighborBackprop");const[n,i,r,o]=t.shape,[,a,l]=e.shape,c=new Float32Array(n*i*r*o),p=this.readSync(e.dataId),u=[s&&a>1?i-1:i,s&&l>1?r-1:r],h=[s&&a>1?a-1:a,s&&l>1?l-1:l],d=u[0]/h[0],m=u[1]/h[1],f=1/d,g=1/m,y=Math.ceil(f)*2+2,w=Math.ceil(g)*2+2;for(let x=0;x<n;x++){const T=x*t.strides[0];for(let A=0;A<i;A++){const _=T+A*t.strides[1],E=Math.floor(A*f),F=Math.floor(E-y/2);for(let D=0;D<r;D++){const M=_+D*t.strides[2],P=Math.floor(D*g),B=Math.floor(P-w/2);for(let Y=0;Y<o;Y++){let q=0;for(let K=0;K<y;K++){const H=K+F;if(H<0||H>=a)continue;const Q=T+H*e.strides[1],J=H*d,ie=Math.min(i-1,s?Math.round(J):Math.floor(J));if(A!==ie)continue;for(let ne=0;ne<w;ne++){const le=ne+B;if(le<0||le>=l)continue;const ue=Q+le*e.strides[2],oe=le*m,de=Math.min(r-1,s?Math.round(oe):Math.floor(oe));D===de&&(q+=p[ue+Y])}}c[M+Y]=q}}}}return ss(c,t.shape,t.dtype)}localResponseNormalization4D(e,t,s,n,i){ee(e,"localResponseNormalization4D");const r=e.shape[3],o=r-1,a=this.readSync(e.dataId),l=e.size,c=new Float32Array(l);function p(u){const h=u%r;let d=u-h+Math.max(0,h-t);const m=u-h+Math.min(h+t,o);let f=0;for(;d<=m;d++){const g=a[d];f+=g*g}return f}for(let u=0;u<l;u++){const h=p(u),d=a[u]*Math.pow(s+n*h,-i);c[u]=d}return ss(c,e.shape)}LRNGrad(e,t,s,n,i,r,o){ee(e,"LRNGrad");const a=e.shape[3],l=this.readSync(e.dataId),c=this.readSync(t.dataId),p=this.readSync(s.dataId),u=new Float32Array(e.size),h=e.size;for(let d=0;d<h;d++){const m=d%a,f=d-m+Math.max(0,m-n),g=d-m+Math.min(a,m+n+1);let y=0;for(let w=f;w<g;w++)y+=Math.pow(c[w],2);y=r*y+i;for(let w=f;w<g;w++){let x=-2*r*o*c[w]*p[d]/y;d===w&&(x+=Math.pow(y,-o)),x*=l[d],u[w]+=x}}return ss(u,e.shape)}multinomial(e,t,s,n){ee(e,"multinomial");const i=t?e:ts(e),r=i.shape[0],o=i.shape[1],a=ye([r,s],"int32"),l=this.readSync(a.dataId),c=this.readSync(i.dataId);for(let p=0;p<r;++p){const u=p*o,h=new Float32Array(o-1);h[0]=c[u];for(let f=1;f<h.length;++f)h[f]=h[f-1]+c[u+f];const d=zC.alea(n.toString()),m=p*s;for(let f=0;f<s;++f){const g=d();l[m+f]=h.length;for(let y=0;y<h.length;y++)if(g<h[y]){l[m+f]=y;break}}}return a}oneHot(e,t,s,n){ee(e,"oneHot");const i=new Float32Array(e.size*t);i.fill(n);const r=this.readSync(e.dataId);for(let o=0;o<e.size;++o)r[o]>=0&&r[o]<t&&(i[o*t+r[o]]=s);return ls(i,[e.size,t],"int32")}nonMaxSuppression(e,t,s,n,i){ee(e,"nonMaxSuppression");const r=this.readSync(e.dataId),o=this.readSync(t.dataId);return gj(r,o,s,n,i)}depthToSpace(e,t,s){N.assert(s==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${s}`),N.assert(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`);const n=e.shape[0],i=e.shape[1],r=e.shape[2],o=e.shape[3],a=i*t,l=r*t,c=o/(t*t),p=this.readSync(e.dataId),u=new Float32Array(n*a*l*c);let h=0;for(let d=0;d<n;++d)for(let m=0;m<a;++m){const f=Math.floor(m/t),g=m%t;for(let y=0;y<l;++y){const w=Math.floor(y/t),x=y%t,T=(g*t+x)*c;for(let A=0;A<c;++A){const _=A+T,E=_+o*(w+r*(f+i*d));u[h++]=p[E]}}}return ss(u,[n,a,l,c])}broadcastedBinaryOp(e,t,s,n){const i=U.assertAndGetBroadcastShape(e.shape,t.shape),r=ge(i,s),o=this.readSync(e.dataId),a=this.readSync(t.dataId),l=U.getBroadcastDims(e.shape,i),c=U.getBroadcastDims(t.shape,i),p=r.values;if(l.length+c.length===0)for(let u=0;u<p.length;++u)p[u]=n(o[u%o.length],a[u%a.length]);else{const u=this.bufferSync(e),h=this.bufferSync(t);for(let d=0;d<p.length;++d){const m=r.indexToLoc(d),f=m.slice(-e.rank);l.forEach(x=>f[x]=0);const g=u.locToIndex(f),y=m.slice(-t.rank);c.forEach(x=>y[x]=0);const w=h.locToIndex(y);p[d]=n(o[g],a[w])}}return r.toTensor()}split(e,t,s){return yj(e,t,s)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}cropAndResize(e,t,s,n,i,r){const[o,a,l,c]=e.shape,p=t.shape[0],[u,h]=n,d=ge([p,u,h,c],"float32"),m=this.readSync(t.dataId),f=this.readSync(s.dataId),g=this.readSync(e.dataId),y=e.strides,w=d.strides;for(let x=0;x<p;x++){const T=x*4,A=m[T],_=m[T+1],E=m[T+2],F=m[T+3],D=f[x];if(D>=o)continue;const M=u>1?(E-A)*(a-1)/(u-1):0,P=h>1?(F-_)*(l-1)/(h-1):0;for(let B=0;B<u;B++){const Y=u>1?A*(a-1)+B*M:.5*(A+E)*(a-1);if(Y<0||Y>a-1){for(let q=0;q<h;q++)for(let K=0;K<c;K++){const H=K+q*w[2]+B*w[1]+x*w[0];d.values[H]=r}continue}if(i==="bilinear"){const q=Math.floor(Y),K=Math.ceil(Y),H=Y-q;for(let Q=0;Q<h;Q++){const J=h>1?_*(l-1)+Q*P:.5*(_+F)*(l-1);if(J<0||J>l-1){for(let ue=0;ue<c;ue++){const oe=ue+Q*w[2]+B*w[1]+x*w[0];d.values[oe]=r}continue}const ie=Math.floor(J),ne=Math.ceil(J),le=J-ie;for(let ue=0;ue<c;ue++){let oe=ue+ie*y[2]+q*y[1]+D*y[0];const de=g[oe];oe=ue+ne*y[2]+q*y[1]+D*y[0];const Ae=g[oe];oe=ue+ie*y[2]+K*y[1]+D*y[0];const Me=g[oe];oe=ue+ne*y[2]+K*y[1]+D*y[0];const Qe=g[oe],St=de+(Ae-de)*le,$t=Me+(Qe-Me)*le;oe=ue+Q*w[2]+B*w[1]+x*w[0],d.values[oe]=St+($t-St)*H}}}else for(let q=0;q<h;++q){const K=h>1?_*(l-1)+q*P:.5*(_+F)*(l-1);if(K<0||K>l-1){for(let J=0;J<c;J++){const ie=J+q*w[2]+B*w[1]+x*w[0];d.values[ie]=r}continue}const H=Math.round(K),Q=Math.round(Y);for(let J=0;J<c;J++){const ie=J+H*y[2]+Q*y[1]+D*y[0],ne=J+q*w[2]+B*w[1]+x*w[0];d.values[ne]=g[ie]}}}}return d.toTensor()}sparseToDense(e,t,s,n){const{sliceRank:i,numUpdates:r,sliceSize:o,strides:a,outputSize:l}=U.calculateShapes(t,e,s),c=!1;return this.scatter(e,t,s,l,o,r,i,a,n,c)}gatherND(e,t){const s=t.shape,n=s[s.length-1],[i,r,o,a]=U.prepareAndValidate(e,t);if(r===0)return ze([],i,e.dtype);const l=new dn([r,o],e.dtype),c=this.readSync(t.dataId),p=this.readSync(e.dataId);for(let u=0;u<r;u++){const h=[];let d=0;for(let m=0;m<n;m++){const f=c[u*n+m];d+=f*a[m],h.push(f)}if(d<0||d>=e.size/o)throw new Error(`Invalid indices: ${h} does not index into ${e.shape}`);for(let m=0;m<o;m++)l.values[u*o+m]=p[d*o+m]}return l.toTensor().reshape(i)}scatterND(e,t,s){const{sliceRank:n,numUpdates:i,sliceSize:r,strides:o,outputSize:a}=U.calculateShapes(t,e,s),l=j(0),c=!0;return this.scatter(e,t,s,a,r,i,n,o,l,c)}fill(e,t,s){s=s||N.inferDtype(t);const n=N.getArrayFromDType(s,N.sizeFromShape(e));return n.fill(t),Us().makeTensor(n,e,s,this)}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported for string tensors");return this.fill(e.shape,1,e.dtype)}zerosLike(e){const t=N.getArrayFromDType(e.dtype,N.sizeFromShape(e.shape));return this.makeOutput(t,e.shape,e.dtype)}linspace(e,t,s){return U.linspaceImpl(e,t,s)}scatter(e,t,s,n,i,r,o,a,l,c){const p=[n/i,i],u=this.readSync(e.dataId),h=this.readSync(t.dataId);if(n===0)return ze([],s,t.dtype);const d=new dn(p,t.dtype);d.values.fill(this.readSync(l.dataId)[0]);for(let m=0;m<r;m++){const f=[];let g=0;for(let y=0;y<o;y++){const w=u[m*o+y];f.push(w),g+=w*a[y]}if(g<0||g>=n/i)throw new Error(`Invalid indices: ${f} does not index into ${s}`);for(let y=0;y<i;y++)c?d.values[g*i+y]+=h[m*i+y]:d.values[g*i+y]=t.rank===0?h[0]:h[m*i+y]}return d.toTensor().reshape(s)}}function Jw(e){const t=new Float32Array(e.length);for(let s=0;s<e.length;++s)t[s]=Math.abs(e[s]);return t}const Lj=e=>{const{x:t}=e.inputs,s=e.backend;let n=new Float32Array(N.sizeFromShape(t.shape));if(t.dtype!=="complex64"){const i=s.data.get(t.dataId).values;n=Jw(i)}else{const i=s.data.get(t.dataId),r=i.complexTensorInfos.real,o=i.complexTensorInfos.imag,a=s.data.get(r.dataId).values,l=s.data.get(o.dataId).values;for(let c=0;c<a.length;c++){const p=a[c],u=l[c];n[c]=Math.hypot(p,u)}}return s.makeOutput(n,t.shape,"float32")},PC={kernelName:_o,backendName:"cpu",kernelFunc:Lj};function js(e){return(t,s,n,i,r)=>{const o=U.assertAndGetBroadcastShape(t,s),a=o.length,l=N.computeStrides(o),c=N.sizeFromShape(o),p=N.getTypedArrayFromDType(r,c),u=t.length,h=s.length,d=N.computeStrides(t),m=N.computeStrides(s),f=U.getBroadcastDims(t,o),g=U.getBroadcastDims(s,o);if(f.length+g.length===0)for(let y=0;y<p.length;++y)p[y]=e(n[y%n.length],i[y%i.length]);else for(let y=0;y<p.length;++y){const w=N.indexToLoc(y,a,l),x=w.slice(-u);f.forEach(E=>x[E]=0);const T=N.locToIndex(x,u,d),A=w.slice(-h);g.forEach(E=>A[E]=0);const _=N.locToIndex(A,h,m);p[y]=e(n[T],i[_])}return[p,o]}}function Es(e){const{inputs:t,backend:s}=e,{real:n,imag:i}=t,r=s.data.get(n.dataId).values,o=s.data.get(i.dataId).values,a=s.makeTensorInfo(n.shape,"complex64"),l=s.data.get(a.dataId);return l.complexTensorInfos={real:s.makeTensorInfo(n.shape,"float32",r),imag:s.makeTensorInfo(i.shape,"float32",o)},a}const BC={kernelName:jc,backendName:"cpu",kernelFunc:Es};function bi(e){const{inputs:t,backend:s}=e,{x:n}=t;return s.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}const jC={kernelName:Ci,backendName:"cpu",kernelFunc:bi};function bo(e){const{inputs:t,backend:s}=e,{input:n}=t,i=s.data.get(n.dataId).complexTensorInfos.real,r=s.data.get(i.dataId).values;return s.makeTensorInfo(i.shape,i.dtype,r)}const VC={kernelName:mp,backendName:"cpu",kernelFunc:bo};function Xl(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{dtype:r}=n;if(r==="complex64"){if(i.dtype==="complex64")return bi({inputs:{x:i},backend:s});const o=ye(i.shape),a=Xl({inputs:{x:i},backend:s,attrs:{dtype:"float32"}}),l=Es({inputs:{real:a,imag:o},backend:s});return o.dispose(),s.disposeIntermediateTensorInfo(a),l}if(i.dtype==="complex64"){const o=bo({inputs:{input:i},backend:s}),a=Xl({inputs:{x:o},backend:s,attrs:{dtype:r}});return s.disposeIntermediateTensorInfo(o),a}if(!N.hasEncodingLoss(i.dtype,r)){const o=bi({inputs:{x:i},backend:s});return{dataId:o.dataId,shape:o.shape,dtype:r}}if(r==="int32"){const o=s.data.get(i.dataId).values,a=Int32Array.from(o);return s.makeTensorInfo(i.shape,"int32",a)}if(r==="bool"){const o=s.data.get(i.dataId).values,a=N.toTypedArray([0],i.dtype),[l,c]=js((p,u)=>p!==u?1:0)(i.shape,[],o,a,"bool");return s.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${r}`)}const GC={kernelName:Ai,backendName:"cpu",kernelFunc:Xl};function On(e,t,s,n){return s==null?({inputs:i,backend:r})=>{const{a:o,b:a}=i,l=r;ee([o,a],e);const c=l.data.get(o.dataId).values,p=l.data.get(a.dataId).values,u=n||o.dtype,[h,d]=t(o.shape,a.shape,c,p,u);return l.makeTensorInfo(d,u,h)}:({inputs:i,backend:r})=>{const{a:o,b:a}=i,l=r;if(o.dtype==="complex64"||a.dtype==="complex64"){const c=Xl({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),p=l.data.get(c.dataId),u=p.complexTensorInfos.real,h=p.complexTensorInfos.imag,d=l.data.get(u.dataId).values,m=l.data.get(h.dataId).values,f=Xl({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),y=g.complexTensorInfos.real,w=g.complexTensorInfos.imag,x=l.data.get(y.dataId).values,T=l.data.get(w.dataId).values,[A,_,E]=s(o.shape,a.shape,d,m,x,T),F=l.makeTensorInfo(E,"float32",A),D=l.makeTensorInfo(E,"float32",_),M=Es({inputs:{real:F,imag:D},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(F),l.disposeIntermediateTensorInfo(D),M}else{const c=l.data.get(o.dataId).values,p=l.data.get(a.dataId).values,u=n||o.dtype,[h,d]=t(o.shape,a.shape,c,p,u);return l.makeTensorInfo(d,u,h)}}}function Jl(e){return(t,s,n,i,r,o)=>{const a=U.assertAndGetBroadcastShape(t,s),l=N.sizeFromShape(a),c=a.length,p=N.computeStrides(a),u=N.getTypedArrayFromDType("float32",l),h=N.getTypedArrayFromDType("float32",l),d=U.getBroadcastDims(t,a),m=U.getBroadcastDims(s,a),f=U.mergeRealAndImagArrays(n,i),g=U.mergeRealAndImagArrays(r,o),y=t.length,w=N.computeStrides(t),x=s.length,T=N.computeStrides(s);if(d.length+m.length===0)for(let A=0;A<u.length;A++){const _=A%f.length,E=A%g.length,F=e(f[_*2],f[_*2+1],g[E*2],g[E*2+1]);u[A]=F.real,h[A]=F.imag}else for(let A=0;A<u.length;A++){const _=N.indexToLoc(A,c,p),E=_.slice(-y);d.forEach(B=>E[B]=0);const F=N.locToIndex(E,y,w),D=_.slice(-x);m.forEach(B=>D[B]=0);const M=N.locToIndex(D,x,T),P=e(f[F*2],f[F*2+1],g[M*2],g[M*2+1]);u[A]=P.real,h[A]=P.imag}return[u,h,a]}}const Zw=js((e,t)=>e+t),Sj=Jl((e,t,s,n)=>({real:e+s,imag:t+n})),Qw=On(Zn,Zw,Sj),qC={kernelName:Zn,backendName:"cpu",kernelFunc:Qw};function En(e){return(t,s,n)=>{const i=N.getTypedArrayFromDType(s,t.length);for(let r=0;r<t.length;++r)i[r]=e(t[r],n);return i}}function fe(e,t,s){return({inputs:n,attrs:i,backend:r})=>{const{x:o}=n;if(ee(o,e),o.dtype==="string"||s==="string")throw new Error("unaryKernelFunc does not support string input/output");const a=r,l=a.data.get(o.dataId).values,c=N.sizeFromShape(o.shape),p=s||o.dtype,u=N.getArrayFromDType(p,c);for(let h=0;h<c;++h)u[h]=t(l[h],i);return a.makeTensorInfo(o.shape,p,u)}}function _n(e,t,s){return({inputs:n,attrs:i,backend:r})=>{const{x:o}=n;if(ee(o,e),o.dtype==="string"||s==="string")throw new Error("unaryKernelFunc does not support string input/output");const a=r,l=a.data.get(o.dataId).values,c=s||o.dtype,p=t(l,c,i);return a.makeTensorInfo(o.shape,c,p)}}const ex=En(e=>Math.ceil(e)),Ij=_n(wr,ex),HC={kernelName:wr,backendName:"cpu",kernelFunc:Ij};const tx=En(e=>Math.exp(e)),vj=_n(vr,tx),YC={kernelName:vr,backendName:"cpu",kernelFunc:vj};const sx=En(e=>Math.expm1(e)),Tj=_n(Tr,sx),KC={kernelName:Tr,backendName:"cpu",kernelFunc:Tj};const nx=En(e=>Math.floor(e)),Aj=_n(Ar,nx),XC={kernelName:Ar,backendName:"cpu",kernelFunc:Aj};const ix=En(e=>Math.log(e)),Nj=_n(Or,ix),JC={kernelName:Or,backendName:"cpu",kernelFunc:Nj};function Yf(e,t,s,n){const i=N.getTypedArrayFromDType(n,N.sizeFromShape(s));for(let r=0;r<i.length;++r){const o=r*t;let a=e[o];for(let l=0;l<t;++l){const c=e[o+l];c>a&&(a=c)}i[r]=a}return i}const rx=js((e,t)=>e*t),Cj=Jl((e,t,s,n)=>({real:e*s-t*n,imag:e*n+t*s})),ox=On(_r,rx,Cj),ZC={kernelName:_r,backendName:"cpu",kernelFunc:ox};const ax=En(e=>1/Math.sqrt(e)),Rj=_n(Fr,ax),QC={kernelName:Fr,backendName:"cpu",kernelFunc:Rj};function lx(e,t,s,n,i){const r=Ms.isSliceContinous(n,t,s),o=N.sizeFromShape(s),a=N.computeStrides(n);if(r){const c=Ms.computeFlatOffset(t,a);return e.subarray(c,c+o)}const l=N.getTypedArrayFromDType(i,o);for(let c=0;c<o;++c){const p=s.length,u=N.computeStrides(s),h=N.indexToLoc(c,p,u),d=h.map((f,g)=>f+t[g]),m=N.locToIndex(d,n.length,a);l[c]=e[m]}return l}function Kf(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{begin:r,size:o}=n;ee(i,"slice");const[a,l]=Ms.parseSliceParams(i,r,o);Ms.assertParamsValid(i,a,l);const c=s.data.get(i.dataId).values,p=lx(c,a,l,i.shape,i.dtype);return s.makeTensorInfo(l,i.dtype,p)}const e0={kernelName:jo,backendName:"cpu",kernelFunc:Kf};const cx=js((e,t)=>e-t),Oj=Jl((e,t,s,n)=>({real:e-s,imag:t-n})),px=On(Br,cx,Oj),t0={kernelName:Br,backendName:"cpu",kernelFunc:px};function Zl(e,t,s,n,i){const r=t.length,o=N.sizeFromShape(t),a=N.computeStrides(t),l=N.computeStrides(i),c=N.getTypedArrayFromDType(s,N.sizeFromShape(i));for(let p=0;p<o;++p){const u=N.indexToLoc(p,r,a),h=new Array(u.length);for(let m=0;m<h.length;m++)h[m]=u[n[m]];const d=N.locToIndex(h,r,l);c[d]=e[p]}return c}function Xf(e,t,s,n){const i=N.parseAxisParam(t,s)[0],r=[1,s[0],1];for(let m=0;m<i;m++)r[0]*=s[m];r[1]=s[i];for(let m=i+1;m<s.length;m++)r[2]*=s[m];const o={},a=new Int32Array(s[i]),l=new dn(r,n,e),c=[],p=r[0]===1&&r[2]===1;for(let m=0;m<s[i];m++){let f;if(p)f=e[m].toString();else{const g=[];for(let y=0;y<r[0];y++)for(let w=0;w<r[2];w++)g.push(l.get(y,m,w));f=g.join(",")}if(o[f]!==void 0)a[m]=o[f];else{const g=Object.keys(o).length;o[f]=g,a[m]=g,c.push(m)}}const u=r.slice();u[1]=Object.keys(o).length;const h=new dn(u,n);c.forEach((m,f)=>{for(let g=0;g<r[0];g++)for(let y=0;y<r[2];y++)h.set(l.get(g,m,y),g,f,y)});const d=s.slice();return d[i]=u[1],{outputValues:h.values,outputShape:d,indices:a}}const ux={};Ee(ux,{addImpl:()=>Zw,ceilImpl:()=>ex,expImpl:()=>tx,expm1Impl:()=>sx,floorImpl:()=>nx,logImpl:()=>ix,maxImpl:()=>Yf,multiplyImpl:()=>rx,rsqrtImpl:()=>ax,simpleAbsImpl:()=>Jw,sliceImpl:()=>lx,subImpl:()=>cx,transposeImpl:()=>Zl,uniqueImpl:()=>Xf});const hx="2.6.0";Vp("cpu",()=>new Xw,1);const Ej=fe(dr,e=>Math.acos(e)),s0={kernelName:dr,backendName:"cpu",kernelFunc:Ej};const _j=fe(mr,e=>Math.acosh(e)),n0={kernelName:mr,backendName:"cpu",kernelFunc:_j};const kj=fe(fr,e=>Math.asin(e)),i0={kernelName:fr,backendName:"cpu",kernelFunc:kj};const Dj=fe(gr,e=>Math.asinh(e)),r0={kernelName:gr,backendName:"cpu",kernelFunc:Dj};const Fj=fe(yr,e=>Math.atan(e)),o0={kernelName:yr,backendName:"cpu",kernelFunc:Fj};const Mj=fe(br,e=>Math.atanh(e)),a0={kernelName:br,backendName:"cpu",kernelFunc:Mj};function Ql(e,t,s,n,i,r){const o=i.strideHeight,a=i.strideWidth,l=i.dilationHeight,c=i.dilationWidth,p=i.effectiveFilterHeight,u=i.effectiveFilterWidth,h=i.padInfo.top,d=i.padInfo.left,m=r==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=ge(i.outShape,s),g=f.values,y=i.outShape[1]*i.outShape[2]*i.outShape[3],w=i.outShape[2]*i.outShape[3],x=i.outShape[3];for(let T=0;T<i.batchSize;++T){const A=T*y,_=T*n[0];for(let E=0;E<i.inChannels;++E)for(let F=0;F<i.outHeight;++F){const D=F*o-h,M=Math.max(0,D),P=Math.min(i.inHeight,p+D),B=A+F*w;for(let Y=0;Y<i.outWidth;++Y){const q=Y*a-d,K=Math.max(0,q),H=Math.min(i.inWidth,u+q);let Q=m,J=0,ie=0;for(let le=M;le<P;le+=l){const ue=_+le*n[1];for(let oe=K;oe<H;oe+=c){const de=ue+oe*n[2],Ae=e[de+E];r==="max"&&Ae>Q?Q=Ae:r==="avg"&&(J+=Ae,ie++)}if(isNaN(Q))break}const ne=B+Y*x+E;g[ne]=r==="avg"?J/ie:Q}}}return f}function Jf(e,t,s,n,i=!1,r=!1){const o=ge(n.outShape,"int32"),a=n.strideHeight,l=n.strideWidth,c=n.dilationHeight,p=n.dilationWidth,u=n.effectiveFilterHeight,h=n.effectiveFilterWidth,d=n.padInfo.top,m=n.padInfo.left,f=ge(t,s,e);for(let g=0;g<n.batchSize;++g)for(let y=0;y<n.inChannels;++y)for(let w=0;w<n.outHeight;++w){const x=w*a-d;let T=x;for(;T<0;)T+=c;const A=Math.min(n.inHeight,u+x);for(let _=0;_<n.outWidth;++_){const E=_*l-m;let F=E;for(;F<0;)F+=p;const D=Math.min(n.inWidth,h+E);let M=Number.NEGATIVE_INFINITY,P=-1;for(let B=T;B<A;B+=c){const Y=B-x;for(let q=F;q<D;q+=p){const K=q-E,H=f.get(g,B,q,y);H>M&&(M=H,i?P=r?((g*n.inHeight+B)*n.inWidth+q)*n.inChannels+y:(B*n.inWidth+q)*n.inChannels+y:P=Y*h+K)}}o.set(P,g,w,_,y)}}return o}function Uj(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;ee(i,"avgPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);let u;if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))u=bi({inputs:{x:i},backend:s});else{const h=s.data.get(i.dataId).values,d=N.computeStrides(i.shape),m=Ql(h,i.shape,i.dtype,d,p,"avg");u=s.makeTensorInfo(p.outShape,i.dtype,m.values)}return u}const l0={kernelName:Ti,backendName:"cpu",kernelFunc:Uj};function $j(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r}=t,o=r;ee([i,r],"avgPoolBackprop");const{filterSize:a,strides:l,pad:c}=n,p=U.computePool2DInfo(o.shape,a,l,1,c),u=p.strideHeight,h=p.strideWidth,d=p.filterHeight,m=p.filterWidth,f=p.dilationHeight,g=p.dilationWidth,y=p.effectiveFilterHeight,w=p.effectiveFilterWidth,x=w-1-p.padInfo.left,T=y-1-p.padInfo.top,A=ge(o.shape,"float32"),_=1/(d*m),E=s.data.get(i.dataId).values,F=ge(i.shape,"float32",E);for(let D=0;D<p.batchSize;++D)for(let M=0;M<p.inChannels;++M)for(let P=0;P<p.inHeight;++P)for(let B=0;B<p.inWidth;++B){const Y=P-T,q=B-x;let K=0;for(let H=0;H<y;H+=f){const Q=(Y+H)/u;if(Q<0||Q>=p.outHeight||Math.floor(Q)!==Q)continue;for(let J=0;J<w;J+=g){const ie=(q+J)/h;if(ie<0||ie>=p.outWidth||Math.floor(ie)!==ie)continue;const ne=F.get(D,Q,ie,M);K+=ne}}A.set(K*_,D,P,B,M)}return s.makeTensorInfo(A.shape,A.dtype,A.values)}const c0={kernelName:Do,backendName:"cpu",kernelFunc:$j};function Wj(e){const{inputs:t,backend:s,attrs:n}=e,{x:i,scale:r,offset:o,mean:a,variance:l}=t;N.assert(a.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),N.assert(o==null||a.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),N.assert(r==null||a.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ee([i,a,l,r,o],"batchNorm");let{varianceEpsilon:c}=n;c==null&&(c=.001);const p=s.data.get(i.dataId).values,u=s.data.get(a.dataId).values,h=s.data.get(l.dataId).values,d=r?s.data.get(r.dataId).values:new Float32Array([1]),m=o?s.data.get(o.dataId).values:new Float32Array([0]),f=new Float32Array(p.length),g=m.length,y=d.length,w=h.length,x=u.length;let T=0,A=0,_=0,E=0;for(let F=0;F<p.length;++F)f[F]=m[T++]+(p[F]-u[A++])*d[_++]/Math.sqrt(h[E++]+c),T>=g&&(T=0),A>=x&&(A=0),_>=y&&(_=0),E>=w&&(E=0);return s.makeTensorInfo(i.shape,i.dtype,f)}const p0={kernelName:Ni,backendName:"cpu",kernelFunc:Wj};const zj=fe(xr,(e,t)=>{const s=t;return e>s.clipValueMax?s.clipValueMax:e<s.clipValueMin?s.clipValueMin:e}),u0={kernelName:xr,backendName:"cpu",kernelFunc:zj};function ec(e){const{inputs:t,backend:s}=e,{input:n}=t,i=s.data.get(n.dataId).complexTensorInfos.imag,r=s.data.get(i.dataId).values;return s.makeTensorInfo(i.shape,i.dtype,r)}const h0={kernelName:ep,backendName:"cpu",kernelFunc:ec};function kn(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{shape:r}=n,o=N.sizeFromShape(i.shape),a=N.inferFromImplicitShape(r,o),l=N.sizeFromShape(a);N.assert(o===l,()=>`The new shape (${a}) has ${l} elements and the old shape (${i.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),s.incRef(i.dataId);const c=s.data.get(i.dataId);if(c.complexTensorInfos!=null){const p=c.complexTensorInfos.real,u=c.complexTensorInfos.imag;p.shape=a,u.shape=a}return{dataId:i.dataId,shape:a,dtype:i.dtype}}const d0={kernelName:Ei,backendName:"cpu",kernelFunc:kn};function tc(e){const{inputs:t,backend:s,attrs:n}=e,{axis:i}=n,r=N.parseAxisParam(i,t[0].shape)[0];let o=U.computeOutShape(t.map(d=>d.shape),r);if(N.sizeFromShape(o)===0)return s.makeTensorInfo(o,t[0].dtype,[]);const a=t.filter(d=>N.sizeFromShape(d.shape)>0);if(a.length===1)return a[0];const l=a.map(d=>d.shape);if(U.assertParamsConsistent(l,r),a[0].dtype==="complex64"){const d=a.map(w=>bo({inputs:{input:w},backend:s})),m=a.map(w=>ec({inputs:{input:w},backend:s})),f=tc({inputs:d,backend:s,attrs:{axis:i}}),g=tc({inputs:m,backend:s,attrs:{axis:i}}),y=Es({inputs:{real:f,imag:g},backend:s});return d.forEach(w=>s.disposeIntermediateTensorInfo(w)),m.forEach(w=>s.disposeIntermediateTensorInfo(w)),s.disposeIntermediateTensorInfo(f),s.disposeIntermediateTensorInfo(g),y}const c=a.map(d=>{const m=N.sizeFromShape(d.shape.slice(r)),f=[-1,m];return kn({inputs:{x:d},backend:s,attrs:{shape:f}})});o=U.computeOutShape(c.map(d=>d.shape),1);const p=N.getTypedArrayFromDType(a[0].dtype,N.sizeFromShape(o));if(c[0].shape[0]===1){let d=0;c.forEach(m=>{const f=s.data.get(m.dataId).values,g=N.sizeFromShape(m.shape);p.set(f,d),d+=g})}else{let d=0;c.forEach(m=>{const f=s.data.get(m.dataId).values;let g=0;for(let y=0;y<m.shape[0];++y){const w=y*o[1]+d;for(let x=0;x<m.shape[1];++x)p[w+x]=f[g++]}d+=m.shape[1]})}const u=U.computeOutShape(a.map(d=>d.shape),r),h=s.makeTensorInfo(u,t[0].dtype,p);return c.forEach(d=>s.disposeIntermediateTensorInfo(d)),h}const m0={kernelName:Fo,backendName:"cpu",kernelFunc:tc};const Pj=fe(Qn,e=>Math.cos(e)),f0={kernelName:Qn,backendName:"cpu",kernelFunc:Pj};const Bj=fe(Lr,e=>Math.cosh(e)),g0={kernelName:Lr,backendName:"cpu",kernelFunc:Bj};const y0={kernelName:Mo,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{x:n,filter:i}=e,{strides:r,pad:o,dilations:a}=s,l=t,c=l.data.get(n.dataId).values,p=n.shape.length,u=l.data.get(i.dataId).values,h=i.shape.length,{batchSize:d,inHeight:m,inWidth:f,inChannels:g,outHeight:y,outWidth:w,padInfo:x,strideHeight:T,strideWidth:A,filterHeight:_,filterWidth:E,dilationHeight:F,dilationWidth:D,outShape:M}=U.computeDilation2DInfo(n.shape,i.shape,r,o,"NHWC",a),P=N.sizeFromShape(M),B=M.length,Y=N.getArrayFromDType(n.dtype,P);for(let K=0;K<d;++K)for(let H=0;H<y;++H){const Q=H*T-x.top;for(let J=0;J<w;++J){const ie=J*A-x.left;for(let ne=0;ne<g;++ne){let le=Number.MIN_SAFE_INTEGER;for(let oe=0;oe<_;++oe){const de=Q+oe*F;if(de>=0&&de<m)for(let Ae=0;Ae<E;++Ae){const Me=ie+Ae*D;if(Me>=0&&Me<f){const Qe=N.locToIndex([K,de,Me,ne],p,N.computeStrides(n.shape)),St=N.locToIndex([oe,Ae,ne],h,N.computeStrides(i.shape)),$t=c[Qe]+u[St];$t>le&&(le=$t)}}}const ue=N.locToIndex([K,H,J,ne],B,N.computeStrides(M));Y[ue]=le}}}const q=l.write(N.toTypedArray(Y,n.dtype),M,n.dtype);return{dataId:q,shape:M,dtype:n.dtype}}};const b0={kernelName:Ha,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{x:n,filter:i,dy:r}=e,{strides:o,pad:a,dilations:l}=s,c=t,p=N.toNestedArray(n.shape,c.data.get(n.dataId).values),u=N.toNestedArray(i.shape,c.data.get(i.dataId).values),{batchSize:h,inHeight:d,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:w,strideHeight:x,strideWidth:T,filterHeight:A,filterWidth:_,dilationHeight:E,dilationWidth:F,outShape:D}=U.computeDilation2DInfo(n.shape,i.shape,o,a,"NHWC",l);N.assert(r.rank===D.length,()=>`Error in ${Ha}, dy must have the same rank as output ${D.length}, but got ${r.rank}`);const M=N.toNestedArray(D,c.data.get(r.dataId).values),P=N.makeZerosNestedTypedArray(i.shape,i.dtype);for(let Y=0;Y<h;++Y)for(let q=0;q<g;++q){const K=q*x-w.top;for(let H=0;H<y;++H){const Q=H*T-w.left;for(let J=0;J<f;++J){let ie=Number.MIN_SAFE_INTEGER,ne=0,le=0;for(let ue=0;ue<A;++ue){const oe=K+ue*E;if(oe>=0&&oe<d)for(let de=0;de<_;++de){const Ae=Q+de*F;if(Ae>=0&&Ae<m){const Me=p[Y][oe][Ae][J]+u[ue][de][J];Me>ie&&(ie=Me,ne=ue,le=de)}}}P[ne][le][J]+=M[Y][q][H][J]}}}const B=c.write(N.toTypedArray(P,n.dtype),i.shape,i.dtype);return{dataId:B,shape:i.shape,dtype:i.dtype}}};const w0={kernelName:qa,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{x:n,filter:i,dy:r}=e,{strides:o,pad:a,dilations:l}=s,c=t,p=N.toNestedArray(n.shape,c.data.get(n.dataId).values),u=N.toNestedArray(i.shape,c.data.get(i.dataId).values),{batchSize:h,inHeight:d,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:w,strideHeight:x,strideWidth:T,filterHeight:A,filterWidth:_,dilationHeight:E,dilationWidth:F,outShape:D}=U.computeDilation2DInfo(n.shape,i.shape,o,a,"NHWC",l);N.assert(r.rank===D.length,()=>`Error in ${qa}, dy must have the same rank as output ${D.length}, but got ${r.rank}`);const M=N.toNestedArray(D,c.data.get(r.dataId).values),P=N.makeZerosNestedTypedArray(n.shape,n.dtype);for(let Y=0;Y<h;++Y)for(let q=0;q<g;++q){const K=q*x-w.top;for(let H=0;H<y;++H){const Q=H*T-w.left;for(let J=0;J<f;++J){let ie=Number.MIN_SAFE_INTEGER,ne=K<0?0:K,le=Q<0?0:Q;for(let ue=0;ue<A;++ue){const oe=K+ue*E;if(oe>=0&&oe<d)for(let de=0;de<_;++de){const Ae=Q+de*F;if(Ae>=0&&Ae<m){const Me=p[Y][oe][Ae][J]+u[ue][de][J];Me>ie&&(ie=Me,ne=oe,le=Ae)}}}P[Y][ne][le][J]+=M[Y][q][H][J]}}}const B=c.write(N.toTypedArray(P,n.dtype),n.shape,n.dtype);return{dataId:B,shape:n.shape,dtype:n.dtype}}};const jj=js((e,t)=>e/t),Vj=On(ei,jj),Du={kernelName:ei,backendName:"cpu",kernelFunc:Vj};const Gj=fe(Sr,e=>e>=0?e:Math.exp(e)-1),x0={kernelName:Sr,backendName:"cpu",kernelFunc:Gj};const qj=U.ERF_P,Hj=U.ERF_A1,Yj=U.ERF_A2,Kj=U.ERF_A3,Xj=U.ERF_A4,Jj=U.ERF_A5,Zj=fe(Ir,e=>{const t=Math.sign(e),s=Math.abs(e),n=1/(1+qj*s);return t*(1-((((Jj*n+Xj)*n+Kj)*n+Yj)*n+Hj)*n*Math.exp(-s*s))}),L0={kernelName:Ir,backendName:"cpu",kernelFunc:Zj};function Zf(e,t,s){const n=e.shape,i=n[0],r=n[1],o=s.data.get(e.dataId),a=o.complexTensorInfos.real,l=o.complexTensorInfos.imag,c=[i,r],p=N.sizeFromShape(c),u=N.getTypedArrayFromDType("float32",p),h=N.getTypedArrayFromDType("float32",p);for(let g=0;g<i;g++){const y=Kf({inputs:{x:a},backend:s,attrs:{begin:[g,0],size:[1,r]}}),w=Kf({inputs:{x:l},backend:s,attrs:{begin:[g,0],size:[1,r]}}),x=Es({inputs:{real:y,imag:w},backend:s}),{real:T,imag:A}=Qj(x,t,s),_=U.mergeRealAndImagArrays(T,A);for(let E=0;E<r;E++){const F=U.getComplexWithIndex(_,E);u[g*r+E]=F.real,h[g*r+E]=F.imag}s.disposeIntermediateTensorInfo(y),s.disposeIntermediateTensorInfo(w),s.disposeIntermediateTensorInfo(x)}const d=s.makeTensorInfo(c,"float32",u),m=s.makeTensorInfo(c,"float32",h),f=Es({inputs:{real:d,imag:m},backend:s});return s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(m),f}function Qj(e,t,s){const n=N.sizeFromShape(e.shape),i=s.data.get(e.dataId),r=s.data.get(i.complexTensorInfos.real.dataId).values,o=s.data.get(i.complexTensorInfos.imag.dataId).values;if(e3(n)){const a=dx(r,o,n,t,s),l=[e.shape[0],e.shape[1]];if(t){const c=s.makeTensorInfo(l,"float32",a.real),p=s.makeTensorInfo(l,"float32",a.imag),u=s.makeTensorInfo([],"float32",N.createScalarValue(n,"float32")),h=bi({inputs:{x:u},backend:s}),d=Du.kernelFunc({inputs:{a:c,b:u},backend:s}),m=Du.kernelFunc({inputs:{a:p,b:h},backend:s}),f=s.data.get(d.dataId).values,g=s.data.get(m.dataId).values;return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(p),s.disposeIntermediateTensorInfo(u),s.disposeIntermediateTensorInfo(h),s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(m),{real:f,imag:g}}return a}else{const a=U.mergeRealAndImagArrays(r,o),l=t3(a,n,t);return U.splitRealAndImagArrays(l)}}function e3(e){return(e&e-1)===0}function dx(e,t,s,n,i){if(s===1)return{real:e,imag:t};const r=U.mergeRealAndImagArrays(e,t),o=s/2,a=U.complexWithEvenIndex(r),l=a.real,c=a.imag,p=[l.length],u=i.makeTensorInfo(p,"float32",l),h=i.makeTensorInfo(p,"float32",c),d=Es({inputs:{real:u,imag:h},backend:i}),m=U.complexWithOddIndex(r),f=m.real,g=m.imag,y=[f.length],w=i.makeTensorInfo(y,"float32",f),x=i.makeTensorInfo(y,"float32",g),T=Es({inputs:{real:w,imag:x},backend:i}),A=dx(l,c,o,n,i),_=A.real,E=A.imag,F=[_.length],D=i.makeTensorInfo(F,"float32",_),M=i.makeTensorInfo(F,"float32",E),P=Es({inputs:{real:D,imag:M},backend:i}),B=dx(f,g,o,n,i),Y=B.real,q=B.imag,K=[Y.length],H=i.makeTensorInfo(K,"float32",Y),Q=i.makeTensorInfo(K,"float32",q),J=Es({inputs:{real:H,imag:Q},backend:i}),ie=U.exponents(s,n),ne=[ie.real.length],le=i.makeTensorInfo(ne,"float32",ie.real),ue=i.makeTensorInfo(ne,"float32",ie.imag),oe=Es({inputs:{real:le,imag:ue},backend:i}),de=ox({inputs:{a:oe,b:J},backend:i}),Ae=Qw({inputs:{a:P,b:de},backend:i}),Me=px({inputs:{a:P,b:de},backend:i}),Qe=bo({inputs:{input:Ae},backend:i}),St=bo({inputs:{input:Me},backend:i}),$t=ec({inputs:{input:Ae},backend:i}),ks=ec({inputs:{input:Me},backend:i}),bt=tc({inputs:[Qe,St],backend:i,attrs:{axis:0}}),ps=tc({inputs:[$t,ks],backend:i,attrs:{axis:0}}),Fn=i.data.get(bt.dataId).values,Gs=i.data.get(ps.dataId).values;return i.disposeIntermediateTensorInfo(u),i.disposeIntermediateTensorInfo(h),i.disposeIntermediateTensorInfo(d),i.disposeIntermediateTensorInfo(w),i.disposeIntermediateTensorInfo(x),i.disposeIntermediateTensorInfo(T),i.disposeIntermediateTensorInfo(D),i.disposeIntermediateTensorInfo(M),i.disposeIntermediateTensorInfo(P),i.disposeIntermediateTensorInfo(H),i.disposeIntermediateTensorInfo(Q),i.disposeIntermediateTensorInfo(J),i.disposeIntermediateTensorInfo(le),i.disposeIntermediateTensorInfo(ue),i.disposeIntermediateTensorInfo(oe),i.disposeIntermediateTensorInfo(de),i.disposeIntermediateTensorInfo(Ae),i.disposeIntermediateTensorInfo(Me),i.disposeIntermediateTensorInfo(Qe),i.disposeIntermediateTensorInfo($t),i.disposeIntermediateTensorInfo(St),i.disposeIntermediateTensorInfo(ks),i.disposeIntermediateTensorInfo(bt),i.disposeIntermediateTensorInfo(ps),{real:Fn,imag:Gs}}function t3(e,t,s){const n=new Float32Array(t*2);for(let i=0;i<t;i++){let r=0,o=0;for(let a=0;a<t;a++){const l=U.exponent(i*a,t,s),c=U.getComplexWithIndex(e,a);r+=c.real*l.real-c.imag*l.imag,o+=c.real*l.imag+c.imag*l.real}s&&(r/=t,o/=t),U.assignToTypedArray(n,r,o,i)}return n}function s3(e){const{inputs:t,backend:s}=e,{input:n}=t,i=N.sizeFromShape(n.shape),r=n.shape[n.shape.length-1],o=i/r,a=kn({inputs:{x:n},backend:s,attrs:{shape:[o,r]}}),l=Zf(a,!1,s),c=kn({inputs:{x:l},backend:s,attrs:{shape:n.shape}});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(l),c}const S0={kernelName:Kc,backendName:"cpu",kernelFunc:s3};const I0={kernelName:Uo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,i=s,r=N.getTypedArrayFromDType(n.dtype,N.sizeFromShape(n.shape)),[o,a,l,c]=n.shape,p=i.data.get(n.dataId).values;for(let h=0;h<o;h++){const d=h*l*a*c;for(let m=0;m<a;m++){const f=m*(l*c);for(let g=0;g<l;g++){const y=g*c;for(let w=0;w<c;w++){const x=[o,m,g,w],T=x[2],A=Math.round(l-T),_=d+f+y+w;let E=p[_];if(A>=0&&A<l){const F=A*c,D=d+f+F+w;E=p[D]}r[_]=E}}}}const u=i.write(r,n.shape,n.dtype);return{dataId:u,shape:n.shape,dtype:n.dtype}}};function n3(e){const{inputs:t,backend:s}=e,{input:n}=t,i=N.sizeFromShape(n.shape),r=n.shape[n.shape.length-1],o=i/r,a=kn({inputs:{x:n},backend:s,attrs:{shape:[o,r]}}),l=Zf(a,!0,s),c=kn({inputs:{x:l},backend:s,attrs:{shape:n.shape}});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(l),c}const v0={kernelName:Qc,backendName:"cpu",kernelFunc:n3};const i3=fe(Nr,e=>Number.isFinite(e)?1:0,"bool"),T0={kernelName:Nr,backendName:"cpu",kernelFunc:i3};const r3=fe(Cr,e=>Math.abs(e)===Infinity?1:0,"bool"),A0={kernelName:Cr,backendName:"cpu",kernelFunc:r3};const o3=fe(Rr,e=>Number.isNaN(e)?1:0,"bool"),N0={kernelName:Rr,backendName:"cpu",kernelFunc:o3};const a3=fe(Er,e=>Math.log1p(e)),C0={kernelName:Er,backendName:"cpu",kernelFunc:a3};const l3=fe(Ya,e=>e?0:1,"bool"),R0={kernelName:Ya,backendName:"cpu",kernelFunc:l3};const O0={kernelName:Ri,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{reductionIndices:i,keepDims:r}=t,o=s;let a=n.shape;const l=a.length,c=N.parseAxisParam(i,a);let p=c;const u=U.getAxesPermutation(p,l);let h=o.data.get(n.dataId).values;if(u!=null){const x=new Array(l);for(let T=0;T<x.length;T++)x[T]=a[u[T]];h=Zl(h,a,n.dtype,u,x),p=U.getInnerMostAxes(p.length,l),a=x}ee(n,"max"),U.assertAxesAreInnerMostDims("max",p,l);const[d,m]=U.computeOutAndReduceShapes(a,p),f=N.sizeFromShape(m),g=Yf(h,f,d,n.dtype),y=o.write(g,d,n.dtype);let w=d;if(r){const x=U.expandShapeToKeepDim(d,c);w=x}return{dataId:y,shape:w,dtype:n.dtype}}};function c3(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;ee(i,"maxPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);let u;if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))u=bi({inputs:{x:i},backend:s});else{const h=s.data.get(i.dataId).values,d=N.computeStrides(i.shape),m=Ql(h,i.shape,i.dtype,d,p,"max");u=s.makeTensorInfo(p.outShape,i.dtype,m.values)}return u}const E0={kernelName:Oi,backendName:"cpu",kernelFunc:c3};function p3(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r,output:o}=t,a=r;ee([r,o],"maxPoolBackprop");const{filterSize:l,strides:c,pad:p,dimRoundingMode:u}=n,h=U.computePool2DInfo(a.shape,l,c,1,p,u),d=s.data.get(a.dataId).values,m=ge(h.outShape,a.dtype,Jf(d,a.shape,a.dtype,h).values),f=h.strideHeight,g=h.strideWidth,y=h.dilationHeight,w=h.dilationWidth,x=h.effectiveFilterHeight,T=h.effectiveFilterWidth,A=T-1-h.padInfo.left,_=x-1-h.padInfo.top,E=ge(a.shape,"float32"),F=s.data.get(i.dataId).values,D=ge(i.shape,"float32",F);for(let M=0;M<h.batchSize;++M)for(let P=0;P<h.inChannels;++P)for(let B=0;B<h.inHeight;++B)for(let Y=0;Y<h.inWidth;++Y){const q=B-_,K=Y-A;let H=0;for(let Q=0;Q<x;Q+=y){const J=(q+Q)/f;if(J<0||J>=h.outHeight||Math.floor(J)!==J)continue;for(let ie=0;ie<T;ie+=w){const ne=(K+ie)/g;if(ne<0||ne>=h.outWidth||Math.floor(ne)!==ne)continue;const le=x*T-1-m.get(M,J,ne,P),ue=Q*T+ie,oe=le===ue?1:0;if(oe===0)continue;const de=D.get(M,J,ne,P);H+=de*oe}}E.set(H,M,B,Y,P)}return s.makeTensorInfo(E.shape,E.dtype,E.values)}const _0={kernelName:$o,backendName:"cpu",kernelFunc:p3};function k0(e,t,s,n,i){const r=N.computeStrides(t),o=Ql(e,t,s,r,i,"max"),a=Jf(e,t,s,i,!0,n);return[o.values,a.values]}const D0={kernelName:Wo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{filterSize:i,strides:r,pad:o,includeBatchInIndex:a}=t,l=s;ee(n,"MaxPoolWithArgmax");const c=l.data.get(n.dataId).values,p=U.computePool2DInfo(n.shape,i,r,[1,1],o),[u,h]=k0(c,n.shape,n.dtype,a,p),d=l.write(u,p.outShape,n.dtype),m=l.write(h,p.outShape,n.dtype);return[{dataId:d,shape:p.outShape,dtype:n.dtype},{dataId:m,shape:p.outShape,dtype:"int32"}]}};const u3=vt.nonMaxSuppressionV4Impl,F0={kernelName:zo,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,padToMaxOutputSize:l}=s,c=t;ee(n,"NonMaxSuppressionPadded");const p=c.data.get(n.dataId).values,u=c.data.get(i.dataId).values,{selectedIndices:h,validOutputs:d}=u3(p,u,r,o,a,l);return[h,d]}};const h3=vt.nonMaxSuppressionV5Impl,M0={kernelName:Po,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}=s,c=t;ee(n,"NonMaxSuppressionWithScore");const p=c.data.get(n.dataId).values,u=c.data.get(i.dataId).values,h=r,d=o,m=a,f=l,{selectedIndices:g,selectedScores:y}=h3(p,u,h,d,m,f);return[g,y]}};const d3=js((e,t)=>e!==t?1:0),m3=On(Ka,d3,null,"bool"),U0={kernelName:Ka,backendName:"cpu",kernelFunc:m3};function f3(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{paddings:r,constantValue:o}=n;ee(i,"pad");const a=r.map((w,x)=>w[0]+i.shape[x]+w[1]),l=r.map(w=>w[0]),c=s.data.get(i.dataId).values,p=N.sizeFromShape(i.shape),u=i.shape.length,h=N.computeStrides(i.shape),d=N.sizeFromShape(a),m=a.length,f=N.computeStrides(a),g=N.getTypedArrayFromDType(i.dtype,d);o!==0&&g.fill(o);for(let w=0;w<p;w++){const x=N.indexToLoc(w,u,h),T=x.map((_,E)=>_+l[E]),A=N.locToIndex(T,m,f);g[A]=c[w]}const y=s.write(g,a,i.dtype);return{dataId:y,shape:a,dtype:i.dtype}}const Qf={kernelName:Bo,backendName:"cpu",kernelFunc:f3};const g3=fe(kr,e=>1/e),$0={kernelName:kr,backendName:"cpu",kernelFunc:g3};const W0={kernelName:Ho,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,{radians:i,fillValue:r,center:o}=t,a=s,l=N.getTypedArrayFromDType(n.dtype,N.sizeFromShape(n.shape)),[c,p,u,h]=n.shape,[d,m]=U.getImageCenter(o,p,u),f=255,g=Math.sin(i),y=Math.cos(i),w=a.data.get(n.dataId).values;for(let T=0;T<c;T++){const A=T*u*p*h;for(let _=0;_<p;_++){const E=_*(u*h);for(let F=0;F<u;F++){const D=F*h;for(let M=0;M<h;M++){const P=[c,_,F,M],B=P[2],Y=P[1];let q=(B-d)*y-(Y-m)*g,K=(B-d)*g+(Y-m)*y;q=Math.round(q+d),K=Math.round(K+m);let H=r;if(typeof r!="number"&&(M===3?H=f:H=r[M]),q>=0&&q<u&&K>=0&&K<p){const J=K*(u*h),ie=q*h,ne=A+J+ie+M;H=w[ne]}const Q=A+E+D+M;l[Q]=H}}}}const x=a.write(l,n.shape,n.dtype);return{dataId:x,shape:n.shape,dtype:n.dtype}}};const y3=fe(Dr,e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2===0?t:t+1}),z0={kernelName:Dr,backendName:"cpu",kernelFunc:y3};const b3=U.SELU_SCALEALPHA,w3=U.SELU_SCALE,x3=fe(Mr,e=>e>=0?w3*e:b3*(Math.exp(e)-1)),P0={kernelName:Mr,backendName:"cpu",kernelFunc:x3};const L3=fe(Wr,e=>1/(1+Math.exp(-e))),B0={kernelName:Wr,backendName:"cpu",kernelFunc:L3};const S3=fe($r,e=>e<0?-1:e>0?1:0),j0={kernelName:$r,backendName:"cpu",kernelFunc:S3};const I3=fe(ti,e=>Math.sin(e)),V0={kernelName:ti,backendName:"cpu",kernelFunc:I3};const v3=fe(Ur,e=>Math.sinh(e)),G0={kernelName:Ur,backendName:"cpu",kernelFunc:v3};const T3=11920928955078125e-23,q0=Math.log(T3)+2,A3=fe(zr,e=>{const t=e>-q0,s=e<q0,n=Math.exp(e);let i;return s?i=n:t?i=e:i=Math.log(1+n),i}),H0={kernelName:zr,backendName:"cpu",kernelFunc:A3};function mx(e){const{inputs:t,attrs:s,backend:n}=e,{x:i}=t,{perm:r}=s;ee(i,"transpose");const o=i.shape.length,a=new Array(o);for(let u=0;u<a.length;u++)a[u]=i.shape[r[u]];const l=n.data.get(i.dataId).values,c=Zl(l,i.shape,i.dtype,r,a),p=n.write(c,a,i.dtype);return{dataId:p,shape:a,dtype:i.dtype}}const Y0={kernelName:_i,backendName:"cpu",kernelFunc:mx};function N3(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{blockShape:r,paddings:o}=n;ee([i],"spaceToBatchND");const a=N.sizeFromShape(r),l=[[0,0]];l.push(...o);for(let _=1+r.length;_<i.shape.length;++_)l.push([0,0]);const c=Qf.kernelFunc({inputs:{x:i},backend:s,attrs:{paddings:l,constantValue:0}}),p=U.getReshaped(c.shape,r,a,!1),u=U.getPermuted(p.length,r.length,!1),h=U.getReshapedPermuted(c.shape,r,a,!1),d={x:c},m={shape:p},f=kn({inputs:d,backend:s,attrs:m}),g={x:f},y={perm:u},w=mx({inputs:g,backend:s,attrs:y}),x={x:w},T={shape:h},A=kn({inputs:x,backend:s,attrs:T});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(f),s.disposeIntermediateTensorInfo(w),A}const K0={kernelName:Vo,backendName:"cpu",kernelFunc:N3};const C3=fe(Pr,e=>Math.sqrt(e)),X0={kernelName:Pr,backendName:"cpu",kernelFunc:C3};const J0={kernelName:Go,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:s}=e,n=t;ee(s,"square");const i=n.data.get(s.dataId).values,r=new Float32Array(i.length);for(let a=0;a<i.length;++a){const l=i[a];r[a]=l*l}const o=n.write(r,s.shape,s.dtype);return{dataId:o,shape:s.shape,dtype:s.dtype}}};const R3=js((e,t)=>{const s=e-t;return s*s}),O3=On(si,R3),Z0={kernelName:si,backendName:"cpu",kernelFunc:O3};const E3=fe(Vr,(e,t)=>{const s=t;return isNaN(e)?NaN:e>0?1:s.alpha}),Q0={kernelName:Vr,backendName:"cpu",kernelFunc:E3};const _3=fe(ni,e=>Math.tan(e)),eR={kernelName:ni,backendName:"cpu",kernelFunc:_3};const k3=fe(jr,e=>Math.tanh(e)),tR={kernelName:jr,backendName:"cpu",kernelFunc:k3};function D3(e){const{inputs:t,attrs:s,backend:n}=e,{axis:i}=s,{x:r}=t;ee(r,"unique");const o=n.data.get(r.dataId).values,{outputValues:a,outputShape:l,indices:c}=Xf(o,i,r.shape,r.dtype);return[n.makeTensorInfo(l,r.dtype,a),n.makeTensorInfo([c.length],"int32",c)]}const sR={kernelName:qo,backendName:"cpu",kernelFunc:D3};const F3=[PC,s0,n0,qC,i0,r0,o0,a0,l0,c0,p0,GC,HC,u0,BC,m0,f0,g0,y0,w0,b0,Du,x0,L0,YC,KC,S0,I0,XC,jC,v0,h0,T0,A0,N0,JC,C0,R0,E0,_0,D0,O0,ZC,F0,M0,U0,Qf,VC,$0,d0,W0,z0,QC,P0,B0,j0,V0,G0,e0,H0,K0,X0,J0,Z0,Q0,t0,eR,tR,Y0,sR];for(const e of F3)Za(e);const va={},fx={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function gx(e,t){va[e]=t}function on(e){if(!(e in va)){const s=M3(e);if(s!==null)va[e]=s;else return console.log("Could not get context for WebGL version",e),null}const t=va[e];return t.isContextLost()?(delete va[e],on(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),va[e])}function U3(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function M3(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=U3(e);return t.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete va[e]},!1),e===1?t.getContext("webgl",fx)||t.getContext("experimental-webgl",fx):t.getContext("webgl2",fx)}var wo;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(wo||(wo={}));var is;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(is||(is={}));var Xt;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Xt||(Xt={}));function Ta(e,t){return[t,e]}function nR(e,t){return e*t}function xo(e){const t=N.sizeFromShape(e),s=Math.ceil(t/4);return N.sizeToSquarishShape(s)}function wi(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function iR(e,t){const[s,n]=wi(e,t);return s*n*4}function Fu(e,t){const s=e;let n,i,r,o,a,l,c,p,u,h;return W().getNumber("WEBGL_VERSION")===2?(n=s.R32F,i=s.R16F,r=s.RGBA16F,o=s.RGBA32F,a=s.RED,c=4,p=1,u=s.HALF_FLOAT,h=s.FLOAT):(n=e.RGBA,i=e.RGBA,r=e.RGBA,o=s.RGBA,a=e.RGBA,c=4,p=4,u=t!=null?t.HALF_FLOAT_OES:null,h=e.FLOAT),l=e.RGBA,{internalFormatFloat:n,internalFormatHalfFloat:i,internalFormatPackedHalfFloat:r,internalFormatPackedFloat:o,textureFormatFloat:a,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:p,textureTypeHalfFloat:u,textureTypeFloat:h}}function pe(e,t){const s=t();return W().getBool("DEBUG")&&$3(e),s}function $3(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+W3(e,t))}const z3=596e-10,P3=65504;function rR(e){return!!(W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||z3<Math.abs(e)&&Math.abs(e)<P3)}function W3(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function Mu(e,t){return Ji(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function oR(e,t){const s=Ji(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(pe(e,()=>e.shaderSource(s,t)),pe(e,()=>e.compileShader(s)),e.getShaderParameter(s,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(s)),new Error("Failed to compile vertex shader.");return s}function aR(e,t){const s=Ji(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(pe(e,()=>e.shaderSource(s,t)),pe(e,()=>e.compileShader(s)),e.getShaderParameter(s,e.COMPILE_STATUS)===!1)throw B3(t,e.getShaderInfoLog(s)),new Error("Failed to compile fragment shader.");return s}const j3=/ERROR: [0-9]+:([0-9]+):/g;function B3(e,t){const s=j3.exec(t);if(s==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}const n=+s[1],i=e.split(`
`),r=i.length.toString().length+2,o=i.map((u,h)=>N.rightPad((h+1).toString(),r)+u);let a=0;for(let u=0;u<o.length;u++)a=Math.max(o[u].length,a);const l=o.slice(0,n-1),c=o.slice(n-1,n),p=o.slice(n);console.log(l.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${N.rightPad(c[0],a)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join(`
`))}function lR(e){return Ji(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function cR(e,t){if(pe(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function eg(e,t){if(pe(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function pR(e,t){const s=Ji(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),pe(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),s}function uR(e,t){const s=Ji(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return pe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,s)),pe(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),s}function hR(e){return Ji(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function dR(e,t){const s=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const n=`[${e}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(e>s||t>s){const n=`[${e}x${t}]`,i=`[${s}x${s}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+i+".")}}function mR(e){return Ji(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function yx(e,t,s,n,i,r,o){const a=e.getAttribLocation(t,s);return a===-1?!1:(pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),pe(e,()=>e.vertexAttribPointer(a,i,e.FLOAT,!1,r,o)),pe(e,()=>e.enableVertexAttribArray(a)),!0)}function G3(e,t,s){V3(e,s),pe(e,()=>e.activeTexture(e.TEXTURE0+s)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function fR(e,t,s){return Ji(e,()=>e.getUniformLocation(t,s),'uniform "'+s+'" not present in program.')}function gR(e,t,s){return e.getUniformLocation(t,s)}function yR(e,t,s,n){pe(e,()=>G3(e,t,n)),pe(e,()=>e.uniform1i(s,n))}function tg(e,t,s){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,s)),pe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function bx(e,t){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),pe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Uu(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+q3(e,t))}function q3(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function Ji(e,t,s){const n=pe(e,()=>t());if(n==null)throw new Error(s);return n}function V3(e,t){const s=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(n<e.TEXTURE0||n>s){const i=`[gl.TEXTURE0, gl.TEXTURE${s}]`;throw new Error(`textureUnit must be in ${i}.`)}}function Lo(e,t=2){return N.sizeFromShape(e.slice(0,e.length-t))}function So(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function sg(e){let t=[1,1,1];const s=e.length===0||e.length===1&&e[0]===1;return s||(t=[Lo(e),...So(e)]),t}function bR(e,t=!1){let s=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(s=s*2,e=e.map((i,r)=>r>=e.length-2?N.nearestLargerEven(e[r]):e[r]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=N.squeezeShape(e);e=i.newShape}let n=N.sizeFromShape(e);if(e.length<=1&&n<=s)return[1,n];if(e.length===2&&e[0]<=s&&e[1]<=s)return e;if(e.length===3&&e[0]*e[1]<=s&&e[2]<=s)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=s&&e[1]*e[2]<=s)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=s&&e[3]<=s)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=s&&e[1]*e[2]*e[3]<=s)return[e[0],e[1]*e[2]*e[3]];if(t){const i=Lo(e);let r=2,o=2;return e.length&&([r,o]=So(e)),n=i*(r/2)*(o/2),N.sizeToSquarishShape(n).map(a=>a*2)}return N.sizeToSquarishShape(n)}function ng(e){return e%2===0}function sc(e,t){if(e=e.slice(-2),t=t.slice(-2),N.arraysEqual(e,t))return!0;if(!e.length||!t.length)return!0;if(e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){const s=e.slice(-1)[0],n=t.slice(-1)[0];if(s===n)return!0;if(ng(s)&&ng(n)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&ng(e[0])&&ng(t[0])}let wx,xx;function wR(e){if(wx==null){const t=on(e);wx=t.getParameter(t.MAX_TEXTURE_SIZE)}return wx}function xR(e){if(xx==null){const t=on(e);xx=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,xx)}function LR(e){if(e===0)return 0;let t;const s=on(e);return an(s,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:an(s,"EXT_disjoint_timer_query")?t=1:t=0,t}function an(e,t){const s=e.getExtension(t);return s!=null}function Lx(e){try{const t=on(e);if(t!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function SR(e){if(e===0)return!1;const t=on(e);if(e===1){if(!an(t,"OES_texture_float"))return!1}else if(!an(t,"EXT_color_buffer_float"))return!1;const s=Sx(t);return s}function IR(e){if(e===0)return!1;const t=on(e);if(e===1){if(!an(t,"OES_texture_float"))return!1;if(!an(t,"WEBGL_color_buffer_float"))return!1}else{if(an(t,"EXT_color_buffer_float"))return Sx(t);const n="EXT_color_buffer_half_float";if(an(t,n)){const i=t.getExtension(n);return H3(t,i)}return!1}const s=Sx(t);return s}function Sx(e){const t=Fu(e),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const n=1,i=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,n,i,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(r),o}function H3(e,t){const s=Fu(e,t),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);const i=1,r=1;e.texImage2D(e.TEXTURE_2D,0,s.internalFormatHalfFloat,i,r,0,s.textureFormatFloat,s.textureTypeHalfFloat,null);const o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(o),a}function vR(e){if(e!==2)return!1;const t=on(e),s=t.fenceSync!=null;return s}function xi(e,t){Array.isArray(e)||(e=[e]),e.forEach(s=>{s!=null&&N.assert(s.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const ve=W();ve.registerFlag("HAS_WEBGL",()=>ve.getNumber("WEBGL_VERSION")>0);ve.registerFlag("WEBGL_VERSION",()=>Lx(2)?2:Lx(1)?1:0);ve.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);ve.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>ve.get("WEBGL_VERSION")===2);ve.registerFlag("WEBGL_CPU_FORWARD",()=>!0);ve.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);ve.registerFlag("WEBGL_PACK",()=>ve.getBool("HAS_WEBGL"));ve.registerFlag("WEBGL_PACK_NORMALIZATION",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_CLIP",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1);ve.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_REDUCE",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_LAZILY_UNPACK",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_CONV_IM2COL",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>wR(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>xR(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=ve.getNumber("WEBGL_VERSION");return e===0?0:LR(e)});ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>ve.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!rl.isMobile());ve.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>SR(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>ve.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:ve.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));ve.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>IR(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_FENCE_API_ENABLED",()=>vR(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>{const e=ve.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return e?4:0});ve.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)});const{simpleAbsImpl:TR,addImpl:AR,ceilImpl:NR,expImpl:CR,expm1Impl:RR,floorImpl:OR,logImpl:ER,maxImpl:_R,multiplyImpl:kR,rsqrtImpl:DR,sliceImpl:FR,subImpl:MR,transposeImpl:ig,uniqueImpl:UR}=ux;class $R{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((i,r)=>`T${r}`);const s=[];this.variableNames.forEach(i=>{s.push(`float v${i} = get${i}AtOutCoords();`)});const n=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${s.join(`
`)}
float result = ${n};
setOutput(result);
}
`}}class WR{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((i,r)=>`T${r}`);const s=[];this.variableNames.forEach(i=>{s.push(`vec4 v${i} = get${i}AtOutCoords();`)});const n=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${s.join(`
`)}
vec4 result = ${n};
setOutput(result);
}
`}}class zR{constructor(e,t,s){this.variableNames=["A"];const{windowSize:n,batchSize:i,outSize:r}=e;s||this.variableNames.push("bestIndicesA"),this.outputShape=[i,r];const o=t==="max"?">":"<",a=s?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${n}; i++) {
int inIdx = ${a};
float candidate = getA(batch, inIdx);
if (candidate ${o} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}}function Ix(e,t){return["x","y","z","w","u","v"].slice(0,t).map(s=>`${e}.${s}`)}function _t(e,t){return t===1?[e]:Ix(e,t)}function PR(e,t){if(e===1)return"rc";let s="";for(let n=0;n<e;n++)s+=t[n],n<e-1&&(s+=",");return s}function ct(){let e,t,s,n,i,r,o,a,l,c;return W().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",s="out",n="in",i="texture",r="outputColor",o="out vec4 outputColor;",a=`
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`,l="",c=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`):(e="",t="attribute",s="varying",n="varying",i="texture2D",r="gl_FragColor",o="",a=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`,l=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,c=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`),{version:e,attribute:t,varyingVs:s,varyingFs:n,texture2D:i,output:r,defineOutput:o,defineSpecialNaN:a,defineSpecialInf:l,defineRound:c}}function Hn(e,t,s="index"){const n=N.computeStrides(t);return n.map((i,r)=>{const o=`int ${e[r]} = ${s} / ${i}`,a=r===n.length-1?`int ${e[r+1]} = ${s} - ${e[r]} * ${i}`:`index -= ${e[r]} * ${i}`;return`${o}; ${a};`}).join("")}function nc(e){const t=N.computeStrides(e).map(s=>s.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}const rg=`
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
`;const{getBroadcastDims:BR}=U;function jR(e,t,s,n){const i=[];e.forEach(m=>{const f=N.sizeFromShape(m.shapeInfo.logicalShape);m.shapeInfo.isUniform?i.push(`uniform float ${m.name}${f>1?`[${f}]`:""};`):(i.push(`uniform sampler2D ${m.name};`),i.push(`uniform int offset${m.name};`))});const r=i.join(`
`),o=e.map(m=>Y3(m,t,n)).join(`
`),a=t.texShape,l=ct(),c=J3(l);let p,u,h=eV(l);t.isPacked?(p=K3(t.logicalShape,a),u=Q3(l)):(p=X3(t.logicalShape,a),u=Z3(l)),n&&(h+=tV);const d=[h,c,u,r,p,o,s].join(`
`);return d}function ic(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return sV(e);case 1:return nV(e);case 2:return iV(e);case 3:return rV(e);case 4:return oV(e);case 5:return aV(e);case 6:return lV(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function VR(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return cV(e);case 1:return pV(e);case 2:return uV(e);case 3:return hV(e);default:return dV(e)}}function Y3(e,t,s=!1){let n="";s?n+=VR(e):n+=ic(e);const i=e.shapeInfo.logicalShape,r=t.logicalShape;return i.length<=r.length&&(s?n+=mV(e,t):n+=fV(e,t)),n}function K3(e,t){switch(e.length){case 0:return GR();case 1:return gV(e,t);case 2:return wV(e,t);case 3:return yV(e,t);default:return bV(e,t)}}function X3(e,t){switch(e.length){case 0:return GR();case 1:return xV(e,t);case 2:return TV(e,t);case 3:return LV(e,t);case 4:return SV(e,t);case 5:return IV(e,t);case 6:return vV(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function J3(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function Z3(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function Q3(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function eV(e){const t=`${e.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
${AV}
${NV}
${CV}
`;return t}const AV=`
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,NV=`
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,CV=`
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,tV=`
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
`;function GR(){return`
int getOutputCoords() {
return 0;
}
`}function gV(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return s[0]===1?`
int getOutputCoords() {
return 2 * int(resultUV.x * ${s[1]}.0);
}
`:s[1]===1?`
int getOutputCoords() {
return 2 * int(resultUV.y * ${s[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);
}
`}function xV(e,t){return t[0]===1?`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
`}function yV(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[2]/2),i=n*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec3(b, r, c);
}
`}function LV(e,t){const s=Hn(["r","c","d"],e);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
return ivec3(r, c, d);
}
`}function bV(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[e.length-1]/2),i=n*Math.ceil(e[e.length-2]/2);let r=i,o="",a="b, r, c";for(let l=2;l<e.length-1;l++)r*=e[e.length-l-1],o=`
int b${l} = index / ${r};
index -= b${l} * ${r};
`+o,a=`b${l}, `+a;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
${o}
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec${e.length}(${a});
}
`}function SV(e,t){const s=Hn(["r","c","d","d2"],e);return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
return ivec4(r, c, d, d2);
}
`}function IV(e,t){const s=Hn(["r","c","d","d2","d3"],e);return`
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function vV(e,t){const s=Hn(["r","c","d","d2","d3","d4"],e);return`
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${s}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function wV(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(N.arraysEqual(e,t))return`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));
}
`;const n=Math.ceil(e[1]/2);return`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec2(r, c);
}
`}function TV(e,t){return N.arraysEqual(e,t)?`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
`:e[1]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
`:e[0]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
}
`}function Aa(e){return`offset${e}`}function cV(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1),n=ct();return`
vec4 ${s}() {
return ${n.texture2D}(${t}, halfCR);
}
`}function sV(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${s}() {return ${t};}`;const[n,i]=e.shapeInfo.texShape;if(n===1&&i===1)return`
float ${s}() {
return sampleTexture(${t}, halfCR);
}
`;const[r,o]=e.shapeInfo.texShape,a=Aa(t);return`
float ${s}() {
vec2 uv = uvFromFlat(${r}, ${o}, ${a});
return sampleTexture(${t}, uv);
}
`}function pV(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e.shapeInfo.texShape,i=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],r=ct();return`
vec4 ${s}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${r.texture2D}(${t}, uv);
}
`}function nV(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${s}(int index) {
${rc(e)}
}
`;const n=e.shapeInfo.texShape,i=n[0],r=n[1];if(r===1&&i===1)return`
float ${s}(int index) {
return sampleTexture(${t}, halfCR);
}
`;const o=Aa(t);return r===1?`
float ${s}(int index) {
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${i}.0);
return sampleTexture(${t}, uv);
}
`:i===1?`
float ${s}(int index) {
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${r}.0, 0.5);
return sampleTexture(${t}, uv);
}
`:`
float ${s}(int index) {
vec2 uv = uvFromFlat(${i}, ${r}, index + ${o});
return sampleTexture(${t}, uv);
}
`}function uV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape,r=i[0],o=i[1],a=ct();if(i!=null&&N.arraysEqual(t,i))return`
vec4 ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${r}.0);
return ${a.texture2D}(${s}, uv);
}
`;const l=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],c=Math.ceil(t[1]/2);return`
vec4 ${n}(int row, int col) {
vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);
return ${a.texture2D}(${s}, uv);
}
`}function iV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape;if(i!=null&&N.arraysEqual(t,i)){const u=i[0],h=i[1];return`
float ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`}const{newShape:r,keptDims:o}=N.squeezeShape(t),a=r;if(a.length<t.length){const u=oc(e,a),h=["row","col"];return`
${ic(u)}
float ${n}(int row, int col) {
return ${n}(${ac(h,o)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${rc(e)}
}
`;const l=i[0],c=i[1],p=Aa(s);return c===1?`
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
return sampleTexture(${s}, uv);
}
`:l===1?`
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
return sampleTexture(${s}, uv);
}
`:`
float ${n}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${t[1]} + col + ${p};
vec2 uv = uvFromFlat(${l}, ${c}, index);
return sampleTexture(${s}, uv);
}
`}function hV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape,r=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const u=t.slice(1),h=[1,2],d=oc(e,u),m=["b","row","col"];return`
${VR(d)}
vec4 ${n}(int b, int row, int col) {
return ${n}(${ac(m,h)});
}
`}const o=r[0],a=r[1],l=Math.ceil(t[2]/2),c=l*Math.ceil(t[1]/2),p=ct();return`
vec4 ${n}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${o}, ${a}, ${c}, ${l}, b, row, col);
return ${p.texture2D}(${s}, uv);
}
`}function rV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[1]*t[2],r=t[2],{newShape:o,keptDims:a}=N.squeezeShape(t),l=o;if(l.length<t.length){const m=oc(e,l),f=["row","col","depth"];return`
${ic(m)}
float ${n}(int row, int col, int depth) {
return ${n}(${ac(f,a)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${i}, ${r}, 1)));
${rc(e)}
}
`;const c=e.shapeInfo.texShape,p=c[0],u=c[1],h=e.shapeInfo.flatOffset;if(u===i&&h==null)return`
float ${n}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${r}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${u}.0, ${p}.0);
return sampleTexture(${s}, uv);
}
`;if(u===r&&h==null)return`
float ${n}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}.0, ${p}.0);
return sampleTexture(${s}, uv);
}
`;const d=Aa(s);return`
float ${n}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${r} + depth + ${d};
vec2 uv = uvFromFlat(${p}, ${u}, index);
return sampleTexture(${s}, uv);
}
`}function dV(e){const t=e.shapeInfo.logicalShape,s=t.length,n=e.name,i="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=o[0],l=o[1],c=Math.ceil(t[s-1]/2);let p=c*Math.ceil(t[s-2]/2),u="int b, int row, int col",h=`b * ${p} + (row / 2) * ${c} + (col / 2)`;for(let m=2;m<s-1;m++)u=`int b${m}, `+u,p*=t[s-m-1],h=`b${m} * ${p} + `+h;const d=ct();return`
vec4 ${i}(${u}) {
int index = ${h};
int texR = index / ${l};
int texC = index - texR * ${l};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${a});
return ${d.texture2D}(${n}, uv);
}
`}function oV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[3],r=t[2]*i,o=t[1]*r,{newShape:a,keptDims:l}=N.squeezeShape(t);if(a.length<t.length){const m=oc(e,a),f=["row","col","depth","depth2"];return`
${ic(m)}
float ${n}(int row, int col, int depth, int depth2) {
return ${n}(${ac(f,l)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${o}, ${r}, ${i}, 1)));
${rc(e)}
}
`;const c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,u=p[0],h=p[1];if(h===o&&c==null)return`
float ${n}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${r}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`;if(h===i&&c==null)return`
float ${n}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${t[1]*t[2]}, ${t[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`;const d=Aa(s);return`
float ${n}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${o} + col * ${r} +
depth * ${i} + depth2;
vec2 uv = uvFromFlat(${u}, ${h}, index + ${d});
return sampleTexture(${s}, uv);
}
`}function aV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[4],r=t[3]*i,o=t[2]*r,a=t[1]*o,{newShape:l,keptDims:c}=N.squeezeShape(t);if(l.length<t.length){const f=oc(e,l),g=["row","col","depth","depth2","depth3"];return`
${ic(f)}
float ${n}(int row, int col, int depth, int depth2, int depth3) {
return ${n}(${ac(g,c)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${a}, ${o}, ${r}, ${i})) +
depth3;
${rc(e)}
}
`;const p=e.shapeInfo.flatOffset,u=e.shapeInfo.texShape,h=u[0],d=u[1];if(d===a&&p==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${o}, ${r}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${h}.0);
return sampleTexture(${s}, uv);
}
`;if(d===i&&p==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${h}.0);
return sampleTexture(${s}, uv);
}
`;const m=Aa(s);return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} + depth * ${r} +
depth2 * ${i} + depth3 + ${m};
vec2 uv = uvFromFlat(${h}, ${d}, index);
return sampleTexture(${s}, uv);
}
`}function lV(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),{newShape:i,keptDims:r}=N.squeezeShape(t);if(i.length<t.length){const g=oc(e,i),y=["row","col","depth","depth2","depth3","depth4"];return`
${ic(g)}
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${n}(${ac(y,r)});
}
`}const o=t[5],a=t[4]*o,l=t[3]*a,c=t[2]*l,p=t[1]*c;if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${p}, ${c}, ${l}, ${a})) +
dot(
vec2(depth3, depth4),
vec2(${o}, 1)));
${rc(e)}
}
`;const u=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],m=h[1];if(m===p&&u==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${c}, ${l}, ${a}, ${o})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${m}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;if(m===o&&u==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${m}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;const f=Aa(s);return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${p} + col * ${c} + depth * ${l} +
depth2 * ${a} + depth3 * ${o} + depth4 + ${f};
vec2 uv = uvFromFlat(${d}, ${m}, index);
return sampleTexture(${s}, uv);
}
`}function rc(e){const t=e.name,s=N.sizeFromShape(e.shapeInfo.logicalShape);return s<2?`return ${t};`:`
for (int i = 0; i < ${s}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function mV(e,t){const s=e.name,n=s.charAt(0).toUpperCase()+s.slice(1),i="get"+n+"AtOutCoords",r=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,a=BR(e.shapeInfo.logicalShape,t.logicalShape),l=Re(o),c=o-r;let p;const u=["x","y","z","w","u","v"];r===0?p="":o<2&&a.length>=1?p="coords = 0;":p=a.map(w=>`coords.${u[w+c]} = 0;`).join(`
`);let h="";o<2&&r>0?h="coords":h=e.shapeInfo.logicalShape.map((w,x)=>`coords.${u[x+c]}`).join(", ");let d="return outputValue;";const m=N.sizeFromShape(e.shapeInfo.logicalShape),f=m===1,g=N.sizeFromShape(t.logicalShape),y=g===1;if(r===1&&!f&&!y)d=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(f&&!y)o===1?d=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:d=`
return vec4(outputValue.x);
`;else if(a.length){const w=r-2,x=r-1;a.indexOf(w)>-1&&a.indexOf(x)>-1?d="return vec4(outputValue.x);":a.indexOf(w)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(x)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${i}() {
${l} coords = getOutputCoords();
${p}
vec4 outputValue = get${n}(${h});
${d}
}
`}function fV(e,t){const s=e.name,n=s.charAt(0).toUpperCase()+s.slice(1),i="get"+n+"AtOutCoords",r=t.texShape,o=e.shapeInfo.texShape,a=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&a===l&&e.shapeInfo.flatOffset==null&&N.arraysEqual(o,r))return`
float ${i}() {
return sampleTexture(${s}, resultUV);
}
`;const c=Re(l),p=BR(e.shapeInfo.logicalShape,t.logicalShape),u=l-a;let h;const d=["x","y","z","w","u","v"];a===0?h="":l<2&&p.length>=1?h="coords = 0;":h=p.map(f=>`coords.${d[f+u]} = 0;`).join(`
`);let m="";return l<2&&a>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${d[g+u]}`).join(", "),`
float ${i}() {
${c} coords = getOutputCoords();
${h}
return get${n}(${m});
}
`}function Re(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function oc(e,t){const s=JSON.parse(JSON.stringify(e));return s.shapeInfo.logicalShape=t,s}function ac(e,t){return t.map(s=>e[s]).join(", ")}class qR{constructor(e,t,s,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,N.assert(e.length>2,()=>`Packed arg${s.charAt(0).toUpperCase()+s.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],r=Math.ceil(i/t);this.outputShape=e.slice(0,-1),r>1&&this.outputShape.push(r),n||this.variableNames.push("bestIndicesA");const o=this.outputShape,a=o.length,l=Re(a),c=_t("coords",a);let p,u;if(r===1){u=a+1;const E=Re(u);p=`
${E} sourceLocR = ${E}(${c.join()}, 0);
++${c[a-1]};
${E} sourceLocG = ${E}(${c.join()}, 0);
++${c[a-2]};
${E} sourceLocA = ${E}(${c.join()}, 0);
--${c[a-1]};
${E} sourceLocB = ${E}(${c.join()}, 0);
--${c[a-2]};`}else u=a,p=`
${l} sourceLocR = coords;
++${c[a-1]};
${l} sourceLocG = coords;
++${c[a-2]};
${l} sourceLocA = coords;
--${c[a-1]};
${l} sourceLocB = coords;
--${c[a-2]};`;const h=["x","y","z","w","u","v"].slice(0,u),d="."+h[u-1],m=h.map(E=>"int "+E),f=_t("sourceLocR",u-1).concat("inIdx.r"),g=_t("sourceLocG",u-1).concat("inIdx.g"),y=_t("sourceLocB",u-1).concat("inIdx.b"),w=_t("sourceLocA",u-1).concat("inIdx.a"),x=s==="max"?"greaterThan":"lessThan",T=n?"":`
inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${y.join()}),
getBestIndicesAChannel(${w.join()})));`,A=`vec4(
getAChannel(${f.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${y.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,_=n?"":`
float getBestIndicesAChannel(${m.join()}) {
return getChannel(getBestIndicesA(${h.join()}),
vec2(${h.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${m.join()}) {
return getChannel(getA(${h.join()}),
vec2(${h.slice(-2).join()}));
}
${_}
void main() {
${l} coords = getOutputCoords();
bool hasNextCol = ${c[a-1]} < ${o[a-1]-1};
bool hasNextRow = ${c[a-2]} < ${o[a-2]-1};
${p}
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
sourceLocB${d}, sourceLocA${d}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${A};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${T}
vec4 candidate = ${A};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`}}class HR{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=e.dilationHeight,o=e.dilationWidth,a=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=a-1-e.padInfo.top,p=l-1-e.padInfo.left,u=1/(t*s);this.userCode=`
const ivec2 pads = ivec2(${c}, ${p});
const float avgMultiplier = float(${u});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${a};
wR += ${r}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${l};
wC+= ${o}) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`}}class YR{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,n=e.filterWidth,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterDepth,u=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=p-1-e.padInfo.front,m=u-1-e.padInfo.top,f=h-1-e.padInfo.left,g=1/(t*s*n);this.userCode=`
const ivec3 pads = ivec3(${d}, ${m}, ${f});
const float avgMultiplier = float(${g});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${p};
wD += ${a}) {
float dyD = float(dyDCorner + wD) / ${i}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${u};
wR += ${l}) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${h};
wC += ${c}) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`}}const vx={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class Tx{constructor(e,t,s){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=U.assertAndGetBroadcastShape(t,s),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}}const KR=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,og="return a + b;",ag="return a - b;",Ax="return a * b;",XR=`
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
`,JR=`
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
`,ZR="return float(a == b);",QR="return float(a != b);",e2="return float(a < b);",t2="return float(a <= b);",s2="return float(a > b);",n2="return float(a >= b);",i2="return float(a >= 1.0 && b >= 1.0);",r2="return float(a >= 1.0 || b >= 1.0);",o2=KR+`
return max(a, b);
`,a2=KR+`
return min(a, b);
`,l2=`if (b == 0.0) return NAN;
return mod(a, b);`,c2="return (b >= 1.0) ? a : a * (b + 1.0);",Nx="return (a < 0.) ? b * a : a;";class kt{constructor(e,t,s){this.variableNames=["A","B"],this.outputShape=U.assertAndGetBroadcastShape(t,s),this.userCode=`
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}}const lg=`
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`,p2=`
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
`,u2=`
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
`+lg+`
return result;
`,Cx=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,h2=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,d2=`
return vec4(equal(a, b));
`,m2=`
return vec4(notEqual(a, b));
`,f2=`
return vec4(lessThan(a, b));
`,g2=`
return vec4(lessThanEqual(a, b));
`,y2=`
return vec4(greaterThan(a, b));
`,b2=`
return vec4(greaterThanEqual(a, b));
`,w2=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,x2=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,L2=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+lg+`
return result;
`,S2=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+lg+`
return result;
`,I2=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+lg+`
return result;
`;class Li{constructor(e,t,s,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=U.assertAndGetBroadcastShape(t,s);const i=this.outputShape.length;let r="";if(n)if(i===0||N.sizeFromShape(this.outputShape)===1)r=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{const o=Re(i);if(r=`
${o} coords = getOutputCoords();
`,i===1)r+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{const a=_t("coords",i);r+=`
bool nextRowOutOfBounds =
(${a[i-2]} + 1) >= ${this.outputShape[i-2]};
bool nextColOutOfBounds =
(${a[i-1]} + 1) >= ${this.outputShape[i-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${r}
setOutput(result);
}
`}}class v2{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode=`
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`}getCustomSetupFunc(e,t){return(s,n)=>{this.minLoc==null&&(this.minLoc=s.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=s.getUniformLocationNoThrow(n,"maxVal")),s.gl.uniform1f(this.minLoc,e),s.gl.uniform1f(this.maxLoc,t)}}}class T2{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
uniform float minVal;
uniform float maxVal;
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`}getCustomSetupFunc(e,t){return(s,n)=>{this.minLoc==null&&(this.minLoc=s.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=s.getUniformLocationNoThrow(n,"maxVal")),s.gl.uniform1f(this.minLoc,e),s.gl.uniform1f(this.maxLoc,t)}}}class A2{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
`}}class N2{constructor(e){this.outputShape=[],this.outputShape=U.computeOutShape(e,1),this.variableNames=e.map((r,o)=>`T${o}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let r=1;r<t.length;r++)t[r]=t[r-1]+e[r][1];const s=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let r=1;r<t.length;r++){const o=t[r-1];s.push(`else if (yC < ${t[r]}) setOutput(getT${r}(yR, yC-${o}));`)}const n=t.length,i=t[t.length-1];s.push(`else setOutput(getT${n}(yR, yC-${i}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${s.join(`
`)}
}
`}}class C2{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=U.computeOutShape(e,t);const s=this.outputShape,n=s.length,i=Re(n),r=_t("coords",n),o=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((m,f)=>`T${f}`);const a=new Array(e.length-1);a[0]=e[0][t];for(let m=1;m<a.length;m++)a[m]=a[m-1]+e[m][t];const l=o[t],c=o.slice(-2),p=o.join();let u=`if (${l} < ${a[0]}) {
return getChannel(
getT0(${p}), vec2(${c.join()}));
}`;for(let m=1;m<a.length;m++){const f=a[m-1];u+=`
if (${l} < ${a[m]} && ${l} >= ${a[m-1]}) {
return getChannel(
getT${m}(${cg(o,l,f)}),
vec2(${cg(c,l,f)}));
}`}const h=a.length,d=a[a.length-1];u+=`
return getChannel(
getT${h}(${cg(o,l,d)}),
vec2(${cg(c,l,d)}));`,this.userCode=`
float getValue(${o.map(m=>"int "+m)}) {
${u}
}
void main() {
${i} coords = getOutputCoords();
vec4 result = vec4(getValue(${r}), 0., 0., 0.);
${r[n-1]} = ${r[n-1]} + 1;
if (${r[n-1]} < ${s[n-1]}) {
result.g = getValue(${r});
}
${r[n-2]} = ${r[n-2]} + 1;
if (${r[n-2]} < ${s[n-2]}) {
result.a = getValue(${r});
}
${r[n-1]} = ${r[n-1]} - 1;
if (${r[n-2]} < ${s[n-2]} &&
${r[n-1]} < ${s[n-1]}) {
result.b = getValue(${r});
}
setOutput(result);
}
`}}function cg(e,t,s){const n=e.indexOf(t),i=e.map((r,o)=>o===n?`${r} - ${s}`:r);return i.join()}class R2{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,n=e.padInfo.top,i=e.padInfo.left,r=e.dataFormat==="channelsLast";this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${n};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${r}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class O2{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,a=s-1-e.padInfo.left,l=r?1:2,c=r?2:3,p=r?3:1;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${p}];
ivec2 dyCorner = ivec2(coords[${l}], coords[${c}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${r}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class E2{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,s=e.strideHeight,n=e.strideWidth,i=e.padInfo.front,r=e.padInfo.top,o=e.padInfo.left;this.userCode=`
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${s} - ${r};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${o};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class _2{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,n=e.filterWidth,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=t-1-e.padInfo.front,l=s-1-e.padInfo.top,c=n-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${a}, ${l}, ${c});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${i}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${s}; wR++) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${s} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class k2{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,n=e.padInfo.top,i=e.padInfo.left,r=e.outChannels/e.inChannels;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${r} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${n};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`}}class D2{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=t-1-e.padInfo.top,o=s-1-e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${r}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${a}; dm++) {
int d2 = d1 * ${a} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}}class Rx{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,r=e.padInfo.left,o=e.strideHeight,a=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,p=e.filterHeight,u=e.filterWidth,h=Math.floor(e.inChannels/4)*4,d=e.inChannels%4,m=e.dataFormat==="channelsLast",f=m?1:2,g=m?2:3,y=m?3:1;let w="",x="";s&&(n?w=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}`:w=`
float activation(float x) {
${s}
}
`,x="result = activation(result);");const T=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${w}
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${i}, ${r});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${y}];
ivec2 xRCCorner =
ivec2(coords[${f}], coords[${g}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${p}; wR++) {
int xR = xRCorner + wR * ${l};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${u}; wC++) {
int xC = xCCorner + wC * ${c};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${m}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${d===1}) {
if (${m}) {
dotProd +=
getX(batch, xR, xC, ${h}) *
getW(wR, wC, ${h}, d2);
} else {
dotProd +=
getX(batch, ${h}, xR, xC) *
getW(wR, wC, ${h}, d2);
}
} else if (${d===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2)
);
if (${m}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${d===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2),
getW(wR, wC, ${h} + 2, d2)
);
if (${m}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1),
getX(batch, xR, xC, ${h} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC),
getX(batch, ${h} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${T}
${x}
setOutput(result);
}
`}}class F2{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,s=e.padInfo.top,n=e.padInfo.left,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,p=e.filterDepth,u=e.filterHeight,h=e.filterWidth,d=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${i}, ${r}, ${o});
const ivec3 pads = ivec3(${t}, ${s}, ${n});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${p}; wF++) {
int xF = xFCorner + wF * ${a};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${u}; wR++) {
int xR = xRCorner + wR * ${l};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${h}; wC++) {
int xC = xCCorner + wC * ${c};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${d}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${m===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${d}) *
getW(wF, wR, wC, ${d}, d2);
} else if (${m===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${m===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1),
getX(batch, xF, xR, xC, ${d} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2),
getW(wF, wR, wC, ${d} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`}}class Ox{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.inHeight,r=e.inWidth,o=e.padInfo.top,a=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,p=e.dilationHeight,u=e.dilationWidth,h=e.filterHeight,d=e.filterWidth,m=e.outChannels/e.inChannels;let f="",g="";s&&(n?f=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}`:f=`
float activation(float x) {
${s}
}
`,g="result = activation(result);");const y=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${f}
const ivec2 strides = ivec2(${l}, ${c});
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${m};
int q = d2 - d1 * ${m};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${h}; wR++) {
int xR = xRCorner + wR * ${p};
if (xR < 0 || xR >= ${i}) {
continue;
}
for (int wC = 0; wC < ${d}; wC++) {
int xC = xCCorner + wC * ${u};
if (xC < 0 || xC >= ${r}) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${y}
${g}
setOutput(result);
}
`}}class Ex{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const i=e.inHeight,r=e.inWidth,o=e.padInfo.top,a=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,p=e.dilationHeight,u=e.dilationWidth,h=e.filterHeight,d=e.filterWidth,m=d;let f="int xR; int xC; int xCOffset;";for(let x=0;x<h;x++)for(let T=0;T<d;T++)f+=`
vec4 xTexelR${x}C${T*2} = vec4(0.);
vec4 wR${x}C${T} = vec4(0.);
vec4 xR${x}C${T} = vec4(0.);`;for(let x=0;x<h;x++)for(let T=0;T<m;T++){const A=T*2;if(f+=`
xR = xRCorner + ${x*p};
xC = xCCorner + ${A*u};
`,c===1){if(A<d&&(a%2===1?f+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${r}) {
xTexelR${x}C${A}.zw = vec2(0.);
}
} else {
xTexelR${x}C${A} = vec4(0.);
}
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${r}) {
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${r}) {
previous.zw = vec2(0.);
}
xR${x}C${A} = vec4(previous.zw, xTexelR${x}C${A}.xy);
} else {
xR${x}C${A} = vec4(0, 0, xTexelR${x}C${A}.xy);
}
`:f+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xC, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
xR${x}C${A} = xTexelR${x}C${A};
`,A+1<d)){const _=a%2===0?N.nearestLargerEven(u):u;u%2===0&&a%2===1||u%2!==0&&a%2!==1?(f+=`
xCOffset = xC + ${a%2} + ${_};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
}
`,u>1&&(f+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
`),f+=`
xR${x}C${A+1} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.xy);
`):f+=`
xCOffset = xC + ${_};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
}
xR${x}C${A+1} = xTexelR${x}C${A+2};
`}}else A<d&&(f+=`
if(xR >= 0 && xR < ${i}) {
`,a%2===1?(f+=`
xCOffset = xC + 1 - ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${x}C${A+2} = vec4(0.);
}
xR${x}C${A} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.zw);
`,A+1<d&&(f+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
final = getX(batch, xR, xCOffset, d1);
}
xR${x}C${A+1} = vec4(xTexelR${x}C${A+2}.xy, final.xy);
`)):(f+=`
if(xC >= 0 && xC < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xC, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
xCOffset = xC + ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A+2} = vec4(0.);
}
xR${x}C${A} = vec4(
xTexelR${x}C${A}.xy, xTexelR${x}C${A+2}.xy);
`,A+1<d&&(f+=`
xR${x}C${A+1} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.zw);
`)),f+="}");A<d&&(f+=`
vec4 wTexelR${x}C${A} = getW(${x}, ${A}, d1, q);
wR${x}C${A} = vec4(wTexelR${x}C${A}.xz, wTexelR${x}C${A}.xz);
`,A+1<d&&(f+=`
vec4 wTexelR${x}C${A+1} = getW(${x}, ${A+1}, d1, q);
wR${x}C${A+1} =
vec4(wTexelR${x}C${A+1}.xz, wTexelR${x}C${A+1}.xz);`))}for(let x=0;x<h;x++)for(let T=0;T<d;T++)f+=`dotProd += xR${x}C${T} * wR${x}C${T};`;let g="",y="";s&&(n?g=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${s}
}`:g=`vec4 activation(vec4 x) {
${s}
}`,y="result = activation(result);");const w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${g}
const ivec2 strides = ivec2(${l}, ${c});
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
${f}
vec4 result = dotProd;
${w}
${y}
setOutput(result);
}
`}}class M2{constructor(e,t,s,n,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[r,o,a,l]=e,[c]=t,[p,u]=s;this.outputShape=[c,p,u,l];const h=n==="bilinear"?1:0,[d,m]=[`${o-1}.0`,`${a-1}.0`],[f,g,y]=p>1?[`${(o-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[w,x,T]=u>1?[`${(a-1)/(u-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=`
const float height_ratio = float(${f});
const float width_ratio = float(${w});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${r}) {
return;
}
float height_scale = ${g};
float width_scale = ${x};
float in_y = ${y};
if( in_y < 0.0 || in_y > ${d} ) {
setOutput(float(${i}));
return;
}
float in_x = ${T};
if( in_x < 0.0 || in_x > ${m} ) {
setOutput(float(${i}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${h} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
`}}class _x{constructor(e,t,s){this.variableNames=["x"],this.outputShape=e;const n=e.length,i=t?"0.0":`getX(${U2(n,"coords")})`,r=e[e.length-1];let o="",a="";t?(o=s?`end != ${r-1}`:"end != 0",a=s?"end + 1":"end - 1"):(o=s?`end + pow2 < ${r}`:"end >= pow2",a=s?"end + pow2":"end - pow2"),this.userCode=`
uniform float index;
void main() {
${Re(n)} coords = getOutputCoords();
int end = ${$2(n,"coords")};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${o}) {
int idx = ${a};
${$2(n,"coords")} = idx;
val += getX(${U2(n,"coords")});
}
setOutput(val);
}
`}getCustomSetupFunc(e){return(t,s)=>{this.index==null&&(this.index=t.getUniformLocation(s,"index")),t.gl.uniform1f(this.index,e)}}}function U2(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function $2(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}class W2{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=wo.DENSE;const t=xo(e),s=ct();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${Hn(["r","c","d"],e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
${s.output} = result;
}
`}}class z2{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=wo.DENSE;const t=xo(e),s=ct();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${Hn(["r","c","d"],e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
${s.output} = result;
}
`}}class P2{constructor(e,t,s){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=s,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}class B2{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`}}class j2{constructor(e){this.variableNames=["A"],this.outTexUsage=is.DOWNLOAD;const t=ct();this.outputShape=e,this.userCode=`
${rg}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}}class V2{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=is.DOWNLOAD;const t=ct();this.outputShape=e,this.userCode=`
${rg}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}}class G2{constructor(e,t,s=!1){this.variableNames=["A"];const n=ct(),[i,r]=t;this.outputShape=e;let o="result";s&&(o="floor(result * 255. + 0.5)"),this.userCode=`
${nc(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / ${r};
int c = imod(flatIndex, ${r});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${r}.0, ${i}.0);
vec4 values = ${n.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
${n.output} = vec4(${o}, 0., 0., 0.);
}
`}}class q2{constructor(e,t,s=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const n=ct(),[i,r]=t;this.outputShape=e;let o="",a="result";s&&(a="floor(result * 255. + 0.5)");for(let l=0;l<=1;l++)for(let c=0;c<=1;c++){const p=l*2+c;o+=`
localCoords = coords;
if(localCoords[2] + ${c} < ${e[2]}) {
localCoords[2] += ${c};
if(localCoords[1] + ${l} < ${e[1]}) {
localCoords[1] += ${l};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
r = flatIndex / ${r};
c = imod(flatIndex, ${r});
uv = (vec2(c, r) + halfCR) / vec2(${r}.0, ${i}.0);
values = ${n.texture2D}(A, uv);
if(offset == 0) {
result[${p}] = values[0];
} else if(offset == 1) {
result[${p}] = values[1];
} else if(offset == 2) {
result[${p}] = values[2];
} else {
result[${p}] = values[3];
}
}
}
`}this.userCode=`
${nc(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${o}
${n.output} = ${a};
}
`}}const kx={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"};class Dx{constructor(e,t,s){this.variableNames=["real","imag"];const n=t[1];this.outputShape=t;const i=s?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,r=s?`${n}.0`:"1.0";this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${e}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${n});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${n}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${r};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}}class H2{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode=`
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`}getCustomSetupFunc(e){return(t,s)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(s,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class Y2{constructor(e,t,s){this.variableNames=["A","indices"];const n=e.slice();n[s]=t,this.outputShape=n,this.rank=n.length;const i=Re(this.rank),r=RV(e,s);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`}}function RV(e,t){const s=e.length;if(s>4)throw Error(`Gather for rank ${s} is not yet supported`);if(s===1)return"int(getIndices(resRC))";const n=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[];for(let r=0;r<e.length;r++)r===t?i.push(`int(getIndices(${n[r]}))`):i.push(`${n[r]}`);return i.join()}class K2{constructor(e,t,s){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=s;const n=Re(t.length),i=Re(s.length),r=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${n} strides = ${n}(${this.strides});
void main() {
${i} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${r};
}
setOutput(getX(flattenIndex, coords[1]));
}
`}}function X2(e){const t=ct(),s=`${t.version}
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;return oR(e,s)}function J2(e){const t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return pR(e,t)}function Z2(e){const t=new Uint16Array([0,1,2,2,1,3]);return uR(e,t)}function $u(e,t,s,n,i,r){dR(t,s);const o=hR(e),a=e.TEXTURE_2D;return pe(e,()=>e.bindTexture(a,o)),pe(e,()=>e.texParameteri(a,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),pe(e,()=>e.texParameteri(a,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),pe(e,()=>e.texParameteri(a,e.TEXTURE_MIN_FILTER,e.NEAREST)),pe(e,()=>e.texParameteri(a,e.TEXTURE_MAG_FILTER,e.NEAREST)),pe(e,()=>e.texImage2D(a,0,n,t,s,0,i,r,null)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function Fx(e){return e.internalFormatFloat}function Q2(e,t,s,n){const[i,r]=Ta(t,s);return $u(e,i,r,Fx(n),n.textureFormatFloat,e.FLOAT)}function Mx(e){return e.internalFormatHalfFloat}function eO(e,t,s,n){const[i,r]=Ta(t,s);return $u(e,i,r,Mx(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function Ux(e){return e.downloadTextureFormat}function tO(e,t,s,n){const[i,r]=Ta(t,s);return $u(e,i,r,Ux(n),e.RGBA,e.UNSIGNED_BYTE)}function $x(e){return e.internalFormatPackedFloat}function sO(e,t,s,n){const[i,r]=wi(t,s);return $u(e,i,r,$x(n),e.RGBA,e.FLOAT)}function Wx(e){return e.internalFormatPackedHalfFloat}function nO(e,t,s,n){const[i,r]=wi(t,s);return $u(e,i,r,Wx(n),e.RGBA,n.textureTypeHalfFloat)}function iO(e,t,s){const n=0,i=3*4,r=3*4+2*4;pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s));const o=yx(e,t,"clipSpacePos",s,3,r,n);return o&&yx(e,t,"uv",s,2,r,i)}function rO(e,t,s,n,i,r){pe(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,a,l;i instanceof Uint8Array?(o=new Uint8Array(s*n*4),a=e.UNSIGNED_BYTE,l=e.RGBA):(o=new Float32Array(s*n*4),a=e.FLOAT,l=r.internalFormatPackedFloat),o.set(i),pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,s,n,0,e.RGBA,a,o)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function oO(e,t,s){pe(e,()=>e.bindTexture(e.TEXTURE_2D,t)),s.data instanceof Uint8Array?pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s.width,s.height,0,e.RGBA,e.UNSIGNED_BYTE,s.data)):pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function aO(e,t,s,n){const i=e.createBuffer();pe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const r=4,o=4,a=r*o*t*s;return pe(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ)),pe(e,()=>e.readPixels(0,0,s,t,e.RGBA,e.FLOAT,0)),pe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function lO(e,t,s){const n=e,i=new Float32Array(s);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,i),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),i}function cO(e,t,s,n){const[i,r]=Ta(t,s),o=4,a=new Uint8Array(nR(t*s,o));return pe(e,()=>e.readPixels(0,0,i,r,n.downloadTextureFormat,e.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function pO(e,t,s,n,i,r,o,a){const l=e,c=new Float32Array(iR(r,o));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function uO(e,t,s){const n=new Float32Array(t*s*4);return pe(e,()=>e.readPixels(0,0,s,t,e.RGBA,e.FLOAT,n)),n}class zx{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=W().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,gx(t,e)):this.gl=on(t);let s="WEBGL_color_buffer_float";const n="EXT_color_buffer_half_float";if(W().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",r="OES_texture_half_float";if(this.textureFloatExtension=Mu(this.gl,i),an(this.gl,r))this.textureHalfFloatExtension=Mu(this.gl,r);else if(W().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),an(this.gl,n))this.colorBufferHalfFloatExtension=Mu(this.gl,n);else if(W().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",an(this.gl,s))this.colorBufferFloatExtension=this.gl.getExtension(s);else if(an(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=J2(this.gl),this.indexBuffer=Z2(this.gl),this.framebuffer=mR(this.gl),this.textureConfig=Fu(this.gl,this.textureHalfFloatExtension)}get debug(){return W().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;pe(e,()=>e.finish()),pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),pe(e,()=>e.deleteFramebuffer(this.framebuffer)),pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),pe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),pe(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),Q2(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),eO(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),tO(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),oO(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,s,n){this.throwIfDisposed(),rO(this.gl,e,t,s,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),nO(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),sO(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(bx(this.gl,this.framebuffer),this.outputTexture=null),pe(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,s){return this.downloadMatrixDriver(e,()=>cO(this.gl,t,s,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,s,n,i,r){return pO(this.gl,e,t,s,n,i,r,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return lO(this.gl,e,t)}createBufferFromTexture(e,t,s){this.bindTextureToFrameBuffer(e);const n=aO(this.gl,t,s,this.textureConfig);return this.unbindTextureToFrameBuffer(),n}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,s;if(W().getBool("WEBGL_FENCE_API_ENABLED")){const n=e,i=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),s=()=>{const r=n.clientWaitSync(i,0,0);return r===n.ALREADY_SIGNALED||r===n.CONDITION_SATISFIED},t=i}else W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),s=()=>this.isQueryAvailable(t,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):s=()=>!0;return{query:t,isFencePassed:s}}downloadMatrixFromPackedTexture(e,t,s){return this.downloadMatrixDriver(e,()=>uO(this.gl,t,s))}createProgram(e){this.throwIfDisposed();const t=this.gl,s=aR(t,e),n=X2(t),i=lR(t);return pe(t,()=>t.attachShader(i,n)),pe(t,()=>t.attachShader(i,s)),cR(t,i),this.debug&&eg(t,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=iO(t,this.program,this.vertexBuffer)),i}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&pe(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&eg(this.gl,this.program),pe(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,s=!0){return this.throwIfDisposed(),s?fR(this.gl,e,t):gR(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),pe(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,s){this.throwIfDisposed(),this.throwIfNoProgram(),yR(this.gl,e,t,s)}setOutputMatrixTexture(e,t,s){this.setOutputMatrixTextureDriver(e,s,t)}setOutputPackedMatrixTexture(e,t,s){this.throwIfDisposed();const[n,i]=wi(t,s);this.setOutputMatrixTextureDriver(e,n,i)}setOutputMatrixWriteRegion(e,t,s,n){this.setOutputMatrixWriteRegionDriver(s,e,n,t)}setOutputPackedMatrixWriteRegion(e,t,s,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&eg(this.gl,this.program),Uu(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),pe(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),pe(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Mu(this.gl,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const s=this.gl,n=this.getQueryTimerExtensionWebGL2(),i=s.createQuery();return s.beginQuery(n.TIME_ELAPSED_EXT,i),i}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const t=this.gl,s=this.getQueryTimerExtensionWebGL2();t.endQuery(s.TIME_ELAPSED_EXT);return}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await N.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){const s=this.gl,n=s.getQueryParameter(e,s.QUERY_RESULT);return n/1e6}else{const s=this.getQueryTimerExtensionWebGL1(),n=s.getQueryObjectEXT(e,s.QUERY_RESULT_EXT);return n/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){const s=this.gl,n=this.getQueryTimerExtensionWebGL2(),i=s.getQueryParameter(e,s.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),i&&!this.disjoint}else{const s=this.getQueryTimerExtensionWebGL1(),n=s.getQueryObjectEXT(e,s.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=OV(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:s}=this.itemsToPoll[t];s()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;N.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),tg(this.gl,e,this.framebuffer),this.debug&&Uu(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(tg(this.gl,this.outputTexture,this.framebuffer),this.debug&&Uu(this.gl)):bx(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const s=t();return this.unbindTextureToFrameBuffer(),s}setOutputMatrixTextureDriver(e,t,s){this.throwIfDisposed();const n=this.gl;tg(n,e,this.framebuffer),this.debug&&Uu(n),this.outputTexture=e,pe(n,()=>n.viewport(0,0,t,s)),pe(n,()=>n.scissor(0,0,t,s))}setOutputMatrixWriteRegionDriver(e,t,s,n){this.throwIfDisposed(),pe(this.gl,()=>this.gl.scissor(e,t,s,n))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}}function OV(e){let t=0;for(;t<e.length;++t){const s=e[t]();if(!s)break}return t-1}function hO(e,t,s,n){const i=t.userCode,r=s.map((d,m)=>{const f={logicalShape:d.shape,texShape:d.isUniform?null:d.texData.texShape,isUniform:d.isUniform,isPacked:d.isUniform?!1:d.texData.isPacked,flatOffset:null};return d.texData!=null&&d.texData.slice!=null&&d.texData.slice.flatOffset>0&&(f.flatOffset=d.texData.slice.flatOffset),{name:t.variableNames[m],shapeInfo:f}}),o=r.map(d=>d.shapeInfo),a={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},l=jR(r,a,i,t.packedInputs),c=e.createProgram(l);let p=null;const u=e.getUniformLocation(c,"NAN",!1);W().getNumber("WEBGL_VERSION")===1&&(p=e.getUniformLocation(c,"INFINITY",!1));const h={};for(let d=0;d<t.variableNames.length;d++){const m=t.variableNames[d],f=!1;h[m]=e.getUniformLocation(c,m,f),h[`offset${m}`]=e.getUniformLocation(c,`offset${m}`,f)}return{program:t,source:l,webGLProgram:c,uniformLocations:h,inShapeInfos:o,outShapeInfo:a,infLoc:p,nanLoc:u}}function dO(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((s,n)=>{const i=s.logicalShape,r=t[n],o=r.shape;if(!N.arraysEqual(i,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${i} and ${o} must match`);if(s.isUniform&&r.isUniform)return;const a=s.texShape,l=r.isUniform?null:r.texData.texShape;if(!N.arraysEqual(a,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${l} must match`)})}function mO(e,t,s,n,i){dO(t.inShapeInfos,s),dO([t.outShapeInfo],[n]);const r=n.texData.texture,o=n.texData.texShape;n.texData.isPacked?e.setOutputPackedMatrixTexture(r,o[0],o[1]):e.setOutputMatrixTexture(r,o[0],o[1]),e.setProgram(t.webGLProgram),W().getNumber("WEBGL_VERSION")===1&&(t.infLoc!==null&&e.gl.uniform1f(t.infLoc,Infinity)),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),s.forEach((a,l)=>{const c=t.program.variableNames[l],p=t.uniformLocations[c],u=t.uniformLocations[`offset${c}`];if(p==null)return;if(a.isUniform){if(N.sizeFromShape(a.shape)<2)e.gl.uniform1f(p,a.uniformValues[0]);else{let h=a.uniformValues;h instanceof Float32Array||(h=new Float32Array(h)),e.gl.uniform1fv(p,h)}return}a.texData.slice!=null&&u!=null&&e.gl.uniform1i(u,a.texData.slice.flatOffset),e.setInputMatrixTexture(a.texData.texture,p,l)}),i!=null&&i(e,t.webGLProgram),e.executeProgram()}function fO(e,t,s){let n="";t.concat(s).forEach(o=>{const a=o.texData!=null&&o.texData.slice!=null&&o.texData.slice.flatOffset>0,l=o.isUniform?"uniform":o.texData.texShape;n+=`${o.shape}_${l}_${a}`});const i=e.userCode;let r=e.constructor.name;return r+="_"+n+"_"+i,r}class gO{constructor(e,t,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;const{filterWidth:n,inChannels:i,strideWidth:r,strideHeight:o,padInfo:a,outWidth:l,dilationWidth:c,dilationHeight:p,dataFormat:u}=s,{left:h,top:d}=a,m=i*n,f=ct(),g=u==="channelsLast",y=g?0:1,w=g?1:2;let x="";for(let T=0;T<=1;T++)for(let A=0;A<=1;A++)x+=`
blockIndex = rc.y + ${A};
pos = rc.x + ${T};
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
offsetY = int(blockIndex / (${l})) * ${o} - ${d};
d0 = offsetY + ${p} * (pos / ${m});
if(d0 < ${t[y]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${l}.) * ${r}. - ${h}.);
d1 = offsetX + ${c} * (int(mod(float(pos), ${m}.) / ${i}.));
if(d1 < ${t[w]} && d1 >= 0) {
ch = int(mod(float(pos), ${i}.));
if (${g}) {
innerDims = vec2(d1, ch);
result[${T*2+A}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${T*2+A}] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${x}
${f.output} = result;
}
`}}class yO{constructor(e,t,s,n,i){this.variableNames=["x"],this.outputShape=[];const r=t,o=e[3]-1;this.outputShape=e;let a;const l=`float(${s}) + float(${n}) * sum`;i===.5?a=`inversesqrt(${l})`:i===1?a=`1.0/(${l})`:a=`exp(log(${l}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${r}; j <= ${r}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${o}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${a};
setOutput(val);
}
`}}class bO{constructor(e,t,s,n,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=s,this.alpha=n,this.beta=i,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${n}) * norm + float(${s});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${n})
* float(${i})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${i});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`}}class wO{constructor(e,t,s,n,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const r=t,o=e[3]-1;this.outputShape=e;let a;const l=`float(${s}) + float(${n}) * sum`;i===.5?a=`inversesqrt(${l})`:i===1?a=`1.0/(${l})`:a=`exp(log(${l}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${r};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${r}; j <= ${r}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${a};
setOutput(result);
}
`}}class xO{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,s=e.strideWidth,n=e.dilationHeight,i=e.effectiveFilterHeight,r=e.effectiveFilterWidth,o=i-1-e.padInfo.top,a=r-1-e.padInfo.left,l=i*r-1;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${i};
wR += ${n}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${r} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}}class LO{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,s=e.strideHeight,n=e.strideWidth,i=e.dilationDepth,r=e.dilationHeight,o=e.dilationWidth,a=e.effectiveFilterDepth,l=e.effectiveFilterHeight,c=e.effectiveFilterWidth,p=a-1-e.padInfo.front,u=l-1-e.padInfo.top,h=c-1-e.padInfo.left,d=a*l*c-1;this.userCode=`
const ivec3 pads = ivec3(${p}, ${u}, ${h});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${a};
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${l};
wR += ${r}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${c};
wC += ${o}) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${d} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${l} * ${c} +
wR * ${c} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}}class pg{constructor(e,t,s=!1,n=!1,i=!1,r=null,o=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;const a=s?e[1]:e[2],l=Math.ceil(a/2),c=s?"i * 2, rc.y":"rc.y, i * 2",p=n?"rc.z, i * 2":"i * 2, rc.z",u=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=n?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let d="",m="";r&&(o?d=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${r}
}`:d=`vec4 activation(vec4 x) {
${r}
}`,m="result = activation(result);");const f=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${d}
const float sharedDimension = ${l}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${l}; i++) {
vec4 a = getMatrixA(rc.x, ${c});
vec4 b = getMatrixB(rc.x, ${p});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${u[0]} * ${h[0]});
result += (${u[1]} * ${h[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${f}
${m}
setOutput(result);
}
`}}class SO{constructor(e,t,s){this.variableNames=["probs"],this.outputShape=[e,s],this.userCode=`
uniform float seed;
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t-1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${t-1}));
}
`}getCustomSetupFunc(e){return(t,s)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(s,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class IO{constructor(e,t,s,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${n}), float(${s}),
float(index == coords.y)));
}
`}}class vO{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;const t=e.length;if(t===0)this.userCode=`
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{const s=_t("rc",t),n=Re(t),i=EV(t,e,s),r=_V(t,e[e.length-1],e[e.length-2],s),o=kV(e,s);this.userCode=`
void main() {
${n} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${r}
setOutput(vec4(${o}));
}
}
`}}}function DV(e,t){const s=[];for(let n=0;n<=1;n++)for(let i=0;i<=1;i++){let r=`${n===0?"r":"rp1"}, ${i===0?"c":"cp1"}`;for(let o=2;o<e;o++)r=`${t[t.length-1-o]},`+r;s.push(r)}return s}function EV(e,t,s){if(e===1)return`rc > ${t[0]}`;let n="";for(let i=e-2;i<e;i++)n+=`${s[i]} >= ${t[i]}`,i<e-1&&(n+="||");return n}function _V(e,t,s,n){if(e===1)return"";const i=n.slice(-2);return`
int r = ${i[0]};
int c = ${i[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
bool rEdge = rp1 >= ${s};
`}function kV(e,t){const s=e.length,n=DV(s,t);return s===1?`getA(rc),
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${n[0]}),
cEdge ? 0. : getA(${n[1]}),
rEdge ? 0. : getA(${n[2]}),
rEdge || cEdge ? 0. : getA(${n[3]})`}class TO{constructor(e,t,s){this.variableNames=["x"],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);const n=e.length,i=Re(n),r=t.map(l=>l[0]).join(","),o=t.map((l,c)=>l[0]+e[c]).join(","),a=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
int start = ${r};
int end = ${o};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(${s}));
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${i} start = ${i}(${r});
${i} end = ${i}(${o});
void main() {
${i} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(${s}));
} else {
${i} coords = outC - start;
setOutput(getX(${a}));
}
}
`}}class AO{constructor(e,t,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);const n=e.length,i=Re(n),r=t.map(m=>m[0]).join(","),o=t.map((m,f)=>m[0]+e[f]).join(","),a=_t("rc",n),l=_t("source",n),c=`${a[n-1]} < ${this.outputShape[n-1]}`,p=n===1?"source":`vec2(${l.slice(-2).join()})`,u=[`${i} rc = outputLoc;`,`${a[n-1]} += 1;
if(${c}) {
`,n===1?"":`}
rc = outputLoc;
${a[n-2]} += 1;
if(${a[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${a[n-1]} += 1;
if(${c}) {`],h=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let m=0,f=n===1?2:4;m<f;m++)d+=`
${u[m]}
if (${h}) {
result[${m}] = float(${s});
} else {
${i} source = rc - start;
result[${m}] = getChannel(getX(${l.join()}), ${p});
}
`;d+=n===1?"} ":"}}",this.userCode=`
const ${i} start = ${i}(${r});
const ${i} end = ${i}(${o});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${d}
setOutput(result);
}
`}}class Zi{constructor(e,t,s,n=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const r=e.filterWidth,o=e.strideHeight,a=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterHeight,u=e.effectiveFilterWidth,h=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const m=t==="avg",f=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(m||(y="-1.0 / 1e-20"),s){const E=">=";this.userCode=`
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${h}, ${d});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${u};
wC += ${c}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${E} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?i?f:g:`wR * ${u} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const w="max";let x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / count");const T=Math.floor(r/4)*4,A=r%4,_=`
if (${m}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${w}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${h}, ${d});
const float initializationValue = ${y};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${y});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${T}; wC += 4) {
int xC = xCCorner + wC * ${c};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
getValue(batch, xR, xC + 3 * ${c}, d)
);
${_}
}
int xC = xCCorner + ${T};
if (${A===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${_}
} else if (${A===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
initializationValue,
initializationValue
);
${_}
} else if (${A===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
initializationValue
);
${_}
}
}
setOutput(${x});
}
`}}class ug{constructor(e,t,s,n=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const r=e.filterWidth,o=e.strideDepth,a=e.strideHeight,l=e.strideWidth,c=e.dilationDepth,p=e.dilationHeight,u=e.dilationWidth,h=e.effectiveFilterDepth,d=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const w=t==="avg";let x="0.0";if(w||(x="-1.0 / 1e-20"),s){const D=">=";this.userCode=`
const ivec3 strides =
ivec3(${o}, ${a}, ${l});
const ivec3 pads = ivec3(${f}, ${g}, ${y});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < ${h};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${m};
wC += ${u}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${D} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?i?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${d} * ${m} +
wR * ${m} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const T="max";let A=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(A="avgValue / count");const _=Math.floor(r/4)*4,E=r%4,F=`
if (${w}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${T}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${o}, ${a}, ${l});
const ivec3 pads = ivec3(${f}, ${g}, ${y});
const float initializationValue = ${x};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${x});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${h};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${_}; wC += 4) {
int xC = xCCorner + wC * ${u};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
getValue(batch, xD, xR, xC + 2 * ${u}, ch),
getValue(batch, xD, xR, xC + 3 * ${u}, ch)
);
${F}
}
int xC = xCCorner + ${_};
if (${E===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${F}
} else if (${E===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
initializationValue,
initializationValue
);
${F}
} else if (${E===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
getValue(batch, xD, xR, xC + 2 * ${u}, ch),
initializationValue
);
${F}
}
}
setOutput(${A});
}
}
`}}class hg{constructor(e,t){this.variableNames=["x"];const{windowSize:s,batchSize:n,inSize:i,outSize:r}=e;this.outputShape=[n,r];let o="0.0",a="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",a="min"):t==="max"&&(o="-1.0 / 1e-20",a="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");const c=Math.floor(s/4)*4,p=s%4;let u=`
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${a}(values, minMaxValue);
}
`,h="vec4";t==="all"?(o="1.0",u=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,h="bvec4"):t==="any"&&(o="0.0",u=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,h="bvec4");let d="";i%s>0&&(d=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${o};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${d}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
vec4 minMaxValue = vec4(${o});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${u}
}
int inIdx = inOffset + ${c};
if (${p===1}) {
${h} values = ${h}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${u}
} else if (${p===2}) {
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${u}
} else if (${p===3}) {
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${u}
}
setOutput(${l});
}
`}}class dg{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let s="";for(let n=0;n<4;n++){let i="thisRC = rc;";n%2===1&&(i+="thisRC.z += 1;"),n>1&&(i+="thisRC.y += 1;"),s+=`
${i}
${n>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${n}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${n>0?"}":""}
`}this.userCode=`
${FV(t)}
${nc(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${s}
setOutput(result);
}
`}}function FV(e){const t=Hn(["r","c","d"],e);return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
`}class NO{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,n,i]=t.shape,[,r,o]=e.shape,a=[s&&r>1?n-1:n,s&&o>1?i-1:i],l=[s&&r>1?r-1:r,s&&o>1?o-1:o],c=a[0]/l[0],p=a[1]/l[1],u=1/c,h=1/p,d=Math.ceil(u)*2+2,m=Math.ceil(h)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${c});
const float widthScale = float(${p});
const float invHeightScale = float(${u});
const float invWidthScale = float(${h});
const int winHeight = int(${d});
const int winWidth = int(${m});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${r}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${n-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${i-1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class CO{constructor(e,t,s,n){this.variableNames=["A"],this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s];this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0]/c[0]},
${l[1]/c[1]});
const vec2 inputShapeRC = vec2(${r}.0, ${o}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
`}}class RO{constructor(e,t,s,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s];this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${l[0]/c[0]},
${l[1]/c[1]},
${l[1]/c[1]});
const vec3 inputShapeRC = vec3(${r}.0, ${o}.0,
${o}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${a-1};
bool hasNextRow = coords.z < ${s-1};
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
`}}class OO{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,n,i]=t.shape,[,r,o]=e.shape,a=[s&&r>1?n-1:n,s&&o>1?i-1:i],l=[s&&r>1?r-1:r,s&&o>1?o-1:o],c=a[0]/l[0],p=a[1]/l[1],u=1/c,h=1/p,d=Math.ceil(u)*2+2,m=Math.ceil(h)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${c});
const float widthScale = float(${p});
const float invHeightScale = float(${u});
const float invWidthScale = float(${h});
const int winHeight = int(${d});
const int winWidth = int(${m});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${r}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
float sourceFracRow =
float(${a[0]}) *
(float(dyR) / float(${l[0]}));
float sourceFracCol =
float(${a[1]}) *
(float(dyC) / float(${l[1]}));
int sourceNearestRow = int(min(
float(int(${n}) - 1),
${s} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${i}) - 1),
${s} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class EO{constructor(e,t,s,n){this.variableNames=["A"],this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s],p=n?"0.5":"0.0";this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0]/c[0]},
${l[1]/c[1]});
const vec2 inputShapeRC = vec2(${r}.0, ${o}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}}class _O{constructor(e,t){this.variableNames=["x"];const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);if(this.outputShape=e,s===1){this.userCode=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;return}const n=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,i=e.map((o,a)=>n(a)).join(","),r=Re(s);this.userCode=`
void main() {
${r} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}}class kO{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);this.outputShape=e;const n=_t("rc",s),i=`${n[s-1]} + 1 < ${this.outputShape[s-1]}`,r=`${n[s-2]} + 1 < ${this.outputShape[s-2]}`,o=Re(s);s===1?this.userCode=`
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${i}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${a(n.slice())};
if(${i}){
result.g = ${l(n.slice())};
}
if(${r}) {
result.b = ${c(n.slice())};
if(${i}) {
result.a = ${p(n.slice())};
}
}
setOutput(result);
}
`;function a(d){return u(d)}function l(d){return d[s-1]="("+d[s-1]+" + 1)",u(d)}function c(d){return d[s-2]="("+d[s-2]+" + 1)",u(d)}function p(d){return d[s-1]="("+d[s-1]+" + 1)",d[s-2]="("+d[s-2]+" + 1)",u(d)}function u(d){const m=e.map((y,w)=>h(w,d)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function h(d,m){return t.indexOf(d)!==-1&&e[d]!==1?`${e[d]} - ${m[d]} - 1`:`${m[d]}`}}}class Px{constructor(e,t,s,n,i,r,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=r;const a=Re(i.length),l=Re(r.length);let c="";s===1?c="i":s===2&&(c="i, j");const p=`getIndices(${c})`;let u="";n===1?u="i":n===2&&(u="i, coords[1]");const h=`getUpdates(${u})`,d=t>1?"strides[j]":"strides";this.userCode=`
${a} strides = ${a}(${i});
void main() {
${l} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${p});
flattenedIndex += index * ${d};
}
if (flattenedIndex == coords[0]) {
sum += ${h};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}}class DO{constructor(e,t){this.variableNames=["x","segmentIds"];const s=e.windowSize,n=e.batchSize,i=e.inSize,r=e.numSegments,o=r*Math.ceil(i/s);this.outputShape=[n,o];const a="0.0",l="sumValue",c=Math.floor(s/4)*4,p=s%4,u=`
sumValue += dot(values, segFilter);
`;let h="";i%s>0&&(h=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`);let d="";i%s>0&&(d=`
if (inIdx < 0 || inIdx >= ${i}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${a};
float getValue(int batch, int inIdx) {
${h}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${d}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${r})) * float(${s}));
int currentSeg = int(mod(float(outIdx), float(${r})));
float sumValue = 0.0;
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${u}
}
int inIdx = inOffset + ${c};
if (${p===1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
${u}
} else if (${p===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
${u}
} else if (${p===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
${u}
}
setOutput(${l});
}
`}}class FO{constructor(e,t,s){this.variableNames=["c","a","b"],this.outputShape=t;let n,i;if(s>4)throw Error(`Where for rank ${s} is not yet supported`);if(s===1)i="resRC",n="resRC";else{const o=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],l=[];for(let c=0;c<t.length;c++)l.push(`${o[c]}`),c<e&&a.push(`${o[c]}`);n=a.join(),i=l.join()}const r=Re(s);this.userCode=`
void main() {
${r} resRC = getOutputCoords();
float cVal = getC(${n});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
`}}class MO{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Re(this.rank),s=`uniform int start[${this.rank}];`,n=MV(this.rank);let i;const r=e.map((o,a)=>`sourceLoc.${Bx[a]} = start[${a}] + coords.${Bx[a]};`);i=`
${t} sourceLoc;
${t} coords = getOutputCoords();
${r.join(`
`)}
`,this.userCode=`
${s}
void main() {
${i}
setOutput(getSource(${n}));
}
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,s)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(s,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}const Bx=["x","y","z","w","u","v"];function MV(e){if(e===1)return"sourceLoc";if(e<=6)return Bx.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class UO{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Re(this.rank),s=_t("coords",this.rank),n=_t("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,r=`getChannel(getSource(${n.join()}), ${i})`,o=`
result.x = ${r};
if (++${s[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.y = ${r};
--${n[this.rank-1]};
}
`,a=this.rank===1?"":`
--${s[this.rank-1]};
if (++${s[this.rank-2]} < ${e[this.rank-2]}) {
++${n[this.rank-2]};
result.z = ${r};
if (++${s[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.w = ${r};
}
}
`,l=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((c,p)=>`start[${p}]`).join()});`:e.map((c,p)=>`${n[p]} = ${s[p]} + start[${p}];`).join(`
`);this.userCode=`
uniform int start[${this.rank}];
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${l}
vec4 result = vec4(0.);
${o}
${a}
setOutput(result);
}
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,s)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(s,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}class $O{constructor(e,t,s){this.variableNames=["x"],this.outputShape=s;const n=s.length,i=Re(s.length),r=Re(s.length);let o="";if(n===1)o="coords * strides + begin";else{let a=0;o=s.map((l,c)=>(a++,s.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${a-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
void main() {
${r} coords = getOutputCoords();
setOutput(getX(${o}));
}
`}}class BO{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,s){const n=zO(t,s),i=PO(e,n,s);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const r=WO(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,s);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=r,this.log();const a=this.freeTextures[i].shift();return this.usedTextures[i].push(a),a}let o;return n===Xt.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===Xt.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===Xt.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===Xt.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===Xt.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(o),this.numUsedTextures++,this._numBytesAllocated+=r,this.log(),o}releaseTexture(e,t,s,n){if(this.freeTextures==null)return;const i=zO(s,n),r=PO(t,i,n);r in this.freeTextures||(this.freeTextures[r]=[]);const o=WO(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,n),a=W().get("WEBGL_DELETE_TEXTURE_THRESHOLD");a!==-1&&this._numBytesAllocated>a?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[r].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const l=this.usedTextures[r],c=l.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures==null)return;for(const e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(const e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}function UV(e,t){const s=e;if(t===s.R32F)return 4;if(t===s.R16F)return 2;if(t===s.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===s.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function WO(e,t,s,n,i){const r=$V(t,n);let o;if(i){const[l,c]=wi(e[0],e[1]);o=l*c}else{const[l,c]=Ta(e[0],e[1]);o=l*c}const a=UV(s,r);return o*a}function $V(e,t){switch(e){case Xt.PACKED_2X2_FLOAT32:return $x(t);case Xt.PACKED_2X2_FLOAT16:return Wx(t);case Xt.UNPACKED_FLOAT32:return Fx(t);case Xt.UNPACKED_FLOAT16:return Mx(t);case Xt.PACKED_4X1_UNSIGNED_BYTE:return Ux(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function WV(e){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Xt.PACKED_2X2_FLOAT32:Xt.UNPACKED_FLOAT32:e?Xt.PACKED_2X2_FLOAT16:Xt.UNPACKED_FLOAT16}function zO(e,t){if(e===is.UPLOAD)return Xt.PACKED_2X2_FLOAT32;if(e===is.RENDER||e==null)return WV(t);if(e===is.DOWNLOAD||e===is.PIXELS)return Xt.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function PO(e,t,s){return`${e[0]}_${e[1]}_${t}_${s}`}class jO{constructor(e,t){this.variableNames=["A"];const s=new Array(e.length);for(let r=0;r<s.length;r++)s[r]=e[r]*t[r];this.outputShape=s,this.rank=s.length;const n=Re(this.rank),i=zV(e);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function zV(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;const s=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let i=0;i<e.length;i++)n.push(`imod(${s[i]}, ${e[i]})`);return n.join()}class $e{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=`
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}}const Qi="if (isnan(x)) return x;",VO="return x;",jx="return abs(x);",Vx=Qi+`
return (x < 0.0) ? 0.0 : x;
`,Gx=Qi+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,qx="return (x >= 0.0) ? x : (exp(x) - 1.0);",GO=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${U.SELU_SCALEALPHA};
float scale = ${U.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;function qO(e=0){return Qi+`
return x > 0.0 ? 1.0 : float(${e});
`}const Hx="return -x;",Yx="return ceil(x);",Kx="return floor(x);",HO=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,YO="return float(isnan(x));",KO="return float(isinf(x));",XO="return float(!isnan(x) && !isinf(x));",JO=`
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
`,Xx="return exp(x);",Jx="return exp(x) - 1.0;",ZO=`if (x < 0.0) return NAN;
return log(x);`,QO="return log(1.0 + x);",e1="return sqrt(x);",t1="return inversesqrt(x);",s1="return 1.0 / (1.0 + exp(-1.0 * x));",n1=`
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
`,i1=Qi+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,r1=Qi+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,o1=Qi+`
return atan(x);
`,a1=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,l1=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,c1=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,p1=Qi+"return log(x + sqrt(x * x + 1.0));",u1=Qi+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,h1=Qi+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,d1=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${U.ERF_P};
float a1 = ${U.ERF_A1};
float a2 = ${U.ERF_A2};
float a3 = ${U.ERF_A3};
float a4 = ${U.ERF_A4};
float a5 = ${U.ERF_A5};
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
`,m1="return 1.0 / x;",f1="return float(!(x >= 1.0));",g1="return float(int(x));",Wu="return x;";const y1="return x;",b1=`
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
`,Zx=`
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,Qx=`
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,eL=`
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`;class lc{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`}}class w1{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,s=_t("rc",t),n=Re(t),i=PR(t,s),r=s.slice(-2),o=t<=1?"rc":`vec2(${r.join(",")})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 packedInput = getA(${i});
setOutput(getChannel(packedInput, ${o}));
}
`}}const{segment_util:x1}=U,PV=vt.split,BV=vt.tile,jV=vt.topkImpl,VV=vt.whereImpl,GV=1e-7,qV=1e-4,mg={};function HV(e){return e in mg||(mg[e]={}),mg[e]}function fg(e,t=!1){if(e==="linear")return t?y1:VO;if(e==="relu")return t?Zx:Vx;if(e==="elu")return t?eL:qx;if(e==="relu6")return t?Qx:Gx;if(e==="prelu")return t?Cx:Nx;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const YV=128,KV=600;function XV(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*KV/1024/1024}const L1=1e3;class tL extends Eo{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!W().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=on(W().getNumber("WEBGL_VERSION"));this.binaryCache=HV(W().getNumber("WEBGL_VERSION")),this.gpgpu=new zx(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new BO(this.gpgpu),this.numMBBeforeWarning=XV(),this.texData=new Fc(this,Us())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,s){if((W().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||W().getBool("DEBUG"))&&this.checkNumericalProblems(e),s==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const n={};return this.texData.set(n,{shape:t,dtype:s,values:e,usage:is.UPLOAD,refCount:1}),n}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,s,n){if(W().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:s,dtype:n,values:t,usage:is.UPLOAD,refCount:1})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const s=this.texData.get(t);s.refCount--,s.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:s,dtype:n,complexTensors:i,slice:r,shape:o,isPacked:a}=t;if(r!=null){let u;a?u=new lc(o,Wu):u=new $e(o,Wu);const h=this.runWebGLProgram(u,[{dataId:e,shape:o,dtype:n}],n),d=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),d}if(s!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return s;const l=this.activeTimers!=null;let c;l&&(c=N.now());let p;if(n==="complex64"){const u=i.real.dataSync(),h=i.imag.dataSync();p=U.mergeRealAndImagArrays(u,h)}else p=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=N.now()-c),this.convertAndCacheOnCPU(e,p)}async read(e){if(this.pendingRead.has(e)){const d=this.pendingRead.get(e);return new Promise(m=>d.push(m))}const t=this.texData.get(e),{values:s,shape:n,slice:i,dtype:r,complexTensors:o,isPacked:a}=t;if(i!=null){let d;a?d=new lc(n,Wu):d=new $e(n,Wu);const m=this.runWebGLProgram(d,[{dataId:e,shape:n,dtype:r}],r),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(s!=null)return this.convertAndCacheOnCPU(e);if(!W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&W().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(r!=="complex64"&&W().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);const d=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(d.texture,...xo(n))}this.pendingRead.set(e,[]),r!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(r==="complex64"){const d=await Promise.all([o.real.data(),o.imag.data()]),m=d[0],f=d[1];p=U.mergeRealAndImagArrays(m,f)}else if(l==null)p=this.getValuesFromTexture(e);else{const d=N.sizeFromShape(n);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,d)}c!=null&&this.disposeIntermediateTensorInfo(c);const u=this.convertAndCacheOnCPU(e,p),h=this.pendingRead.get(e);return this.pendingRead.delete(e),h.forEach(d=>d(u)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),u}checkNumericalProblems(e){if(e==null)return;for(let t=0;t<e.length;t++){const s=e[t];if(!rR(s))throw W().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${s} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${s} cannot be represented on this device.`)}}getValuesFromTexture(e){const{shape:t,dtype:s,isPacked:n}=this.texData.get(e),i=N.sizeFromShape(t);if(W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const u=this.decode(e),h=this.texData.get(u.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(h.texture,...xo(t)).subarray(0,i);return this.disposeIntermediateTensorInfo(u),d}const r=W().getBool("WEBGL_PACK")&&n===!0,o=r?sg(t):t,a=r?new V2(o):new j2(o),l=this.runWebGLProgram(a,[{shape:o,dtype:s,dataId:e}],"float32"),c=this.texData.get(l.dataId),p=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture,c.texShape[0],c.texShape[1]).subarray(0,i);return this.disposeIntermediateTensorInfo(l),p}async time(e){const t=this.activeTimers,s=[];let n=!1;this.programTimersStack==null?(this.programTimersStack=s,n=!0):this.activeTimers.push(s),this.activeTimers=s,e();const i=N.flatten(this.activeTimers.map(a=>a.query)).filter(a=>a!=null),r=N.flatten(this.activeTimers.map(a=>a.name)).filter(a=>a!=null);this.activeTimers=t,n&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const a=await Promise.all(i);o.kernelMs=N.sum(a),o.getExtraProfileInfo=()=>a.map((l,c)=>({name:r[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:N.now(),endMs:null}}endTimer(e){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=N.now(),e)}async getQueryTime(e){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e){if(this.pendingDisposal.has(e))return;if(this.pendingRead.has(e)){this.pendingDisposal.add(e),this.pendingDeletes++;return}if(!this.texData.has(e))return;this.releaseGPUData(e);const{complexTensors:t}=this.texData.get(e);t!=null&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}releaseGPUData(e){const{texture:t,dtype:s,texShape:n,usage:i,isPacked:r,slice:o}=this.texData.get(e),a=o&&o.origDataId||e,l=this.dataRefCount.get(a);l>1?this.dataRefCount.set(a,l-1):(this.dataRefCount.delete(a),t!=null&&(this.numBytesInGPU-=this.computeBytes(n,s),this.textureManager.releaseTexture(t,n,i,r)));const c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}getCPUBackend(){return W().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=Us().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=YV){const s=this.getCPUBackend();return!this.warnedAboutCPUBackend&&s==null&&(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),s!=null&&e.every(n=>this.texData.get(n.dataId).texture==null&&N.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}complex(e,t){const s=this.makeOutput(e.shape,"complex64"),n=this.texData.get(s.dataId);return n.complexTensors={real:Us().keep(e.clone()),imag:Us().keep(t.clone())},s}real(e){const t=this.texData.get(e.dataId);return t.complexTensors.real.clone()}imag(e){const t=this.texData.get(e.dataId);return t.complexTensors.imag.clone()}slice(e,t,s){if(this.shouldExecuteOnCPU([e])){const r=FR(this.texData.get(e.dataId).values,t,s,e.shape,e.dtype);return this.makeOutput(s,e.dtype,r)}if(N.sizeFromShape(s)===0)return ze([],s,e.dtype);const{isPacked:n}=this.texData.get(e.dataId),i=Ms.isSliceContinous(e.shape,t,s);if(n||!i){const r=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new UO(s):new MO(s),o=r.getCustomSetupFunc(t);return this.compileAndRun(r,[e],null,o)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,t,s)}shallowSlice(e,t,s){const n=this.texData.get(e.dataId),i=this.makeOutput(s,e.dtype),r=this.texData.get(i.dataId);Object.assign(r,n),r.shape=s,r.dtype=e.dtype;let o=Ms.computeFlatOffset(t,e.strides);n.slice&&(o+=n.slice.flatOffset),r.slice={flatOffset:o,origDataId:n.slice&&n.slice.origDataId||e.dataId};const a=this.dataRefCount.get(r.slice.origDataId)||1;return this.dataRefCount.set(r.slice.origDataId,a+1),i}stridedSlice(e,t,s,n){const i=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.stridedSlice(e,t,s,n));if(i)return i;const r=Ms.computeOutShape(t,s,n);if(r.some(a=>a===0))return ze([],r);const o=new $O(t,n,r);return this.compileAndRun(o,[e])}reverse(e,t){const s=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new kO(e.shape,t):new _O(e.shape,t);return this.compileAndRun(s,[e])}concat(e,t){if(e[0].dtype==="complex64"){const o=e.map(l=>Zs(l)),a=e.map(l=>yn(l));return Gt(this.concat(o,t),this.concat(a,t))}if(e.length===1)return e[0];if(e.length>W().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const o=Math.floor(e.length/2),a=this.concat(e.slice(0,o),t),l=this.concat(e.slice(o),t);return this.concat([a,l],t)}if(W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){const o=new C2(e.map(a=>a.shape),t);return this.compileAndRun(o,e)}const s=U.computeOutShape(e.map(o=>o.shape),t),n=e.map(o=>o.as2D(-1,N.sizeFromShape(o.shape.slice(t)))),i=new N2(n.map(o=>o.shape)),r=this.compileAndRun(i,n);return r.reshape(s)}neg(e){const t=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.neg(e));if(t)return t;if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Hx,e.dtype);const s=new $e(e.shape,Hx);return this.compileAndRun(s,[e])}batchMatMul(e,t,s,n){const i=s?e.shape[2]:e.shape[1],r=n?t.shape[1]:t.shape[2],o=s?e.shape[1]:e.shape[2],[a,,]=e.shape;if((i===1||r===1)&&o>L1){s&&(e=se(e,[0,2,1])),n&&(t=se(t,[0,2,1]));const p=r===1?e:e.as3D(a,o,1),u=r===1?2:1,h=r===1?t.as3D(a,1,o):t;return this.multiply(p,h).sum(u,!0)}const l=Ft(e.dtype,t.dtype),c=new pg(e.shape,[a,i,r],s,n);return this.compileAndRun(c,[e,t],l)}fusedBatchMatMul({a:e,b:t,transposeA:s,transposeB:n,bias:i,activation:r,preluActivationWeights:o}){const a=s?e.shape[2]:e.shape[1],l=n?t.shape[1]:t.shape[2],[c,,]=e.shape,p=Ft(e.dtype,t.dtype),u=i!=null,h=o!=null,d=r?fg(r,!0):null,m=new pg(e.shape,[c,a,l],s,n,u,d,h),f=[e,t];return i&&f.push(i),o&&f.push(o),this.compileAndRun(m,f,p)}multiply(e,t){if(e.dtype==="complex64"){const i=this.texData.get(e.dataId),r=this.texData.get(t.dataId),o=new Tx(vx.REAL,e.shape,t.shape),a=new Tx(vx.IMAG,e.shape,t.shape),l=[this.makeComplexComponentTensorInfo(e,i.complexTensors.real),this.makeComplexComponentTensorInfo(e,i.complexTensors.imag),this.makeComplexComponentTensorInfo(t,r.complexTensors.real),this.makeComplexComponentTensorInfo(t,r.complexTensors.imag)],c=this.compileAndRun(o,l),p=this.compileAndRun(a,l),u=this.complex(c,p);return c.dispose(),p.dispose(),u}const s=Ft(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),r=this.texData.get(t.dataId),[o,a]=kR(e.shape,t.shape,i.values,r.values,s);return this.makeOutput(a,s,o)}if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,Ax,e.dtype);const n=new kt(Ax,e.shape,t.shape);return this.compileAndRun(n,[e,t],e.dtype)}localResponseNormalization4D(e,t,s,n,i){const r=W().getBool("WEBGL_PACK_NORMALIZATION")?new wO(e.shape,t,s,n,i):new yO(e.shape,t,s,n,i);return this.compileAndRun(r,[e])}LRNGrad(e,t,s,n,i,r,o){const a=new bO(t.shape,n,i,r,o);return this.compileAndRun(a,[t,s,e])}tile(e,t){if(e.dtype==="string"){const n=this.readSync(e.dataId),i=n.map(o=>N.decodeString(o)),r=ge(e.shape,e.dtype,i);return BV(r,t)}const s=new jO(e.shape,t);return this.compileAndRun(s,[e])}pad(e,t,s){const n=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new AO(e.shape,t,s):new TO(e.shape,t,s);return this.compileAndRun(n,[e])}gather(e,t,s){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.gather(e,t,s));if(n)return n;const i=new Y2(e.shape,t.size,s);return this.compileAndRun(i,[e,t])}batchToSpaceND(e,t,s){N.assert(e.rank<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const n=t.reduce((c,p)=>c*p),i=U.getReshaped(e.shape,t,n),r=U.getPermuted(i.length,t.length),o=U.getReshapedPermuted(e.shape,t,n),a=U.getSliceBeginCoords(s,t.length),l=U.getSliceSize(o,s,t.length);return se(e.reshape(i),r).reshape(o).slice(a,l)}spaceToBatchND(e,t,s){N.assert(e.rank<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const n=t.reduce((p,u)=>p*u),i=[[0,0]];i.push(...s);for(let p=1+t.length;p<e.shape.length;++p)i.push([0,0]);const r=e.pad(i),o=U.getReshaped(r.shape,t,n,!1),a=U.getPermuted(o.length,t.length,!1),l=U.getReshapedPermuted(r.shape,t,n,!1),c=se(r.reshape(o),a);return O(c,l)}reduce(e,t,s){const n=e.shape[0],i=e.shape[1],r=U.computeOptimalWindowSize(i),o=Math.ceil(i/r),a={windowSize:r,inSize:i,batchSize:n,outSize:o},l=new hg(a,t),c=this.compileAndRun(l,[e],s);return c.shape[1]===1?c:this.reduce(c,t,s)}argReduce(e,t,s=null){let n=e.shape[0],i=e.shape[1];s!=null&&(n=s.shape[0],i=s.shape[1]);const r=U.computeOptimalWindowSize(i),o={windowSize:r,inSize:i,batchSize:n,outSize:Math.ceil(i/r)},a=new zR(o,t,s==null),l=[e];s!=null&&l.push(s);const c=this.compileAndRun(a,l,"int32");return c.shape[1]===1?c:this.argReduce(e,t,c)}argReducePacked(e,t,s=null){const n=s!=null?s.shape:e.shape,i=n[n.length-1],r=U.computeOptimalWindowSize(i),o=new qR(n,r,t,s==null),a=s==null?[e]:[e,s],l=this.compileAndRun(o,a,"int32");return l.rank===e.rank?this.argReducePacked(e,t,l):l}sum(e,t){U.assertAxesAreInnerMostDims("sum",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=N.sizeFromShape(n),r=e.as2D(-1,i),o=Mp(e.dtype);return this.reduce(r,"sum",o).reshape(s)}prod(e,t){const s=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.prod(e,t));if(s)return s;const[n,i]=U.computeOutAndReduceShapes(e.shape,t),r=N.sizeFromShape(i),o=e.as2D(-1,r),a=Mp(e.dtype);return this.reduce(o,"prod",a).reshape(n)}unsortedSegmentSum(e,t,s){let n=0;const i=U.getAxesPermutation([n],e.rank);let r=e;i!=null&&(r=se(e,i),n=U.getInnerMostAxes(1,e.rank)[0]);const o=x1.computeOutShape(r.shape,n,s),a=N.sizeFromShape([r.shape[n]]),l=r.as2D(-1,a),c=Mp(e.dtype);let p=this.segOpCompute(l,"unsortedSegmentSum",t,c,s).reshape(o);return i!=null&&(p=se(p,U.getUndoAxesPermutation(i))),p}segOpCompute(e,t,s,n,i){const r=e.shape[0],o=e.shape[1],a=x1.segOpComputeOptimalWindowSize(o,i),l={windowSize:a,inSize:o,batchSize:r,numSegments:i},c=new DO(l,t),p=this.compileAndRun(c,[e,s],n);return p.shape[1]===i?p:(s=$i(0,i).tile([o/a]),this.segOpCompute(p,t,s,n,i))}argMinMaxReduce(e,t,s){const n=[t];if(U.assertAxesAreInnerMostDims("arg"+s.charAt(0).toUpperCase()+s.slice(1),n,e.rank),!W().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){const[i,r]=U.computeOutAndReduceShapes(e.shape,n),o=N.sizeFromShape(r),a=e.as2D(-1,o);return this.argReduce(a,s).reshape(i)}return this.argReducePacked(e,s)}argMin(e,t){return this.argMinMaxReduce(e,t,"min")}argMax(e,t){return this.argMinMaxReduce(e,t,"max")}cumsum(e,t,s,n){if(t!==e.rank-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${e.rank-1} but got axis=${t}`);const i=e.shape[t];let r=e;for(let o=0;o<=Math.ceil(Math.log2(i))-1;o++){const a=new _x(e.shape,!1,n),l=a.getCustomSetupFunc(o),c=r;r=this.compileAndRun(a,[r],r.dtype,l),c.dispose()}if(s){const o=new _x(e.shape,s,n),a=r;r=this.compileAndRun(o,[r]),a.dispose()}return r}equal(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,d2,"bool");const s=new kt(ZR,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}notEqual(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,m2,"bool");const s=new kt(QR,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}less(e,t){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.less(e,t));if(s)return s;if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,f2,"bool");const n=new kt(e2,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}lessEqual(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,g2,"bool");const s=new kt(t2,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}greater(e,t){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.greater(e,t));if(s)return s;if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,y2,"bool");const n=new kt(s2,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}greaterEqual(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,b2,"bool");const s=new kt(n2,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}logicalNot(e){const t=new $e(e.shape,f1);return this.compileAndRun(t,[e])}logicalAnd(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,w2,"bool");const s=new kt(i2,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}logicalOr(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,x2,"bool");const s=new kt(r2,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}select(e,t,s){const n=new FO(e.rank,t.shape,t.rank);return this.compileAndRun(n,[e,t,s],Ft(t.dtype,s.dtype))}where(e){U.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return VV(e.shape,t)}topk(e,t,s){const n=e.dataSync();return jV(n,e.shape,e.dtype,t,s)}min(e,t){U.assertAxesAreInnerMostDims("min",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=N.sizeFromShape(n),r=e.as2D(-1,i);return this.reduce(r,"min",r.dtype).reshape(s)}minimum(e,t){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.minimum(e,t));if(s)return s;const n=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Li(S2,e.shape,t.shape):new kt(a2,e.shape,t.shape);return this.compileAndRun(n,[e,t])}mod(e,t){const s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Li(I2,e.shape,t.shape):new kt(l2,e.shape,t.shape);return this.compileAndRun(s,[e,t])}maximum(e,t){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.maximum(e,t));if(s)return s;const n=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Li(L2,e.shape,t.shape):new kt(o2,e.shape,t.shape);return this.compileAndRun(n,[e,t])}all(e,t){U.assertAxesAreInnerMostDims("all",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=N.sizeFromShape(n),r=e.as2D(-1,i);return this.reduce(r,"all",r.dtype).reshape(s)}any(e,t){U.assertAxesAreInnerMostDims("any",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=N.sizeFromShape(n),r=e.as2D(-1,i);return this.reduce(r,"any",r.dtype).reshape(s)}floorDiv(e,t){const s=XR,n="int32";if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,p2,n);const i=new kt(s,e.shape,t.shape);return this.compileAndRun(i,[e,t],n)}add(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,og);const s=Ft(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),r=this.texData.get(t.dataId),[o,a]=AR(e.shape,t.shape,i.values,r.values,s);return this.makeOutput(a,s,o)}if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,og,s);const n=new kt(og,e.shape,t.shape);return this.compileAndRun(n,[e,t],s)}packedUnaryOp(e,t,s){const n=new lc(e.shape,t);return this.compileAndRun(n,[e],s)}packedBinaryOp(e,t,s,n,i=!1){const r=new Li(s,e.shape,t.shape,i);return this.compileAndRun(r,[e,t],n)}complexSeparableBinaryOp(e,t,s){const n=this.texData.get(e.dataId),i=this.texData.get(t.dataId),[r,o]=[[n.complexTensors.real,i.complexTensors.real],[n.complexTensors.imag,i.complexTensors.imag]].map(l=>{const[c,p]=l,u=this.makeComplexComponentTensorInfo(e,c),h=this.makeComplexComponentTensorInfo(t,p),d=new kt(s,e.shape,t.shape);return this.compileAndRun(d,[u,h],Ft(c.dtype,p.dtype))}),a=this.complex(r,o);return r.dispose(),o.dispose(),a}makeComplexComponentTensorInfo(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}addN(e){if(e.length===1)return e[0];if(e.length>W().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const r=Math.floor(e.length/2),o=this.addN(e.slice(0,r)),a=this.addN(e.slice(r));return this.addN([o,a])}const t=e.map(r=>r.dtype).reduce((r,o)=>Ft(r,o)),s=e.map(r=>r.shape),n=W().getBool("WEBGL_PACK"),i=n?new WR(e[0].shape,s):new $R(e[0].shape,s);return this.compileAndRun(i,e,t)}subtract(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,ag);const s=Ft(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),r=this.texData.get(t.dataId),[o,a]=MR(e.shape,t.shape,i.values,r.values,s);return this.makeOutput(a,s,o)}if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,ag,e.dtype);const n=new kt(ag,e.shape,t.shape);return this.compileAndRun(n,[e,t],s)}pow(e,t){const s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS"),n=s?new Li(u2,e.shape,t.shape):new kt(JR,e.shape,t.shape),i=Ft(e.dtype,t.dtype);return this.compileAndRun(n,[e,t],i)}ceil(e){if(this.shouldExecuteOnCPU([e])){const s=NR(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Yx,e.dtype);const t=new $e(e.shape,Yx);return this.compileAndRun(t,[e])}floor(e){if(this.shouldExecuteOnCPU([e])){const s=OR(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Kx,e.dtype);const t=new $e(e.shape,Kx);return this.compileAndRun(t,[e])}sign(e){const t=new $e(e.shape,HO);return this.compileAndRun(t,[e])}isNaN(e){const t=new $e(e.shape,YO);return this.compileAndRun(t,[e],"bool")}isInf(e){const t=new $e(e.shape,KO);return this.compileAndRun(t,[e],"bool")}isFinite(e){const t=new $e(e.shape,XO);return this.compileAndRun(t,[e],"bool")}round(e){const t=new $e(e.shape,JO);return this.compileAndRun(t,[e])}exp(e){if(this.shouldExecuteOnCPU([e])){const s=CR(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Xx,e.dtype);const t=new $e(e.shape,Xx);return this.compileAndRun(t,[e])}expm1(e){if(this.shouldExecuteOnCPU([e])){const s=RR(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Jx,e.dtype);const t=new $e(e.shape,Jx);return this.compileAndRun(t,[e])}softmax(e,t){const s=N.parseAxisParam([t],e.shape),n=Lt(e,s),i=U.expandShapeToKeepDim(n.shape,s),r=this.subtract(e,n.reshape(i)),o=this.exp(r),a=this.sum(o,s).reshape(i);return Z(o,a)}log(e){if(this.shouldExecuteOnCPU([e])){const s=ER(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,b1,e.dtype);const t=new $e(e.shape,ZO);return this.compileAndRun(t,[e])}log1p(e){const t=new $e(e.shape,QO);return this.compileAndRun(t,[e])}sqrt(e){const t=new $e(e.shape,e1);return this.compileAndRun(t,[e])}rsqrt(e){if(this.shouldExecuteOnCPU([e])){const s=DR(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}const t=new $e(e.shape,t1);return this.compileAndRun(t,[e])}reciprocal(e){const t=new $e(e.shape,m1);return this.compileAndRun(t,[e])}relu(e){let t;return W().getBool("WEBGL_PACK")?t=new lc(e.shape,Zx):t=new $e(e.shape,Vx),this.compileAndRun(t,[e])}relu6(e){let t;return W().getBool("WEBGL_PACK")?t=new lc(e.shape,Qx):t=new $e(e.shape,Gx),this.compileAndRun(t,[e])}prelu(e,t){const s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Li(Cx,e.shape,t.shape):new kt(Nx,e.shape,t.shape);return this.compileAndRun(s,[e,t])}elu(e){if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,eL,e.dtype);const t=new $e(e.shape,qx);return this.compileAndRun(t,[e])}eluDer(e,t){const s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Li(h2,e.shape,t.shape):new kt(c2,e.shape,t.shape);return this.compileAndRun(s,[e,t])}selu(e){const t=new $e(e.shape,GO);return this.compileAndRun(t,[e])}int(e){const t=new $e(e.shape,g1);return this.compileAndRun(t,[e],"int32")}clip(e,t,s){let n;W().getBool("WEBGL_PACK_CLIP")?n=new T2(e.shape):n=new v2(e.shape);const i=n.getCustomSetupFunc(t,s);return this.compileAndRun(n,[e],null,i)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){const s=TR(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,jx,e.dtype);const t=new $e(e.shape,jx);return this.compileAndRun(t,[e])}complexAbs(e){const t=this.texData.get(e.dataId),s=new A2(e.shape),n=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(s,n)}sigmoid(e){const t=new $e(e.shape,s1);return this.compileAndRun(t,[e])}softplus(e){const t=new $e(e.shape,n1);return this.compileAndRun(t,[e])}asin(e){const t=new $e(e.shape,i1);return this.compileAndRun(t,[e])}acos(e){const t=new $e(e.shape,r1);return this.compileAndRun(t,[e])}atan(e){const t=new $e(e.shape,o1);return this.compileAndRun(t,[e])}sinh(e){const t=new $e(e.shape,a1);return this.compileAndRun(t,[e])}cosh(e){const t=new $e(e.shape,l1);return this.compileAndRun(t,[e])}tanh(e){const t=new $e(e.shape,c1);return this.compileAndRun(t,[e])}asinh(e){const t=new $e(e.shape,p1);return this.compileAndRun(t,[e])}acosh(e){const t=new $e(e.shape,u1);return this.compileAndRun(t,[e])}atanh(e){const t=new $e(e.shape,h1);return this.compileAndRun(t,[e])}erf(e){const t=new $e(e.shape,d1);return this.compileAndRun(t,[e])}step(e,t){const s=new $e(e.shape,qO(t));return this.compileAndRun(s,[e])}conv2dByMatMul(e,t,s,n,i,r){const o=e.shape,a=this.texData.get(e.dataId),l=s.inChannels,c=o[0]*o[1]*o[2],p=s.outChannels,u=s.dataFormat==="channelsLast",h=!1,d=!1,m=(c===1||p===1)&&l>L1,f=o[2]%2!==0&&!!a.isPacked;if(m||!W().getBool("WEBGL_LAZILY_UNPACK")||!W().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!f){const _=u?o[0]*o[1]*o[2]:o[0]*o[2]*o[3],E=O(e,[1,_,s.inChannels]),F=O(t,[1,s.inChannels,s.outChannels]),D=this.fusedBatchMatMul({a:E,b:F,transposeA:h,transposeB:d,bias:n,activation:i,preluActivationWeights:r});return O(D,s.outShape)}const g=u?o[0]*o[1]*(o[2]+1):o[0]*o[2]*(o[3]+1),y={dataId:e.dataId,shape:[1,g,s.inChannels],dtype:e.dtype},w=a.shape;a.shape=a.shape.slice(),a.shape[a.shape.length-2]++,N.assert(sc(a.shape,y.shape),()=>`packed reshape ${a.shape} to ${y.shape} isn't free`);const x=O(t,[1,s.inChannels,s.outChannels]),T=this.fusedBatchMatMul({a:y,b:x,transposeA:h,transposeB:d,bias:n,activation:i,preluActivationWeights:r}),A=this.texData.get(T.dataId);return N.assert(A.isPacked,()=>"batchMatMul result is expected to be packed"),a.shape=w,A.shape=s.outShape,Us().makeTensorFromDataId(T.dataId,s.outShape,T.dtype)}conv2dWithIm2Row(e,t,s,n,i,r){const{filterWidth:o,filterHeight:a,inChannels:l,outWidth:c,outHeight:p,dataFormat:u}=s,h=u==="channelsLast",d=o*a*l,m=p*c,f=[d,m],g=!0,y=!1,w=e.squeeze([0]),x=t.reshape([1,d,-1]),T=new gO(f,w.shape,s),A=this.compileAndRun(T,[w]).reshape([1,f[0],f[1]]),_=n!=null,E=r!=null,F=i?fg(i,!0):null,D=new pg(A.shape,[1,m,s.outChannels],g,y,_,F,E),M=[A,x];n&&M.push(n),E&&M.push(r);const P=this.compileAndRun(D,M);return h?P.reshape([1,p,c,s.outChannels]):P.reshape([1,s.outChannels,p,c])}fusedConv2d({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){if(s.filterHeight===1&&s.filterWidth===1&&s.dilationHeight===1&&s.dilationWidth===1&&s.strideHeight===1&&s.strideWidth===1&&(s.padInfo.type==="SAME"||s.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,s,n,i,r);if(W().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,s,n,i,r);const o=n!=null,a=r!=null,l=i?fg(i,!1):null,c=new Rx(s,o,l,a),p=[e,t];return n&&p.push(n),r&&p.push(r),this.compileAndRun(c,p)}conv2d(e,t,s){if(s.filterHeight===1&&s.filterWidth===1&&s.dilationHeight===1&&s.dilationWidth===1&&s.strideHeight===1&&s.strideWidth===1&&(s.padInfo.type==="SAME"||s.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,s);if(W().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,s);const n=new Rx(s);return this.compileAndRun(n,[e,t])}conv2dDerInput(e,t,s){const n=new O2(s);return this.compileAndRun(n,[e,t])}conv2dDerFilter(e,t,s){const n=new R2(s);return this.compileAndRun(n,[e,t])}fusedDepthwiseConv2D({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){const o=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&s.strideWidth<=2&&s.outChannels/s.inChannels===1,a=i?fg(i,o):null,l=[e,t],c=n!=null,p=r!=null;c&&l.push(n),p&&l.push(r);let u;return o?(u=new Ex(s,c,a,p),this.compileAndRun(u,l)):(u=new Ox(s,c,a,p),this.compileAndRun(u,l))}depthwiseConv2D(e,t,s){let n;return W().getBool("WEBGL_PACK_DEPTHWISECONV")&&s.strideWidth<=2&&s.outChannels/s.inChannels===1?(n=new Ex(s),this.compileAndRun(n,[e,t])):(n=new Ox(s),this.compileAndRun(n,[e,t]))}depthwiseConv2DDerInput(e,t,s){const n=new D2(s);return this.compileAndRun(n,[e,t])}depthwiseConv2DDerFilter(e,t,s){const n=new k2(s);return this.compileAndRun(n,[e,t])}conv3d(e,t,s){const n=new F2(s);return this.compileAndRun(n,[e,t])}conv3dDerInput(e,t,s){const n=new _2(s);return this.compileAndRun(n,[e,t])}conv3dDerFilter(e,t,s){const n=new E2(s);return this.compileAndRun(n,[e,t])}cast(e,t){return U.castTensor(e,t,this)}unstack(e,t){const s=e.shape[t],n=new Array(e.rank-1);let i=0;for(let l=0;l<e.rank;l++)l!==t&&(n[i++]=e.shape[l]);const r=new Array(e.rank).fill(0),o=e.shape.slice();o[t]=1;const a=new Array(s);for(let l=0;l<a.length;l++)r[t]=l,a[l]=this.slice(e,r,o).reshape(n);return a}avgPool3d(e,t){const s=new ug(t,"avg",!1);return this.compileAndRun(s,[e],"float32")}avgPool3dBackprop(e,t,s){const n=new YR(s);return this.compileAndRun(n,[e],t.dtype)}maxPool3d(e,t){const s=new ug(t,"max",!1);return this.compileAndRun(s,[e],"float32")}maxPool3dBackprop(e,t,s,n){const i=!0,r=new ug(n,"max",i),o=this.compileAndRun(r,[t]),a=new LO(n),l=this.compileAndRun(a,[e,o],t.dtype);return o.dispose(),l}resizeBilinear(e,t,s,n){const i=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new RO(e.shape,t,s,n):new CO(e.shape,t,s,n);return this.compileAndRun(i,[e],"float32")}resizeBilinearBackprop(e,t,s){const n=new NO(e,t,s);return this.compileAndRun(n,[e])}resizeNearestNeighbor(e,t,s,n){const i=new EO(e.shape,t,s,n);return this.compileAndRun(i,[e])}resizeNearestNeighborBackprop(e,t,s){const n=new OO(e,t,s);return this.compileAndRun(n,[e])}multinomial(e,t,s,n){const i=t?e:ts(e),r=i.shape[0],o=i.shape[1],a=new SO(r,o,s),l=a.getCustomSetupFunc(n);return this.compileAndRun(a,[i],"int32",l)}oneHot(e,t,s,n){const i=new IO(e.size,t,s,n);return this.compileAndRun(i,[e])}diag(e){const t=new B2(e.size);return this.compileAndRun(t,[e])}cropAndResize(e,t,s,n,i,r){const o=new M2(e.shape,t.shape,n,i,r);return this.compileAndRun(o,[e,t,s],"float32")}depthToSpace(e,t,s){N.assert(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`);const n=e.shape[0],i=s==="NHWC"?e.shape[1]:e.shape[2],r=s==="NHWC"?e.shape[2]:e.shape[3],o=s==="NHWC"?e.shape[3]:e.shape[1],a=i*t,l=r*t,c=o/(t*t),p=s==="NHWC"?[n,a,l,c]:[n,c,a,l],u=new P2(p,t,s);return this.compileAndRun(u,[e])}split(e,t,s){return PV(e,t,s)}scatterND(e,t,s){const{sliceRank:n,numUpdates:i,sliceSize:r,strides:o,outputSize:a}=U.calculateShapes(t,e,s),l=[a/r,r],c=e.reshape([i,n]),p=t.reshape([i,r]);if(a===0)return U.reshapeTensor(ze([]),s);const u=j(0),h=new Px(i,n,c.rank,p.rank,o,l),d=this.compileAndRun(h,[p,c,u]);return d.reshape(s)}sparseToDense(e,t,s,n){const{sliceRank:i,numUpdates:r,strides:o,outputSize:a}=U.calculateShapes(t,e,s),l=!1,c=new Px(r,i,e.rank,t.rank,o,[a,1],l),p=this.compileAndRun(c,[t,e,n]);return p.reshape(s)}fft(e){const t=!1;return this.fftImpl(e,t)}ifft(e){const t=!0;return this.fftImpl(e,t)}fftImpl(e,t){const s=this.texData.get(e.dataId),n=new Dx(kx.REAL,e.shape,t),i=new Dx(kx.IMAG,e.shape,t),r=[this.makeComplexComponentTensorInfo(e,s.complexTensors.real),this.makeComplexComponentTensorInfo(e,s.complexTensors.imag)],o=this.compileAndRun(n,r),a=this.compileAndRun(i,r),l=this.complex(o,a).as2D(e.shape[0],e.shape[1]);return o.dispose(),a.dispose(),l}gatherND(e,t){const s=t.shape,n=s[s.length-1],[i,r,o,a]=U.prepareAndValidate(e,t),l=t.reshape([r,n]),c=e.reshape([e.size/o,o]),p=new K2(n,a,[r,o]),u=this.compileAndRun(p,[c,l]);return u.reshape(i)}fill(e,t,s){if(s=s||N.inferDtype(t),s==="string"){const n=N.getArrayFromDType(s,N.sizeFromShape(e));return n.fill(t),Us().makeTensor(n,e,s,this)}else{const n=new H2(e,t),i=n.getCustomSetupFunc(t);return this.compileAndRun(n,[],s,i)}}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)}zerosLike(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)}linspace(e,t,s){return U.linspaceImpl(e,t,s)}makeTensorInfo(e,t,s){const n=this.write(s,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}}makeOutput(e,t,s){const{dataId:n}=this.makeTensorInfo(e,t,s);return Us().makeTensorFromDataId(n,e,t,this)}unpackTensor(e){const t=new w1(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new vO(e.shape),s=!0;return this.runWebGLProgram(t,[e],e.dtype,null,s)}packedReshape(e,t){const s=[Lo(e.shape),...So(e.shape)],n={dtype:e.dtype,shape:s,dataId:e.dataId},i=[Lo(t),...So(t)],r=new dg(i,s),o=!0,a=this.runWebGLProgram(r,[n],e.dtype,null,o);return{dataId:a.dataId,shape:t,dtype:a.dtype}}decode(e){const t=this.texData.get(e),{isPacked:s,shape:n,dtype:i}=t,r=sg(n);let o;s?o=new z2(r):o=new W2(r);const a=!0,l=this.runWebGLProgram(o,[{shape:r,dtype:i,dataId:e}],i,null,a);return{dtype:i,shape:n,dataId:l.dataId}}runWebGLProgram(e,t,s,n,i=!1){const r=this.makeTensorInfo(e.outputShape,s),o=this.texData.get(r.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===wo.DENSE){const m=xo(e.outputShape);o.texShape=m.map(f=>f*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),N.sizeFromShape(r.shape)===0)return o.values=N.getTypedArrayFromDType(r.dtype,0),r;const a=[],l=t.map(m=>{if(m.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let f=this.texData.get(m.dataId);if(f.texture==null){if(!e.packedInputs&&N.sizeFromShape(m.shape)<=W().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:m.shape,texData:null,isUniform:!0,uniformValues:f.values};e.packedInputs&&(f.isPacked=!0,f.shape=m.shape)}else if(!!f.isPacked!==!!e.packedInputs)m=f.isPacked?this.unpackTensor(m):this.packTensor(m),a.push(m),f=this.texData.get(m.dataId);else if(f.isPacked&&!sc(f.shape,m.shape)){const g=m,y=m.shape;m.shape=f.shape,m=this.packedReshape(m,y),a.push(m),f=this.texData.get(m.dataId),g.shape=y}return this.uploadToGPU(m.dataId),{shape:m.shape,texData:f,isUniform:!1}});this.uploadToGPU(r.dataId);const c={shape:r.shape,texData:o,isUniform:!1},p=fO(e,l,c),u=this.getAndSaveBinary(p,()=>hO(this.gpgpu,e,l,c)),h=this.activeTimers!=null;let d;if(h&&(d=this.startTimer()),mO(this.gpgpu,u,l,c,n),a.forEach(m=>this.disposeIntermediateTensorInfo(m)),h&&(d=this.endTimer(d),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(d)})),!W().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&i===!1){const m=this.unpackTensor(r);return this.disposeIntermediateTensorInfo(r),m}return r}compileAndRun(e,t,s,n,i=!1){s=s||t[0].dtype;const r=this.runWebGLProgram(e,t,s,n,i);return Us().makeTensorFromDataId(r.dataId,r.shape,r.dtype)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(this.disposed)return;if(!W().getBool("IS_TEST")){const e=Object.keys(this.binaryCache);e.forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]})}this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=C(()=>{if(!W().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=W().getBool("DEBUG");W().set("DEBUG",!1);const t=this.abs(j(1e-8)).dataSync()[0];if(W().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?GV:qV}uploadToGPU(e){const t=this.texData.get(e),{shape:s,dtype:n,values:i,texture:r,usage:o,isPacked:a}=t;if(r!=null)return;const l=this.activeTimers!=null;let c;l&&(c=N.now());let p=t.texShape;if(p==null&&(p=bR(s,a),t.texShape=p),i!=null){const u=sg(s);let h,d=p[1],m=p[0];const f=i instanceof Uint8Array;a?([d,m]=wi(p[0],p[1]),h=new q2(u,[m,d],f)):h=new G2(u,[m,d],f);const g=this.makeTensorInfo([m,d],n);f?this.texData.get(g.dataId).usage=is.PIXELS:this.texData.get(g.dataId).usage=is.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),d,m,i);const y=!0,w=this.runWebGLProgram(h,[g],n,null,y),x=this.texData.get(w.dataId);t.texture=x.texture,t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(w.dataId),t.values=null,l&&(this.uploadWaitMs+=N.now()-c)}else{const u=this.acquireTexture(p,o,n,a);t.texture=u}}convertAndCacheOnCPU(e,t){const s=this.texData.get(e),{dtype:n}=s;return this.releaseGPUData(e),t!=null&&(s.values=JV(t,n)),s.values}acquireTexture(e,t,s,n){if(this.numBytesInGPU+=this.computeBytes(e,s),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){const i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${i} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,n)}computeBytes(e,t){return e[0]*e[1]*N.bytesPerElement(t)}tryRunOnCpuOrThrow(e,t){if(this.shouldExecuteOnCPU(e))try{return t()}catch(s){if(W().getBool("IS_TEST"))throw new Error("CPU forwarding failed")}return null}}function JV(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){const s=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let n=0;n<s.length;++n)s[n]=Math.round(e[n]);return s}else throw new Error(`Unknown dtype ${t}`)}const sL="2.6.0";function S1(){W().set("WEBGL_FORCE_F16_TEXTURES",!0)}rl.isBrowser()&&Vp("webgl",()=>new tL,2);const d5e={forceHalfFloat:S1};const gg="if (isnan(x)) return x;",I1=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,v1=`
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;function Io(e){return({inputs:t,backend:s})=>{const{x:n}=t,i=s,r=new $e(n.shape,e);return i.runWebGLProgram(r,[n],n.dtype)}}function cc(e,t,s,n){return({inputs:i,backend:r})=>{const{a:o,b:a}=i,l=r,c=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Li(t,o.shape,a.shape,!!s):new kt(e,o.shape,a.shape),p=n||o.dtype,u=l.runWebGLProgram(c,[o,a],p);return u}}const ZV=I1+`
return atan(a, b);
`,QV=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+v1+`
return result;
`,eG=cc(ZV,QV),T1={kernelName:ko,backendName:"webgl",kernelFunc:eG};function zu(e){const{inputs:t,backend:s}=e,{x:n}=t;return s.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}const A1={kernelName:Ci,backendName:"webgl",kernelFunc:zu};function tG(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;xi(i,"avgPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))return zu({inputs:{x:i},backend:s});const u=new Zi(p,"avg",!1);return s.runWebGLProgram(u,[i],"float32")}const N1={kernelName:Ti,backendName:"webgl",kernelFunc:tG};function sG(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r}=t,o=r;xi([i,r],"avgPoolBackprop");const{filterSize:a,strides:l,pad:c}=n,p=U.computePool2DInfo(o.shape,a,l,1,c),u=new HR(p);return s.runWebGLProgram(u,[i],o.dtype)}const C1={kernelName:Do,backendName:"webgl",kernelFunc:sG};class R1{constructor(e,t,s,n,i,r){this.outputShape=[],this.variableNames=["x","mean","variance"],U.assertAndGetBroadcastShape(e,t),U.assertAndGetBroadcastShape(e,s);let o="0.0";n!=null&&(U.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let a="1.0";i!=null&&(U.assertAndGetBroadcastShape(e,i),this.variableNames.push("scale"),a="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${o};
float scale = ${a};
float inv = scale * inversesqrt(variance + float(${r}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}}class O1{constructor(e,t,s,n,i,r){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],U.assertAndGetBroadcastShape(e,t),U.assertAndGetBroadcastShape(e,s);let o="vec4(0.0)";n!=null&&(U.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let a="vec4(1.0)";i!=null&&(U.assertAndGetBroadcastShape(e,i),this.variableNames.push("scale"),a="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
vec4 offset = ${o};
vec4 scale = ${a};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${r}));
setOutput((x - mean) * inv + offset);
}
`}}const nG=({inputs:e,backend:t,attrs:s})=>{const{x:n,mean:i,variance:r,offset:o,scale:a}=e;N.assert(i.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),N.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),N.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=s;l==null&&(l=.001);const c=[n,i,r];let p=null;o!=null&&(p=o.shape,c.push(o));let u=null;a!=null&&(u=a.shape,c.push(a));const h=W().getBool("WEBGL_PACK_NORMALIZATION")?new O1(n.shape,i.shape,r.shape,p,u,l):new R1(n.shape,i.shape,r.shape,p,u,l),d=t.runWebGLProgram(h,c,c[0].dtype);return d},E1={kernelName:Ni,backendName:"webgl",kernelFunc:nG};const iG=gg+`
return cos(x);
`,rG=Io(iG),_1={kernelName:Qn,backendName:"webgl",kernelFunc:rG};const oG=`
if (a == b) {
return 1.0;
};
return a / b;`,aG=`
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
`,lG=cc(oG,aG,!0),k1={kernelName:ei,backendName:"webgl",kernelFunc:lG};class D1{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
`}}const F1={kernelName:Uo,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:s}=e,n=t,i=new D1(s.shape),r=n.runWebGLProgram(i,[s],s.dtype);return r}};class M1{constructor(e){this.variableNames=["A"];const t=ct(),[s,n]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}.0, ${s}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`}}class U1{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=ct(),[s,n]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}.0, ${s}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
}
`}}const $1={kernelName:Xa,backendName:"webgl",kernelFunc:cG};let pc;function cG(e){const{inputs:t,backend:s,attrs:n}=e;let{pixels:i}=t;const{numChannels:r}=n,o=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,a=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,[l,c]=o?[i.videoWidth,i.videoHeight]:[i.width,i.height],p=[c,l],u=[c,l,r];(a||o)&&(pc==null&&(pc=document.createElement("canvas").getContext("2d")),pc.canvas.width=l,pc.canvas.height=c,pc.drawImage(i,0,0,l,c),i=pc.canvas);const h=s.makeTensorInfo(p,"int32");s.texData.get(h.dataId).usage=is.PIXELS,s.gpgpu.uploadPixelDataToTexture(s.getTexture(h.dataId),i);const d=W().getBool("WEBGL_PACK")?new U1(u):new M1(u),m=s.runWebGLProgram(d,[h],"int32");return s.disposeData(h.dataId),m}function pG(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const s=t.length?t[t.length-1].outSize:e[1],n=U.computeOptimalWindowSize(s);t.push({inSize:s,windowSize:n,outSize:Math.ceil(s/n)})}return t}function W1(e,t,s,n){const i=pG(e.shape);let r=e;for(let o=0;o<i.length;o++){const{inSize:a,windowSize:l,outSize:c}=i[o],p=new hg({windowSize:l,inSize:a,batchSize:e.shape[0],outSize:c},s),u=r;r=n.runWebGLProgram(p,[r],t),u.dataId!==e.dataId&&n.disposeData(u.dataId)}return r}function z1(e,t,s){const n=[Lo(e.shape),...So(e.shape)],i={dtype:e.dtype,shape:n,dataId:e.dataId},r=[Lo(t),...So(t)],o=new dg(r,n),a=!0,l=s.runWebGLProgram(o,[i],e.dtype,null,a);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function yg(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{shape:r}=n,o=s,a=N.sizeFromShape(i.shape),l=N.inferFromImplicitShape(r,a),c=N.sizeFromShape(l);N.assert(a===c,()=>`The new shape (${l}) has ${c} elements and the old shape (${i.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);const p=o.texData.get(i.dataId);return p.isPacked&&!sc(i.shape,l)&&!(p.texture!==null&&sc(p.shape,l))?z1(i,l,o):(o.incRef(i.dataId),{dataId:i.dataId,shape:l,dtype:i.dtype})}const P1={kernelName:Ei,backendName:"webgl",kernelFunc:yg};function B1(e,t,s,n){const i=N.sizeFromShape(t),r=N.sizeFromShape(e.shape),o=r/i,a=yg({inputs:{x:e},attrs:{shape:[o,i]},backend:n}),l=W1(a,e.dtype,"max",n),c=yg({inputs:{x:l},attrs:{shape:s},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(l),c}class j1{constructor(e,t){this.variableNames=["A"];const s=new Array(e.length);for(let r=0;r<s.length;r++)s[r]=e[t[r]];this.outputShape=s,this.rank=s.length;const n=Re(this.rank),i=uG(t);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function uG(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const s=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t);for(let i=0;i<e.length;i++)n[e[i]]=s[i];return n.join()}class V1{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const s=new Array(e.length);for(let c=0;c<s.length;c++)s[c]=e[t[c]];if(this.outputShape=s,this.rank=s.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const n=Re(this.rank),i=Ix("rc",this.rank),r=new Array(this.rank);for(let c=0;c<t.length;c++)r[t[c]]=i[c];const o=`vec2(${r.slice(-2).join()})`,a=`++${i[this.rank-1]} < ${s[this.rank-1]}`,l=`getChannel(getA(${r.join()}), ${o})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${l};
if(${a}) {
result[1] = ${l};
}
--${i[this.rank-1]};
if(++${i[this.rank-2]} < ${s[this.rank-2]}) {
result[2] = ${l};
if(${a}) {
result[3] = ${l};
}
}
setOutput(result);
}
`}}function bg(e,t,s){const n=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new V1(e.shape,t):new j1(e.shape,t);return s.runWebGLProgram(n,[e],e.dtype)}const G1={kernelName:Ri,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{reductionIndices:i,keepDims:r}=t,o=s,a=n.shape.length,l=N.parseAxisParam(i,n.shape);let c=l;const p=U.getAxesPermutation(c,a),u=p!=null,h=o.shouldExecuteOnCPU([n]);let d=n;if(u){if(h){const w=o.texData.get(d.dataId),x=w.values,T=new Array(a);for(let E=0;E<T.length;E++)T[E]=n.shape[p[E]];const A=ig(x,n.shape,n.dtype,p,T);d=o.makeTensorInfo(T,n.dtype);const _=o.texData.get(d.dataId);_.values=A}else d=bg(n,p,o);c=U.getInnerMostAxes(c.length,a)}U.assertAxesAreInnerMostDims("max",c,a);const[m,f]=U.computeOutAndReduceShapes(d.shape,c);let g=m;r&&(g=U.expandShapeToKeepDim(m,l));let y;if(h){const w=o.texData.get(d.dataId),x=w.values,T=_R(x,N.sizeFromShape(f),g,n.dtype);y=o.makeTensorInfo(g,n.dtype);const A=o.texData.get(y.dataId);A.values=T}else y=B1(d,f,g,o);return u&&o.disposeIntermediateTensorInfo(d),y}};function hG(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;xi(i,"maxPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))return zu({inputs:{x:i},backend:s});const u=new Zi(p,"max",!1);return s.runWebGLProgram(u,[i],i.dtype)}const q1={kernelName:Oi,backendName:"webgl",kernelFunc:hG};function dG(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r,output:o}=t,a=r;xi([r,o],"maxPoolBackprop");const{filterSize:l,strides:c,pad:p,dimRoundingMode:u}=n,h=U.computePool2DInfo(a.shape,l,c,1,p,u),d=!0,m=new Zi(h,"max",d),f=s.runWebGLProgram(m,[a],a.dtype),g=new xO(h),y=s.runWebGLProgram(g,[i,f],a.dtype);return s.disposeIntermediateTensorInfo(f),y}const H1={kernelName:$o,backendName:"webgl",kernelFunc:dG};function Y1(e,t,s,n){let i=new Zi(s,"max",!1);const r=n.runWebGLProgram(i,[e],"float32");i=new Zi(s,"max",!0,!0,t);const o=n.runWebGLProgram(i,[e],"float32");return[r,o]}const K1={kernelName:Wo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{filterSize:i,strides:r,pad:o,includeBatchInIndex:a}=t,l=s;N.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);const c=[1,1];N.assert(U.eitherStridesOrDilationsAreOne(r,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${c}'`);const p=U.computePool2DInfo(n.shape,i,r,c,o),[u,h]=Y1(n,a,p,l);return[u,h]}};const X1={kernelName:cp,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a}=s,l=t,c=l.readSync(n.dataId),p=l.readSync(i.dataId),u=r,h=o,d=a;return vt.nonMaxSuppressionV3Impl(c,p,u,h,d)}};const mG=vt.nonMaxSuppressionV4Impl,J1={kernelName:zo,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,padToMaxOutputSize:l}=s,c=t,p=c.readSync(n.dataId),u=c.readSync(i.dataId),{selectedIndices:h,validOutputs:d}=mG(p,u,r,o,a,l);return[h,d]}};const fG=vt.nonMaxSuppressionV5Impl,Z1={kernelName:Po,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}=s,c=t,p=c.readSync(n.dataId),u=c.readSync(i.dataId),h=r,d=o,m=a,f=l,{selectedIndices:g,selectedScores:y}=fG(p,u,h,d,m,f);return[g,y]}};class Q1{constructor(e,t,s,n){this.variableNames=["Image"],this.outputShape=[];const i=e[1],r=e[2],o=Math.sin(t).toFixed(3),a=Math.cos(t).toFixed(3);this.outputShape=e;const[l,c]=U.getImageCenter(n,i,r),p=l.toFixed(3),u=c.toFixed(3);let h="";typeof s=="number"?h=`float outputValue = ${s.toFixed(2)};`:h=`
vec3 fill = vec3(${s.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - ${p}) * ${a} - (float(y) - ${u}) * ${o};
float coordYFloat = (float(x) - ${p}) * ${o} + (float(y) - ${u}) * ${a};
int coordX = int(round(coordXFloat + ${p}));
int coordY = int(round(coordYFloat + ${u}));
${h}
if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${i}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}}const eE={kernelName:Ho,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,{radians:i,fillValue:r,center:o}=t,a=s,l=new Q1(n.shape,i,r,o),c=a.runWebGLProgram(l,[n],n.dtype);return c}};const gG=gg+`
return sin(x);
`,yG=Io(gG),tE={kernelName:ti,backendName:"webgl",kernelFunc:yG};const bG="return x * x;",wG=Io(bG),sE={kernelName:Go,backendName:"webgl",kernelFunc:wG};const nE="return (a - b) * (a - b);",xG=cc(nE,nE),iE={kernelName:si,backendName:"webgl",kernelFunc:xG};const LG="return tan(x);",SG=Io(LG),rE={kernelName:ni,backendName:"webgl",kernelFunc:SG};const oE={kernelName:_i,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{perm:i}=t,r=s,o=n.shape.length,a=new Array(o);for(let c=0;c<a.length;c++)a[c]=n.shape[i[c]];let l;if(r.shouldExecuteOnCPU([n])){const c=r.texData.get(n.dataId),p=c.values,u=ig(p,n.shape,n.dtype,i,a);l=r.makeTensorInfo(a,n.dtype);const h=r.texData.get(l.dataId);h.values=u}else l=bg(n,i,r);return l}};function IG(e){const{inputs:t,attrs:s,backend:n}=e,{axis:i}=s,{x:r}=t;xi(r,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const o=n.readSync(r.dataId),{outputValues:a,outputShape:l,indices:c}=UR(o,i,r.shape,r.dtype);return[n.makeTensorInfo(l,r.dtype,a),n.makeTensorInfo([c.length],"int32",c)]}const aE={kernelName:qo,backendName:"webgl",kernelFunc:IG};const vG=[T1,N1,C1,E1,_1,k1,F1,$1,A1,G1,q1,H1,K1,X1,J1,Z1,P1,eE,tE,sE,iE,rE,oE,aE];for(const e of vG)Za(e);const lE="2.6.0";const Ju={};Ee(Ju,{Abs:()=>_o,Acos:()=>dr,Acosh:()=>mr,AdadeltaOptimizer:()=>ca,AdagradOptimizer:()=>pa,AdamOptimizer:()=>ua,AdamaxOptimizer:()=>ha,Add:()=>Zn,AddN:()=>Mc,All:()=>ty,Any:()=>sy,ArgMax:()=>Uc,ArgMin:()=>$c,Asin:()=>fr,Asinh:()=>gr,Atan:()=>yr,Atan2:()=>ko,Atanh:()=>br,AvgPool:()=>Ti,AvgPool3D:()=>Wc,AvgPool3DBackprop:()=>ny,AvgPoolBackprop:()=>Do,BatchMatMul:()=>zc,BatchToSpaceND:()=>Pc,BroadcastTo:()=>Bc,Callback:()=>fw,CallbackList:()=>Hb,Cast:()=>Ai,Ceil:()=>wr,ClipByValue:()=>xr,Complex:()=>jc,Concat:()=>Fo,Conv2D:()=>Vc,Conv2DBackpropFilter:()=>iy,Conv2DBackpropInput:()=>Gc,Conv3D:()=>qc,Conv3DBackpropFilterV2:()=>ry,Conv3DBackpropInputV2:()=>oy,Cos:()=>Qn,Cosh:()=>Lr,CropAndResize:()=>ay,Cumsum:()=>Hc,CustomCallback:()=>Kb,DataStorage:()=>Fc,DepthToSpace:()=>ly,DepthwiseConv2dNative:()=>Yc,DepthwiseConv2dNativeBackpropFilter:()=>cy,DepthwiseConv2dNativeBackpropInput:()=>py,Diag:()=>uy,Dilation2D:()=>Mo,Dilation2DBackpropFilter:()=>Ha,Dilation2DBackpropInput:()=>qa,Div:()=>ei,ENV:()=>Jg,EarlyStopping:()=>gw,Elu:()=>Sr,EluGrad:()=>hy,Environment:()=>Xg,Equal:()=>dy,Erf:()=>Ir,Exp:()=>vr,Expm1:()=>Tr,FFT:()=>Kc,Fill:()=>my,FlipLeftRight:()=>Uo,Floor:()=>Ar,FloorDiv:()=>Xc,FromPixels:()=>Xa,FusedBatchNorm:()=>Ni,FusedConv2D:()=>Ah,FusedDepthwiseConv2D:()=>Nh,GatherNd:()=>fy,GatherV2:()=>Jc,GraphModel:()=>Pw,Greater:()=>gy,GreaterEqual:()=>Zc,History:()=>Yb,IFFT:()=>Qc,Identity:()=>Ci,Imag:()=>ep,InputSpec:()=>st,IsFinite:()=>Nr,IsInf:()=>Cr,IsNan:()=>Rr,KernelBackend:()=>Eo,LRN:()=>sp,LRNBackprop:()=>Sy,LayerVariable:()=>nm,LayersModel:()=>nn,Less:()=>yy,LessEqual:()=>by,LinSpace:()=>wy,Log:()=>Or,Log1p:()=>Er,LogSoftmax:()=>tp,LogicalAnd:()=>xy,LogicalNot:()=>Ya,LogicalOr:()=>Ly,Max:()=>Ri,MaxPool:()=>Oi,MaxPool3D:()=>ip,MaxPool3DBackprop:()=>Iy,MaxPoolBackprop:()=>$o,MaxPoolWithArgmax:()=>Wo,Maximum:()=>np,Mean:()=>g_,Min:()=>rp,Minimum:()=>op,Mod:()=>ap,MomentumOptimizer:()=>da,Multiply:()=>_r,Negate:()=>lp,NonMaxSuppressionV3:()=>cp,NonMaxSuppressionV4:()=>zo,NonMaxSuppressionV5:()=>Po,NotEqual:()=>Ka,OP_SCOPE_SUFFIX:()=>Xy,OneHot:()=>up,OnesLike:()=>pp,Optimizer:()=>gs,PadV2:()=>Bo,Pool:()=>y_,Pow:()=>hp,Prelu:()=>dp,Prod:()=>vy,RMSPropOptimizer:()=>ma,RNN:()=>rn,Range:()=>Ty,Rank:()=>By,Real:()=>mp,Reciprocal:()=>kr,Reduction:()=>gt,Relu:()=>fp,Relu6:()=>bp,Reshape:()=>Ei,ResizeBilinear:()=>yp,ResizeBilinearGrad:()=>Ny,ResizeNearestNeighbor:()=>gp,ResizeNearestNeighborGrad:()=>Ay,Reverse:()=>wp,RotateWithOffset:()=>Ho,Round:()=>Dr,Rsqrt:()=>Fr,SGDOptimizer:()=>zi,ScatterNd:()=>Cy,SelectV2:()=>xp,Selu:()=>Mr,Sequential:()=>mo,Sigmoid:()=>Wr,Sign:()=>$r,Sin:()=>ti,Sinh:()=>Ur,Slice:()=>jo,Softmax:()=>Ip,Softplus:()=>zr,SpaceToBatchND:()=>Vo,SparseToDense:()=>Ry,SplitV:()=>Sp,Sqrt:()=>Pr,Square:()=>Go,SquaredDifference:()=>si,Step:()=>Vr,StridedSlice:()=>Oy,Sub:()=>Br,Sum:()=>Lp,SymbolicTensor:()=>xs,Tan:()=>ni,Tanh:()=>jr,Tensor:()=>me,TensorBuffer:()=>dn,Tile:()=>vp,TopK:()=>Ey,Transpose:()=>_i,Unique:()=>qo,Unpack:()=>Tp,UnsortedSegmentSum:()=>Ap,Variable:()=>ci,ZerosLike:()=>Np,_FusedMatMul:()=>Th,abs:()=>et,acos:()=>Uh,acosh:()=>$h,add:()=>$,addN:()=>Wh,addStrict:()=>kU,all:()=>hl,any:()=>Zo,argMax:()=>Qo,argMin:()=>zh,asin:()=>Ph,asinh:()=>Bh,atan:()=>jh,atan2:()=>Vh,atanh:()=>Gh,avgPool:()=>ds,avgPool3d:()=>ml,backend:()=>mb,backend_util:()=>U,basicLSTMCell:()=>hI,batchNorm:()=>Xs,batchNorm2d:()=>Yh,batchNorm3d:()=>Kh,batchNorm4d:()=>Xh,batchToSpaceND:()=>Yr,booleanMaskAsync:()=>uU,broadcastTo:()=>ta,browser:()=>Gr,buffer:()=>ge,callbacks:()=>$N,cast:()=>G,ceil:()=>Jh,clipByValue:()=>xt,clone:()=>Fs,complex:()=>Gt,concat:()=>be,concat1d:()=>Zh,concat2d:()=>Qh,concat3d:()=>ed,concat4d:()=>td,constraints:()=>zb,conv1d:()=>fl,conv2d:()=>rt,conv2dTranspose:()=>yl,conv3d:()=>bl,conv3dTranspose:()=>mI,copyRegisteredKernels:()=>x_,cos:()=>Kr,cosh:()=>wl,cosineWindow:()=>Jp,cumsum:()=>xl,customGrad:()=>fs,data:()=>Yw,deprecationWarn:()=>It,depthToSpace:()=>nd,depthwiseConv2d:()=>fn,deregisterOp:()=>PN,device_util:()=>rl,diag:()=>fI,dilation2d:()=>id,disableDeprecationWarnings:()=>jk,dispose:()=>ce,disposeVariables:()=>Vk,div:()=>Z,divNoNan:()=>rd,divStrict:()=>DU,dot:()=>gI,dropout:()=>Tb,elu:()=>gn,enableDebugMode:()=>Bk,enableProdMode:()=>Pk,enclosingPowerOfTwo:()=>Ab,engine:()=>Us,env:()=>W,equal:()=>as,equalStrict:()=>bU,erf:()=>od,exp:()=>ut,expandDims:()=>Mt,expm1:()=>ad,eye:()=>sa,fft:()=>so,fill:()=>Wt,findBackend:()=>Xk,findBackendFactory:()=>Jk,floor:()=>ui,floorDiv:()=>ul,fused:()=>xn,gather:()=>hi,gatherND:()=>vb,gather_util:()=>XS,getBackend:()=>Yk,getGradient:()=>Ch,getKernel:()=>Rp,getKernelsForBackend:()=>Op,grad:()=>_F,grads:()=>kF,greater:()=>Ut,greaterEqual:()=>ms,greaterEqualStrict:()=>wU,greaterStrict:()=>xU,ifft:()=>Wi,imag:()=>yn,image:()=>en,inTopKAsync:()=>XU,initializers:()=>Gb,input:()=>wm,io:()=>Rt,irfft:()=>kl,isFinite:()=>bI,isInf:()=>wI,isNaN:()=>xI,keep:()=>pt,kernel_impls:()=>vt,layers:()=>lw,leakyRelu:()=>Ll,less:()=>Xr,lessEqual:()=>Ws,lessEqualStrict:()=>LU,lessStrict:()=>SU,linalg:()=>Cb,linspace:()=>cd,loadGraphModel:()=>gC,loadLayersModel:()=>iN,localResponseNormalization:()=>pd,log:()=>zt,log1p:()=>Sl,logSigmoid:()=>LI,logSoftmax:()=>Il,logSumExp:()=>dd,logicalAnd:()=>Yt,logicalNot:()=>Jr,logicalOr:()=>vl,logicalXor:()=>SI,losses:()=>B$,matMul:()=>Te,math:()=>KS,max:()=>Lt,maxPool:()=>ft,maxPool3d:()=>Tl,maxPoolWithArgmax:()=>md,maximum:()=>Ht,maximumStrict:()=>FU,mean:()=>Xe,memory:()=>pl,metrics:()=>hw,min:()=>Ui,minimum:()=>bn,minimumStrict:()=>MU,mod:()=>Al,modStrict:()=>UU,model:()=>sN,models:()=>dw,moments:()=>na,movingAverage:()=>VU,mul:()=>R,mulStrict:()=>$U,multiRNNCell:()=>II,multinomial:()=>fd,neg:()=>ke,nextFrame:()=>Zp,norm:()=>Kp,notEqual:()=>Js,notEqualStrict:()=>IU,oneHot:()=>pi,ones:()=>Kt,onesLike:()=>Ot,op:()=>S,outerProduct:()=>vI,pad:()=>Pt,pad1d:()=>TI,pad2d:()=>AI,pad3d:()=>NI,pad4d:()=>CI,pool:()=>RI,pow:()=>es,powStrict:()=>WU,prelu:()=>Qr,print:()=>Fh,prod:()=>Nl,profile:()=>Gk,rand:()=>OI,randomGamma:()=>kI,randomNormal:()=>qp,randomUniform:()=>wn,range:()=>$i,ready:()=>Hk,real:()=>Zs,reciprocal:()=>yd,registerBackend:()=>Vp,registerCallbackConstructor:()=>rN,registerGradient:()=>ky,registerKernel:()=>Za,registerOp:()=>zN,regularizers:()=>mw,relu:()=>Fe,relu6:()=>bd,removeBackend:()=>Kk,reshape:()=>O,reverse:()=>Et,reverse1d:()=>DI,reverse2d:()=>FI,reverse3d:()=>MI,reverse4d:()=>UI,rfft:()=>no,round:()=>wd,rsqrt:()=>Cl,scalar:()=>j,scatterND:()=>Ib,scatter_util:()=>ZS,selu:()=>Rl,separableConv2d:()=>eo,sequential:()=>nN,serialization:()=>V,setBackend:()=>pI,setPlatform:()=>Zk,setdiff1dAsync:()=>xd,sigmoid:()=>os,sign:()=>Ld,signal:()=>P$,sin:()=>Ol,sinh:()=>El,slice:()=>he,slice1d:()=>_l,slice2d:()=>Hp,slice3d:()=>to,slice4d:()=>ia,slice_util:()=>Ms,softmax:()=>ts,softplus:()=>di,spaceToBatchND:()=>Zr,sparseToDense:()=>Xp,spectral:()=>z$,split:()=>Bt,sqrt:()=>Je,square:()=>xe,squaredDifference:()=>io,squaredDifferenceStrict:()=>zU,squeeze:()=>Qs,stack:()=>Ge,step:()=>mi,stridedSlice:()=>Sd,sub:()=>X,subStrict:()=>PU,sum:()=>te,sumOutType:()=>Mp,tan:()=>Id,tanh:()=>Mi,tensor:()=>ze,tensor1d:()=>Oe,tensor2d:()=>ls,tensor3d:()=>ll,tensor4d:()=>ss,tensor5d:()=>$I,tensor6d:()=>WI,tensor_util:()=>mn,test_util:()=>lI,tidy:()=>C,tile:()=>$s,time:()=>qk,topk:()=>vd,train:()=>ao,transpose:()=>se,truncatedNormal:()=>ro,unique:()=>Yp,unregisterGradient:()=>w_,unregisterKernel:()=>b_,unsortedSegmentSum:()=>Td,unstack:()=>qe,upcastType:()=>Ft,util:()=>N,valueAndGrad:()=>DF,valueAndGrads:()=>FF,variable:()=>Ad,variableGrads:()=>hd,version:()=>TG,version_converter:()=>kf,version_core:()=>db,version_layers:()=>uo,where:()=>mt,whereAsync:()=>Dl,zeros:()=>ye,zerosLike:()=>re});const TG={"tfjs-core":db,"tfjs-backend-cpu":hx,"tfjs-backend-webgl":sL,"tfjs-data":Hf,"tfjs-layers":uo,"tfjs-converter":kf,tfjs:lE};function er(e,t,s=!1){if(e.beginPath(),t.slice(1).forEach(({x:n,y:i},r)=>{const o=t[r];e.moveTo(o.x,o.y),e.lineTo(n,i)}),s){const n=t[t.length-1],i=t[0];if(!n||!i)return;e.moveTo(n.x,n.y),e.lineTo(i.x,i.y)}e.stroke()}class Ts{constructor(e,t){if(!Yn(e)||!Yn(t))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:e,height:t})}`);this._width=e,this._height=t}get width(){return this._width}get height(){return this._height}reverse(){return new Ts(1/this.width,1/this.height)}}const Qu={};Ee(Qu,{computeReshapedDimensions:()=>rL,getCenterPoint:()=>Ra,isDimensions:()=>xg,isEven:()=>wg,isFloat:()=>iL,isTensor:()=>Na,isTensor1D:()=>AG,isTensor2D:()=>nL,isTensor3D:()=>tr,isTensor4D:()=>ln,isValidNumber:()=>Yn,isValidProbablitiy:()=>uc,range:()=>Si,round:()=>Ca});function Na(e,t){return e instanceof me&&e.shape.length===t}function AG(e){return Na(e,1)}function nL(e){return Na(e,2)}function tr(e){return Na(e,3)}function ln(e){return Na(e,4)}function iL(e){return e%1!==0}function wg(e){return e%2===0}function Ca(e,t=2){const s=Math.pow(10,t);return Math.floor(e*s)/s}function xg(e){return e&&e.width&&e.height}function rL({width:e,height:t},s){const n=s/Math.max(t,e);return new Ts(Math.round(e*n),Math.round(t*n))}function Ra(e){return e.reduce((t,s)=>t.add(s),new _e(0,0)).div(new _e(e.length,e.length))}function Si(e,t,s){return Array(e).fill(0).map((n,i)=>t+i*s)}function Yn(e){return!!e&&e!==Infinity&&e!==-Infinity&&!isNaN(e)||e===0}function uc(e){return Yn(e)&&0<=e&&e<=1}class _e{constructor(e,t){this._x=e,this._y=t}get x(){return this._x}get y(){return this._y}add(e){return new _e(this.x+e.x,this.y+e.y)}sub(e){return new _e(this.x-e.x,this.y-e.y)}mul(e){return new _e(this.x*e.x,this.y*e.y)}div(e){return new _e(this.x/e.x,this.y/e.y)}abs(){return new _e(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))}floor(){return new _e(Math.floor(this.x),Math.floor(this.y))}}class it{constructor(e,t=!0){const s=e||{},n=[s.left,s.top,s.right,s.bottom].every(Yn),i=[s.x,s.y,s.width,s.height].every(Yn);if(!i&&!n)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(s)}`);const[r,o,a,l]=i?[s.x,s.y,s.width,s.height]:[s.left,s.top,s.right-s.left,s.bottom-s.top];it.assertIsValidBox({x:r,y:o,width:a,height:l},"Box.constructor",t),this._x=r,this._y=o,this._width=a,this._height=l}static isRect(e){return!!e&&[e.x,e.y,e.width,e.height].every(Yn)}static assertIsValidBox(e,t,s=!1){if(!it.isRect(e))throw new Error(`${t} - invalid box: ${JSON.stringify(e)}, expected object with properties x, y, width, height`);if(!s&&(e.width<0||e.height<0))throw new Error(`${t} - width (${e.width}) and height (${e.height}) must be positive numbers`)}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new _e(this.left,this.top)}get topRight(){return new _e(this.right,this.top)}get bottomLeft(){return new _e(this.left,this.bottom)}get bottomRight(){return new _e(this.right,this.bottom)}round(){const[e,t,s,n]=[this.x,this.y,this.width,this.height].map(i=>Math.round(i));return new it({x:e,y:t,width:s,height:n})}floor(){const[e,t,s,n]=[this.x,this.y,this.width,this.height].map(i=>Math.floor(i));return new it({x:e,y:t,width:s,height:n})}toSquare(){let{x:e,y:t,width:s,height:n}=this;const i=Math.abs(s-n);return s<n&&(e-=i/2,s+=i),n<s&&(t-=i/2,n+=i),new it({x:e,y:t,width:s,height:n})}rescale(e){const t=xg(e)?e.width:e,s=xg(e)?e.height:e;return new it({x:this.x*t,y:this.y*s,width:this.width*t,height:this.height*s})}pad(e,t){let[s,n,i,r]=[this.x-e/2,this.y-t/2,this.width+e,this.height+t];return new it({x:s,y:n,width:i,height:r})}clipAtImageBorders(e,t){const{x:s,y:n,right:i,bottom:r}=this,o=Math.max(s,0),a=Math.max(n,0),l=i-o,c=r-a,p=Math.min(l,e-o),u=Math.min(c,t-a);return new it({x:o,y:a,width:p,height:u}).floor()}shift(e,t){const{width:s,height:n}=this,i=this.x+e,r=this.y+t;return new it({x:i,y:r,width:s,height:n})}padAtBorders(e,t){const s=this.width+1,n=this.height+1;let i=1,r=1,o=s,a=n,l=this.left,c=this.top,p=this.right,u=this.bottom;return p>t&&(o=-p+t+s,p=t),u>e&&(a=-u+e+n,u=e),l<1&&(a=2-l,l=1),c<1&&(a=2-c,c=1),{dy:r,edy:a,dx:i,edx:o,y:c,ey:u,x:l,ex:p,w:s,h:n}}calibrate(e){return new it({left:this.left+e.left*this.width,top:this.top+e.top*this.height,right:this.right+e.right*this.width,bottom:this.bottom+e.bottom*this.height}).toSquare().round()}}class Ga extends it{constructor(e,t,s,n,i=!1){super({left:e,top:t,right:s,bottom:n},i)}}class Oo{constructor(e,t,s,n,i){this._imageDims=new Ts(i.width,i.height),this._score=e,this._classScore=t,this._className=s,this._box=new it(n).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new it(this._box).rescale(this.imageDims.reverse())}forSize(e,t){return new Oo(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:t})}}class ht extends Oo{constructor(e,t,s){super(e,e,"",t,s)}forSize(e,t){const{score:s,relativeBox:n,imageDims:i}=super.forSize(e,t);return new ht(s,n,i)}}function oh(e,t,s=!0){const n=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),i=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),r=n*i;return s?r/(e.area+t.area-r):r/Math.min(e.area,t.area)}function rh(e){const t=e.map(a=>a.x),s=e.map(a=>a.y),n=t.reduce((a,l)=>l<a?l:a,Infinity),i=s.reduce((a,l)=>l<a?l:a,Infinity),r=t.reduce((a,l)=>a<l?l:a,0),o=s.reduce((a,l)=>a<l?l:a,0);return new Ga(n,i,r,o)}function ih(e,t,s,n=!0){let i=t.map((o,a)=>({score:o,boxIndex:a})).sort((o,a)=>o.score-a.score).map(o=>o.boxIndex);const r=[];for(;i.length>0;){const o=i.pop();r.push(o);const a=i,l=[];for(let c=0;c<a.length;c++){const p=a[c],u=e[o],h=e[p];l.push(oh(u,h,n))}i=i.filter((c,p)=>l[p]<=s)}return r}function un(e,t){return C(()=>{const[s,n,i]=t,r=Wt([...e.shape.slice(0,3),1],s),o=Wt([...e.shape.slice(0,3),1],n),a=Wt([...e.shape.slice(0,3),1],i),l=be([r,o,a],3);return X(e,l)})}function nh(e,t=!1){return C(()=>{const[s,n]=e.shape.slice(1);if(s===n)return e;const i=Math.abs(s-n),r=Math.round(i*(t?.5:1)),o=s>n?2:1,a=h=>{const d=e.shape.slice();return d[o]=h,Wt(d,0)},l=a(r),c=i-l.shape[o],p=t&&c?a(c):null,u=[p,e,l].filter(h=>!!h).map(h=>G(h,"float32"));return be(u,o)})}function jL(e){const t=e.slice();for(let s=t.length-1;s>0;s--){const n=Math.floor(Math.random()*(s+1)),i=t[s];t[s]=t[n],t[n]=i}return t}function $a(e){return 1/(1+Math.exp(-e))}function VL(e){return Math.log(e/(1-e))}class ja extends it{constructor(e,t,s,n,i=!1){super({x:e,y:t,width:s,height:n},i)}}const NG=.5,CG=.43,RG=.45;class Hs{constructor(e,t,s=new _e(0,0)){const{width:n,height:i}=t;this._imgDims=new Ts(n,i),this._shift=s,this._positions=e.map(r=>r.mul(new _e(n,i)).add(s))}get shift(){return new _e(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(e=>e.sub(this._shift).div(new _e(this.imageWidth,this.imageHeight)))}forSize(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})}shiftBy(e,t){return new this.constructor(this.relativePositions,this._imgDims,new _e(e,t))}shiftByPoint(e){return this.shiftBy(e.x,e.y)}align(e,t={}){if(e){const i=e instanceof ht?e.box.floor():new it(e);return this.shiftBy(i.x,i.y).align(null,t)}const{useDlibAlignment:s,minBoxPadding:n}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t);return s?this.alignDlib():this.alignMinBbox(n)}alignDlib(){const e=this.getRefPointsForAlignment(),[t,s,n]=e,i=p=>n.sub(p).magnitude(),r=(i(t)+i(s))/2,o=Math.floor(r/RG),a=Ra(e),l=Math.floor(Math.max(0,a.x-NG*o)),c=Math.floor(Math.max(0,a.y-CG*o));return new ja(l,c,Math.min(o,this.imageWidth+l),Math.min(o,this.imageHeight+c))}alignMinBbox(e){const t=rh(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class bS extends Hs{getRefPointsForAlignment(){const e=this.positions;return[e[0],e[1],Ra([e[3],e[4]])]}}class Va extends Hs{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(Ra)}}class Dc{constructor(e,t){this._label=e,this._distance=t}get label(){return this._label}get distance(){return this._distance}toString(e=!0){return`${this.label}${e?` (${Ca(this.distance)})`:""}`}}class kc extends it{constructor(e,t){super(e);this._label=t}static assertIsValidLabeledBox(e,t){if(it.assertIsValidBox(e,t),!Yn(e.label))throw new Error(`${t} - expected property label (${e.label}) to be a number`)}get label(){return this._label}}class hr{constructor(e,t){if(!(typeof e=="string"))throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(t)||t.some(s=>!(s instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=e,this._descriptors=t}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(e=>Array.from(e))}}static fromJSON(e){const t=e.descriptors.map(s=>new Float32Array(s));return new hr(e.label,t)}}class yS extends kc{constructor(e,t,s,n){super(e,t);this._score=s,this._classScore=n}static assertIsValidPredictedBox(e,t){if(kc.assertIsValidLabeledBox(e,t),!uc(e.score)||!uc(e.classScore))throw new Error(`${t} - expected properties score (${e.score}) and (${e.classScore}) to be a number between [0, 1]`)}get score(){return this._score}get classScore(){return this._classScore}}function Mn(e){return e.detection instanceof ht}function ar(e,t){const s={detection:t};return Object.assign({},e,s)}function oL(){const e=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},t=function(){throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:e,readFile:t}}function Lg(e){let t="";if(!e)try{e=require("fs")}catch(n){t=n.toString()}const s=e?function(n){return new Promise((i,r)=>{e.readFile(n,function(o,a){return o?r(o):i(a)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)};return{readFile:s}}function aL(){const e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,s=function(){if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},n=function(){if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},i=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},r=Lg();return{Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:s,createImageElement:n,fetch:i,...r}}function lL(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const cL=vc(ML());let Jt;function OG(){if(!Jt)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Jt}function pL(e){Jt=e}function uL(){if(lL())return pL(oL());if(cL.isNodejs())return pL(aL())}function EG(e){if(Jt||uL(),!Jt)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:t=Jt.Canvas,Image:s=Jt.Image}=e;Jt.Canvas=t,Jt.Image=s,Jt.createCanvasElement=e.createCanvasElement||(()=>new t),Jt.createImageElement=e.createImageElement||(()=>new s),Jt.ImageData=e.ImageData||Jt.ImageData,Jt.Video=e.Video||Jt.Video,Jt.fetch=e.fetch||Jt.fetch,Jt.readFile=e.readFile||Jt.readFile}const Ve={getEnv:OG,setEnv:pL,initialize:uL,createBrowserEnv:oL,createFileSystem:Lg,createNodejsEnv:aL,monkeyPatch:EG,isBrowser:lL,isNodejs:cL.isNodejs};uL();function cr(e){return!Ve.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function us(e){const{Canvas:t,CanvasRenderingContext2D:s}=Ve.getEnv();if(e instanceof s)return e;const n=cr(e);if(!(n instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const i=n.getContext("2d");if(!i)throw new Error("resolveContext2d - canvas 2d context is null");return i}var Ii;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Ii||(Ii={}));class Sg{constructor(e={}){const{anchorPosition:t,backgroundColor:s,fontColor:n,fontSize:i,fontStyle:r,padding:o}=e;this.anchorPosition=t||Ii.TOP_LEFT,this.backgroundColor=s||"rgba(0, 0, 0, 0.5)",this.fontColor=n||"rgba(255, 255, 255, 1)",this.fontSize=i||14,this.fontStyle=r||"Georgia",this.padding=o||4}}class hc{constructor(e,t,s={}){this.text=typeof e=="string"?[e]:e instanceof hc?e.text:e,this.anchor=t,this.options=new Sg(s)}measureWidth(e){const{padding:t}=this.options;return this.text.map(s=>e.measureText(s).width).reduce((s,n)=>s<n?n:s,0)+2*t}measureHeight(){const{fontSize:e,padding:t}=this.options;return this.text.length*e+2*t}getUpperLeft(e,t){const{anchorPosition:s}=this.options,n=s===Ii.BOTTOM_RIGHT||s===Ii.TOP_RIGHT,i=s===Ii.BOTTOM_LEFT||s===Ii.BOTTOM_RIGHT,r=this.measureWidth(e),o=this.measureHeight(),a=n?this.anchor.x-r:this.anchor.x,l=i?this.anchor.y-o:this.anchor.y;if(t){const{width:c,height:p}=t,u=Math.max(Math.min(a,c-r),0),h=Math.max(Math.min(l,p-o),0);return{x:u,y:h}}return{x:a,y:l}}draw(e){const t=cr(e),s=us(t),{backgroundColor:n,fontColor:i,fontSize:r,fontStyle:o,padding:a}=this.options;s.font=`${r}px ${o}`;const l=this.measureWidth(s),c=this.measureHeight();s.fillStyle=n;const p=this.getUpperLeft(s,t);s.fillRect(p.x,p.y,l,c),s.fillStyle=i,this.text.forEach((u,h)=>{const d=a+p.x,m=a+p.y+(h+1)*r;s.fillText(u,d,m)})}}class cE{constructor(e={}){const{boxColor:t,lineWidth:s,label:n,drawLabelOptions:i}=e;this.boxColor=t||"rgba(0, 0, 255, 1)",this.lineWidth=s||2,this.label=n;const r={anchorPosition:Ii.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Sg(Object.assign({},r,i))}}class hL{constructor(e,t={}){this.box=new it(e),this.options=new cE(t)}draw(e){const t=us(e),{boxColor:s,lineWidth:n}=this.options,{x:i,y:r,width:o,height:a}=this.box;t.strokeStyle=s,t.lineWidth=n,t.strokeRect(i,r,o,a);const{label:l}=this.options;l&&new hc([l],{x:i-n/2,y:r},this.options.drawLabelOptions).draw(e)}}function _G(e,t){const s=Array.isArray(t)?t:[t];s.forEach(n=>{const i=n instanceof ht?n.score:Mn(n)?n.detection.score:void 0,r=n instanceof ht?n.box:Mn(n)?n.detection.box:new it(n),o=i?`${Ca(i)}`:void 0;new hL(r,{label:o}).draw(e)})}function Pa(e){const{Image:t,Video:s}=Ve.getEnv();return e instanceof t&&e.complete||e instanceof s&&e.readyState>=3}function Ih(e){return new Promise((t,s)=>{if(e instanceof Ve.getEnv().Canvas||Pa(e))return t(null);function n(r){if(!r.currentTarget)return;r.currentTarget.removeEventListener("load",n),r.currentTarget.removeEventListener("error",i),t(r)}function i(r){if(!r.currentTarget)return;r.currentTarget.removeEventListener("load",n),r.currentTarget.removeEventListener("error",i),s(r)}e.addEventListener("load",n),e.addEventListener("error",i)})}function Sh(e){return new Promise((t,s)=>{if(!(e instanceof Blob))return s("bufferToImage - expected buf to be of type: Blob");const n=new FileReader;n.onload=()=>{if(typeof n.result!="string")return s("bufferToImage - expected reader.result to be a string, in onload");const i=Ve.getEnv().createImageElement();i.onload=()=>t(i),i.onerror=s,i.src=n.result},n.onerror=s,n.readAsDataURL(e)})}function pr(e){const{Image:t,Video:s}=Ve.getEnv();return e instanceof t?new Ts(e.naturalWidth,e.naturalHeight):e instanceof s?new Ts(e.videoWidth,e.videoHeight):new Ts(e.width,e.height)}function Ro({width:e,height:t}){const{createCanvasElement:s}=Ve.getEnv(),n=s();return n.width=e,n.height=t,n}function Ba(e,t){const{ImageData:s}=Ve.getEnv();if(!(e instanceof s)&&!Pa(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:n,height:i}=t||pr(e),r=Ro({width:n,height:i});return e instanceof s?us(r).putImageData(e,0,0):us(r).drawImage(e,0,0,n,i),r}async function xh(e,t){const s=t||Ve.getEnv().createCanvasElement(),[n,i,r]=e.shape.slice(ln(e)?1:0),o=C(()=>e.as3D(n,i,r).toInt());return await Gr.toPixels(o,s),o.dispose(),s}function _c(e){const{Image:t,Canvas:s,Video:n}=Ve.getEnv();return e instanceof t||e instanceof s||e instanceof n}function wh(e,t,s=!1){const{Image:n,Canvas:i}=Ve.getEnv();if(!(e instanceof n||e instanceof i))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const r=pr(e),o=t/Math.max(r.height,r.width),a=o*r.width,l=o*r.height,c=Ro({width:t,height:t}),p=e instanceof i?e:Ba(e),u=Math.abs(a-l)/2,h=s&&a<l?u:0,d=s&&l<a?u:0;return us(c).drawImage(p,h,d,a,l),c}class vi{constructor(e,t=!1){if(this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(e))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${e}`);this._treatAsBatchInput=t,this._batchSize=e.length,e.forEach((s,n)=>{if(tr(s)){this._imageTensors[n]=s,this._inputDimensions[n]=s.shape;return}if(ln(s)){const r=s.shape[0];if(r!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${r} passed, but not supported in input array`);this._imageTensors[n]=s,this._inputDimensions[n]=s.shape.slice(1);return}const i=s instanceof Ve.getEnv().Canvas?s:Ba(s);this._canvases[n]=i,this._inputDimensions[n]=[i.height,i.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return Si(this.batchSize,0,1).map((e,t)=>this.getReshapedInputDimensions(t))}getInput(e){return this.canvases[e]||this.imageTensors[e]}getInputDimensions(e){return this._inputDimensions[e]}getInputHeight(e){return this._inputDimensions[e][0]}getInputWidth(e){return this._inputDimensions[e][1]}getReshapedInputDimensions(e){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");const t=this.getInputWidth(e),s=this.getInputHeight(e);return rL({width:t,height:s},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,C(()=>{const s=Si(this.batchSize,0,1).map(i=>{const r=this.getInput(i);if(r instanceof me){let o=ln(r)?r:r.expandDims();return o=nh(o,t),(o.shape[1]!==e||o.shape[2]!==e)&&(o=en.resizeBilinear(o,[e,e])),o.as3D(e,e,3)}if(r instanceof Ve.getEnv().Canvas)return Gr.fromPixels(wh(r,e,t));throw new Error(`toBatchTensor - at batchIdx ${i}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${r}`)}),n=Ge(s.map(i=>G(i,"float32"))).as4D(this.batchSize,e,e,3);return n})}}async function nt(e){if(e instanceof vi)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");const s=i=>Array.isArray(e)?` at input index ${i}:`:"",n=t.map(cr);return n.forEach((i,r)=>{if(!_c(i)&&!tr(i)&&!ln(i))throw typeof t[r]=="string"?new Error(`toNetInput -${s(r)} string passed, but could not resolve HTMLElement for element id ${t[r]}`):new Error(`toNetInput -${s(r)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(ln(i)){const o=i.shape[0];if(o!==1)throw new Error(`toNetInput -${s(r)} tf.Tensor4D with batchSize ${o} passed, but not supported in input array`)}}),await Promise.all(n.map(i=>_c(i)&&Ih(i))),new vi(n,Array.isArray(e))}async function No(e,t){const{Canvas:s}=Ve.getEnv();let n=e;if(!(e instanceof s)){const o=await nt(e);if(o.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const a=o.getInput(0);n=a instanceof s?a:await xh(a)}const i=us(n),r=t.map(o=>o instanceof ht?o.forSize(n.width,n.height).box.floor():o).map(o=>o.clipAtImageBorders(n.width,n.height));return r.map(({x:o,y:a,width:l,height:c})=>{const p=Ro({width:l,height:c});return us(p).putImageData(i.getImageData(o,a,l,c),0,0),p})}async function Co(e,t){if(!tr(e)&&!ln(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(ln(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return C(()=>{const[s,n,i]=e.shape.slice(ln(e)?1:0),r=t.map(a=>a instanceof ht?a.forSize(n,s).box:a).map(a=>a.clipAtImageBorders(n,s)),o=r.map(({x:a,y:l,width:c,height:p})=>to(e.as3D(s,n,i),[l,a,0],[p,c,i]));return o})}async function ur(e,t){const s=Ve.getEnv().fetch,n=await s(e,t);if(!(n.status<400))throw new Error(`failed to fetch: (${n.status}) ${n.statusText}, from url: ${n.url}`);return n}async function gS(e){const t=await ur(e),s=await t.blob();if(!s.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${s.type}, for url: ${t.url}`);return Sh(s)}async function Lh(e){return(await ur(e)).json()}async function fS(e){return new Float32Array(await(await ur(e)).arrayBuffer())}function Ig(e,t){const s=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:s};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${s}`};const n=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(n,"");const i=e.split("/").filter(a=>a),r=e.endsWith(".json")?i[i.length-1]:s;let o=n+(e.endsWith(".json")?i.slice(0,i.length-1):i).join("/");return o=e.startsWith("/")?`/${o}`:o,{modelBaseUri:o,manifestUri:o==="/"?`/${r}`:`${o}/${r}`}}async function bh(e,t){const{manifestUri:s,modelBaseUri:n}=Ig(e,t);let i=await Lh(s);return Rt.loadWeights(i,n)}function mS(e,t,s=!1){const{width:n,height:i}=s?pr(t):t;return e.width=n,e.height=i,{width:n,height:i}}class Zt{constructor(e){this._name=e,this._params=void 0,this._paramMappings=[]}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(e){const{obj:t,objProp:s}=this.traversePropertyPath(e);return t[s]}reassignParamFromPath(e,t){const{obj:s,objProp:n}=this.traversePropertyPath(e);s[n].dispose(),s[n]=t}getParamList(){return this._paramMappings.map(({paramPath:e})=>({path:e,tensor:this.getParamFromPath(e)}))}getTrainableParams(){return this.getParamList().filter(e=>e.tensor instanceof ci)}getFrozenParams(){return this.getParamList().filter(e=>!(e.tensor instanceof ci))}variable(){this.getFrozenParams().forEach(({path:e,tensor:t})=>{this.reassignParamFromPath(e,t.variable())})}freeze(){this.getTrainableParams().forEach(({path:e,tensor:t})=>{const s=ze(t.dataSync());t.dispose(),this.reassignParamFromPath(e,s)})}dispose(e=!0){this.getParamList().forEach(t=>{if(e&&t.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${t.path}`);t.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:e})=>Array.from(e.dataSync())).reduce((e,t)=>e.concat(t)))}async load(e){if(e instanceof Float32Array){this.extractWeights(e);return}await this.loadFromUri(e)}async loadFromUri(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);const t=await bh(e,this.getDefaultModelName());this.loadFromWeightMap(t)}async loadFromDisk(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:t}=Ve.getEnv(),{manifestUri:s,modelBaseUri:n}=Ig(e,this.getDefaultModelName()),i=l=>Promise.all(l.map(c=>t(c).then(p=>p.buffer))),r=Rt.weightsLoaderFactory(i),o=JSON.parse((await t(s)).toString()),a=await r(o,n);this.loadFromWeightMap(a)}loadFromWeightMap(e){const{paramMappings:t,params:s}=this.extractParamsFromWeigthMap(e);this._paramMappings=t,this._params=s}extractWeights(e){const{paramMappings:t,params:s}=this.extractParams(e);this._paramMappings=t,this._params=s}traversePropertyPath(e){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");const t=e.split("/").reduce((i,r)=>{if(!i.nextObj.hasOwnProperty(r))throw new Error(`traversePropertyPath - object does not have property ${r}, for path ${e}`);return{obj:i.nextObj,objProp:r,nextObj:i.nextObj[r]}},{nextObj:this.params}),{obj:s,objProp:n}=t;if(!s||!n||!(s[n]instanceof me))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:s,objProp:n}}}function _s(e,t,s){return C(()=>{let n=eo(e,t.depthwise_filter,t.pointwise_filter,s,"same");return n=$(n,t.bias),n})}function vg(e,t,s=!1){return C(()=>{const n=Fe(s?$(rt(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):_s(e,t.conv0,[2,2])),i=_s(n,t.conv1,[1,1]),r=Fe($(n,i)),o=_s(r,t.conv2,[1,1]);return Fe($(n,$(i,o)))})}function Pu(e,t,s=!1,n=!0){return C(()=>{const i=Fe(s?$(rt(e,t.conv0.filters,n?[2,2]:[1,1],"same"),t.conv0.bias):_s(e,t.conv0,n?[2,2]:[1,1])),r=_s(i,t.conv1,[1,1]),o=Fe($(i,r)),a=_s(o,t.conv2,[1,1]),l=Fe($(i,$(r,a))),c=_s(l,t.conv3,[1,1]);return Fe($(i,$(r,$(a,c))))})}function Oa(e,t,s="same",n=!1){return C(()=>{const i=$(rt(e,t.filters,[1,1],s),t.bias);return n?Fe(i):i})}function Is(e,t){Object.keys(e).forEach(s=>{t.some(n=>n.originalPath===s)||e[s].dispose()})}function dc(e,t){return function(s,n,i,r){const o=ss(e(s*n*i*i),[i,i,s,n]),a=Oe(e(n));return t.push({paramPath:`${r}/filters`},{paramPath:`${r}/bias`}),{filters:o,bias:a}}}function Tg(e,t){return function(s,n,i){const r=ls(e(s*n),[s,n]),o=Oe(e(n));return t.push({paramPath:`${i}/weights`},{paramPath:`${i}/bias`}),{weights:r,bias:o}}}class dL{constructor(e,t,s){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=s}}function mc(e,t){return function(s,n,i){const r=ss(e(3*3*s),[3,3,s,1]),o=ss(e(s*n),[1,1,s,n]),a=Oe(e(n));return t.push({paramPath:`${i}/depthwise_filter`},{paramPath:`${i}/pointwise_filter`},{paramPath:`${i}/bias`}),new dL(r,o,a)}}function fc(e){return function(t){const s=e(`${t}/depthwise_filter`,4),n=e(`${t}/pointwise_filter`,4),i=e(`${t}/bias`,1);return new dL(s,n,i)}}function Vs(e,t){return function(s,n,i){const r=e[s];if(!Na(r,n))throw new Error(`expected weightMap[${s}] to be a Tensor${n}D, instead have ${r}`);return t.push({originalPath:s,paramPath:i||s}),r}}function vs(e){let t=e;function s(i){const r=t.slice(0,i);return t=t.slice(i),r}function n(){return t}return{extractWeights:s,getRemainingWeights:n}}function Ag(e,t){const s=dc(e,t),n=mc(e,t);function i(o,a,l,c=!1){const p=c?s(o,a,3,`${l}/conv0`):n(o,a,`${l}/conv0`),u=n(a,a,`${l}/conv1`),h=n(a,a,`${l}/conv2`);return{conv0:p,conv1:u,conv2:h}}function r(o,a,l,c=!1){const{conv0:p,conv1:u,conv2:h}=i(o,a,l,c),d=n(a,a,`${l}/conv3`);return{conv0:p,conv1:u,conv2:h,conv3:d}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:r}}function pE(e){const t=[],{extractWeights:s,getRemainingWeights:n}=vs(e),{extractDenseBlock4Params:i}=Ag(s,t),r=i(3,32,"dense0",!0),o=i(32,64,"dense1"),a=i(64,128,"dense2"),l=i(128,256,"dense3");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{dense0:r,dense1:o,dense2:a,dense3:l}}}function Ng(e){return function(t){const s=e(`${t}/filters`,4),n=e(`${t}/bias`,1);return{filters:s,bias:n}}}function Cg(e,t){const s=Vs(e,t),n=Ng(s),i=fc(s);function r(a,l=!1){const c=l?n(`${a}/conv0`):i(`${a}/conv0`),p=i(`${a}/conv1`),u=i(`${a}/conv2`);return{conv0:c,conv1:p,conv2:u}}function o(a,l=!1){const c=l?n(`${a}/conv0`):i(`${a}/conv0`),p=i(`${a}/conv1`),u=i(`${a}/conv2`),h=i(`${a}/conv3`);return{conv0:c,conv1:p,conv2:u,conv3:h}}return{extractDenseBlock3Params:r,extractDenseBlock4Params:o}}function uE(e){const t=[],{extractDenseBlock4Params:s}=Cg(e,t),n={dense0:s("dense0",!0),dense1:s("dense1"),dense2:s("dense2"),dense3:s("dense3")};return Is(e,t),{params:n,paramMappings:t}}class Rg extends Zt{constructor(){super("FaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return C(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=un(s,n).div(j(255));let r=Pu(i,t.dense0,!0);return r=Pu(r,t.dense1),r=Pu(r,t.dense2),r=Pu(r,t.dense3),r=ds(r,[7,7],[2,2],"valid"),r})}async forward(e){return this.forwardInput(await nt(e))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(e){return uE(e)}extractParams(e){return pE(e)}}function Bu(e,t){return C(()=>$(Te(e,t.weights),t.bias))}function hE(e,t,s){const n=[],{extractWeights:i,getRemainingWeights:r}=vs(e),o=Tg(i,n),a=o(t,s,"fc");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:n,params:{fc:a}}}function dE(e){const t=[],s=Vs(e,t);function n(r){const o=s(`${r}/weights`,2),a=s(`${r}/bias`,1);return{weights:o,bias:a}}const i={fc:n("fc")};return Is(e,t),{params:i,paramMappings:t}}function Og(e){const t={},s={};return Object.keys(e).forEach(n=>{const i=n.startsWith("fc")?s:t;i[n]=e[n]}),{featureExtractorMap:t,classifierMap:s}}class Eg extends Zt{constructor(e,t){super(e);this._faceFeatureExtractor=t}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){const{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return C(()=>{const s=e instanceof vi?this.faceFeatureExtractor.forwardInput(e):e;return Bu(s.as2D(s.shape[0],-1),t.fc)})}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:s}=this.extractClassifierParams(e);this._params=t,this._paramMappings=s}extractClassifierParams(e){return hE(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:s}=Og(e);return this.faceFeatureExtractor.loadFromWeightMap(t),dE(s)}extractParams(e){const t=this.getClassifierChannelsIn(),s=this.getClassifierChannelsOut(),n=s*t+s,i=e.slice(0,e.length-n),r=e.slice(e.length-n);return this.faceFeatureExtractor.extractWeights(i),this.extractClassifierParams(r)}}const fh=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class lr{constructor(e){if(e.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${e.length}`);fh.forEach((t,s)=>{this[t]=e[s]})}asSortedArray(){return fh.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}}class gh extends Eg{constructor(e=new Rg){super("FaceExpressionNet",e)}forwardInput(e){return C(()=>ts(this.runNet(e)))}async forward(e){return this.forwardInput(await nt(e))}async predictExpressions(e){const t=await nt(e),s=await this.forwardInput(t),n=await Promise.all(qe(s).map(async r=>{const o=await r.data();return r.dispose(),o}));s.dispose();const i=n.map(r=>new lr(r));return t.isBatchInput?i:i[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function dh(e){return e.expressions instanceof lr}function Rc(e,t){const s={expressions:t};return Object.assign({},e,s)}function kG(e,t,s=.1,n){const i=Array.isArray(t)?t:[t];i.forEach(r=>{const o=r instanceof lr?r:dh(r)?r.expressions:void 0;if(!o)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const a=o.asSortedArray(),l=a.filter(u=>u.probability>s),c=Mn(r)?r.detection.box.bottomLeft:n||new _e(0,0),p=new hc(l.map(u=>`${u.expression} (${Ca(u.probability)})`),c);p.draw(e)})}function or(e){return Mn(e)&&e.landmarks instanceof Hs&&e.unshiftedLandmarks instanceof Hs&&e.alignedRect instanceof ht}function Ao(e,t){const{box:s}=e.detection,n=t.shiftBy(s.x,s.y),i=n.align(),{imageDims:r}=e.detection,o=new ht(e.detection.score,i.rescale(r.reverse()),r),a={landmarks:n,unshiftedLandmarks:t,alignedRect:o};return Object.assign({},e,a)}class mE{constructor(e={}){const{drawLines:t=!0,drawPoints:s=!0,lineWidth:n,lineColor:i,pointSize:r,pointColor:o}=e;this.drawLines=t,this.drawPoints=s,this.lineWidth=n||1,this.pointSize=r||2,this.lineColor=i||"rgba(0, 255, 255, 1)",this.pointColor=o||"rgba(255, 0, 255, 1)"}}class fE{constructor(e,t={}){this.faceLandmarks=e,this.options=new mE(t)}draw(e){const t=us(e),{drawLines:s,drawPoints:n,lineWidth:i,lineColor:r,pointSize:o,pointColor:a}=this.options;if(s&&this.faceLandmarks instanceof Va&&(t.strokeStyle=r,t.lineWidth=i,er(t,this.faceLandmarks.getJawOutline()),er(t,this.faceLandmarks.getLeftEyeBrow()),er(t,this.faceLandmarks.getRightEyeBrow()),er(t,this.faceLandmarks.getNose()),er(t,this.faceLandmarks.getLeftEye(),!0),er(t,this.faceLandmarks.getRightEye(),!0),er(t,this.faceLandmarks.getMouth(),!0)),n){t.strokeStyle=a,t.fillStyle=a;const l=c=>{t.beginPath(),t.arc(c.x,c.y,o,0,2*Math.PI),t.fill()};this.faceLandmarks.positions.forEach(l)}}}function DG(e,t){const s=Array.isArray(t)?t:[t];s.forEach(n=>{const i=n instanceof Hs?n:or(n)?n.landmarks:void 0;if(!i)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new fE(i).draw(e)})}const Zu={};Ee(Zu,{AnchorPosition:()=>Ii,DrawBox:()=>hL,DrawBoxOptions:()=>cE,DrawFaceLandmarks:()=>fE,DrawFaceLandmarksOptions:()=>mE,DrawTextField:()=>hc,DrawTextFieldOptions:()=>Sg,drawContour:()=>er,drawDetections:()=>_G,drawFaceExpressions:()=>kG,drawFaceLandmarks:()=>DG});function FG(e,t){const s=dc(e,t),n=mc(e,t);function i(o,a,l){const c=n(o,a,`${l}/separable_conv0`),p=n(a,a,`${l}/separable_conv1`),u=s(o,a,1,`${l}/expansion_conv`);return{separable_conv0:c,separable_conv1:p,expansion_conv:u}}function r(o,a){const l=n(o,o,`${a}/separable_conv0`),c=n(o,o,`${a}/separable_conv1`),p=n(o,o,`${a}/separable_conv2`);return{separable_conv0:l,separable_conv1:c,separable_conv2:p}}return{extractConvParams:s,extractSeparableConvParams:n,extractReductionBlockParams:i,extractMainBlockParams:r}}function gE(e,t){const s=[],{extractWeights:n,getRemainingWeights:i}=vs(e),{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:a,extractMainBlockParams:l}=FG(n,s),c=r(3,32,3,"entry_flow/conv_in"),p=a(32,64,"entry_flow/reduction_block_0"),u=a(64,128,"entry_flow/reduction_block_1"),h={conv_in:c,reduction_block_0:p,reduction_block_1:u},d={};Si(t,0,1).forEach(y=>{d[`main_block_${y}`]=l(128,`middle_flow/main_block_${y}`)});const m=a(128,256,"exit_flow/reduction_block"),f=o(256,512,"exit_flow/separable_conv"),g={reduction_block:m,separable_conv:f};if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{paramMappings:s,params:{entry_flow:h,middle_flow:d,exit_flow:g}}}function MG(e,t){const s=Vs(e,t),n=Ng(s),i=fc(s);function r(a){const l=i(`${a}/separable_conv0`),c=i(`${a}/separable_conv1`),p=n(`${a}/expansion_conv`);return{separable_conv0:l,separable_conv1:c,expansion_conv:p}}function o(a){const l=i(`${a}/separable_conv0`),c=i(`${a}/separable_conv1`),p=i(`${a}/separable_conv2`);return{separable_conv0:l,separable_conv1:c,separable_conv2:p}}return{extractConvParams:n,extractSeparableConvParams:i,extractReductionBlockParams:r,extractMainBlockParams:o}}function yE(e,t){const s=[],{extractConvParams:n,extractSeparableConvParams:i,extractReductionBlockParams:r,extractMainBlockParams:o}=MG(e,s),a=n("entry_flow/conv_in"),l=r("entry_flow/reduction_block_0"),c=r("entry_flow/reduction_block_1"),p={conv_in:a,reduction_block_0:l,reduction_block_1:c},u={};Si(t,0,1).forEach(f=>{u[`main_block_${f}`]=o(`middle_flow/main_block_${f}`)});const h=r("exit_flow/reduction_block"),d=i("exit_flow/separable_conv"),m={reduction_block:h,separable_conv:d};return Is(e,s),{params:{entry_flow:p,middle_flow:u,exit_flow:m},paramMappings:s}}function bE(e,t,s){return $(rt(e,t.filters,s,"same"),t.bias)}function mL(e,t,s=!0){let n=s?Fe(e):e;return n=_s(n,t.separable_conv0,[1,1]),n=_s(Fe(n),t.separable_conv1,[1,1]),n=ft(n,[3,3],[2,2],"same"),n=$(n,bE(e,t.expansion_conv,[2,2])),n}function UG(e,t){let s=_s(Fe(e),t.separable_conv0,[1,1]);return s=_s(Fe(s),t.separable_conv1,[1,1]),s=_s(Fe(s),t.separable_conv2,[1,1]),s=$(s,e),s}class wE extends Zt{constructor(e){super("TinyXception");this._numMainBlocks=e}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyXception - load model before inference");return C(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=un(s,n).div(j(256));let r=Fe(bE(i,t.entry_flow.conv_in,[2,2]));return r=mL(r,t.entry_flow.reduction_block_0,!1),r=mL(r,t.entry_flow.reduction_block_1),Si(this._numMainBlocks,0,1).forEach(o=>{r=UG(r,t.middle_flow[`main_block_${o}`])}),r=mL(r,t.exit_flow.reduction_block),r=Fe(_s(r,t.exit_flow.separable_conv,[1,1])),r})}async forward(e){return this.forwardInput(await nt(e))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(e){return yE(e,this._numMainBlocks)}extractParams(e){return gE(e,this._numMainBlocks)}}function xE(e){const t=[],{extractWeights:s,getRemainingWeights:n}=vs(e),i=Tg(s,t),r=i(512,1,"fc/age"),o=i(512,2,"fc/gender");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{fc:{age:r,gender:o}}}}function LE(e){const t=[],s=Vs(e,t);function n(r){const o=s(`${r}/weights`,2),a=s(`${r}/bias`,1);return{weights:o,bias:a}}const i={fc:{age:n("fc/age"),gender:n("fc/gender")}};return Is(e,t),{params:i,paramMappings:t}}var Jn;(function(e){e.FEMALE="female",e.MALE="male"})(Jn||(Jn={}));class vh extends Zt{constructor(e=new wE(2)){super("AgeGenderNet");this._faceFeatureExtractor=e}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){const{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return C(()=>{const s=e instanceof vi?this.faceFeatureExtractor.forwardInput(e):e,n=ds(s,[7,7],[2,2],"valid").as2D(s.shape[0],-1),i=Bu(n,t.fc.age).as1D(),r=Bu(n,t.fc.gender);return{age:i,gender:r}})}forwardInput(e){return C(()=>{const{age:t,gender:s}=this.runNet(e);return{age:t,gender:ts(s)}})}async forward(e){return this.forwardInput(await nt(e))}async predictAgeAndGender(e){const t=await nt(e),s=await this.forwardInput(t),n=qe(s.age),i=qe(s.gender),r=n.map((a,l)=>({ageTensor:a,genderTensor:i[l]})),o=await Promise.all(r.map(async({ageTensor:a,genderTensor:l})=>{const c=(await a.data())[0],p=(await l.data())[0],u=p>.5,h=u?Jn.MALE:Jn.FEMALE,d=u?p:1-p;return a.dispose(),l.dispose(),{age:c,gender:h,genderProbability:d}}));return s.age.dispose(),s.gender.dispose(),t.isBatchInput?o:o[0]}getDefaultModelName(){return"age_gender_model"}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:s}=this.extractClassifierParams(e);this._params=t,this._paramMappings=s}extractClassifierParams(e){return xE(e)}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:s}=Og(e);return this.faceFeatureExtractor.loadFromWeightMap(t),LE(s)}extractParams(e){const t=512*1+1+(512*2+2),s=e.slice(0,e.length-t),n=e.slice(e.length-t);return this.faceFeatureExtractor.extractWeights(s),this.extractClassifierParams(n)}}class _g extends Eg{postProcess(e,t,s){const n=s.map(({width:r,height:o})=>{const a=t/Math.max(o,r);return{width:r*a,height:o*a}}),i=n.length;return C(()=>{const r=(p,u)=>Ge([Wt([68],p),Wt([68],u)],1).as2D(1,136).as1D(),o=(p,u)=>{const{width:h,height:d}=n[p];return u(h,d)?Math.abs(h-d)/2:0},a=p=>o(p,(u,h)=>u<h),l=p=>o(p,(u,h)=>h<u),c=e.mul(Wt([i,136],t)).sub(Ge(Array.from(Array(i),(p,u)=>r(a(u),l(u))))).div(Ge(Array.from(Array(i),(p,u)=>r(n[u].width,n[u].height))));return c})}forwardInput(e){return C(()=>{const t=this.runNet(e);return this.postProcess(t,e.inputSize,e.inputDimensions.map(([s,n])=>({height:s,width:n})))})}async forward(e){return this.forwardInput(await nt(e))}async detectLandmarks(e){const t=await nt(e),s=C(()=>qe(this.forwardInput(t))),n=await Promise.all(s.map(async(i,r)=>{const o=Array.from(await i.data()),a=o.filter((c,p)=>wg(p)),l=o.filter((c,p)=>!wg(p));return new Va(Array(68).fill(0).map((c,p)=>new _e(a[p],l[p])),{height:t.getInputHeight(r),width:t.getInputWidth(r)})}));return s.forEach(i=>i.dispose()),t.isBatchInput?n:n[0]}getClassifierChannelsOut(){return 136}}class za extends _g{constructor(e=new Rg){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function SE(e){const t=[],{extractDenseBlock3Params:s}=Cg(e,t),n={dense0:s("dense0",!0),dense1:s("dense1"),dense2:s("dense2")};return Is(e,t),{params:n,paramMappings:t}}function IE(e){const t=[],{extractWeights:s,getRemainingWeights:n}=vs(e),{extractDenseBlock3Params:i}=Ag(s,t),r=i(3,32,"dense0",!0),o=i(32,64,"dense1"),a=i(64,128,"dense2");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{dense0:r,dense1:o,dense2:a}}}class vE extends Zt{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return C(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=un(s,n).div(j(255));let r=vg(i,t.dense0,!0);return r=vg(r,t.dense1),r=vg(r,t.dense2),r=ds(r,[14,14],[2,2],"valid"),r})}async forward(e){return this.forwardInput(await nt(e))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(e){return SE(e)}extractParams(e){return IE(e)}}class mh extends _g{constructor(e=new vE){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class dS extends za{}function TE(e,t){return $(R(e,t.weights),t.biases)}function fL(e,t,s,n,i="same"){const{filters:r,bias:o}=t.conv;let a=rt(e,r,s,i);return a=$(a,o),a=TE(a,t.scale),n?Fe(a):a}function AE(e,t){return fL(e,t,[1,1],!0)}function gL(e,t){return fL(e,t,[1,1],!1)}function kg(e,t){return fL(e,t,[2,2],!0,"valid")}function $G(e,t){function s(a,l,c){const p=e(a),u=p.length/(l*c*c);if(iL(u))throw new Error(`depth has to be an integer: ${u}, weights.length: ${p.length}, numFilters: ${l}, filterSize: ${c}`);return C(()=>se(ss(p,[l,u,c,c]),[2,3,1,0]))}function n(a,l,c,p){const u=s(a,l,c),h=Oe(e(l));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/bias`}),{filters:u,bias:h}}function i(a,l){const c=Oe(e(a)),p=Oe(e(a));return t.push({paramPath:`${l}/weights`},{paramPath:`${l}/biases`}),{weights:c,biases:p}}function r(a,l,c,p){const u=n(a,l,c,`${p}/conv`),h=i(l,`${p}/scale`);return{conv:u,scale:h}}function o(a,l,c,p,u=!1){const h=r((u?.5:1)*a,l,c,`${p}/conv1`),d=r(a,l,c,`${p}/conv2`);return{conv1:h,conv2:d}}return{extractConvLayerParams:r,extractResidualLayerParams:o}}function NE(e){const{extractWeights:t,getRemainingWeights:s}=vs(e),n=[],{extractConvLayerParams:i,extractResidualLayerParams:r}=$G(t,n),o=i(4704,32,7,"conv32_down"),a=r(9216,32,3,"conv32_1"),l=r(9216,32,3,"conv32_2"),c=r(9216,32,3,"conv32_3"),p=r(36864,64,3,"conv64_down",!0),u=r(36864,64,3,"conv64_1"),h=r(36864,64,3,"conv64_2"),d=r(36864,64,3,"conv64_3"),m=r(147456,128,3,"conv128_down",!0),f=r(147456,128,3,"conv128_1"),g=r(147456,128,3,"conv128_2"),y=r(589824,256,3,"conv256_down",!0),w=r(589824,256,3,"conv256_1"),x=r(589824,256,3,"conv256_2"),T=r(589824,256,3,"conv256_down_out"),A=C(()=>se(ls(t(256*128),[128,256]),[1,0]));if(n.push({paramPath:"fc"}),s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);const _={conv32_down:o,conv32_1:a,conv32_2:l,conv32_3:c,conv64_down:p,conv64_1:u,conv64_2:h,conv64_3:d,conv128_down:m,conv128_1:f,conv128_2:g,conv256_down:y,conv256_1:w,conv256_2:x,conv256_down_out:T,fc:A};return{params:_,paramMappings:n}}function WG(e,t){const s=Vs(e,t);function n(o){const a=s(`${o}/scale/weights`,1),l=s(`${o}/scale/biases`,1);return{weights:a,biases:l}}function i(o){const a=s(`${o}/conv/filters`,4),l=s(`${o}/conv/bias`,1),c=n(o);return{conv:{filters:a,bias:l},scale:c}}function r(o){return{conv1:i(`${o}/conv1`),conv2:i(`${o}/conv2`)}}return{extractConvLayerParams:i,extractResidualLayerParams:r}}function CE(e){const t=[],{extractConvLayerParams:s,extractResidualLayerParams:n}=WG(e,t),i=s("conv32_down"),r=n("conv32_1"),o=n("conv32_2"),a=n("conv32_3"),l=n("conv64_down"),c=n("conv64_1"),p=n("conv64_2"),u=n("conv64_3"),h=n("conv128_down"),d=n("conv128_1"),m=n("conv128_2"),f=n("conv256_down"),g=n("conv256_1"),y=n("conv256_2"),w=n("conv256_down_out"),x=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!nL(x))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${x}`);const T={conv32_down:i,conv32_1:r,conv32_2:o,conv32_3:a,conv64_down:l,conv64_1:c,conv64_2:p,conv64_3:u,conv128_down:h,conv128_1:d,conv128_2:m,conv256_down:f,conv256_1:g,conv256_2:y,conv256_down_out:w,fc:x};return Is(e,t),{params:T,paramMappings:t}}function Kn(e,t){let s=AE(e,t.conv1);return s=gL(s,t.conv2),s=$(s,e),s=Fe(s),s}function ju(e,t){let s=kg(e,t.conv1);s=gL(s,t.conv2);let n=ds(e,2,2,"valid");const i=ye(n.shape),r=n.shape[3]!==s.shape[3],o=n.shape[1]!==s.shape[1]||n.shape[2]!==s.shape[2];if(o){const a=[...s.shape];a[1]=1;const l=ye(a);s=be([s,l],1);const c=[...s.shape];c[2]=1;const p=ye(c);s=be([s,p],2)}return n=r?be([n,i],3):n,s=$(n,s),s=Fe(s),s}class Wa extends Zt{constructor(){super("FaceRecognitionNet")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return C(()=>{const s=G(e.toBatchTensor(150,!0),"float32"),n=[122.782,117.001,104.298],i=un(s,n).div(j(256));let r=kg(i,t.conv32_down);r=ft(r,3,2,"valid"),r=Kn(r,t.conv32_1),r=Kn(r,t.conv32_2),r=Kn(r,t.conv32_3),r=ju(r,t.conv64_down),r=Kn(r,t.conv64_1),r=Kn(r,t.conv64_2),r=Kn(r,t.conv64_3),r=ju(r,t.conv128_down),r=Kn(r,t.conv128_1),r=Kn(r,t.conv128_2),r=ju(r,t.conv256_down),r=Kn(r,t.conv256_1),r=Kn(r,t.conv256_2),r=ju(r,t.conv256_down_out);const o=r.mean([1,2]),a=Te(o,t.fc);return a})}async forward(e){return this.forwardInput(await nt(e))}async computeFaceDescriptor(e){const t=await nt(e),s=C(()=>qe(this.forwardInput(t))),n=await Promise.all(s.map(i=>i.data()));return s.forEach(i=>i.dispose()),t.isBatchInput?n:n[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(e){return CE(e)}extractParams(e){return NE(e)}}function hS(e){const t=new Wa;return t.extractWeights(e),t}function Oc(e,t){const s={descriptor:t};return Object.assign({},e,s)}function uS(e){return typeof e.age=="number"}function Ec(e,t){const s={age:t};return Object.assign({},e,s)}function pS(e){return(e.gender===Jn.MALE||e.gender===Jn.FEMALE)&&uc(e.genderProbability)}function Cc(e,t,s){const n={gender:t,genderProbability:s};return Object.assign({},e,n)}function zG(e,t){function s(l,c){const p=ss(e(3*3*l),[3,3,l,1]),u=Oe(e(l)),h=Oe(e(l)),d=Oe(e(l)),m=Oe(e(l));return t.push({paramPath:`${c}/filters`},{paramPath:`${c}/batch_norm_scale`},{paramPath:`${c}/batch_norm_offset`},{paramPath:`${c}/batch_norm_mean`},{paramPath:`${c}/batch_norm_variance`}),{filters:p,batch_norm_scale:u,batch_norm_offset:h,batch_norm_mean:d,batch_norm_variance:m}}function n(l,c,p,u,h){const d=ss(e(l*c*p*p),[p,p,l,c]),m=Oe(e(c));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/${h?"batch_norm_offset":"bias"}`}),{filters:d,bias:m}}function i(l,c,p,u){const{filters:h,bias:d}=n(l,c,p,u,!0);return{filters:h,batch_norm_offset:d}}function r(l,c,p){const u=s(l,`${p}/depthwise_conv`),h=i(l,c,1,`${p}/pointwise_conv`);return{depthwise_conv:u,pointwise_conv:h}}function o(){const l=i(3,32,3,"mobilenetv1/conv_0"),c=r(32,64,"mobilenetv1/conv_1"),p=r(64,128,"mobilenetv1/conv_2"),u=r(128,128,"mobilenetv1/conv_3"),h=r(128,256,"mobilenetv1/conv_4"),d=r(256,256,"mobilenetv1/conv_5"),m=r(256,512,"mobilenetv1/conv_6"),f=r(512,512,"mobilenetv1/conv_7"),g=r(512,512,"mobilenetv1/conv_8"),y=r(512,512,"mobilenetv1/conv_9"),w=r(512,512,"mobilenetv1/conv_10"),x=r(512,512,"mobilenetv1/conv_11"),T=r(512,1024,"mobilenetv1/conv_12"),A=r(1024,1024,"mobilenetv1/conv_13");return{conv_0:l,conv_1:c,conv_2:p,conv_3:u,conv_4:h,conv_5:d,conv_6:m,conv_7:f,conv_8:g,conv_9:y,conv_10:w,conv_11:x,conv_12:T,conv_13:A}}function a(){const l=i(1024,256,1,"prediction_layer/conv_0"),c=i(256,512,3,"prediction_layer/conv_1"),p=i(512,128,1,"prediction_layer/conv_2"),u=i(128,256,3,"prediction_layer/conv_3"),h=i(256,128,1,"prediction_layer/conv_4"),d=i(128,256,3,"prediction_layer/conv_5"),m=i(256,64,1,"prediction_layer/conv_6"),f=i(64,128,3,"prediction_layer/conv_7"),g=n(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),y=n(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),w=n(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),x=n(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),T=n(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),A=n(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),_=n(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),E=n(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),F=n(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),D=n(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),M=n(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),P=n(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),B={box_encoding_predictor:g,class_predictor:y},Y={box_encoding_predictor:w,class_predictor:x},q={box_encoding_predictor:T,class_predictor:A},K={box_encoding_predictor:_,class_predictor:E},H={box_encoding_predictor:F,class_predictor:D},Q={box_encoding_predictor:M,class_predictor:P};return{conv_0:l,conv_1:c,conv_2:p,conv_3:u,conv_4:h,conv_5:d,conv_6:m,conv_7:f,box_predictor_0:B,box_predictor_1:Y,box_predictor_2:q,box_predictor_3:K,box_predictor_4:H,box_predictor_5:Q}}return{extractMobilenetV1Params:o,extractPredictionLayerParams:a}}function RE(e){const t=[],{extractWeights:s,getRemainingWeights:n}=vs(e),{extractMobilenetV1Params:i,extractPredictionLayerParams:r}=zG(s,t),o=i(),a=r(),l=ll(s(5118*4),[1,5118,4]),c={extra_dim:l};if(t.push({paramPath:"output_layer/extra_dim"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{params:{mobilenetv1:o,prediction_layer:a,output_layer:c},paramMappings:t}}function PG(e,t){const s=Vs(e,t);function n(c,p,u){const h=s(`${c}/Conv2d_${p}_pointwise/weights`,4,`${u}/filters`),d=s(`${c}/Conv2d_${p}_pointwise/convolution_bn_offset`,1,`${u}/batch_norm_offset`);return{filters:h,batch_norm_offset:d}}function i(c){const p=`mobilenetv1/conv_${c}`,u=`MobilenetV1/Conv2d_${c}_depthwise`,h=`${p}/depthwise_conv`,d=`${p}/pointwise_conv`,m=s(`${u}/depthwise_weights`,4,`${h}/filters`),f=s(`${u}/BatchNorm/gamma`,1,`${h}/batch_norm_scale`),g=s(`${u}/BatchNorm/beta`,1,`${h}/batch_norm_offset`),y=s(`${u}/BatchNorm/moving_mean`,1,`${h}/batch_norm_mean`),w=s(`${u}/BatchNorm/moving_variance`,1,`${h}/batch_norm_variance`);return{depthwise_conv:{filters:m,batch_norm_scale:f,batch_norm_offset:g,batch_norm_mean:y,batch_norm_variance:w},pointwise_conv:n("MobilenetV1",c,d)}}function r(){return{conv_0:n("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:i(1),conv_2:i(2),conv_3:i(3),conv_4:i(4),conv_5:i(5),conv_6:i(6),conv_7:i(7),conv_8:i(8),conv_9:i(9),conv_10:i(10),conv_11:i(11),conv_12:i(12),conv_13:i(13)}}function o(c,p){const u=s(`${c}/weights`,4,`${p}/filters`),h=s(`${c}/biases`,1,`${p}/bias`);return{filters:u,bias:h}}function a(c){const p=o(`Prediction/BoxPredictor_${c}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${c}/box_encoding_predictor`),u=o(`Prediction/BoxPredictor_${c}/ClassPredictor`,`prediction_layer/box_predictor_${c}/class_predictor`);return{box_encoding_predictor:p,class_predictor:u}}function l(){return{conv_0:n("Prediction",0,"prediction_layer/conv_0"),conv_1:n("Prediction",1,"prediction_layer/conv_1"),conv_2:n("Prediction",2,"prediction_layer/conv_2"),conv_3:n("Prediction",3,"prediction_layer/conv_3"),conv_4:n("Prediction",4,"prediction_layer/conv_4"),conv_5:n("Prediction",5,"prediction_layer/conv_5"),conv_6:n("Prediction",6,"prediction_layer/conv_6"),conv_7:n("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:a(0),box_predictor_1:a(1),box_predictor_2:a(2),box_predictor_3:a(3),box_predictor_4:a(4),box_predictor_5:a(5)}}return{extractMobilenetV1Params:r,extractPredictionLayerParams:l}}function OE(e){const t=[],{extractMobilenetV1Params:s,extractPredictionLayerParams:n}=PG(e,t),i=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!tr(i))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${i}`);const r={mobilenetv1:s(),prediction_layer:n(),output_layer:{extra_dim:i}};return Is(e,t),{params:r,paramMappings:t}}function Dn(e,t,s){return C(()=>{let n=rt(e,t.filters,s,"same");return n=$(n,t.batch_norm_offset),xt(n,0,6)})}const BG=.0010000000474974513;function jG(e,t,s){return C(()=>{let n=fn(e,t.filters,s,"same");return n=Xs(n,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,BG),xt(n,0,6)})}function VG(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function EE(e,t){return C(()=>{let s,n=Dn(e,t.conv_0,[2,2]);const i=[t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13];if(i.forEach((r,o)=>{const a=o+1,l=VG(a);n=jG(n,r.depthwise_conv,l),n=Dn(n,r.pointwise_conv,[1,1]),a===11&&(s=n)}),s===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:n,conv11:s}})}function _E(e,t,s,n,i){const r=e.shape[0],o=Math.min(s,r),a=t.map((p,u)=>({score:p,boxIndex:u})).filter(p=>p.score>i).sort((p,u)=>u.score-p.score),l=p=>p<=n?1:0,c=[];return a.forEach(p=>{if(c.length>=o)return;const u=p.score;for(let h=c.length-1;h>=0;--h){const d=GG(e,p.boxIndex,c[h]);if(d===0)continue;if(p.score*=l(d),p.score<=i)break}u===p.score&&c.push(p.boxIndex)}),c}function GG(e,t,s){const n=e.arraySync(),i=Math.min(n[t][0],n[t][2]),r=Math.min(n[t][1],n[t][3]),o=Math.max(n[t][0],n[t][2]),a=Math.max(n[t][1],n[t][3]),l=Math.min(n[s][0],n[s][2]),c=Math.min(n[s][1],n[s][3]),p=Math.max(n[s][0],n[s][2]),u=Math.max(n[s][1],n[s][3]),h=(o-i)*(a-r),d=(p-l)*(u-c);if(h<=0||d<=0)return 0;const m=Math.max(i,l),f=Math.max(r,c),g=Math.min(o,p),y=Math.min(a,u),w=Math.max(g-m,0)*Math.max(y-f,0);return w/(h+d-w)}function qG(e){const t=qe(se(e,[1,0])),s=[X(t[2],t[0]),X(t[3],t[1])],n=[$(t[0],Z(s[0],j(2))),$(t[1],Z(s[1],j(2)))];return{sizes:s,centers:n}}function HG(e,t){const{sizes:s,centers:n}=qG(e),i=qe(se(t,[1,0])),r=Z(R(ut(Z(i[2],j(5))),s[0]),j(2)),o=$(R(Z(i[0],j(10)),s[0]),n[0]),a=Z(R(ut(Z(i[3],j(5))),s[1]),j(2)),l=$(R(Z(i[1],j(10)),s[1]),n[1]);return se(Ge([X(o,r),X(l,a),$(o,r),$(l,a)]),[1,0])}function kE(e,t,s){return C(()=>{const n=e.shape[0];let i=HG(O($s(s.extra_dim,[n,1,1]),[-1,4]),O(e,[-1,4]));i=O(i,[n,i.shape[0]/n,4]);const r=os(he(t,[0,0,1],[-1,-1,-1]));let o=he(r,[0,0,0],[-1,-1,1]);o=O(o,[n,o.shape[1]]);const a=qe(i),l=qe(o);return{boxes:a,scores:l}})}function Ea(e,t){return C(()=>{const s=e.shape[0],n=O(Oa(e,t.box_encoding_predictor),[s,-1,1,4]),i=O(Oa(e,t.class_predictor),[s,-1,3]);return{boxPredictionEncoding:n,classPrediction:i}})}function DE(e,t,s){return C(()=>{const n=Dn(e,s.conv_0,[1,1]),i=Dn(n,s.conv_1,[2,2]),r=Dn(i,s.conv_2,[1,1]),o=Dn(r,s.conv_3,[2,2]),a=Dn(o,s.conv_4,[1,1]),l=Dn(a,s.conv_5,[2,2]),c=Dn(l,s.conv_6,[1,1]),p=Dn(c,s.conv_7,[2,2]),u=Ea(t,s.box_predictor_0),h=Ea(e,s.box_predictor_1),d=Ea(i,s.box_predictor_2),m=Ea(o,s.box_predictor_3),f=Ea(l,s.box_predictor_4),g=Ea(p,s.box_predictor_5),y=be([u.boxPredictionEncoding,h.boxPredictionEncoding,d.boxPredictionEncoding,m.boxPredictionEncoding,f.boxPredictionEncoding,g.boxPredictionEncoding],1),w=be([u.classPrediction,h.classPrediction,d.classPrediction,m.classPrediction,f.classPrediction,g.classPrediction],1);return{boxPredictions:y,classPredictions:w}})}class pn{constructor({minConfidence:e,maxResults:t}={}){if(this._name="SsdMobilenetv1Options",this._minConfidence=e||.5,this._maxResults=t||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(`${this._name} - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!="number")throw new Error(`${this._name} - expected maxResults to be a number`)}get minConfidence(){return this._minConfidence}get maxResults(){return this._maxResults}}class To extends Zt{constructor(){super("SsdMobilenetv1")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("SsdMobilenetv1 - load model before inference");return C(()=>{const s=G(e.toBatchTensor(512,!1),"float32"),n=X(R(s,j(.007843137718737125)),j(1)),i=EE(n,t.mobilenetv1),{boxPredictions:r,classPredictions:o}=DE(i.out,i.conv11,t.prediction_layer);return kE(r,o,t.output_layer)})}async forward(e){return this.forwardInput(await nt(e))}async locateFaces(e,t={}){const{maxResults:s,minConfidence:n}=new pn(t),i=await nt(e),{boxes:r,scores:o}=this.forwardInput(i),a=r[0],l=o[0];for(let w=1;w<r.length;w++)r[w].dispose(),o[w].dispose();const c=Array.from(await l.data()),p=.5,u=_E(a,c,s,p,n),h=i.getReshapedInputDimensions(0),d=i.inputSize,m=d/h.width,f=d/h.height,g=a.arraySync(),y=u.map(w=>{const[x,T]=[Math.max(0,g[w][0]),Math.min(1,g[w][2])].map(E=>E*f),[A,_]=[Math.max(0,g[w][1]),Math.min(1,g[w][3])].map(E=>E*m);return new ht(c[w],new ja(A,x,_-A,T-x),{height:i.getInputHeight(0),width:i.getInputWidth(0)})});return a.dispose(),l.dispose(),y}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(e){return OE(e)}extractParams(e){return RE(e)}}function jg(e){const t=new To;return t.extractWeights(e),t}function PL(e){return jg(e)}class BL extends To{}const FE=.4,ME=[new _e(.738768,.874946),new _e(2.42204,2.65704),new _e(4.30971,7.04493),new _e(10.246,4.59428),new _e(12.6868,11.8741)],UE=[new _e(1.603231,2.094468),new _e(6.041143,7.080126),new _e(2.882459,3.518061),new _e(4.266906,5.178857),new _e(9.041765,10.66308)],$E=[117.001,114.697,97.404],WE="tiny_yolov2_model",zE="tiny_yolov2_separable_conv_model";const Dg=e=>typeof e=="number";function eh(e){if(!e)throw new Error(`invalid config: ${e}`);if(typeof e.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${e.withSeparableConvs}`);if(!Dg(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${e.iouThreshold}`);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every(t=>typeof t=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(e.classes)}`);if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map(t=>t||{}).every(t=>Dg(t.x)&&Dg(t.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(e.anchors)}`);if(e.meanRgb&&(!Array.isArray(e.meanRgb)||e.meanRgb.length!==3||!e.meanRgb.every(Dg)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function gc(e){return C(()=>{const t=R(e,j(.10000000149011612));return $(Fe(X(e,t)),t)})}function sr(e,t){return C(()=>{let s=Pt(e,[[0,0],[1,1],[1,1],[0,0]]);return s=rt(s,t.conv.filters,[1,1],"valid"),s=X(s,t.bn.sub),s=R(s,t.bn.truediv),s=$(s,t.conv.bias),gc(s)})}function nr(e,t){return C(()=>{let s=Pt(e,[[0,0],[1,1],[1,1],[0,0]]);return s=eo(s,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),s=$(s,t.bias),gc(s)})}function YG(e,t){const s=dc(e,t);function n(o,a){const l=Oe(e(o)),c=Oe(e(o));return t.push({paramPath:`${a}/sub`},{paramPath:`${a}/truediv`}),{sub:l,truediv:c}}function i(o,a,l){const c=s(o,a,3,`${l}/conv`),p=n(a,`${l}/bn`);return{conv:c,bn:p}}const r=mc(e,t);return{extractConvParams:s,extractConvWithBatchNormParams:i,extractSeparableConvParams:r}}function PE(e,t,s,n){const{extractWeights:i,getRemainingWeights:r}=vs(e),o=[],{extractConvParams:a,extractConvWithBatchNormParams:l,extractSeparableConvParams:c}=YG(i,o);let p;if(t.withSeparableConvs){const[u,h,d,m,f,g,y,w,x]=n,T=t.isFirstLayerConv2d?a(u,h,3,"conv0"):c(u,h,"conv0"),A=c(h,d,"conv1"),_=c(d,m,"conv2"),E=c(m,f,"conv3"),F=c(f,g,"conv4"),D=c(g,y,"conv5"),M=w?c(y,w,"conv6"):void 0,P=x?c(w,x,"conv7"):void 0,B=a(x||w||y,5*s,1,"conv8");p={conv0:T,conv1:A,conv2:_,conv3:E,conv4:F,conv5:D,conv6:M,conv7:P,conv8:B}}else{const[u,h,d,m,f,g,y,w,x]=n,T=l(u,h,"conv0"),A=l(h,d,"conv1"),_=l(d,m,"conv2"),E=l(m,f,"conv3"),F=l(f,g,"conv4"),D=l(g,y,"conv5"),M=l(y,w,"conv6"),P=l(w,x,"conv7"),B=a(x,5*s,1,"conv8");p={conv0:T,conv1:A,conv2:_,conv3:E,conv4:F,conv5:D,conv6:M,conv7:P,conv8:B}}if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{params:p,paramMappings:o}}function KG(e,t){const s=Vs(e,t);function n(a){const l=s(`${a}/sub`,1),c=s(`${a}/truediv`,1);return{sub:l,truediv:c}}function i(a){const l=s(`${a}/filters`,4),c=s(`${a}/bias`,1);return{filters:l,bias:c}}function r(a){const l=i(`${a}/conv`),c=n(`${a}/bn`);return{conv:l,bn:c}}const o=fc(s);return{extractConvParams:i,extractConvWithBatchNormParams:r,extractSeparableConvParams:o}}function BE(e,t){const s=[],{extractConvParams:n,extractConvWithBatchNormParams:i,extractSeparableConvParams:r}=KG(e,s);let o;if(t.withSeparableConvs){const a=t.filterSizes&&t.filterSizes.length||9;o={conv0:t.isFirstLayerConv2d?n("conv0"):r("conv0"),conv1:r("conv1"),conv2:r("conv2"),conv3:r("conv3"),conv4:r("conv4"),conv5:r("conv5"),conv6:a>7?r("conv6"):void 0,conv7:a>8?r("conv7"):void 0,conv8:n("conv8")}}else o={conv0:i("conv0"),conv1:i("conv1"),conv2:i("conv2"),conv3:i("conv3"),conv4:i("conv4"),conv5:i("conv5"),conv6:i("conv6"),conv7:i("conv7"),conv8:n("conv8")};return Is(e,s),{params:o,paramMappings:s}}var th;(function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"})(th||(th={}));class Xn{constructor({inputSize:e,scoreThreshold:t}={}){if(this._name="TinyYolov2Options",this._inputSize=e||416,this._scoreThreshold=t||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}}class yc extends Zt{constructor(e){super("TinyYolov2");eh(e),this._config=e}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(e,t){let s=sr(e,t.conv0);return s=ft(s,[2,2],[2,2],"same"),s=sr(s,t.conv1),s=ft(s,[2,2],[2,2],"same"),s=sr(s,t.conv2),s=ft(s,[2,2],[2,2],"same"),s=sr(s,t.conv3),s=ft(s,[2,2],[2,2],"same"),s=sr(s,t.conv4),s=ft(s,[2,2],[2,2],"same"),s=sr(s,t.conv5),s=ft(s,[2,2],[1,1],"same"),s=sr(s,t.conv6),s=sr(s,t.conv7),Oa(s,t.conv8,"valid",!1)}runMobilenet(e,t){let s=this.config.isFirstLayerConv2d?gc(Oa(e,t.conv0,"valid",!1)):nr(e,t.conv0);return s=ft(s,[2,2],[2,2],"same"),s=nr(s,t.conv1),s=ft(s,[2,2],[2,2],"same"),s=nr(s,t.conv2),s=ft(s,[2,2],[2,2],"same"),s=nr(s,t.conv3),s=ft(s,[2,2],[2,2],"same"),s=nr(s,t.conv4),s=ft(s,[2,2],[2,2],"same"),s=nr(s,t.conv5),s=ft(s,[2,2],[1,1],"same"),s=t.conv6?nr(s,t.conv6):s,s=t.conv7?nr(s,t.conv7):s,Oa(s,t.conv8,"valid",!1)}forwardInput(e,t){const{params:s}=this;if(!s)throw new Error("TinyYolov2 - load model before inference");return C(()=>{let n=G(e.toBatchTensor(t,!1),"float32");return n=this.config.meanRgb?un(n,this.config.meanRgb):n,n=n.div(j(256)),this.config.withSeparableConvs?this.runMobilenet(n,s):this.runTinyYolov2(n,s)})}async forward(e,t){return await this.forwardInput(await nt(e),t)}async detect(e,t={}){const{inputSize:s,scoreThreshold:n}=new Xn(t),i=await nt(e),r=await this.forwardInput(i,s),o=C(()=>qe(r)[0].expandDims()),a={width:i.getInputWidth(0),height:i.getInputHeight(0)},l=await this.extractBoxes(o,i.getReshapedInputDimensions(0),n);r.dispose(),o.dispose();const c=l.map(f=>f.box),p=l.map(f=>f.score),u=l.map(f=>f.classScore),h=l.map(f=>this.config.classes[f.label]),d=ih(c.map(f=>f.rescale(s)),p,this.config.iouThreshold,!0),m=d.map(f=>new Oo(p[f],u[f],h[f],c[f],a));return m}getDefaultModelName(){return""}extractParamsFromWeigthMap(e){return BE(e,this.config)}extractParams(e){const t=this.config.filterSizes||yc.DEFAULT_FILTER_SIZES,s=t?t.length:void 0;if(s!==7&&s!==8&&s!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${s} filterSizes in config`);return PE(e,this.config,this.boxEncodingSize,t)}async extractBoxes(e,t,s){const{width:n,height:i}=t,r=Math.max(n,i),o=r/n,a=r/i,l=e.shape[1],c=this.config.anchors.length,[p,u,h]=C(()=>{const g=e.reshape([l,l,c,this.boxEncodingSize]),y=g.slice([0,0,0,0],[l,l,c,4]),w=g.slice([0,0,0,4],[l,l,c,1]),x=this.withClassScores?ts(g.slice([0,0,0,5],[l,l,c,this.config.classes.length]),3):j(0);return[y,w,x]}),d=[],m=await u.array(),f=await p.array();for(let g=0;g<l;g++)for(let y=0;y<l;y++)for(let w=0;w<c;w++){const x=$a(m[g][y][w][0]);if(!s||x>s){const T=(y+$a(f[g][y][w][0]))/l*o,A=(g+$a(f[g][y][w][1]))/l*a,_=Math.exp(f[g][y][w][2])*this.config.anchors[w].x/l*o,E=Math.exp(f[g][y][w][3])*this.config.anchors[w].y/l*a,F=T-_/2,D=A-E/2,M={row:g,col:y,anchor:w},{classScore:P,label:B}=this.withClassScores?await this.extractPredictedClass(h,M):{classScore:1,label:0};d.push({box:new Ga(F,D,F+_,D+E),score:x,classScore:x*P,label:B,...M})}}return p.dispose(),u.dispose(),h.dispose(),d}async extractPredictedClass(e,t){const{row:s,col:n,anchor:i}=t,r=await e.array();return Array(this.config.classes.length).fill(0).map((o,a)=>r[s][n][i][a]).map((o,a)=>({classScore:o,label:a})).reduce((o,a)=>o.classScore>a.classScore?o:a)}}yc.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class Ma extends yc{constructor(e=!0){const t=Object.assign({},{withSeparableConvs:e,iouThreshold:FE,classes:["face"]},e?{anchors:UE,meanRgb:$E}:{anchors:ME,withClassScores:!0});super(t)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(e,t){const s=await this.detect(e,t);return s.map(n=>new ht(n.score,n.relativeBox,{width:n.imageWidth,height:n.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?zE:WE}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}function WL(e,t=!0){const s=new Ma(t);return s.extractWeights(e),s}class sh extends Xn{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class hn{async then(e){return e(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}async function _a(e,t,s,n,i=({alignedRect:r})=>r){const r=e.map(l=>or(l)?i(l):l.detection),o=n||(t instanceof me?await Co(t,r):await No(t,r)),a=await s(o);return o.forEach(l=>l instanceof me&&l.dispose()),a}async function bc(e,t,s,n,i){return _a([e],t,async r=>s(r[0]),n,i)}const jE=.4,VE=[new _e(1.603231,2.094468),new _e(6.041143,7.080126),new _e(2.882459,3.518061),new _e(4.266906,5.178857),new _e(9.041765,10.66308)],GE=[117.001,114.697,97.404];class Ua extends yc{constructor(){const e={withSeparableConvs:!0,iouThreshold:jE,classes:["face"],anchors:VE,meanRgb:GE,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(e)}get anchors(){return this.config.anchors}async locateFaces(e,t){const s=await this.detect(e,t);return s.map(n=>new ht(n.score,n.relativeBox,{width:n.imageWidth,height:n.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}const Be={ssdMobilenetv1:new To,tinyFaceDetector:new Ua,tinyYolov2:new Ma,faceLandmark68Net:new za,faceLandmark68TinyNet:new mh,faceRecognitionNet:new Wa,faceExpressionNet:new gh,ageGenderNet:new vh},Gg=(e,t)=>Be.ssdMobilenetv1.locateFaces(e,t),GL=(e,t)=>Be.tinyFaceDetector.locateFaces(e,t),qL=(e,t)=>Be.tinyYolov2.locateFaces(e,t),qg=e=>Be.faceLandmark68Net.detectLandmarks(e),HL=e=>Be.faceLandmark68TinyNet.detectLandmarks(e),YL=e=>Be.faceRecognitionNet.computeFaceDescriptor(e),KL=e=>Be.faceExpressionNet.predictExpressions(e),XL=e=>Be.ageGenderNet.predictAgeAndGender(e),Hg=e=>Be.ssdMobilenetv1.load(e),JL=e=>Be.tinyFaceDetector.load(e),ZL=e=>Be.tinyYolov2.load(e),QL=e=>Be.faceLandmark68Net.load(e),eS=e=>Be.faceLandmark68TinyNet.load(e),tS=e=>Be.faceRecognitionNet.load(e),sS=e=>Be.faceExpressionNet.load(e),nS=e=>Be.ageGenderNet.load(e),iS=Hg,rS=Gg,oS=qg;class qE extends hn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.extractedFaces=s}}class qu extends qE{async run(){const e=await this.parentTask,t=await _a(e,this.input,async s=>await Promise.all(s.map(n=>Be.faceExpressionNet.predictExpressions(n))),this.extractedFaces);return e.map((s,n)=>Rc(s,t[n]))}withAgeAndGender(){return new Vu(this,this.input)}}class Hu extends qE{async run(){const e=await this.parentTask;if(!e)return;const t=await bc(e,this.input,s=>Be.faceExpressionNet.predictExpressions(s),this.extractedFaces);return Rc(e,t)}withAgeAndGender(){return new Gu(this,this.input)}}class Lc extends qu{withAgeAndGender(){return new wc(this,this.input)}withFaceDescriptors(){return new ir(this,this.input)}}class Sc extends Hu{withAgeAndGender(){return new xc(this,this.input)}withFaceDescriptor(){return new rr(this,this.input)}}class HE extends hn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.extractedFaces=s}}class Vu extends HE{async run(){const e=await this.parentTask,t=await _a(e,this.input,async s=>await Promise.all(s.map(n=>Be.ageGenderNet.predictAgeAndGender(n))),this.extractedFaces);return e.map((s,n)=>{const{age:i,gender:r,genderProbability:o}=t[n];return Ec(Cc(s,r,o),i)})}withFaceExpressions(){return new qu(this,this.input)}}class Gu extends HE{async run(){const e=await this.parentTask;if(!e)return;const{age:t,gender:s,genderProbability:n}=await bc(e,this.input,i=>Be.ageGenderNet.predictAgeAndGender(i),this.extractedFaces);return Ec(Cc(e,s,n),t)}withFaceExpressions(){return new Hu(this,this.input)}}class wc extends Vu{withFaceExpressions(){return new Lc(this,this.input)}withFaceDescriptors(){return new ir(this,this.input)}}class xc extends Gu{withFaceExpressions(){return new Sc(this,this.input)}withFaceDescriptor(){return new rr(this,this.input)}}class hh extends hn{constructor(e,t){super();this.parentTask=e,this.input=t}}class ir extends hh{async run(){const e=await this.parentTask,t=await _a(e,this.input,s=>Promise.all(s.map(n=>Be.faceRecognitionNet.computeFaceDescriptor(n))),null,s=>s.landmarks.align(null,{useDlibAlignment:!0}));return t.map((s,n)=>Oc(e[n],s))}withFaceExpressions(){return new Lc(this,this.input)}withAgeAndGender(){return new wc(this,this.input)}}class rr extends hh{async run(){const e=await this.parentTask;if(!e)return;const t=await bc(e,this.input,s=>Be.faceRecognitionNet.computeFaceDescriptor(s),null,s=>s.landmarks.align(null,{useDlibAlignment:!0}));return Oc(e,t)}withFaceExpressions(){return new Sc(this,this.input)}withAgeAndGender(){return new xc(this,this.input)}}class ch extends hn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.useTinyLandmarkNet=s}get landmarkNet(){return this.useTinyLandmarkNet?Be.faceLandmark68TinyNet:Be.faceLandmark68Net}}class ph extends ch{async run(){const e=await this.parentTask,t=e.map(i=>i.detection),s=this.input instanceof me?await Co(this.input,t):await No(this.input,t),n=await Promise.all(s.map(i=>this.landmarkNet.detectLandmarks(i)));return s.forEach(i=>i instanceof me&&i.dispose()),e.map((i,r)=>Ao(i,n[r]))}withFaceExpressions(){return new Lc(this,this.input)}withAgeAndGender(){return new wc(this,this.input)}withFaceDescriptors(){return new ir(this,this.input)}}class uh extends ch{async run(){const e=await this.parentTask;if(!e)return;const{detection:t}=e,s=this.input instanceof me?await Co(this.input,[t]):await No(this.input,[t]),n=await this.landmarkNet.detectLandmarks(s[0]);return s.forEach(i=>i instanceof me&&i.dispose()),Ao(e,n)}withFaceExpressions(){return new Sc(this,this.input)}withAgeAndGender(){return new xc(this,this.input)}withFaceDescriptor(){return new rr(this,this.input)}}class ah extends hn{constructor(e,t=new pn){super();this.input=e,this.options=t}}class Nc extends ah{async run(){const{input:e,options:t}=this,s=t instanceof sh?n=>Be.tinyFaceDetector.locateFaces(n,t):t instanceof pn?n=>Be.ssdMobilenetv1.locateFaces(n,t):t instanceof Xn?n=>Be.tinyYolov2.locateFaces(n,t):null;if(!s)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return s(e)}runAndExtendWithFaceDetections(){return new Promise(async e=>{const t=await this.run();return e(t.map(s=>ar({},s)))})}withFaceLandmarks(e=!1){return new ph(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new qu(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Vu(this.runAndExtendWithFaceDetections(),this.input)}}class lh extends ah{async run(){const e=await new Nc(this.input,this.options);let t=e[0];return e.forEach(s=>{s.score>t.score&&(t=s)}),t}runAndExtendWithFaceDetection(){return new Promise(async e=>{const t=await this.run();return e(t?ar({},t):void 0)})}withFaceLandmarks(e=!1){return new uh(this.runAndExtendWithFaceDetection(),this.input,e)}withFaceExpressions(){return new Hu(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Gu(this.runAndExtendWithFaceDetection(),this.input)}}function aS(e,t=new pn){return new lh(e,t)}function Ac(e,t=new pn){return new Nc(e,t)}async function Yg(e,t){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await Ac(e,new pn(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function lS(e,t={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await Ac(e,new Xn(t)).withFaceLandmarks().withFaceDescriptors()}const cS=Yg;function yh(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const s=Array.from(e),n=Array.from(t);return Math.sqrt(s.map((i,r)=>i-n[r]).reduce((i,r)=>i+Math.pow(r,2),0))}class Kg{constructor(e,t=.6){this._distanceThreshold=t;const s=Array.isArray(e)?e:[e];if(!s.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let n=1;const i=()=>`person ${n++}`;this._labeledDescriptors=s.map(r=>{if(r instanceof hr)return r;if(r instanceof Float32Array)return new hr(i(),[r]);if(r.descriptor&&r.descriptor instanceof Float32Array)return new hr(i(),[r.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(e,t){return t.map(s=>yh(s,e)).reduce((s,n)=>s+n,0)/(t.length||1)}matchDescriptor(e){return this.labeledDescriptors.map(({descriptors:t,label:s})=>new Dc(s,this.computeMeanDistance(e,t))).reduce((t,s)=>t.distance<s.distance?t:s)}findBestMatch(e){const t=this.matchDescriptor(e);return t.distance<this.distanceThreshold?t:new Dc("unknown",t.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(e=>e.toJSON())}}static fromJSON(e){const t=e.labeledDescriptors.map(s=>hr.fromJSON(s));return new Kg(t,e.distanceThreshold)}}function zL(e){const t=new Ua;return t.extractWeights(e),t}function Vg(e,t){const{width:s,height:n}=new Ts(t.width,t.height);if(s<=0||n<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:s,height:n})}`);if(Array.isArray(e))return e.map(i=>Vg(i,{width:s,height:n}));if(or(e)){const i=e.detection.forSize(s,n),r=e.unshiftedLandmarks.forSize(i.box.width,i.box.height);return Ao(ar(e,i),r)}return Mn(e)?ar(e,e.detection.forSize(s,n)):e instanceof Hs||e instanceof ht?e.forSize(s,n):e}var UL="0.6.2";return wS();})();
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @license See the LICENSE file. */
//# sourceMappingURL=face-api.js.map