face-api/dist/face-api.min.js

3944 lines
906 KiB
JavaScript

var faceapi=(()=>{var Yu=Object.defineProperty,WO=Object.prototype.hasOwnProperty,$s=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),Jx=e=>Yu(e,"__esModule",{value:!0}),Re=(e,t)=>{Jx(e);for(var s in t)Yu(e,s,{get:t[s],enumerable:!0})},zO=(e,t)=>{if(Jx(e),typeof t=="object"||typeof t=="function")for(let s in t)!WO.call(e,s)&&s!=="default"&&Yu(e,s,{get:()=>t[s],enumerable:!0});return e},nl=e=>e&&e.__esModule?e:zO(Yu({},"default",{value:e,enumerable:!0}),e);var Qx=$s((Zx,Qf)=>{(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})(Zx,typeof Qf=="object"&&Qf,typeof define=="function"&&define)});var tL=$s((eL,eg)=>{(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})(eL,typeof eg=="object"&&eg,typeof define=="function"&&define)});var nL=$s((sL,tg)=>{(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 tg=="object"&&tg,typeof define=="function"&&define)});var rL=$s((iL,sg)=>{(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})(iL,typeof sg=="object"&&sg,typeof define=="function"&&define)});var aL=$s((oL,ng)=>{(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,y=[],b=128;for(p===(p|0)?(h=p,p=null):(p=p+"\0",h=0,b=Math.max(b,p.length)),d=0,m=-32;m<b;++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=y[m&127]^=h+f,d=u==0?d+1:0);for(d>=128&&(y[(p&&p.length||0)&127]=-1),d=127,m=4*128;m>0;--m)h=y[d+34&127],u=y[d=d+1&127],h^=h<<13,u^=u<<17,h^=h>>>15,u^=u>>>12,y[d]=h^u;c.w=f,c.X=y,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})(oL,typeof ng=="object"&&ng,typeof define=="function"&&define)});var cL=$s((lL,ig)=>{(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})(lL,typeof ig=="object"&&ig,typeof define=="function"&&define)});var pL=$s(()=>{});var uL=$s((AP,Ku)=>{(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,I,A){var k=[];I=I==!0?{entropy:!0}:I||{};var R=y(f(I.entropy?[x,S(e)]:x==null?b():x,3),k),D=new d(k),F=function(){for(var M=D.g(i),B=a,V=0;M<l;)M=(M+V)*n,B*=n,V=D.g(1);for(;M>=c;)M/=2,B/=2,V>>>=1;return(M+V)/B};return F.int32=function(){return D.g(4)|0},F.quick=function(){return D.g(4)/4294967296},F.double=F,y(S(D.S),e),(I.pass||A||function(M,B,V,Y){return Y&&(Y.S&&m(Y,D),M.state=function(){return m(D,{})}),V?(t[o]=M,B):M})(F,R,"global"in I?I.global:this==t,I.state)}t["seed"+o]=h;function d(x){var I,A=x.length,k=this,R=0,D=k.i=k.j=0,F=k.S=[];for(A||(x=[A++]);R<n;)F[R]=R++;for(R=0;R<n;R++)F[R]=F[D=p&D+x[R%A]+(I=F[R])],F[D]=I;(k.g=function(M){for(var B,V=0,Y=k.i,G=k.j,Z=k.S;M--;)B=Z[Y=p&Y+1],V=V*n+Z[p&(Z[Y]=Z[G=p&G+B])+(Z[G]=B)];return k.i=Y,k.j=G,V})(n)}function m(x,I){return I.i=x.i,I.j=x.j,I.S=x.S.slice(),I}function f(x,I){var A=[],k=typeof x,R;if(I&&k=="object")for(R in x)try{A.push(f(x[R],I-1))}catch(D){}return A.length?A:k=="string"?x:x+"\0"}function y(x,I){for(var A=x+"",k,R=0;R<A.length;)I[p&R]=p&(k^=I[p&R]*19)+A.charCodeAt(R++);return S(I)}function b(){try{var x;return u&&(x=u.randomBytes)?x=x(n):(x=new Uint8Array(n),(s.crypto||s.msCrypto).getRandomValues(x)),S(x)}catch(k){var I=s.navigator,A=I&&I.plugins;return[+new Date(),s,A,s.screen,S(e)]}}function S(x){return String.fromCharCode.apply(0,x)}if(y(t.random(),e),typeof Ku=="object"&&Ku.exports){Ku.exports=h;try{u=pL()}catch(x){}}else typeof define=="function"&&define.amd&&define(function(){return h})})([],Math)});var il=$s((NP,hL)=>{var BO=Qx(),PO=tL(),jO=nL(),VO=rL(),GO=aL(),HO=cL(),Tr=uL();Tr.alea=BO;Tr.xor128=PO;Tr.xorwow=jO;Tr.xorshift7=VO;Tr.xor4096=GO;Tr.tychei=HO;hL.exports=Tr});var dL=$s(()=>{});var mL=$s(()=>{});var gL=$s((qO,fL)=>{Re(qO,{isNodejs:()=>YO});function YO(){return typeof global=="object"&&!0&&typeof fL!="undefined"&&typeof process!="undefined"&&!!process.version}});var HL=$s(KO=>{Re(KO,{AgeGenderNet:()=>vh,BoundingBox:()=>Zo,Box:()=>tt,ComposableTask:()=>nn,ComputeAllFaceDescriptorsTask:()=>qi,ComputeFaceDescriptorsTaskBase:()=>ph,ComputeSingleFaceDescriptorTask:()=>Yi,DetectAllFaceLandmarksTask:()=>lh,DetectAllFacesTask:()=>rl,DetectFaceLandmarksTaskBase:()=>ah,DetectFacesTaskBase:()=>rh,DetectSingleFaceLandmarksTask:()=>ch,DetectSingleFaceTask:()=>oh,Dimensions:()=>Ls,FACE_EXPRESSION_LABELS:()=>dh,FaceDetection:()=>bt,FaceExpressionNet:()=>mh,FaceExpressions:()=>Ji,FaceLandmark68Net:()=>Yo,FaceLandmark68TinyNet:()=>hh,FaceLandmarkNet:()=>zL,FaceLandmarks:()=>Ws,FaceLandmarks5:()=>GL,FaceLandmarks68:()=>Jo,FaceMatch:()=>hl,FaceMatcher:()=>lg,FaceRecognitionNet:()=>qo,Gender:()=>Vn,LabeledBox:()=>ul,LabeledFaceDescriptors:()=>tr,NetInput:()=>pi,NeuralNetwork:()=>hs,ObjectDetection:()=>Or,Point:()=>Ee,PredictedBox:()=>VL,Rect:()=>Sh,TinyFaceDetector:()=>Ir,TinyFaceDetectorOptions:()=>Hi,TinyYolov2:()=>Go,TinyYolov2Options:()=>Vo,TinyYolov2SizeType:()=>eh,awaitMediaLoaded:()=>Lh,bufferToImage:()=>xh,computeFaceDescriptor:()=>vL,createCanvas:()=>Rr,createCanvasFromMedia:()=>Xo,createFaceRecognitionNet:()=>WL,createTinyFaceDetector:()=>bL,createTinyYolov2:()=>yL,detectAllFaces:()=>ML,detectFaceLandmarks:()=>og,detectFaceLandmarksTiny:()=>SL,detectLandmarks:()=>DL,detectSingleFace:()=>FL,draw:()=>Ju,env:()=>Ve,euclideanDistance:()=>fh,extendWithAge:()=>cl,extendWithFaceDescriptor:()=>ll,extendWithFaceDetection:()=>Xi,extendWithFaceExpressions:()=>al,extendWithFaceLandmarks:()=>Ar,extendWithGender:()=>ol,extractFaceTensors:()=>Cr,extractFaces:()=>Nr,fetchImage:()=>jL,fetchJson:()=>wh,fetchNetWeights:()=>PL,fetchOrThrow:()=>er,getContext2dOrThrow:()=>us,getMediaDimensions:()=>Qi,imageTensorToCanvas:()=>bh,imageToSquare:()=>yh,inverseSigmoid:()=>xL,iou:()=>ih,isMediaElement:()=>pl,isMediaLoaded:()=>Ko,isWithAge:()=>$L,isWithFaceDetection:()=>Sn,isWithFaceExpressions:()=>uh,isWithFaceLandmarks:()=>Ki,isWithGender:()=>UL,loadAgeGenderModel:()=>EL,loadFaceDetectionModel:()=>kL,loadFaceExpressionModel:()=>OL,loadFaceLandmarkModel:()=>NL,loadFaceLandmarkTinyModel:()=>CL,loadFaceRecognitionModel:()=>RL,loadTinyFaceDetectorModel:()=>ag,loadTinyYolov2Model:()=>AL,loadWeightMap:()=>gh,locateFaces:()=>_L,matchDimensions:()=>BL,minBbox:()=>nh,nets:()=>Qe,nonMaxSuppression:()=>sh,normalize:()=>sn,padToSquare:()=>th,predictAgeAndGender:()=>IL,recognizeFaceExpressions:()=>TL,resizeResults:()=>rg,resolveInput:()=>Zi,shuffleArray:()=>wL,sigmoid:()=>Ho,tf:()=>Xu,tinyFaceDetector:()=>LL,toNetInput:()=>pt,utils:()=>Zu,validateConfig:()=>Qu})});const qL="tfjsflags";class cg{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=XO(this.global.location.search);if(qL in e){const t=e[qL].split(",");t.forEach(s=>{const[n,i]=s.split(":");this.urlFlags[n]=JO(n,i)})}}}function XO(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(s,...n)=>(ZO(t,n[0],n[1]),n.join("="))),t}function ZO(e,t,s){e[decodeURIComponent(t)]=decodeURIComponent(s||"")}function JO(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 $(){return pg}let pg=null;function YL(e){pg=e}let ug;function hg(){if(ug==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");ug=e}return ug}function QO(){const e=hg();return e._tfGlobals==null&&(e._tfGlobals=new Map()),e._tfGlobals}function dg(e,t){const s=QO();if(s.has(e))return s.get(e);{const n=t();return s.set(e,n),s.get(e)}}const dl="Abs",ml="Acos",fl="Acosh",Er="Add",gl="AddN",mg="All",fg="Any",yl="ArgMax",bl="ArgMin",wl="Asin",xl="Asinh",Ll="Atan",Sl="Atanh",vl="Atan2",Tl="AvgPool",gg="AvgPoolBackprop",Il="AvgPool3D",yg="AvgPool3DBackprop",Al="BatchMatMul",Nl="BatchToSpaceND",Cl="BroadcastTo",kr="Cast",Rl="Ceil",Ol="ClipByValue",bg="Complex",El="Concat",kl="Conv2D",wg="Conv2DBackpropFilter",_l="Conv2DBackpropInput",Dl="Conv3D",xg="Conv3DBackpropFilterV2",Lg="Conv3DBackpropInputV2",Fl="Cos",Ml="Cosh",Ul="Cumsum",Sg="CropAndResize",vg="DepthToSpace",$l="DepthwiseConv2dNative",Tg="DepthwiseConv2dNativeBackpropFilter",Ig="DepthwiseConv2dNativeBackpropInput",Ag="Diag",_r="Dilation2D",Qo="Dilation2DBackpropInput",ea="Dilation2DBackpropFilter",ui="Div",Wl="Elu",Ng="EluGrad",zl="Erf",Cg="Equal",Bl="Exp",Pl="Expm1",Rg="FFT",Og="Fill",Dr="FlipLeftRight",jl="Floor",Vl="FloorDiv",Gl="FusedBatchNorm",Hl="GatherV2",Eg="GatherNd",kg="Greater",ql="GreaterEqual",Yl="Identity",_g="IFFT",Dg="Imag",Kl="IsFinite",Xl="IsInf",Jl="IsNan",Fg="Less",Mg="LessEqual",Ug="LinSpace",Zl="Log",Ql="Log1p",$g="LogicalAnd",Wg="LogicalNot",zg="LogicalOr",ec="LogSoftmax",tc="LRN",Bg="LRNBackprop",hi="Max",sc="Maximum",nc="MaxPool",Pg="MaxPoolBackprop",ic="MaxPool3D",jg="MaxPool3DBackprop",Fr="MaxPoolWithArgmax",e1="Mean",rc="Min",oc="Minimum",ac="Mod",lc="Multiply",cc="Negate",Vg="NotEqual",pc="NonMaxSuppressionV3",Mr="NonMaxSuppressionV4",Ur="NonMaxSuppressionV5",uc="OnesLike",hc="OneHot",dc="PadV2",t1="Pool",mc="Pow",fc="Prelu",Gg="Prod",Hg="Range",qg="Real",gc="Reciprocal",yc="Relu",bc="Reshape",wc="ResizeNearestNeighbor",Yg="ResizeNearestNeighborGrad",xc="ResizeBilinear",Kg="ResizeBilinearGrad",Lc="Relu6",Sc="Reverse",vc="Round",Tc="Rsqrt",Xg="ScatterNd",Ic="SelectV2",Ac="Selu",Nc="Slice",Cc="Sin",Rc="Sinh",Oc="Sign",Ec="Sigmoid",kc="Softplus",_c="Sqrt",Dc="Sum",Fc="SpaceToBatchND",Mc="SplitV",Uc="Softmax",di="SquaredDifference",$r="Square",$c="Sub",Jg="SparseToDense",Zg="StridedSlice",Wc="Tan",zc="Tanh",Bc="Tile",Qg="TopK",mi="Transpose",Pc="Unpack",jc="UnsortedSegmentSum",Vc="ZerosLike",Gc="Step",ta="FromPixels",Wr="RotateWithOffset",Th="_FusedMatMul",Ih="FusedConv2D",Ah="FusedDepthwiseConv2D";const sa=dg("kernelRegistry",()=>new Map()),Hc=dg("gradRegistry",()=>new Map());function qc(e,t){const s=ey(e,t);return sa.get(s)}function Nh(e){return Hc.get(e)}function Ch(e){const t=sa.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 Yc(e){const{kernelName:t,backendName:s}=e,n=ey(t,s);sa.has(n)&&console.warn(`The kernel '${t}' for backend '${s}' is already registered`),sa.set(n,e)}function ty(e){const{kernelName:t}=e;Hc.has(t)&&($().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),Hc.set(t,e)}function s1(e,t){const s=ey(e,t);if(!sa.has(s))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);sa.delete(s)}function n1(e){if(!Hc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Hc.delete(e)}function ey(e,t){return`${t}_${e}`}const E={};Re(E,{arraysEqual:()=>It,assert:()=>v,assertNonNegativeIntegerDimensions:()=>Jc,assertNonNull:()=>zs,assertShapesMatch:()=>xe,bytesFromStringArray:()=>ly,bytesPerElement:()=>ay,checkConversionForErrors:()=>XL,clamp:()=>na,computeStrides:()=>qn,createShuffledIndices:()=>u1,decodeString:()=>Oh,distSquared:()=>a1,encodeString:()=>cy,fetch:()=>f1,flatten:()=>Gn,getArrayFromDType:()=>iy,getTypedArrayFromDType:()=>ia,hasEncodingLoss:()=>oy,indexToLoc:()=>y1,inferDtype:()=>ra,inferFromImplicitShape:()=>sy,isBoolean:()=>JL,isFunction:()=>Hn,isInt:()=>De,isNumber:()=>ZL,isScalarShape:()=>l1,isString:()=>vn,isTypedArray:()=>_t,isValidDtype:()=>ry,locToIndex:()=>g1,makeOnesTypedArray:()=>Xc,makeZerosNestedTypedArray:()=>m1,makeZerosTypedArray:()=>Yn,nearestDivisor:()=>oa,nearestLargerEven:()=>i1,now:()=>Rh,parseAxisParam:()=>Te,randUniform:()=>o1,repeatedTry:()=>h1,rightPad:()=>zr,shuffle:()=>KL,sizeFromShape:()=>We,sizeToSquarishShape:()=>p1,squeezeShape:()=>ny,sum:()=>r1,tanh:()=>c1,toNestedArray:()=>Br,toTypedArray:()=>Kc});function KL(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 na(e,t,s){return Math.max(e,Math.min(t,s))}function i1(e){return e%2===0?e:e+1}function r1(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s];return t}function o1(e,t){const s=Math.random();return t*s+(1-s)*e}function a1(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 v(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function xe(e,t,s=""){v(It(e,t),()=>s+` Shapes ${e} and ${t} must match`)}function zs(e){v(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Gn(e,t=[],s=!1){if(t==null&&(t=[]),Array.isArray(e)||_t(e)&&!s)for(let n=0;n<e.length;++n)Gn(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 l1(e){return e.length===0}function It(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 c1(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 p1(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function u1(e){const t=new Uint32Array(e);for(let s=0;s<e;++s)t[s]=s;return KL(t),t}function zr(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function h1(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 sy(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 Te(e,t){const s=t.length;return e=e==null?t.map((n,i)=>i):[].concat(e),v(e.every(n=>n>=-s&&n<s),()=>`All values in axis param must be in range [-${s}, ${s}) but got axis ${e}`),v(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 ny(e,t){const s=[],n=[],i=t!=null&&Array.isArray(t)&&t.length===0,r=t==null||i?null:Te(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 ia(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 iy(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 XL(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 ry(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function oy(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function _t(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function ay(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 ly(e){if(e==null)return 0;let t=0;return e.forEach(s=>t+=s.length),t}function vn(e){return typeof e=="string"||e instanceof String}function JL(e){return typeof e=="boolean"}function ZL(e){return typeof e=="number"}function ra(e){return Array.isArray(e)?ra(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":ZL(e)?"float32":vn(e)?"string":JL(e)?"bool":"float32"}function Hn(e){return!!(e&&e.constructor&&e.call&&e.apply)}function oa(e,t){for(let s=t;s<e;++s)if(e%s===0)return s;return e}function qn(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 Kc(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Gn(e)),$().getBool("DEBUG")&&XL(e,t),d1(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 QL(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]=QL(e+a*o,r,s)}return n}function Br(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 QL(0,e,t)}function d1(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Xc(e,t){const s=Yn(e,t);for(let n=0;n<s.length;n++)s[n]=1;return s}function Yn(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 m1(e,t){const s=e.reduce((n,i)=>n*i,1);if(t==null||t==="float32")return Br(e,new Float32Array(s));if(t==="int32")return Br(e,new Int32Array(s));if(t==="bool")return Br(e,new Uint8Array(s));throw new Error(`Unknown data type ${t}`)}function Rh(){return $().platform.now()}function Jc(e){e.forEach(t=>{v(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function f1(e,t){return $().platform.fetch(e,t)}function cy(e,t="utf-8"){return t=t||"utf-8",$().platform.encode(e,t)}function Oh(e,t="utf-8"){return t=t||"utf-8",$().platform.decode(e,t)}function g1(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 y1(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 eS{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new w1())}profileKernel(e,t,s){let n;const i=()=>{n=s()},r=this.backendTimer.time(i);n.map(a=>{a.data().then(l=>{b1(l,a.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 b1(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 w1{logKernelProfile(e,t,s,n,i,r){const o=typeof n=="number"?zr(`${n}ms`,9):n.error,a=zr(e,25),l=t.rank,c=t.size,p=zr(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 tS(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 sS(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(!It(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 nS=20,Zc=3,py=7;function iS(e,t,s,n){const i=qn(t),r=x1(e,t,s,i),o=t.length,a=Eh(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 x1(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"?ep(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],Qc(l[p+u],0,s).length)}return o}function Qc(e,t,s){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed(py))} + ${parseFloat(e[1].toFixed(py))}j`:vn(e)?n=`'${e}'`:s==="bool"?n=rS(e):n=parseFloat(e.toFixed(py)).toString(),zr(n,t)}function rS(e){return e===0?"false":"true"}function Eh(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=ep(e);return[Qc(f[0],0,s)]}return s==="bool"?[rS(e[0])]:[e[0].toString()]}if(l===1){if(a>nS){const y=Zc*o;let b=Array.from(e.slice(0,y)),S=Array.from(e.slice((a-Zc)*o,a*o));return s==="complex64"&&(b=ep(b),S=ep(S)),["["+b.map((x,I)=>Qc(x,i[I],s)).join(", ")+", ..., "+S.map((x,I)=>Qc(x,i[a-Zc+I],s)).join(", ")+"]"]}const f=s==="complex64"?ep(e):Array.from(e);return["["+f.map((y,b)=>Qc(y,i[b],s)).join(", ")+"]"]}const c=t.slice(1),p=n.slice(1),u=n[0]*o,h=[];if(a>nS){for(let f=0;f<Zc;f++){const y=f*u,b=y+u;h.push(...Eh(e.slice(y,b),c,s,p,i,!1))}h.push("...");for(let f=a-Zc;f<a;f++){const y=f*u,b=y+u;h.push(...Eh(e.slice(y,b),c,s,p,i,f===a-1))}}else for(let f=0;f<a;f++){const y=f*u,b=y+u;h.push(...Eh(e.slice(y,b),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 ep(e){const t=[];for(let s=0;s<e.length;s+=2)t.push([e[s],e[s+1]]);return t}class fi{constructor(e,t,s){if(this.dtype=t,this.shape=e.slice(),this.size=We(e),s!=null){const n=s.length;v(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||iy(t,this.size),this.strides=qn(e)}set(e,...t){t.length===0&&(t=[0]),v(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 Kn().makeTensor(this.values,this.shape,this.dtype)}}let Kn=null,aa=null,L1=null;function oS(e){Kn=e}function aS(e){aa=e}function lS(e){L1=e}class ue{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=qn(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 aa.buffer(this.shape,this.dtype,e)}bufferSync(){return aa.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Br(this.shape,e)}arraySync(){return Br(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=Kn().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(s=>Oh(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=Kn().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Oh(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 Kn().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;Kn().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return aa.print(this,e)}clone(){return this.throwIfDisposed(),aa.clone(this)}toString(e=!1){const t=this.dataSync();return iS(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),aa.cast(this,e)}variable(e=!0,t,s){return this.throwIfDisposed(),Kn().makeVariable(this,e,t,s)}}Object.defineProperty(ue,Symbol.hasInstance,{value:e=>!!e&&e.dataId!=null&&e.shape!=null&&e.dtype!=null});class Xn extends ue{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(!It(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Kn().disposeTensor(this),this.dataId=e.dataId,Kn().incRef(this,null)}dispose(){Kn().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Xn,Symbol.hasInstance,{value:e=>e instanceof ue&&e.assign!=null&&e.assign instanceof Function});var uy;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(uy||(uy={}));var hy;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(hy||(hy={}));var dy;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(dy||(dy={}));var my;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(my||(my={}));var fy;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(fy||(fy={}));const S1={float32:my,int32:hy,bool:dy,complex64:fy};function wt(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return S1[e][t]}function tp(e){return wt(e,"int32")}const rn={};Re(rn,{assertTypesMatch:()=>gy,getTensorsInContainer:()=>sp,isTensorInList:()=>v1,makeTypesMatch:()=>Ne});function Ne(e,t){if(e.dtype===t.dtype)return[e,t];const s=wt(e.dtype,t.dtype);return[e.cast(s),t.cast(s)]}function gy(e,t){v(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function v1(e,t){return t.some(s=>s.id===e.id)}function sp(e){const t=[],s=new Set();return cS(e,t,s),t}function cS(e,t,s){if(e==null)return;if(e instanceof ue){t.push(e);return}if(!T1(e))return;const n=e;for(const i in n){const r=n[i];s.has(r)||(s.add(r),cS(r,t,s))}}function T1(e){return Array.isArray(e)||typeof e=="object"}class pS{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 np{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new pS()}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 eS(this.backendInstance),!0}setupRegisteredKernels(){const e=Ch(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=Ch(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(Promise.resolve(s)===s){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 np.nextTensorId++}nextVariableId(){return np.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 T.runKernelFunc(c=>c.cast(r,o),a,null,kr,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=qc(n,this.backendName);let m;if(d!=null)h=()=>{const y=this.backend.numDataIds();m=d.kernelFunc({inputs:t,attrs:i,backend:this.backend});const b=Array.isArray(m)?m:[m];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(n,y,b);const S=b.map(({dataId:x,shape:I,dtype:A})=>this.makeTensorFromDataId(x,I,A));if(c){let x=this.getTensorsForGradient(n,t,S);if(x==null){o==null&&(o=[]);const I=S.filter((A,k)=>o[k]);x=(r||[]).slice().concat(I)}l=this.saveTensorsForBackwardMode(x)}return S};else{const y=b=>{if(!c)return;l=b.map(S=>this.keep(this.clone(S)))};h=()=>{const b=this.backend.numDataIds();m=this.tidy(()=>e(this.backend,y));const S=Array.isArray(m)?m:[m];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(n,b,S),S}}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(y=>t[y]!=null?t[y].shape:null),outputShapes:a.map(y=>y.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=Nh(e);if(n!=null){const i=n.inputsToSave||[],r=n.outputsToSave||[];let o;n.saveAllInputs?(v(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"&&vn(e[0])&&(i=e.map(a=>cy(a)));const r=n.write(i,t,s),o=new ue(t,s,r,this.nextTensorId());if(this.incRef(o,n),s==="string"){const a=this.state.tensorInfo.get(r),l=ly(i);this.state.numBytes+=l-a.bytes,a.bytes=l}return o}makeTensorFromDataId(e,t,s,n){s=s||"float32";const i=new ue(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 Xn(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*ay(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 Xn||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=Nh(e);a!=null&&(n=a.gradFunc),n!=null&&(o.gradient=l=>(l=l.map((c,p)=>{if(c==null){const u=s[p],h=Yn(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=sp(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(v(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));v(i instanceof ue,()=>"The result y returned by f() must be a tensor.");const r=tS(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==null?I1(i.shape):s,sS(o,r,l=>this.tidy(l),A1);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 v(Hn(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{v(t.every(i=>i instanceof ue),()=>"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),v(s.value instanceof ue,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),v(Hn(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];v(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(...)."),v(a.every(c=>c instanceof ue),()=>"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=Rh(),s=await this.backend.time(e);return s.wallMs=Rh()-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 pS();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}}np.nextTensorId=0;np.nextVariableId=0;function I1(e){const t=Xc(We(e),"float32");return T.makeTensor(t,e,"float32")}function N1(){const e=hg();if(e._tfengine==null){const t=new cg(e);e._tfengine=new np(t)}return YL(e._tfengine.ENV),oS(()=>e._tfengine),e._tfengine}const T=N1();function A1(e,t){const s={a:e,b:t};return T.runKernelFunc((n,i)=>{const r=n.add(e,t);return i([e,t]),r},s,null,Er)}const la={};Re(la,{isBrowser:()=>yy,isMobile:()=>R1});function C1(){return typeof navigator!="undefined"&&navigator!=null}function R1(){if(C1()){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 yy(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const gi=$();gi.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.")});gi.registerFlag("IS_BROWSER",()=>yy());gi.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");gi.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));gi.registerFlag("PROD",()=>!1);gi.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>gi.getBool("DEBUG"));gi.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);gi.registerFlag("IS_TEST",()=>!1);function Zt(e,t){let s=e;if(_t(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const n=[];for(;Array.isArray(s)||_t(s)&&t!=="string";)n.push(s.length),s=s[0];return Array.isArray(e)&&$().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&uS(e,n,[]),n}function uS(e,t,s){if(s=s||[],!Array.isArray(e)&&!_t(e)){v(t.length===0,()=>`Element arr[${s.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}v(t.length>0,()=>`Element arr[${s.join("][")}] should be a primitive, but is an array of ${e.length} elements`),v(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)uS(e[i],n,s.concat(i))}function hS(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 g(e,t,s,n="numeric"){if(e instanceof ue)return hS(n,e.dtype,t,s),e;let i=ra(e);if(i!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(i=n),hS(n,i,t,s),e==null||!_t(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=Zt(e,i);!_t(e)&&!Array.isArray(e)&&(e=[e]);const o=!0,a=i!=="string"?Kc(e,i):Gn(e,[],o);return T.makeTensor(a,r,i)}function yi(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)=>g(r,`${t}[${o}]`,s),n)}function L(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));const i=(...r)=>{T.startScope(s);try{const o=n(...r);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),T.endScope(o),o}catch(o){throw T.endScope(null),o}};return Object.defineProperty(i,"name",{value:s,configurable:!0}),i}function O1(e){const t=g(e,"x","abs"),s={x:t};return T.runKernelFunc((n,i)=>(i([t]),t.dtype==="complex64"?n.complexAbs(t):n.abs(t)),s,null,dl)}const Je=L({abs_:O1});function E1(e){const t=g(e,"x","acos"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.acos(t);return i([t]),r},s,null,ml)}const ip=L({acos_:E1});function k1(e){const t=g(e,"x","acosh"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.acosh(t);return i([t]),r},s,null,fl)}const rp=L({acosh_:k1});function _1(e,t){let s=g(e,"a","add"),n=g(t,"b","add");[s,n]=Ne(s,n);const i=(o,a)=>{const l=o.add(s,n);return a([s,n]),l},r={a:s,b:n};return T.runKernelFunc(i,r,null,Er)}const W=L({add_:_1});function D1(e){v(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),v(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((r,o)=>g(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(!It(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 T.runKernelFunc(n,i,null,gl)}const op=L({addN_:D1});function by(e,t){for(let s=0;s<e.length;++s)if(e[e.length-s-1]!==t-1-s)return!1;return!0}function dS(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 wy(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 ft(e,t){const s=t.map(n=>1);return dS(e,s,t)}function F1(e,t,s){v(by(t,s),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${s} input.`)}function ut(e,t){if(by(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 Pr(e){return e.map((t,s)=>[s,t]).sort((t,s)=>t[1]-s[1]).map(t=>t[0])}function Gt(e,t){const s=[];for(let n=t-e;n<t;++n)s.push(n);return s}function M1(e,t){const s=g(e,"x","reshape",null);t=sy(t,s.size),v(s.size===We(t),()=>"new shape and old shape must have the same number of elements.");const n={x:s},i={shape:t},r=(o,a)=>(a([s]),o.reshape(s,t));return T.runKernelFunc(r,n,null,bc,i)}const O=L({reshape_:M1});function U1(e,t){const s=g(e,"x","transpose");if(t==null&&(t=s.shape.map((r,o)=>o).reverse()),v(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`),t.forEach(r=>{v(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 T.runKernelFunc(r=>r.transpose(s,t),n,null,mi,i)}const se=L({transpose_:U1});function $1(e,t=null,s=!1){let n=g(e,"x","all","bool");const i=a=>{const l=Te(t,n.shape);let c=l;const p=ut(c,n.rank);p!=null&&(n=se(n,p),c=Gt(c.length,n.rank));const u=a.all(n,c);if(s){const h=ft(u.shape,l);return O(u,h)}return u},r={x:n},o={axis:t,keepDims:s};return T.runKernelFunc(i,r,null,mg,o)}const jr=L({all_:$1});function W1(e,t=null,s=!1){let n=g(e,"x","any","bool");const i=a=>{const l=Te(t,n.shape);let c=l;const p=ut(c,n.rank);p!=null&&(n=se(n,p),c=Gt(c.length,n.rank));const u=a.any(n,c);if(s){const h=ft(u.shape,l);return O(u,h)}return u},r={x:n},o={axis:t,keepDims:s};return T.runKernelFunc(i,r,null,fg,o)}const sr=L({any_:W1});function z1(e,t=0){let s=g(e,"x","argMax");const n=(o,a)=>{a([s]);let l=Te(t,s.shape);const c=ut(l,s.rank);return c!=null&&(s=se(s,c),l=Gt(l.length,s.rank)),o.argMax(s,l[0])},i={x:s},r={axis:t};return T.runKernelFunc(n,i,null,yl,r)}const nr=L({argMax_:z1});function B1(e,t=0){let s=g(e,"x","argMin");const n=(o,a)=>{a([s]),t==null&&(t=0);let l=Te(t,s.shape);const c=ut(l,s.rank);return c!=null&&(s=se(s,c),l=Gt(l.length,s.rank)),o.argMin(s,l[0])},i={x:s},r={axis:t};return T.runKernelFunc(n,i,null,bl,r)}const ap=L({argMin_:B1});function P1(e){const t=g(e,"x","asin"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.asin(t);return i([t]),r},s,null,wl)}const lp=L({asin_:P1});function j1(e){const t=g(e,"x","asinh"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.asinh(t);return i([t]),r},s,null,xl)}const cp=L({asinh_:j1});function V1(e){const t=g(e,"x","atan"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.atan(t);return i([t]),r},s,null,Ll)}const pp=L({atan_:V1});function G1(e,t){let s=g(e,"a","atan2"),n=g(t,"b","atan2");[s,n]=Ne(s,n);const i=(o,a)=>{const l=o.atan2(s,n);return a([s,n]),l},r={a:s,b:n};return T.runKernelFunc(i,r,null,vl)}const up=L({atan2_:G1});function H1(e){const t=g(e,"x","atanh"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.atanh(t);return i([t]),r},s,null,Sl)}const hp=L({atanh_:H1});function q1(e,t){const s=g(e,"x","cast");if(!ry(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 T.runKernelFunc(r=>r.cast(s,t),n,null,kr,i)}const K=L({cast_:q1});function Y1(e,t,s,n,i="NHWC",r){const o=e[3],a=[...t,o],l=ir(i);return is(e,a,s,r,n,null,null,l)}function Tn(e,t,s,n,i,r,o="channelsLast"){const[a,l]=kh(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 is(e,c,s,n,i,r,!1,o)}function bi(e,t,s,n,i,r,o="NDHWC"){const[a,l,c]=xy(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 rr(e,p,s,n,i,!1,u,r)}function is(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,y]=kh(s),[b,S]=kh(n),x=ca(h,b),I=ca(d,S),{padInfo:A,outHeight:k,outWidth:R}=K1(i,c,p,f,y,x,I,r,a),D=o?m*u:m;let F;return a==="channelsFirst"?F=[l,D,k,R]:a==="channelsLast"&&(F=[l,k,R,D]),{batchSize:l,dataFormat:a,inHeight:c,inWidth:p,inChannels:u,outHeight:k,outWidth:R,outChannels:D,padInfo:A,strideHeight:f,strideWidth:y,filterHeight:h,filterWidth:d,effectiveFilterHeight:x,effectiveFilterWidth:I,dilationHeight:b,dilationWidth:S,inShape:e,outShape:F,filterShape:t}}function rr(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,,y]=t,[b,S,x]=xy(s),[I,A,k]=xy(n),R=ca(d,I),D=ca(m,A),F=ca(f,k),{padInfo:M,outDepth:B,outHeight:V,outWidth:Y}=X1(i,c,p,u,b,S,x,R,D,F,a),G=r?y*h:y;let Z;return o==="channelsFirst"?Z=[l,G,B,V,Y]:o==="channelsLast"&&(Z=[l,B,V,Y,G]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:p,inWidth:u,inChannels:h,outDepth:B,outHeight:V,outWidth:Y,outChannels:G,padInfo:M,strideDepth:b,strideHeight:S,strideWidth:x,filterDepth:d,filterHeight:m,filterWidth:f,effectiveFilterDepth:R,effectiveFilterHeight:D,effectiveFilterWidth:F,dilationDepth:I,dilationHeight:A,dilationWidth:k,inShape:e,outShape:Z,filterShape:t}}function J1(e,t,s,n,i){n==null&&(n=Ly(e,t,s));const r=e[0],o=e[1],a=Vr((r-t+2*n)/s+1,i);v(De(a),()=>`The output # of rows (${a}) must be an integer. Change the stride and/or zero pad parameters`);const l=Vr((o-t+2*n)/s+1,i);return v(De(l),()=>`The output # of columns (${l}) must be an integer. Change the stride and/or zero pad parameters`),[a,l]}function Z1(e,t,s,n,i,r){i==null&&(i=Ly(e,t,n));const o=e[0],a=e[1],l=e[2],c=Vr((o-t+2*i)/n+1,r);v(De(c),()=>`The output # of depths (${c}) must be an integer. Change the stride and/or zero pad parameters`);const p=Vr((a-t+2*i)/n+1,r);v(De(p),()=>`The output # of rows (${p}) must be an integer. Change the stride and/or zero pad parameters`);const u=Vr((l-t+2*i)/n+1,r);return v(De(u),()=>`The output # of columns (${u}) must be an integer. Change the stride and/or zero pad parameters`),[c,p,u,s]}function Ly(e,t,s,n=1){const i=ca(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)}function kh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function xy(e){return typeof e=="number"?[e,e,e]:e}function ca(e,t){return t<=1?e:e+(e-1)*(t-1)}function K1(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=J1([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,y=Math.floor(d/2),b=d-y;c={top:m,bottom:f,left:y,right:b,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],y=h===0&&d===0&&m===0&&f===0?"VALID":"EXPLICIT";c={top:h,bottom:d,left:m,right:f,type:y},p=Vr((t-r+h+d)/n+1,a),u=Vr((s-o+m+f)/i+1,a)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:p,outWidth:u}}function X1(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 y=Z1([t,s,n,1],a,1,i,e,p);h=y[0],d=y[1],m=y[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,y=(d-1)*r+l-s,b=(m-1)*o+c-n,S=Math.floor(f/2),x=f-S,I=Math.floor(y/2),A=y-I,k=Math.floor(b/2),R=b-k;u={top:I,bottom:A,left:k,right:R,front:S,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 Vr(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 Bs(e){const[t,s,n]=kh(e);return t===1&&s===1&&n===1}function et(e,t){return Bs(e)||Bs(t)}function ir(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Q1(e,t,s,n,i){const r=g(e,"x","avgPool","float32"),o=1;v(et(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]])),v(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),i!=null&&v(De(n),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const c=(d,m)=>{const f=Tn(a.shape,t,s,1,n,i);return m([a]),f.filterWidth===1&&f.filterHeight===1&&It(f.inShape,f.outShape)?a.clone():d.avgPool(a,f)},p={x:a},u={filterSize:t,strides:s,pad:n,dimRoundingMode:i};let h=T.runKernelFunc(c,p,null,Tl,u);return h=K(h,r.dtype),l?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const rs=L({avgPool_:Q1});function eE(){$().set("PROD",!0)}function tE(){$().set("DEBUG",!0)}function sE(){$().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function xt(e){$().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}lS(xt);function nE(){T.disposeVariables()}function os(){return T}function pa(){return T.memory()}function iE(e){return T.profile(e)}function N(e,t){return T.tidy(e,t)}function ce(e){const t=sp(e);t.forEach(s=>s.dispose())}function gt(e){return T.keep(e)}function rE(e){return T.time(e)}function mS(e){return T.setBackend(e)}function oE(){return T.ready()}function aE(){return T.backendName}function lE(e){T.removeBackend(e)}function cE(e){return T.findBackend(e)}function pE(e){return T.findBackendFactory(e)}function dp(e,t,s=1){return T.registerBackend(e,t,s)}function Sy(){return T.backend}function uE(e,t){$().setPlatform(e,t)}function hE(e,t,s,n,i,r="NDHWC",o){o==null?o=[1,1,1]:xt("dilations is deprecated, this field will be gone in v3.0.0.");const a=g(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]])),v(l.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${l.rank}.`),v(r==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),v(et(s,o),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&v(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 y=bi(l.shape,t,s,o,n,i,r);return f([l]),m.avgPool3d(l,y)},u={x:l},h={filterSize:t,strides:s,pad:n,dimRoundingMode:i,dataFormat:r,dilations:o};let d=T.runKernelFunc(p,u,null,Il,h);return d=K(d,l.dtype),c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const Gr=L({avgPool3d_:hE});function vy(e,t){const s=e[0].length;e.forEach((i,r)=>{v(i.length===s,()=>`Error in concat${s}D: rank of tensors[${r}] must be the same as the rank of the rest (${s})`)}),v(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++)v(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 Ty(e,t){const s=e[0].slice();for(let n=1;n<e.length;n++)s[t]+=e[n][t];return s}function ds(e,t,s,n){if(n==null&&(n=ra(e)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!_t(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){Jc(t);const i=We(t),r=We(s);v(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;v(s[o]===t[o]||!l,()=>`Error creating a new Tensor. Inferred shape (${s}) does not match the provided shape (${t}). `)}}return!_t(e)&&!Array.isArray(e)&&(e=[e]),t=t||s,e=n!=="string"?Kc(e,n):Gn(e,[],!0),T.makeTensor(e,t,n)}function ze(e,t,s){const n=Zt(e,s);return ds(e,t,n,s)}function dE(e,t=0){v(e.length>=1,()=>"Pass at least one tensor to concat");let s=yi(e,"tensors","concat");s[0].dtype==="complex64"&&s.forEach(c=>{if(c.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${c.dtype}. `)});const n=Te(t,s[0].shape)[0],i=Ty(s.map(c=>c.shape),n);if(We(i)===0)return ze([],i);if(s=s.filter(c=>c.size>0),s.length===1)return s[0];const r=s.map(c=>c.shape);vy(r,n);const o=(c,p)=>{const u=c.concat(s,n);return p(s),u},a=s,l={axis:t};return T.runKernelFunc(o,a,null,El,l)}const ge=L({concat_:dE});function mE(e,t,s=!1,n=!1){let i=g(e,"a","matMul"),r=g(t,"b","matMul");[i,r]=Ne(i,r),v(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);v(It(p,u),()=>`Error in matMul: outer dimensions (${p}) and (${u}) of Tensors with shapes ${i.shape} and ${r.shape} must match.`),v(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]),y=n?O(r,[d,c,a]):O(r,[d,a,c]),b=(A,k)=>(k([f,y]),A.batchMatMul(f,y,s,n)),S={a:f,b:y},x={transposeA:s,transposeB:n},I=T.runKernelFunc(b,S,null,Al,x);return O(I,m)}const Le=L({matMul_:mE});function fE(e,t){let s=g(e,"a","mul"),n=g(t,"b","mul");[s,n]=Ne(s,n);const i=(o,a)=>{const l=o.multiply(s,n);return a([s,n]),l},r={a:s,b:n};return T.runKernelFunc(i,r,null,lc)}const C=L({mul_:fE});function gE(e){const t=g(e,"x","sigmoid"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.sigmoid(t);return i([r]),r},s,null,Ec)}const Ss=L({sigmoid_:gE});const Jn={};Re(Jn,{assertParamsValid:()=>Iy,computeFlatOffset:()=>bE,computeOutShape:()=>Ay,isSliceContinous:()=>yE,maskToAxes:()=>mp,parseSliceParams:()=>fp,startForAxis:()=>Ey,startIndicesWithElidedDims:()=>Cy,stopForAxis:()=>ky,stopIndicesWithElidedDims:()=>Ry,stridesForAxis:()=>Oy,stridesWithElidedDims:()=>Ny});function Iy(e,t,s){v(e.rank===t.length,()=>`Error in slice${e.rank}D: Length of begin ${t} must match the rank of the array (${e.rank}).`),v(e.rank===s.length,()=>`Error in slice${e.rank}D: Length of size ${s} must match the rank of the array (${e.rank}).`);for(let n=0;n<e.rank;++n)v(t[n]+s[n]<=e.shape[n],()=>`Error in slice${e.rank}D: begin[${n}] + size[${n}] (${t[n]+s[n]}) would overflow input.shape[${n}] (${e.shape[n]})`)}function mp(e){const t=[];let s=0;for(;e>0;)e&1&&t.push(s),e/=2,s++;return t}function Ay(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 Ny(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 fS(e,t,s){return s<=e?s:s-(t-1)}function gS(e,t){const s=[];for(let n=0;n<e;n++)s.push(t+n);return s}function Cy(e,t,s,n,i){const r=[...i],o=gS(s,t);for(let a=0;a<r.length;a++)if(o.indexOf(a)>-1)r[a]=0;else{const l=fS(t,s,a);let c=n[l];e&1<<l&&(c=0),r[a]=c}return r}function Ry(e,t,s,n,i){const r=[...i],o=gS(s,t);for(let a=0;a<r.length;a++)if(o.indexOf(a)>-1)r[a]=Number.MAX_SAFE_INTEGER;else{const l=fS(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]=na(0,r[a],i[a])}return r}function Oy(e,t,s){let n=e[t];return(s&1<<t||n==null)&&(n=1),n}function Ey(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=na(0,o,l-1),o}function ky(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=na(0,o,l):o=na(-1,o,l-1),o}function yE(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 bE(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 fp(e,t,s){let n;typeof t=="number"?n=[t,...new Array(e.rank-1).fill(0)]:t.length<e.rank?n=t.concat(new Array(e.rank-t.length).fill(0)):n=t.slice(),n.forEach(r=>{v(r!==-1,()=>"slice() does not support negative begin indexing.")});let i;return s==null?i=new Array(e.rank).fill(-1):typeof s=="number"?i=[s,...new Array(e.rank-1).fill(-1)]:s.length<e.rank?i=s.concat(new Array(e.rank-s.length).fill(-1)):i=s,i=i.map((r,o)=>r>=0?r:(v(r===-1,()=>`Negative size values should be exactly -1 but got ${r} for the slice() size at index ${o}.`),e.shape[o]-n[o])),[n,i]}function wE(e,t,s){const n=g(e,"x","slice");if(n.rank===0)throw new Error("Slicing scalar is not possible");const[i,r]=fp(n,t,s);Iy(n,i,r);const o=(c,p)=>(p([n]),c.slice(n,i,r)),a={x:n},l={begin:t,size:s};return T.runKernelFunc(o,a,null,Nc,l)}const he=L({slice_:wE});function xE(e){const t=g(e,"x","tanh"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.tanh(t);return i([r]),r},s,null,zc)}const Zn=L({tanh_:xE});function LE(e,t,s,n,i,r){const o=g(e,"forgetBias","basicLSTMCell"),a=g(t,"lstmKernel","basicLSTMCell"),l=g(s,"lstmBias","basicLSTMCell"),c=g(n,"data","basicLSTMCell"),p=g(i,"c","basicLSTMCell"),u=g(r,"h","basicLSTMCell"),h=ge([c,u],1),d=Le(h,a),m=W(d,l),f=m.shape[0],y=m.shape[1]/4,b=[f,y],S=he(m,[0,0],b),x=he(m,[0,y],b),I=he(m,[0,y*2],b),A=he(m,[0,y*3],b),k=W(C(Ss(S),Zn(x)),C(p,Ss(W(o,I)))),R=C(Zn(k),Ss(A));return[k,R]}const _y=L({basicLSTMCell_:LE});function SE(e,t,s){const n=g(e,"x","batchToSpaceND"),i=t.reduce((l,c)=>l*c);v(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),v(s.length===t.length,()=>`crops.length is ${s.length} but should be equal to blockShape.length ${t.length}`),v(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 T.runKernelFunc(r,o,null,Nl,a)}const wi=L({batchToSpaceND_:SE});function yS(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 vE(e,t,s,n,i,r){r==null&&(r=.001);const o=g(e,"x","batchNorm"),a=g(t,"mean","batchNorm"),l=g(s,"variance","batchNorm");let c;i!=null&&(c=g(i,"scale","batchNorm"));let p;n!=null&&(p=g(n,"offset","batchNorm")),v(a.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v(p==null||a.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v(c==null||a.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const u=yS(o),h=(y,b)=>(b([u,a,l,c]),y.batchNorm(u,_h(a),_h(l),_h(p),_h(c),r)),d={x:u,scale:c,offset:p,mean:a,variance:l},m={varianceEpsilon:r},f=T.runKernelFunc(h,d,null,Gl,m);return O(f,o.shape)}function _h(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 on=L({batchNorm_:vE});function TE(e,t,s,n,i,r){const o=g(e,"x","batchNorm"),a=g(t,"mean","batchNorm"),l=g(s,"variance","batchNorm");let c;i!=null&&(c=g(i,"scale","batchNorm"));let p;return n!=null&&(p=g(n,"offset","batchNorm")),v(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),v(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),v(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&v(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),p!=null&&v(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),on(o,a,l,p,c,r)}const gp=L({batchNorm2d_:TE});function IE(e,t,s,n,i,r){const o=g(e,"x","batchNorm"),a=g(t,"mean","batchNorm"),l=g(s,"variance","batchNorm");let c;i!=null&&(c=g(i,"scale","batchNorm"));let p;return n!=null&&(p=g(n,"offset","batchNorm")),v(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),v(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),v(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&v(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),p!=null&&v(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),on(o,a,l,p,c,r)}const yp=L({batchNorm3d_:IE});function AE(e,t,s,n,i,r){const o=g(e,"x","batchNorm"),a=g(t,"mean","batchNorm"),l=g(s,"variance","batchNorm");let c;i!=null&&(c=g(i,"scale","batchNorm"));let p;return n!=null&&(p=g(n,"offset","batchNorm")),v(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),v(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),v(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&v(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),p!=null&&v(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),on(o,a,l,p,c,r)}const bp=L({batchNorm4d_:AE});function NE(e){const t=g(e,"x","clone",null),s=()=>T.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return T.runKernelFunc(s,n,null,Yl)}const Ps=L({clone_:NE});function CE(e,t){let s=g(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 Ps(s);const a=p=>p.tile(s,r),l={x:s},c={shape:t,inputShape:i};return T.runKernelFunc(a,l,null,Cl,c)}const or=L({broadcastTo_:CE});function le(e,t="float32",s){return t=t||"float32",Jc(e),new fi(e,t,s)}function RE(e){const t=g(e,"x","ceil"),s={x:t};return T.runKernelFunc(n=>n.ceil(t),s,null,Rl)}const wp=L({ceil_:RE});function OE(e,t,s){const n=g(e,"x","clipByValue");v(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 T.runKernelFunc((o,a)=>{const l=o.clip(n,t,s);return a([n]),l},i,null,Ol,r)}const Dt=L({clipByValue_:OE});function EE(e,t){const s=g(e,"real","complex"),n=g(t,"imag","complex");xe(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 T.runKernelFunc(i,r,null,bg)}const Ze=L({complex_:EE});function kE(e){return ge(e,0)}const xp=L({concat1d_:kE});function _E(e,t){return ge(e,t)}const Lp=L({concat2d_:_E});function DE(e,t){return ge(e,t)}const Sp=L({concat3d_:DE});function FE(e,t){return ge(e,t)}const vp=L({concat4d_:FE});function ME(e,t,s,n,i="NHWC",r=[1,1],o){const a=g(e,"x","conv2d"),l=g(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]])),v(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),v(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&v(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];v(u===l.shape[2],()=>`Error in conv2d: depth of input (${u}) must match input depth for filter ${l.shape[2]}.`),v(et(s,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);const h=(y,b)=>{const S=ir(i),x=is(c.shape,l.shape,s,r,n,o,!1,S),I=y.conv2d(c,l,x);return b([c,l]),I},d={x:c,filter:l},m={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o},f=T.runKernelFunc(h,d,null,kl,m);return p?O(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const yt=L({conv2d_:ME});function UE(e,t,s,n,i="NWC",r=1,o){const a=g(e,"x","conv1d"),l=g(t,"filter","conv1d");let c=a,p=!1;a.rank===2&&(p=!0,c=O(a,[1,a.shape[0],a.shape[1]])),v(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),v(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&v(De(n),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`),v(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),v(et(s,r),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${s} and dilation '${r}'`),v(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",y=yt(h,u,d,n,f,m,o);return p?O(y,[y.shape[2],y.shape[3]]):O(y,[y.shape[0],y.shape[2],y.shape[3]])}const Hr=L({conv1d_:UE});function $E(e,t,s,n,i,r="NHWC",o){v(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]]),v(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),v(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),v(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];v(p===s.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${s.shape[2]}.`),v(u===s.shape[3],()=>`Error in conv2dDerInput: depth of output (${u}) must match output depth for filter ${s.shape[3]}.`),o!=null&&v(De(i),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${i}.`);const h=(y,b)=>{const S=1,x=ir(r),I=is(a,s.shape,n,S,i,o,!1,x),A=y.conv2dDerInput(l,s,I);return b([l,s]),A},d={dy:l,filter:s},m={strides:n,pad:i,dataFormat:r,dimRoundingMode:o,inputShape:a},f=T.runKernelFunc(h,d,null,_l,m);return c?O(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const ua=L({conv2DBackpropInput_:$E});function WE(e,t,s,n,i,r){const o=g(e,"x","conv2dTranspose"),a=g(t,"filter","conv2dTranspose");return ua(s,o,a,n,i,"NHWC",r)}const qr=L({conv2dTranspose_:WE});function zE(e,t,s,n,i="NDHWC",r=[1,1,1]){const o=g(e,"x","conv3d"),a=g(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]])),v(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),v(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),v(l.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${a.shape[3]}.`),v(et(s,r),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),v(i==="NDHWC",()=>`Error in conv3d: got dataFormat of ${i} but only NDHWC is currently supported.`);const p=(m,f)=>{const y=rr(l.shape,a.shape,s,r,n),b=m.conv3d(l,a,y);return f([l,a]),b},u={x:l,filter:a},h={strides:s,pad:n,dataFormat:i,dilations:r},d=T.runKernelFunc(p,u,null,Dl,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const Yr=L({conv3d_:zE});function BE(e,t,s,n,i){v(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];v(r.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${r.length}.`),v(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),v(s.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${s.rank}`),v(l===s.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${s.shape[3]}.`),v(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,y=rr(r,s.shape,n,f,i);return m.conv3dDerInput(o,s,y)},u={dy:o},h={pad:i},d=T.runKernelFunc(p,u,null,Lg,h);return a?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const Dh=L({conv3DBackpropInput_:BE});function PE(e,t,s,n,i){const r=g(e,"x","conv3dTranspose"),o=g(t,"filter","conv3dTranspose");return Dh(s,r,o,n,i)}const Dy=L({conv3dTranspose_:PE});function jE(e){const t=g(e,"x","cos"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.cos(t);return i([t]),r},s,null,Fl)}const xi=L({cos_:jE});function VE(e){const t=g(e,"x","cosh"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.cosh(t);return i([t]),r},s,null,Ml)}const Kr=L({cosh_:VE});function GE(e,t=0,s=!1,n=!1){const i=g(e,"x","cumsum"),r=(l,c)=>{const p=ut([t],i.rank);let u=i;p!=null&&(u=se(i,p));const h=Gt(1,i.rank)[0];let d=l.cumsum(u,h,s,n);if(c([i]),p!=null){const m=Pr(p);d=se(d,m)}return d},o={x:i},a={axis:t,exclusive:s,reverse:n};return T.runKernelFunc(r,o,null,Ul,a)}const Xr=L({cumsum_:GE});function HE(e,t,s="NHWC"){const n=g(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];v(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${n.shape}`),v(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${n.shape}`),v(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 T.runKernelFunc(a,l,null,vg,c)}const Tp=L({depthToSpace_:HE});function qE(e,t,s,n,i="NHWC",r=[1,1],o){const a=g(e,"x","depthwiseConv2d"),l=g(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]])),v(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),v(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),v(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&&v(De(n),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);const u=(f,y)=>{r==null&&(r=[1,1]),v(et(s,r),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);const b=is(c.shape,l.shape,s,r,n,o,!0),S=f.depthwiseConv2D(c,l,b);return y([c,l]),S},h={x:c,filter:l},d={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o},m=T.runKernelFunc(u,h,null,$l,d);return p?O(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const In=L({depthwiseConv2d_:qE});function YE(e){const t=g(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 T.runKernelFunc(s,n,null,Ag)}const Fy=L({diag_:YE});function KE(e,t,s,n,i=[1,1],r="NHWC"){const o=g(e,"x","dilation2d"),a=g(t,"filter","dilation2d");v(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),v(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),v(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=T.runKernel(_r,p,u);return c?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Ip=L({dilation2d_:KE});function XE(e,t){let s=g(e,"a","floorDiv"),n=g(t,"b","floorDiv");[s,n]=Ne(s,n);const i=(o,a)=>{const l=o.floorDiv(s,n);return a([s,n]),l},r={a:s,b:n};return T.runKernelFunc(i,r,null,Vl)}const Jr=L({floorDiv_:XE});function JE(e,t){let s=g(e,"a","div"),n=g(t,"b","div");if([s,n]=Ne(s,n),s.dtype==="int32"&&n.dtype==="int32")return Jr(s,n);const i=(a,l)=>{const c=a.realDivide(s,n);return l([s,n]),c},r={a:s,b:n},o={};return T.runKernelFunc(i,r,null,ui,o)}const J=L({div_:JE});function ZE(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 Se(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 QE(e,t){let s=g(e,"a","equal"),n=g(t,"b","equal");[s,n]=Ne(s,n),Se(s.shape,n.shape);const i=o=>o.equal(s,n),r={a:s,b:n};return T.runKernelFunc(i,r,null,Cg)}const Qt=L({equal_:QE});function ek(e,t,s){const n=g(t,"a","where"),i=g(s,"b","where"),r=g(e,"condition","where","bool"),o=Se(n.shape,i.shape),a=or(n,o),l=or(i,o);r.rank===1&&v(r.shape[0]===n.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),r.rank!==1&&xe(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 T.runKernelFunc(c,p,null,Ic)}const at=L({where_:ek});function tk(e){const t=g(e,"x","zerosLike"),s={x:t};return T.runKernelFunc(n=>n.zerosLike(t),s,null,Vc)}const ne=L({zerosLike_:tk});function sk(e,t){let s=g(e,"a","div"),n=g(t,"b","div");[s,n]=Ne(s,n);const i=J(s,n),r=ne(i),o=Qt(n,r);return at(o,r,i)}const Ap=L({divNoNan_:sk});function nk(e,t){const s=g(e,"t1","dot"),n=g(t,"t2","dot");v((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(v(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=Le(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=Le(o,a);return O(l,[l.size])}else if(s.rank===2&&n.rank===1){const o=O(n,[-1,1]),a=Le(s,o);return O(a,[a.size])}else{const o=O(n,[n.shape[0],n.shape[1]]),a=Le(s,o);return a}}const My=L({dot_:nk});function ik(e){const t=g(e,"x","elu"),s=(i,r)=>{const o=i.elu(t);return r([o]),o},n={x:t};return T.runKernelFunc(s,n,null,Wl)}const An=L({elu_:ik});function rk(e){let t=g(e,"x","erf");v(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=K(t,"float32"));const s={x:t};return T.runKernelFunc((n,i)=>{const r=n.erf(t);return i([t]),r},s,null,zl)}const Np=L({erf_:rk});function ok(e){const t=g(e,"x","exp"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.exp(t);return i([r]),r},s,null,Bl)}const At=L({exp_:ok});function ak(e,t=0){const s=null,n=g(e,"x","expandDims",s);v(t<=n.rank,()=>"Axis must be <= rank of the tensor");const i=n.shape.slice();return t<0&&(v(-(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 Nt=L({expandDims_:ak});function lk(e){const t=g(e,"x","expm1"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.expm1(t);return i([t]),r},s,null,Pl)}const Cp=L({expm1_:lk});function ck(e,t){const s=null,n=g(e,"x","tile",s);v(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 T.runKernelFunc(i,o,null,Bc,a,r)}const js=L({tile_:ck});function pk(e,t,s,n="float32"){t==null&&(t=e);const i=le([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 js(Nt(o,0),[s[0],1,1]);if(s.length===2)return js(Nt(Nt(o,0),0),[s[0],s[1],1,1]);if(s.length===3)return js(Nt(Nt(Nt(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 ar=L({eye_:pk});function uk(e){v(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return T.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,Rg)}const Li=L({fft_:uk});function Ft(e,t,s){const n={shape:e,value:t,dtype:s};return T.runKernelFunc(i=>i.fill(e,t,s),{},null,Og,n)}function hk(e){const t=g(e,"x","floor"),s={x:t};return T.runKernelFunc(n=>n.floor(t),s,null,jl)}const Nn=L({floor_:hk});const Fh=30;function dk(e){return e<=Fh?e:oa(e,Math.floor(Math.sqrt(e)))}const bS={};Re(bS,{collectGatherOpShapeInfo:()=>Uy,computeOutShape:()=>fk,segOpComputeOptimalWindowSize:()=>mk});function mk(e,t){let s=!1,n;for(e<=Fh?(n=e,s=!0):n=oa(e,Math.floor(Math.sqrt(e)));!s;)n>t||n===e?s=!0:n=oa(e,n+1);return n}function fk(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 Uy(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 gk(e,t,s=0){const n=g(e,"x","gather"),i=g(t,"indices","gather","int32"),r={x:n,indices:i},o={axis:s},a=(l,c)=>{const p=Te(s,n.shape)[0],u=Uy(n,i,p),h=l.gather(n,O(i,[i.size]),p);return c([n,i]),O(h,u.outputShape)};return T.runKernelFunc(a,r,null,Hl,o)}const Cn=L({gather_:gk});function yk(e,t){let s=g(e,"a","greater"),n=g(t,"b","greater");[s,n]=Ne(s,n),Se(s.shape,n.shape);const i=o=>o.greater(s,n),r={a:s,b:n};return T.runKernelFunc(i,r,null,kg)}const Ct=L({greater_:yk});function bk(e,t){let s=g(e,"a","greaterEqual"),n=g(t,"b","greaterEqual");[s,n]=Ne(s,n),Se(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 T.runKernelFunc(i,r,null,ql)}const as=L({greaterEqual_:bk});function wk(e){v(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return T.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,_g)}const Qn=L({ifft_:wk});function xk(e){const t=g(e,"input","imag"),s=i=>i.imag(t),n={input:t};return T.runKernelFunc(s,n,null,Dg)}const Ht=L({imag_:xk});function Lk(e){const t=g(e,"input","real"),s=i=>i.real(t),n={input:t};return T.runKernelFunc(s,n,null,qg)}const $t=L({real_:Lk});function Sk(e,t){const s=g(e,"x","reverse"),n=o=>{const a=Te(t,s.shape);if(s.rank===0)return Ps(s);const l=o.reverse(s,a);return O(l,s.shape)},i={x:s},r={dims:t};return T.runKernelFunc(n,i,null,Sc,r)}const Lt=L({reverse_:Sk});function j(e,t){if((_t(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"&&_t(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const s=[],n=[];return ds(e,s,n,t)}function vk(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=Qn(i)}else{const i=[s,2*(t-1)],r=O($t(e),[s,t]),o=O(Ht(e),[s,t]),a=Lt(he(r,[0,1],[s,t-2]),1),l=C(Lt(he(o,[0,1],[s,t-2]),1),j(-1)),c=ge([r,a],1),p=ge([o,l],1),u=O(Ze(c,p),[i[0],i[1]]);n=Qn(u)}if(n=$t(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 Zr=L({irfft_:vk});function Tk(e){const t=g(e,"x","isFinite"),s={x:t};return T.runKernelFunc(n=>n.isFinite(t),s,null,Kl)}const $y=L({isFinite_:Tk});function Ik(e){const t=g(e,"x","isInf"),s={x:t};return T.runKernelFunc(n=>n.isInf(t),s,null,Xl)}const Wy=L({isInf_:Ik});function Ak(e){const t=g(e,"x","isNaN"),s={x:t};return T.runKernelFunc(n=>n.isNaN(t),s,null,Jl)}const zy=L({isNaN_:Ak});function Nk(e,t){let s=g(e,"a","maximum"),n=g(t,"b","maximum");[s,n]=Ne(s,n),s.dtype==="bool"&&(s=K(s,"int32"),n=K(n,"int32")),Se(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 T.runKernelFunc(i,r,null,sc)}const Wt=L({maximum_:Nk});function Ck(e,t=.2){const s=g(e,"x","leakyRelu");return Wt(C(j(t),s),s)}const Qr=L({leakyRelu_:Ck});function Rk(e,t){let s=g(e,"a","less"),n=g(t,"b","less");[s,n]=Ne(s,n),Se(s.shape,n.shape);const i=o=>o.less(s,n),r={a:s,b:n};return T.runKernelFunc(i,r,null,Fg)}const Si=L({less_:Rk});function Ok(e,t){let s=g(e,"a","lessEqual"),n=g(t,"b","lessEqual");[s,n]=Ne(s,n),Se(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 T.runKernelFunc(i,r,null,Mg)}const vs=L({lessEqual_:Ok});function Rp(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 T.runKernelFunc(i=>i.linspace(e,t,s),{},null,Ug,n)}function Ek(e,t=5,s=1,n=1,i=.5){const r=g(e,"x","localResponseNormalization");v(r.rank===4||r.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${r.rank}.`),v(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=T.runKernelFunc(l,c,null,tc,p);return a?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const Op=L({localResponseNormalization_:Ek});function kk(e){const t=g(e,"x","log"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.log(t);return i([t]),r},s,null,Zl)}const Mt=L({log_:kk});function _k(e){const t=g(e,"x","log1p"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.log1p(t);return i([t]),r},s,null,Ql)}const eo=L({log1p_:_k});function Dk(e){return v(Hn(e),()=>"The f passed in grad(f) must be a function"),(t,s)=>{const n=g(t,"x","tf.grad",null),i=s!=null?g(s,"dy","tf.grad"):null;return T.tidy(()=>{const{value:r,grads:o}=T.gradients(()=>e(n),[n],i);return i!=null&&xe(r.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Mh(o),o[0]})}}function Fk(e){return v(Hn(e),()=>"The f passed in grads(f) must be a function"),(t,s)=>{v(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const n=yi(t,"args","tf.grads",null),i=s!=null?g(s,"dy","tf.grads"):null;return T.tidy(()=>{const{value:r,grads:o}=T.gradients(()=>e(...n),n,i);return i!=null&&xe(r.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Mh(o),o})}}function Mk(e){return v(Hn(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,s)=>{v(t instanceof ue,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),v(s==null||s instanceof ue,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:n,value:i}=T.gradients(()=>e(t),[t],s);return Mh(n),{grad:n[0],value:i}}}function Uk(e){return v(Hn(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,s)=>{v(Array.isArray(t)&&t.every(i=>i instanceof ue),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),v(s==null||s instanceof ue,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const n=T.gradients(()=>e(...t),t,s);return s!=null&&xe(n.value.shape,s.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Mh(n.grads),n}}function Uh(e,t){v(Hn(e),()=>"The f passed in variableGrads(f) must be a function"),v(t==null||Array.isArray(t)&&t.every(c=>c instanceof Xn),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const s=t!=null;if(!s){t=[];for(const c in T.registeredVariables)t.push(T.registeredVariables[c])}const n=s?t.filter(c=>!c.trainable):null,i=t.length;t=t.filter(c=>c.trainable),v(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}=T.gradients(e,t,null,r);v(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()."),v(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 ms(e){return T.customGrad(e)}function Mh(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 $k(e){const t=g(e,"x","neg"),s={x:t};return T.runKernelFunc(n=>n.neg(t),s,null,cc)}const Oe=L({neg_:$k});function Wk(e){const t=g(e,"x","softplus"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.softplus(t);return i([t]),r},s,null,kc)}const Rn=L({softplus_:Wk});function zk(e){const t=g(e,"x","logSigmoid"),s=ms(n=>{const i=Oe(Rn(Oe(n))),r=o=>{const a=C(o,Ss(Oe(n)));return a};return{value:i,gradFunc:r}});return s(t)}const By=L({logSigmoid_:zk});function Bk(e,t=null,s=!1){const n=g(e,"x","max"),i=(a,l)=>{const c=Te(t,n.shape);let p=c;const u=ut(p,n.rank);let h=n;u!=null&&(h=se(n,u),p=Gt(p.length,h.rank));const d=a.max(h,p);u!=null&&h.dispose();let m=d;if(s){const f=ft(m.shape,Te(t,n.shape));m=O(m,f),d.dispose()}return l([n,m]),m},r={x:n},o={reductionIndices:t,keepDims:s};return T.runKernelFunc(i,r,null,hi,o)}const st=L({max_:Bk});function Pk(e,t){let s=g(e,"a","sub"),n=g(t,"b","sub");[s,n]=Ne(s,n);const i=(o,a)=>{const l=o.subtract(s,n);return a([s,n]),l},r={a:s,b:n};return T.runKernelFunc(i,r,null,$c)}const X=L({sub_:Pk});function jk(e,t=null,s=!1){let n=g(e,"x","sum");n.dtype==="bool"&&(n=K(n,"int32"));const i=(a,l)=>{l([n]);const c=Te(t,n.shape),p=ut(c,n.rank);let u=c,h=n;p!=null&&(h=se(n,p),u=Gt(u.length,n.rank));let d=a.sum(h,u);if(s){const m=ft(d.shape,c);d=O(d,m)}return d},r={x:n},o={axis:t,keepDims:s};return T.runKernelFunc(i,r,null,Dc,o)}const te=L({sum_:jk});function Vk(e,t=-1){const s=g(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=st(e,t,!0),p=X(e,c),u=X(K(p,"float32"),Mt(te(At(p),t,l)));return a([u]),u},i={logits:s},r={axis:t};return T.runKernelFunc(n,i,null,ec,r)}const to=L({logSoftmax_:Vk});function Gk(e,t=null,s=!1){const n=g(e,"x","logSumExp"),i=Te(t,n.shape),r=st(n,i,!0),o=X(n,r),a=At(o),l=te(a,i),c=Mt(l),p=W(O(r,c.shape),c);if(s){const u=ft(p.shape,i);return O(p,u)}return p}const Ep=L({logSumExp_:Gk});function Hk(e,t){const s=g(e,"a","logicalAnd","bool"),n=g(t,"b","logicalAnd","bool");Se(s.shape,n.shape);const i={a:s,b:n};return T.runKernelFunc(r=>r.logicalAnd(s,n),i,null,$g)}const zt=L({logicalAnd_:Hk});function qk(e){const t=g(e,"x","logicalNot","bool"),s={x:t};return T.runKernelFunc(n=>n.logicalNot(t),s,null,Wg)}const vi=L({logicalNot_:qk});function Yk(e,t){const s=g(e,"a","logicalOr","bool"),n=g(t,"b","logicalOr","bool");Se(s.shape,n.shape);const i={a:s,b:n};return T.runKernelFunc(r=>r.logicalOr(s,n),i,null,zg)}const so=L({logicalOr_:Yk});function Kk(e,t){const s=g(e,"a","logicalXor","bool"),n=g(t,"b","logicalXor","bool");return Se(s.shape,n.shape),zt(so(e,t),vi(zt(e,t)))}const Py=L({logicalXor_:Kk});function Xk(e,t,s,n,i){const r=g(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]])),v(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),v(et(s,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&v(De(n),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const c=(d,m)=>{const f=Tn(a.shape,t,s,1,n,i);let y;return f.filterWidth===1&&f.filterHeight===1&&It(f.inShape,f.outShape)?y=a.clone():y=d.maxPool(a,f),m([a,y]),y},p={x:a},u={filterSize:t,strides:s,pad:n,dimRoundingMode:i},h=T.runKernelFunc(c,p,null,nc,u);return l?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const lt=L({maxPool_:Xk});function Jk(e,t=[1,1,1],s,n,i,r="NDHWC",o){o==null?o=[1,1,1]:xt("dilations is deprecated, this field will be gone in v3.0.0.");const a=g(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]])),v(l.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${l.rank}.`),v(r==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),v(et(s,o),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&v(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 y=bi(l.shape,t,s,o,n,i,r),b=m.maxPool3d(l,y);return f([l,b]),b},u={x:l},h={filterSize:t,strides:s,pad:n,dimRoundingMode:i,dataFormat:r,dilations:o},d=T.runKernelFunc(p,u,null,ic,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const no=L({maxPool3d_:Jk});function Zk(e,t,s,n,i=!1){const r=g(e,"x","maxPoolWithArgmax"),o={x:r},a={filterSize:t,strides:s,pad:n,includeBatchInIndex:i},l=T.runKernel(Fr,o,a);return{result:l[0],indexes:l[1]}}const kp=L({maxPoolWithArgmax_:Zk});function Ie(e,t="float32"){if(t==="complex64"){const n=Ie(e,"float32"),i=Ie(e,"float32");return Ze(n,i)}const s=Yn(We(e),t);return T.makeTensor(s,e,t)}function es(e,t="float32"){if(t==="complex64"){const n=es(e,"float32"),i=Ie(e,"float32");return Ze(n,i)}const s=Xc(We(e),t);return T.makeTensor(s,e,t)}function Qk(e,t=null,s=!1){const n=g(e,"x","mean"),i=Te(t,n.shape),r=wy(n.shape,i),o=r[1],a=We(o),l=ms(c=>{const p=j(a),u=p.dtype===c.dtype?c:K(c,p.dtype),h=J(u,p),d=te(h,t,s),m=f=>{const y=c.shape.slice();i.forEach(x=>{y[x]=1});const b=O(f,y),S=J(C(b,es(c.shape,"float32")),a);return S};return{value:d,gradFunc:m}});return l(n)}const Ge=L({mean_:Qk});function e_(e,t=null,s=!1){const n=g(e,"x","min"),i=(a,l)=>{const c=Te(t,n.shape);let p=c;const u=ut(p,n.rank);let h=n;u!=null&&(h=se(n,u),p=Gt(p.length,n.rank));const d=a.min(h,p);u!=null&&h.dispose();let m=d;if(s){const f=ft(m.shape,c);m=O(d,f),d.dispose()}return l([n,m]),m},r={x:n},o={axis:t,keepDims:s};return T.runKernelFunc(i,r,null,rc,o)}const an=L({min_:e_});function t_(e,t){let s=g(e,"a","minimum"),n=g(t,"b","minimum");[s,n]=Ne(s,n),s.dtype==="bool"&&(s=K(s,"int32"),n=K(n,"int32")),Se(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 T.runKernelFunc(i,r,null,oc)}const Vs=L({minimum_:t_});function s_(e,t){let s=g(e,"a","mod"),n=g(t,"b","mod");[s,n]=Ne(s,n);const i=(o,a)=>{const l=o.mod(s,n);return a([s,n]),l},r={a:s,b:n};return T.runKernelFunc(i,r,null,ac)}const io=L({mod_:s_});function n_(e){const t=g(e,"x","square"),s={},n=[t],i=[];return T.runKernelFunc((r,o)=>(o([t]),r.square(t)),{x:t},null,"Square",s,n,i)}const ye=L({square_:n_});function i_(e,t=null,s=!1){e=g(e,"x","moments");const n=Te(t,e.shape),i=Ge(e,n,s);let r=i.shape;s||(r=ft(i.shape,n));const o=ye(X(K(e,"float32"),O(i,r))),a=Ge(o,n,s);return{mean:i,variance:a}}const lr=L({moments_:i_});function r_(e,t,s,n){const i=g(t,"data","multiRNNCell"),r=yi(s,"c","multiRNNCell"),o=yi(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 jy=L({multiRNNCell_:r_});function o_(e,t,s,n=!1){const i=g(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=T.runKernelFunc(c=>c.multinomial(a,n,t,s),{logits2D:a});return o===1?O(l,[l.size]):l}const _p=L({multinomial_:o_});function a_(e,t){let s=g(e,"a","notEqual"),n=g(t,"b","notEqual");[s,n]=Ne(s,n),Se(s.shape,n.shape);const i=o=>o.notEqual(s,n),r={a:s,b:n};return T.runKernelFunc(i,r,null,Vg)}const Es=L({notEqual_:a_});function l_(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=g(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 T.runKernelFunc(o,a,null,hc,l)}const On=L({oneHot_:l_});function c_(e){const t=g(e,"x","onesLike"),s=(i,r)=>{if(t.dtype==="complex64"){const o=Bt($t(t)),a=ne(Ht(t));return Ze(o,a)}return i.onesLike(t)},n={x:t};return T.runKernelFunc(s,n,null,uc)}const Bt=L({onesLike_:c_});function p_(e,t){const s=g(e,"v1","outerProduct"),n=g(t,"v2","outerProduct");v(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 Le(i,r)}const Vy=L({outerProduct_:p_});function u_(e,t,s=0){const n=g(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 T.runKernelFunc(i,o,null,dc,r)}const Ut=L({pad_:u_});function h_(e,t,s=0){return v(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Ut(e,[t],s)}const Gy=L({pad1d_:h_});function d_(e,t,s=0){return v(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ut(e,t,s)}const Hy=L({pad2d_:d_});function m_(e,t,s=0){return v(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."),Ut(e,t,s)}const qy=L({pad3d_:m_});function f_(e,t,s=0){return v(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."),Ut(e,t,s)}const Yy=L({pad4d_:f_});function g_(e,t,s){const n=g(e,"x","spaceToBatchND");v(n.rank>=1+t.length,()=>`input rank ${n.rank} should be > than [blockShape] ${t.length}`),v(s.length===t.length,()=>`paddings.shape[0] ${s.length} must be equal to [blockShape] ${t.length}`),v(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 T.runKernelFunc(i,r,null,Fc,o)}const Ti=L({spaceToBatchND_:g_});function w_(e,t,s,n,i,r){i==null&&(i=[1,1]),r==null&&(r=1),n===0&&(n="valid");const o=g(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]])),v(et(r,i),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`);const c=Tn(a.shape,t,r,i,n),p=[c.dilationHeight,c.dilationWidth];let u;n==="same"?u=b_([c.filterHeight,c.filterWidth],p):u=[[0,0],[0,0]];const h=p[0]===1&&p[1]===1,[d,m]=y_([c.inHeight,c.inWidth],p,u),f=h?n:"valid",y=h?a:Ti(a,p,d),b=s==="avg"?()=>rs(y,t,r,f):()=>lt(y,t,r,f),S=b(),x=h?S:wi(S,p,m);return l?O(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function y_(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 b_(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 Ky=L({pool_:w_});function x_(e,t){let s=g(e,"base","pow"),n=g(t,"exp","pow");[s,n]=Ne(s,n);const i={a:s,b:n},r=(o,a)=>{const l=o.pow(s,n);return a([s,n,l]),l};return T.runKernelFunc(r,i,null,mc)}const qt=L({pow_:x_});function L_(e,t){const s=g(e,"x","prelu"),n=g(t,"alpha","prelu"),i=(o,a)=>{const l=o.prelu(s,n);return a([s,n]),l},r={x:s,alpha:n};return T.runKernelFunc(i,r,null,fc)}const Ii=L({prelu_:L_});function Xy(e,t=!1){console.log(e.toString(t))}function S_(e,t=null,s=!1){let n=g(e,"x","prod");const i=a=>{n.dtype==="bool"&&(n=K(n,"int32"));const l=Te(t,n.shape),c=ut(l,n.rank);let p=l,u=n;c!=null&&(u=se(n,c),p=Gt(p.length,n.rank));let h=a.prod(u,p);if(s){const d=ft(h.shape,l);h=O(h,d)}return h},r={x:n},o={axis:t,keepDims:s};return T.runKernelFunc(i,r,null,Gg,o)}const ro=L({prod_:S_});function v_(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 T.makeTensor(i,e,s)}const Jy=L({rand_:v_});const wS={};Re(wS,{TEST_EPSILON_FLOAT16:()=>xS,expectArrayBuffersEqual:()=>O_,expectArraysClose:()=>I_,expectArraysEqual:()=>N_,expectNumbersClose:()=>C_,expectPromiseToFail:()=>A_,expectValuesInRange:()=>R_,testEpsilon:()=>Zy});const T_=.001,xS=.1;function I_(e,t,s){return s==null&&(s=Zy()),Qy(e,t,(n,i)=>eb(n,i,s))}function Zy(){return T.backend.floatPrecision()===32?T_:xS}function Qy(e,t,s){let n=!0;if((_t(e)||_t(t))&&(n=!1),_t(e)&&_t(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=Zt(e),a=Zt(t);if(!It(o,a))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${a}]`)}const i=_t(e)?e:Gn(e),r=_t(t)?t:Gn(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 A_(e,t){e().then(()=>t.fail(),()=>t())}function N_(e,t){const s=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return vn(e)||vn(e[0])||vn(t)||vn(t[0])?Qy(e,s,(n,i)=>n==i):Qy(e,t,(n,i)=>eb(n,i,0))}function C_(e,t,s){if(s==null&&(s=Zy()),!eb(e,t,s))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function eb(e,t,s){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>s)}function R_(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 O_(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const $h=nl(il());class Dp{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=$h.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 LS{constructor(e,t,s,n){this.alpha=e,this.beta=1/t,this.dtype=s;const i=n||Math.random();this.randu=$h.alea(i.toString()),this.randn=new Dp(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 SS{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=$h.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function E_(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 LS(t,s,n,i),o=le(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const tb=L({randomGamma_:E_});function k_(e,t=0,s=1,n,i){if(n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);const r=new Dp(t,s,n,!1,i),o=le(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const ha=L({randomNormal_:k_});function __(e,t=0,s=1,n="float32",i){const r=le(e,n),o=new SS(t,s,null,i);for(let a=0;a<r.values.length;a++)r.values[a]=o.nextValue();return r.toTensor()}const Gs=L({randomUniform_:__});function Fe(e,t){zs(e);const s=Zt(e,t);if(s.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const n=null;return ds(e,n,s,t)}function ei(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 Ie([0],n);const c=Math.abs(Math.ceil((t-e)/s)),p=Yn(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 Fe(p,n)},r={start:e,stop:t,step:s,dtype:n};return T.runKernelFunc(i,{},null,Hg,r)}function D_(e){const t=g(e,"x","reciprocal"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.reciprocal(t);return i([t]),r},s,null,gc)}const Fp=L({reciprocal_:D_});function F_(e){const t=g(e,"x","relu"),s=(i,r)=>(r([t]),t.dtype==="bool"?K(t,"int32"):i.relu(t)),n={x:t};return T.runKernelFunc(s,n,null,yc)}const ke=L({relu_:F_});function M_(e){const t=g(e,"x","relu6"),s=(i,r)=>(r([t]),t.dtype==="bool"?K(t,"int32"):i.relu6(t)),n={x:t};return T.runKernelFunc(s,n,null,Lc)}const Mp=L({relu6_:M_});function U_(e){const t=g(e,"x","reverse");return v(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Lt(t,0)}const sb=L({reverse1d_:U_});function $_(e,t){const s=g(e,"x","reverse");return v(s.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${s.rank}.`),Lt(s,t)}const nb=L({reverse2d_:$_});function W_(e,t){const s=g(e,"x","reverse");return v(s.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${s.rank}.`),Lt(s,t)}const ib=L({reverse3d_:W_});function z_(e,t){const s=g(e,"x","reverse");return v(s.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${s.rank}.`),Lt(s,t)}const rb=L({reverse4d_:z_});function ob(e,t,s=0){let n=[];if(typeof t=="number")v(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);v(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}v(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 B_(e,t,s=0){const n=g(e,"x","split"),i=(a,l)=>{const c=Te(s,n.shape)[0],p=ob(n,t,c);return a.split(n,p,c)},r={x:n},o={numOrSizeSplits:t,axis:s};return T.runKernelFunc(i,r,null,Mc,o)}const ls=L({split_:B_});function P_(e,t){v(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(y=>0),f=e.shape.map(y=>y);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=ge([e,Ie(m)],e.shape.length-1),s=t}else i=e;const r=ne(i),o=O(Ze(i,r),[n,s]),a=Li(o),l=Math.floor(s/2)+1,c=$t(a),p=Ht(a),u=ls(c,[l,s-l],c.shape.length-1),h=ls(p,[l,s-l],p.shape.length-1),d=i.shape.slice();return d[i.shape.length-1]=l,O(Ze(u[0],h[0]),d)}const Ai=L({rfft_:P_});function j_(e){const t=g(e,"x","round"),s={x:t};return T.runKernelFunc(n=>n.round(t),s,null,vc)}const Up=L({round_:j_});function V_(e){const t=g(e,"x","rsqrt"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.rsqrt(t);return i([t]),r},s,null,Tc)}const oo=L({rsqrt_:V_});function G_(e){const t=g(e,"x","selu"),s=(i,r)=>{const o=i.selu(t);return r([t]),o},n={x:t};return T.runKernelFunc(s,n,null,Ac)}const ao=L({selu_:G_});function H_(e,t,s,n,i,r=[1,1],o="NHWC"){const a=g(e,"x","separableConv2d"),l=g(t,"depthwiseFilter","separableConv2d"),c=g(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");v(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.rank}.`),v(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),v(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),v(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),v(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];v(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=In(p,l,n,i,o,r),f=1,y=yt(m,c,f,"valid",o);return u?O(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const Ni=L({separableConv2d_:H_});async function q_(e,t){const s=g(e,"x","setdiff1d"),n=g(t,"y","setdiff1d");v(s.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${s.dtype}) and y (${n.dtype}).`),v(s.rank===1,()=>`x should be 1D tensor, but got x (${s.shape}).`),v(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 fi([a],s.dtype),c=new fi([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 $p=q_;function Y_(e){const t=g(e,"x","sign"),s={x:t};return T.runKernelFunc(n=>n.sign(t),s,null,Oc)}const Wp=L({sign_:Y_});function K_(e){const t=g(e,"x","sin"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.sin(t);return i([t]),r},s,null,Cc)}const lo=L({sin_:K_});function X_(e){const t=g(e,"x","sinh"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.sinh(t);return i([t]),r},s,null,Rc)}const co=L({sinh_:X_});function J_(e,t,s){const n=g(e,"x","slice1d");return v(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),he(n,[t],[s])}const po=L({slice1d_:J_});function Z_(e,t,s){const n=g(e,"x","slice2d");return v(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const da=L({slice2d_:Z_});function Q_(e,t,s){const n=g(e,"x","slice3d");return v(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const Ci=L({slice3d_:Q_});function eD(e,t,s){const n=g(e,"x","slice4d");return v(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const cr=L({slice4d_:eD});function tD(e,t=-1){const s=g(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 T.runKernelFunc((r,o)=>{const a=r.softmax(s,t);return o([a]),a},n,null,Uc,i)}const Yt=L({softmax_:tD});function sD(e){const t=g(e,"x","sqrt"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.sqrt(t);return i([t]),r},s,null,_c)}const He=L({sqrt_:sD});function nD(e,t){let s=g(e,"a","squaredDifference"),n=g(t,"b","squaredDifference");[s,n]=Ne(s,n),Se(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 T.runKernelFunc(i,r,null,di,o)}const Ri=L({squaredDifference_:nD});function iD(e,t){const s=g(e,"x","squeeze");return O(s,ny(s.shape,t).newShape)}const En=L({squeeze_:iD});function rD(e,t=0){const s=yi(e,"tensors","stack");if(v(s.length>=1,()=>"Pass at least one tensor to tf.stack"),s.length===1)return Nt(s[0],t);const n=s[0].rank,i=s[0].shape,r=s[0].dtype;v(t<=n,()=>"Axis must be <= rank of the tensor"),s.forEach(a=>{xe(i,a.shape,"All tensors passed to stack must have matching shapes"),v(r===a.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=s.map(a=>Nt(a,t));return ge(o,t)}const Xe=L({stack_:rD});function oD(e,t=0){const s=g(e,"x","step"),n={x:s},i={alpha:t};return T.runKernelFunc(r=>r.step(s,t),n,null,Gc,i)}const kn=L({step_:oD});function aD(e,t,s,n,i=0,r=0,o=0,a=0,l=0){n==null&&(n=new Array(t.length));let c=g(e,"x","stridedSlice");const p=d=>{const m=mp(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,y=mp(a),b=c.shape.slice();if(y.forEach(R=>{t[R]=0,s[R]=1,b.splice(R,0,1)}),c=O(c,b),m.length&&f>0){const R=m[0],D=f+1;t=Cy(i,R,D,t,c.shape),s=Ry(r,R,D,s,c.shape),n=Ny(n,R,D,c.shape)}else for(let R=0;R<c.rank;R++)t[R]=Ey(i,t,n,c.shape,R,o),s[R]=ky(r,s,n,c.shape,R,o),n[R]=Oy(n,R,o);const S=mp(l);S.forEach(R=>{s[R]=t[R]+1,n[R]=1});const x=Ay(t,s,n),I=x.filter((R,D)=>S.indexOf(D)===-1),A=n.every(R=>R===1);if(A)return O(he(c,t,x),I);const k=d.stridedSlice(c,t,s,n);return O(k,I)},u={x:c},h={begin:t,end:s,strides:n,beginMask:i,endMask:r,ellipsisMask:o,newAxisMask:a,shrinkAxisMask:l};return T.runKernelFunc(p,u,null,Zg,h)}const zp=L({stridedSlice_:aD});function lD(e){const t=g(e,"x","tan"),s={x:t};return T.runKernelFunc((n,i)=>{const r=n.tan(t);return i([t]),r},s,null,Wc)}const Bp=L({tan_:lD});function ts(e,t,s){if(zs(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const n=Zt(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 ds(e,t,n,s)}function Pp(e,t,s){if(zs(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const n=Zt(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 ds(e,t,n,s)}function cs(e,t,s){if(zs(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const n=Zt(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 ds(e,t,n,s)}function ab(e,t,s){if(zs(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const n=Zt(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 ds(e,t,n,s)}function lb(e,t,s){if(zs(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const n=Zt(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,ds(e,t,n,s)}function cD(e,t=1,s=!0){const n=g(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]=T.runKernelFunc(c=>c.topk(n,t,s),r,null,Qg,o);return{values:a,indices:l}}const jp=L({topk_:cD});function pD(e,t=0,s=1,n,i){if(n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");const r=new Dp(t,s,n,!0,i),o=le(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const Oi=L({truncatedNormal_:pD});function uD(e,t,s){const n=g(e,"x","unsortedSegmentSum"),i=g(t,"segmentIds","unsortedSegmentSum","int32");v(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 T.runKernelFunc(a,r,null,jc,o)}const Vp=L({unsortedSegmentSum_:uD});function hD(e,t=0){const s=g(e,"x","unstack");v(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 T.runKernelFunc(r,n,null,Pc,i)}const nt=L({unstack_:hD});function Gp(e,t=!0,s,n){return T.makeVariable(e,t,s,n)}function Wh(e,t){const s=[];for(let r=0;r<t.length;r++)t[r]&&s.push(r);const n=le(e,"int32"),i=le([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 dD(e){const t=g(e,"condition","whereAsync","bool"),s=await t.data(),n=Wh(t.shape,s);return e!==t&&t.dispose(),n}const uo=dD;async function mD(e,t,s){const n=g(e,"tensor","boolMask"),i=g(t,"mask","boolMask","bool"),r=s==null?0:s,o=i.rank,a=n.shape;v(o>0,()=>"mask cannot be scalar"),xe(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 uo(u),d=En(h,[1]),m=Cn(p,d,r);return e!==n&&n.dispose(),t!==i&&i.dispose(),d.dispose(),p.dispose(),u.dispose(),h.dispose(),m}const vS=mD;function fD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","notEqualStrict"),n=g(t,"b","notEqualStrict");return xe(s.shape,n.shape,"Error in notEqualStrict: "),Es(s,n)}function gD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","lessStrict"),n=g(t,"b","lessStrict");return xe(s.shape,n.shape,"Error in lessStrict: "),Si(s,n)}function yD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","equalStrict"),n=g(t,"b","equalStrict");return xe(s.shape,n.shape,"Error in equalStrict: "),Qt(s,n)}function bD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","lessEqualStrict"),n=g(t,"b","lessEqualStrict");return xe(s.shape,n.shape,"Error in lessEqualStrict: "),vs(s,n)}function wD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","greaterStrict"),n=g(t,"b","greaterStrict");return xe(s.shape,n.shape,"Error in greaterStrict: "),Ct(s,n)}function xD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","greaterEqualStrict"),n=g(t,"b","greaterEqualStrict");return xe(s.shape,n.shape,"Error in greaterEqualStrict: "),as(s,n)}const TS=L({equalStrict_:yD}),IS=L({greaterEqualStrict_:xD}),AS=L({greaterStrict_:wD}),NS=L({lessEqualStrict_:bD}),CS=L({lessStrict_:gD}),RS=L({notEqualStrict_:fD});function LD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","addStrict"),n=g(t,"b","addStrict");return xe(s.shape,n.shape,"Error in addStrict: "),W(s,n)}function SD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","subStrict"),n=g(t,"b","subStrict");return xe(s.shape,n.shape,"Error in subStrict: "),X(s,n)}function vD(e,t){return xt("strict variants of ops have been deprecated and will be removed in future"),xe(e.shape,t.shape,"Error in powStrict: "),qt(e,t)}function TD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","mul"),n=g(t,"b","mul");return xe(s.shape,n.shape,"Error in multiplyStrict: "),C(s,n)}function ID(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","div"),n=g(t,"b","div");return xe(s.shape,n.shape,"Error in divideStrict: "),J(s,n)}function AD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","modStrict"),n=g(t,"b","modStrict");return xe(s.shape,n.shape,"Error in modStrict: "),io(s,n)}function ND(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","minimumStrict"),n=g(t,"b","minimumStrict");return xe(s.shape,n.shape,"Error in minimumStrict: "),Vs(s,n)}function CD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","maximumStrict"),n=g(t,"b","maximumStrict");return xe(s.shape,n.shape,"Error in maximumStrict: "),Wt(s,n)}function RD(e,t){xt("strict variants of ops have been deprecated and will be removed in future");const s=g(e,"a","squaredDifferenceStrict"),n=g(t,"b","squaredDifferenceStrict");return xe(s.shape,n.shape,"Error in squaredDifferenceStrict: "),Ri(s,n)}const OS=L({addStrict_:LD}),ES=L({divStrict_:ID}),kS=L({maximumStrict_:CD}),_S=L({minimumStrict_:ND}),DS=L({modStrict_:AD}),FS=L({mulStrict_:TD}),MS=L({powStrict_:vD}),US=L({squaredDifferenceStrict_:RD}),$S=L({subStrict_:SD});function OD(e,t="euclidean",s=null,n=!1){e=g(e,"x","norm");const i=WS(e,t,s);let r=i.shape;if(n){const o=Te(s,e.shape);r=ft(i.shape,o)}return O(i,r)}function WS(e,t,s=null){if(e.rank===0)return Je(e);if(e.rank!==1&&s===null)return WS(O(e,[-1]),t,s);if(e.rank===1||typeof s=="number"||Array.isArray(s)&&s.length===1){if(t===1)return te(Je(e),s);if(t===Infinity)return st(Je(e),s);if(t===-Infinity)return an(Je(e),s);if(t==="euclidean"||t===2)return He(te(qt(Je(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 st(te(Je(e),s[0]),s[1]-1);if(t===Infinity)return st(te(Je(e),s[1]),s[0]);if(t===-Infinity)return an(te(Je(e),s[1]),s[0]);if(t==="fro"||t==="euclidean")return He(te(ye(e),s));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${s}`)}const ma=L({norm_:OD});function ED(e,t,s,n,i=!0){const r=g(e,"v","movingAverage"),o=g(t,"x","movingAverage"),a=g(s,"decay","movingAverage");gy(r,o),v(It(r.shape,o.shape),()=>"Shape mismatch in v and x");const l=j(1),c=X(l,a);let p=C(X(o,r),c);if(i){v(n!=null,()=>"When using zeroDebias: true, step is required.");const u=g(n,"step","movingAverage");p=J(p,X(l,qt(a,u)))}return W(r,p)}const zS=L({movingAverage_:ED});const BS={};Re(BS,{calculateShapes:()=>PS,validateInput:()=>zh,validateUpdateShape:()=>cb});function cb(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 zh(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}`)}cb(s,t,e)}function PS(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=[...qn(s.slice(0,i)),1],p=We(s);return{sliceRank:i,numUpdates:l,sliceSize:o,strides:c,outputSize:p}}function kD(e,t,s){const n=g(e,"indices","scatterND","int32"),i=g(t,"updates","scatterND");zh(i,n,s);const r=l=>l.scatterND(n,i,s),o={indices:n,updates:i},a={shape:s};return T.runKernelFunc(r,o,null,Xg,a)}const Bh=L({scatterND_:kD});function jS(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 _D(e,t,s,n=0){const i=g(e,"sparseIndices","sparseToDense","int32"),r=g(t,"sparseValues","sparseToDense"),o=g(n,"defaultValue","sparseToDense",r.dtype);jS(i,r,s,o);const a={sparseIndices:i,sparseValues:r,defaultValue:o},l={outputShape:s};return T.runKernelFunc(c=>c.sparseToDense(i,r,s,o),a,null,Jg,l)}const fa=L({sparseToDense_:_D});function DD(e,t){const s=g(t,"indices","gatherND","int32"),n=g(e,"x","gatherND"),i=o=>o.gatherND(n,s),r={params:n,indices:s};return T.runKernelFunc(i,r,null,Eg)}const Ph=L({gatherND_:DD});function VS(e,t){if(t==null)return e.shape.slice();if(It(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 FD(e,t,s,n){const i=g(e,"x","dropout");if(v(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.`),v(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof ue?i.clone():i;const r=VS(i,s),o=1-t,a=J(Nn(W(Gs(r,0,1,"float32",n),o)),o);return C(i,a)}const jh=L({dropout_:FD});function Vh(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function ga(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 Fe(i,"float32")}async function MD(e,t,s=1){const n=g(e,"predictions","inTopK"),i=g(t,"targets","inTopK");v(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),v(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}`),xe(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];v(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=ia("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,y)=>y.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 GS=MD;function UD(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]])),v(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),v(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),v(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];v(c===s[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${s[2]}.`),v(p===s[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${s[3]}).`),o!=null&&v(De(i),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${i}.`);const u=m=>{const f=1,y=ir(r),b=is(a.shape,s,n,f,i,o,!1,y);return m.conv2dDerFilter(a,l,b)},h={x:a,dy:l},d={strides:n,pad:i,dataFormat:r,dimRoundingMode:o};return T.runKernelFunc(u,h,null,wg,d)}const ya=L({conv2DBackpropFilter_:UD});function ho(e,t,s){if(s==null||s==="linear")return e;if(s==="relu")return C(e,kn(t));throw new Error(`Cannot compute gradient for fused activation ${s}.`)}function mo(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 fo(e,t,s){if(t==="linear")return e;if(t==="relu")return ke(e);if(t==="elu")return An(e);if(t==="relu6")return Mp(e);if(t==="prelu")return Ii(e,s);throw new Error(`Unknown fused activation ${t}.`)}const go=(e,t)=>{const s=e>0;return!s||t==="linear"};function $D({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",go(T.state.gradientDepth,l)===!1){let A=yt(e,t,s,n,i,r,o);return a!=null&&(A=W(A,a)),fo(A,l,c)}const p=g(e,"x","conv2d"),u=g(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]])),v(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),v(u.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${u.rank}.`),o!=null&&v(De(n),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`),v(h.shape[3]===u.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${u.shape[2]}.`),v(et(s,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),v(i==="NHWC",()=>`Error in conv2d: got dataFormat of ${i} but only NHWC is currently supported.`);const m=is(h.shape,u.shape,s,r,n,o);let f;a!=null&&(f=g(a,"bias","fused conv2d"),[f]=Ne(f,p),Se(m.outShape,f.shape));let y;c!=null&&(y=g(c,"prelu weights","fused conv2d"));const b=(A,k)=>{const[R,D,F,M]=k,B=ho(A,F,l);v(Bs(r),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const V=ua(D.shape,B,R,s,n),Y=ya(D,B,R.shape,s,n),G=[V,Y];if(M!=null){const Z=mo(M,B);G.push(Z)}return G},S=A=>{const k=A.fusedConv2d({input:h,filter:u,convInfo:m,bias:f,activation:l,preluActivationWeights:y});return k},x={x:h,filter:u,bias:f,preluActivationWeights:y},I={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o,activation:l};if(a==null){const A=ms((k,R,D)=>{let F=T.runKernelFunc(S,x,null,Ih,I);return D([R,k,F]),d&&(F=O(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:b}});return A(h,u)}else{const A=ms((k,R,D,F)=>{let M=T.runKernelFunc(S,x,null,Ih,I);return F([R,k,M,D]),d&&(M=O(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}});return A(h,u,f)}}const WD=L({fusedConv2d_:$D});function zD(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 T.runKernelFunc(o,a,null,Tg)}const Gh=L({depthwiseConv2dNativeBackpropFilter_:zD});function BD(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=T.runKernelFunc(o,a,null,Ig);return r?O(l,[l.shape[1],l.shape[2],l.shape[3]]):l}const Hh=L({depthwiseConv2dNativeBackpropInput_:BD});function PD({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(go(T.state.gradientDepth,l)===!1){let A=In(e,t,s,n,i,r,o);return a!=null&&(A=W(A,a)),fo(A,l,c)}const p=g(e,"x","depthwiseConv2d"),u=g(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]])),v(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),v(u.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`),v(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]),v(et(s,r),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),o!=null&&v(De(n),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${n}.`);const m=is(h.shape,u.shape,s,r,n,o,!0);let f;a!=null&&(f=g(a,"bias","fused conv2d"),[f]=Ne(f,p),Se(m.outShape,f.shape));let y;c!=null&&(y=g(c,"prelu weights","fused depthwiseConv2d"));const b=(A,k)=>{v(Bs(r),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${r}'`);const[R,D,F,M]=k,B=ho(A,F,l),V=Hh(D.shape,B,R,m),Y=Gh(D,B,R.shape,m);if(M!=null){const G=mo(f,B);return[V,Y,G]}return[V,Y]},S=A=>{const k=A.fusedDepthwiseConv2D({input:h,filter:u,convInfo:m,bias:f,activation:l,preluActivationWeights:y});return k},x={x:h,filter:u,bias:f,preluActivationWeights:y},I={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o,activation:l};if(a==null){const A=ms((k,R,D)=>{let F=T.runKernelFunc(S,x,null,Ah,I);return D([R,k,F]),d&&(F=O(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:b}});return A(h,u)}else{const A=ms((k,R,D,F)=>{let M=T.runKernelFunc(S,x,null,Ah,I);return F([R,k,M,D]),d&&(M=O(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}});return A(h,u,f)}}const jD=L({fusedDepthwiseConv2d_:PD});function VD({a:e,b:t,transposeA:s=!1,transposeB:n=!1,bias:i,activation:r="linear",preluActivationWeights:o}){if(go(T.state.gradientDepth,r)===!1){let M=Le(e,t,s,n);return i!=null&&(M=W(M,i)),fo(M,r,o)}let a=g(e,"a","fused matMul"),l=g(t,"b","fused matMul");[a,l]=Ne(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),y=We(m);v(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}.`),v(It(d,m),()=>`Error in fused matMul: outer dimensions (${d}) and (${m}) of Tensors with shapes ${a.shape} and ${l.shape} must match.`),v(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 b=a.shape.slice(0,-2).concat([u,h]),S=s?O(a,[f,c,u]):O(a,[f,u,c]),x=n?O(l,[y,h,p]):O(l,[y,p,h]);let I;i!=null&&(I=g(i,"bias","fused matMul"),[I]=Ne(I,a),Se(b,I.shape));let A;o!=null&&(A=g(o,"prelu weights","fused matMul"));const k=(M,B)=>{const[V,Y,G,Z]=B,q=ho(O(M,G.shape),G,r);let ee,Q;if(!s&&!n?(ee=Le(q,Y,!1,!0),Q=Le(V,q,!0,!1)):!s&&n?(ee=Le(q,Y,!1,!1),Q=Le(q,V,!0,!1)):s&&!n?(ee=Le(Y,q,!1,!0),Q=Le(V,q,!1,!1)):(ee=Le(Y,q,!0,!0),Q=Le(q,V,!0,!0)),i!=null){const ie=mo(Z,q);return[ee,Q,ie]}else return[ee,Q]},R=M=>{const B=M.fusedBatchMatMul({a:S,b:x,transposeA:s,transposeB:n,bias:I,activation:r,preluActivationWeights:A});return B},D={a:S,b:x,bias:I,preluActivationWeights:A},F={transposeA:s,transposeB:n,activation:r};if(i==null){const M=ms((B,V,Y)=>{const G=T.runKernelFunc(R,D,null,Th,F);return Y([B,V,G]),{value:O(G,b),gradFunc:k}});return M(S,x)}else{const M=ms((B,V,Y,G)=>{const Z=T.runKernelFunc(R,D,null,Th,F);return G([B,V,Z,Y]),{value:O(Z,b),gradFunc:k}});return M(S,x,I)}}const GD=L({fusedMatMul_:VD});const Hs={};Re(Hs,{conv2d:()=>WD,depthwiseConv2d:()=>jD,matMul:()=>GD});function HD(e){return ga(e,.54,.46)}const HS=L({hammingWindow_:HD});function qD(e){return ga(e,.5,.5)}const qh=L({hannWindow_:qD});function YD(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=ge([he(e,r,t-a),Ft([a],i)]);o.push(l),r+=s}return o.length===0?ts([],[0,t]):O(ge(o),[o.length,t])}const Yh=L({frame_:YD});function KD(e,t,s,n,i=qh){n==null&&(n=Vh(t));const r=Yh(e,t,s),o=C(r,i(t)),a=[];for(let l=0;l<r.shape[0];l++)a.push(Ai(he(o,[l,0],[1,t]),n));return ge(a)}const qS=L({stft_:KD});function XD(e,t,s,n,i,r){const o=g(e,"image","cropAndResize"),a=g(t,"boxes","cropAndResize","float32"),l=g(s,"boxInd","cropAndResize","int32");i=i||"bilinear",r=r||0;const c=a.shape[0];v(o.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),v(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${a.shape}.`),v(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${a.shape}.`),v(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),v(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),v(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=T.runKernelFunc(p,u,null,Sg,h);return d}const YS=L({cropAndResize_:XD});function JD(e){const t=g(e,"image","flipLeftRight","float32");v(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const s={image:t},n=T.runKernel(Dr,s,{});return n}const KS=L({flipLeftRight_:JD});function ZD(e,t,s=0,n=.5){const i=g(e,"image","rotateWithOffset","float32");v(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=T.runKernel(Wr,r,o);return a}const XS=L({rotateWithOffset_:ZD});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),v(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),v(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),v(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),v(t.rank===1,()=>"scores must be a 1D tensor"),v(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),v(0<=r&&r<=1,()=>`softNmsSigma must be in [0, 1], but was '${r}'`),{maxOutputSize:s,iouThreshold:n,scoreThreshold:i,softNmsSigma:r}}function QD(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY){const r=g(e,"boxes","nonMaxSuppression"),o=g(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 T.runKernelFunc(c=>c.nonMaxSuppression(r,o,s,n,i),{boxes:r,scores:o},null,pc,l)}const JS=L({nonMaxSuppression_:QD});function ZS(e,t,s){const n=eF(e,t,s),i=n<0?-(n+1):n;e.splice(i,0,t)}function eF(e,t,s){return sF(e,t,s||tF)}function tF(e,t){return e>t?1:e<t?-1:0}function sF(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 Kh(e,t,s,n,i){return pb(e,t,s,n,i,0).selectedIndices}function Xh(e,t,s,n,i,r){return pb(e,t,s,n,i,0,!1,r,!0)}function Jh(e,t,s,n,i,r){return pb(e,t,s,n,i,r,!0)}function pb(e,t,s,n,i,r,o=!1,a=!1,l=!1){const c=[];for(let y=0;y<t.length;y++)t[y]>i&&c.push({score:t[y],boxIndex:y,suppressBeginIndex:0});c.sort(QS);const p=r>0?-.5/r:0,u=[],h=[];for(;u.length<s&&c.length>0;){const y=c.pop(),{score:b,boxIndex:S,suppressBeginIndex:x}=y;if(b<i)break;let I=!1;for(let A=u.length-1;A>=x;--A){const k=nF(e,S,u[A]);if(k>=n){I=!0;break}if(y.score=y.score*iF(n,p,k),y.score<=i)break}y.suppressBeginIndex=u.length,I||(y.score===b?(u.push(S),h.push(y.score)):y.score>i&&ZS(c,y,QS))}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:Fe(u,"int32")};return o&&(f.selectedScores=Fe(h,"float32")),l&&(f.validOutputs=j(d,"int32")),f}function nF(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),y=Math.max(o,p),b=Math.min(a,u),S=Math.min(l,h),x=Math.max(b-f,0)*Math.max(S-y,0);return x/(d+m-x)}function iF(e,t,s){const n=Math.exp(t*s*s);return s<=e?n:0}function QS(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function rF(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY){const r=g(e,"boxes","nonMaxSuppressionAsync"),o=g(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=Kh(c,p,s,n,i);return r!==e&&r.dispose(),o!==t&&o.dispose(),u}const ev=rF;function oF(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=0){const o=g(e,"boxes","nonMaxSuppression"),a=g(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=T.runKernel(Ur,c,p);return{selectedIndices:u[0],selectedScores:u[1]}}const tv=L({nonMaxSuppressionWithScore_:oF});async function aF(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=0){const o=g(e,"boxes","nonMaxSuppressionAsync"),a=g(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=Jh(p,u,s,n,i,r);return o!==e&&o.dispose(),a!==t&&a.dispose(),h}const sv=aF;function lF(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=!1){const o=g(e,"boxes","nonMaxSuppression"),a=g(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=T.runKernel(Mr,h,d);return{selectedIndices:m[0],validOutputs:m[1]}}const nv=L({nonMaxSuppressionPadded_:lF});async function cF(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=!1){const o=g(e,"boxes","nonMaxSuppressionAsync"),a=g(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=Xh(h,d,c,p,u,r);return o!==e&&o.dispose(),a!==t&&a.dispose(),m}const iv=cF;function pF(e,t,s=!1){const n=g(e,"images","resizeBilinear");v(n.rank===3||n.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`),v(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=T.runKernelFunc(l,c,null,xc,p);return r?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const rv=L({resizeBilinear_:pF});function uF(e,t,s=!1){const n=g(e,"images","resizeNearestNeighbor");v(n.rank===3||n.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`),v(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),v(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=T.runKernelFunc(p,l,null,wc,c);return r?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const ov=L({resizeNearestNeighbor_:uF});function hF(e,t,s){v(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),v(s%1===0,()=>`bandPart(): numUpper must be an integer, got ${s}.`);const n=g(e,"a","bandPart");v(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(ei(0,r,1,"int32"),[-1,1]),l=ei(0,o,1,"int32"),c=X(a,l),p=zt(vs(c,j(+t,"int32")),as(c,j(-s,"int32"))),u=Ie([r,o],n.dtype);return O(Xe(nt(O(n,[-1,r,o])).map(h=>at(p,h,u))),i)}const av=L({bandPart_:hF});function dF(e){let t;if(Array.isArray(e)){t=!1,v(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)v(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=ls(e,e.shape[0],0).map(i=>En(i,[0]));v(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(T.tidy(()=>{let r=n[i];if(i>0)for(let o=0;o<i;++o){const a=C(te(C(s[o],r)),s[o]);r=X(r,a)}return J(r,ma(r,"euclidean"))}));return t?Xe(s,0):s}const lv=L({gramSchmidt_:dF});function mF(e,t=!1){if(v(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return cv(e,t);{const s=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),n=nt(O(e,[s,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],r=[];n.forEach(l=>{const[c,p]=cv(l,t);i.push(c),r.push(p)});const o=O(Xe(i,0),e.shape),a=O(Xe(r,0),e.shape);return[o,a]}}function cv(e,t=!1){return T.tidy(()=>{v(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=ar(s),r=Ps(e);const o=ts([[1]],[1,1]);let a=Ps(o);const l=s>=n?n:s;for(let c=0;c<l;++c){const p=r,u=a,h=i;[a,r,i]=T.tidy(()=>{const d=he(r,[c,c],[s-c,1]),m=ma(d),f=he(r,[c,c],[1,1]),y=at(Ct(f,0),ts([[-1]]),ts([[1]])),b=X(f,C(y,m)),S=J(d,b);S.shape[0]===1?a=Ps(o):a=ge([o,he(S,[1,0],[S.shape[0]-1,S.shape[1]])],0);const x=Oe(J(Le(y,b),m)),I=he(r,[c,0],[s-c,n]),A=C(x,a),k=se(a);if(c===0)r=X(I,Le(A,Le(k,I)));else{const F=X(I,Le(A,Le(k,I)));r=ge([he(r,[0,0],[c,n]),F],0)}const R=se(A),D=he(i,[0,c],[s,i.shape[1]-c]);if(c===0)i=X(D,Le(Le(D,a),R));else{const F=X(D,Le(Le(D,a),R));i=ge([he(i,[0,0],[s,c]),F],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 pv=L({qr_:mF});var ht;(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"})(ht||(ht={}));function fF(e,t,s=ht.SUM_BY_NONZERO_WEIGHTS){const n=g(e,"losses","computeWeightedLoss");let i=null;t!=null&&(i=g(t,"weights","computeWeightedLoss"));const r=i==null?n:C(n,i);if(s===ht.NONE)return r;if(s===ht.SUM)return te(r);if(s===ht.MEAN){if(i==null)return Ge(r);{const o=n.size/i.size,a=J(te(r),te(i));return o>1?J(a,j(o)):a}}if(s===ht.SUM_BY_NONZERO_WEIGHTS){if(i==null)return J(te(r),j(n.size));{const o=C(i,es(n.shape)),a=K(te(Es(o,j(0))),"float32");return J(te(r),a)}}throw Error(`Unknown reduction: ${s}`)}const ss=L({computeWeightedLoss_:fF});function gF(e,t,s,n=ht.SUM_BY_NONZERO_WEIGHTS){const i=g(e,"labels","absoluteDifference"),r=g(t,"predictions","absoluteDifference");let o=null;s!=null&&(o=g(s,"weights","absoluteDifference")),xe(i.shape,r.shape,"Error in absoluteDifference: ");const a=Je(X(i,r));return ss(a,o,n)}const uv=L({absoluteDifference_:gF});function yF(e,t,s,n,i=ht.SUM_BY_NONZERO_WEIGHTS){const r=g(e,"labels","cosineDistance"),o=g(t,"predictions","cosineDistance");let a=null;n!=null&&(a=g(n,"weights","cosineDistance")),xe(r.shape,o.shape,"Error in cosineDistance: ");const l=j(1),c=X(l,te(C(r,o),s,!0));return ss(c,a,i)}const hv=L({cosineDistance_:yF});function bF(e,t,s,n=ht.SUM_BY_NONZERO_WEIGHTS){let i=g(e,"labels","hingeLoss");const r=g(t,"predictions","hingeLoss");let o=null;s!=null&&(o=g(s,"weights","hingeLoss")),xe(i.shape,r.shape,"Error in hingeLoss: ");const a=j(1);i=X(C(j(2),i),a);const l=ke(X(a,C(i,r)));return ss(l,o,n)}const dv=L({hingeLoss_:bF});function wF(e,t,s,n=1,i=ht.SUM_BY_NONZERO_WEIGHTS){const r=g(e,"labels","huberLoss"),o=g(t,"predictions","huberLoss");let a=null;s!=null&&(a=g(s,"weights","huberLoss")),xe(r.shape,o.shape,"Error in huberLoss: ");const l=j(n),c=Je(X(o,r)),p=Vs(c,l),u=X(c,p),h=W(C(j(.5),ye(p)),C(l,u));return ss(h,a,i)}const mv=L({huberLoss_:wF});function xF(e,t,s,n=1e-7,i=ht.SUM_BY_NONZERO_WEIGHTS){const r=g(e,"labels","logLoss"),o=g(t,"predictions","logLoss");let a=null;s!=null&&(a=g(s,"weights","logLoss")),xe(r.shape,o.shape,"Error in logLoss: ");const l=j(1),c=j(n),p=Oe(C(r,Mt(W(o,c)))),u=C(X(l,r),Mt(W(X(l,o),c))),h=X(p,u);return ss(h,a,i)}const fv=L({logLoss_:xF});function LF(e,t,s,n=ht.SUM_BY_NONZERO_WEIGHTS){const i=g(e,"labels","meanSquaredError"),r=g(t,"predictions","meanSquaredError");let o=null;s!=null&&(o=g(s,"weights","meanSquaredError")),xe(i.shape,r.shape,"Error in meanSquaredError: ");const a=Ri(i,r);return ss(a,o,n)}const gv=L({meanSquaredError_:LF});function SF(e,t){const s=g(e,"labels","sigmoidCrossEntropyWithLogits"),n=g(t,"logits","sigmoidCrossEntropyWithLogits");xe(s.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");const i=ke(n),r=C(n,s),o=eo(At(Oe(Je(n))));return W(X(i,r),o)}function vF(e,t,s,n=0,i=ht.SUM_BY_NONZERO_WEIGHTS){let r=g(e,"multiClassLabels","sigmoidCrossEntropy");const o=g(t,"logits","sigmoidCrossEntropy");let a=null;if(s!=null&&(a=g(s,"weights","sigmoidCrossEntropy")),xe(r.shape,o.shape,"Error in sigmoidCrossEntropy: "),n>0){const c=j(n),p=j(1),u=j(.5);r=W(C(r,X(p,c)),C(u,c))}const l=SF(r,o);return ss(l,a,i)}const yv=L({sigmoidCrossEntropy_:vF});function TF(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=ms((i,r,o)=>{const a=!0,l=Ep(r,[s],a),c=X(K(r,"float32"),l);o([i,c]);const p=Oe(C(c,i)),u=te(p,[s]),h=(d,m)=>{const[f,y]=m,b=ft(d.shape,[s]);return[C(O(d,b),X(K(f,"float32"),At(y))),C(O(d,b),X(At(y),K(f,"float32")))]};return{value:u,gradFunc:h}});return n(e,t)}function IF(e,t,s,n=0,i=ht.SUM_BY_NONZERO_WEIGHTS){let r=g(e,"onehotLabels","softmaxCrossEntropy");const o=g(t,"logits","softmaxCrossEntropy");let a=null;if(s!=null&&(a=g(s,"weights","softmaxCrossEntropy")),xe(r.shape,o.shape,"Error in softmaxCrossEntropy: "),n>0){const c=j(n),p=j(1),u=j(r.shape[1]);r=W(C(r,X(p,c)),J(c,u))}const l=TF(r,o);return ss(l,a,i)}const bv=L({softmaxCrossEntropy_:IF});const ub={};Re(ub,{abs:()=>Je,acos:()=>ip,acosh:()=>rp,add:()=>W,addN:()=>op,addStrict:()=>OS,all:()=>jr,any:()=>sr,argMax:()=>nr,argMin:()=>ap,asin:()=>lp,asinh:()=>cp,atan:()=>pp,atan2:()=>up,atanh:()=>hp,avgPool:()=>rs,avgPool3d:()=>Gr,basicLSTMCell:()=>_y,batchNorm:()=>on,batchNorm2d:()=>gp,batchNorm3d:()=>yp,batchNorm4d:()=>bp,batchToSpaceND:()=>wi,booleanMaskAsync:()=>vS,broadcastTo:()=>or,buffer:()=>le,cast:()=>K,ceil:()=>wp,clipByValue:()=>Dt,clone:()=>Ps,complex:()=>Ze,concat:()=>ge,concat1d:()=>xp,concat2d:()=>Lp,concat3d:()=>Sp,concat4d:()=>vp,conv1d:()=>Hr,conv2d:()=>yt,conv2dTranspose:()=>qr,conv3d:()=>Yr,conv3dTranspose:()=>Dy,cos:()=>xi,cosh:()=>Kr,cosineWindow:()=>ga,cumsum:()=>Xr,depthToSpace:()=>Tp,depthwiseConv2d:()=>In,diag:()=>Fy,dilation2d:()=>Ip,div:()=>J,divNoNan:()=>Ap,divStrict:()=>ES,dot:()=>My,dropout:()=>jh,elu:()=>An,enclosingPowerOfTwo:()=>Vh,equal:()=>Qt,equalStrict:()=>TS,erf:()=>Np,exp:()=>At,expandDims:()=>Nt,expm1:()=>Cp,eye:()=>ar,fft:()=>Li,fill:()=>Ft,floor:()=>Nn,floorDiv:()=>Jr,fused:()=>Hs,gather:()=>Cn,gatherND:()=>Ph,greater:()=>Ct,greaterEqual:()=>as,greaterEqualStrict:()=>IS,greaterStrict:()=>AS,ifft:()=>Qn,imag:()=>Ht,image:()=>ks,inTopKAsync:()=>GS,irfft:()=>Zr,isFinite:()=>$y,isInf:()=>Wy,isNaN:()=>zy,leakyRelu:()=>Qr,less:()=>Si,lessEqual:()=>vs,lessEqualStrict:()=>NS,lessStrict:()=>CS,linalg:()=>Zh,linspace:()=>Rp,localResponseNormalization:()=>Op,log:()=>Mt,log1p:()=>eo,logSigmoid:()=>By,logSoftmax:()=>to,logSumExp:()=>Ep,logicalAnd:()=>zt,logicalNot:()=>vi,logicalOr:()=>so,logicalXor:()=>Py,losses:()=>Lv,matMul:()=>Le,max:()=>st,maxPool:()=>lt,maxPool3d:()=>no,maxPoolWithArgmax:()=>kp,maximum:()=>Wt,maximumStrict:()=>kS,mean:()=>Ge,min:()=>an,minimum:()=>Vs,minimumStrict:()=>_S,mod:()=>io,modStrict:()=>DS,moments:()=>lr,movingAverage:()=>zS,mul:()=>C,mulStrict:()=>FS,multiRNNCell:()=>jy,multinomial:()=>_p,neg:()=>Oe,norm:()=>ma,notEqual:()=>Es,notEqualStrict:()=>RS,oneHot:()=>On,ones:()=>es,onesLike:()=>Bt,op:()=>L,outerProduct:()=>Vy,pad:()=>Ut,pad1d:()=>Gy,pad2d:()=>Hy,pad3d:()=>qy,pad4d:()=>Yy,pool:()=>Ky,pow:()=>qt,powStrict:()=>MS,prelu:()=>Ii,print:()=>Xy,prod:()=>ro,rand:()=>Jy,randomGamma:()=>tb,randomNormal:()=>ha,randomUniform:()=>Gs,range:()=>ei,real:()=>$t,reciprocal:()=>Fp,relu:()=>ke,relu6:()=>Mp,reshape:()=>O,reverse:()=>Lt,reverse1d:()=>sb,reverse2d:()=>nb,reverse3d:()=>ib,reverse4d:()=>rb,rfft:()=>Ai,round:()=>Up,rsqrt:()=>oo,scalar:()=>j,scatterND:()=>Bh,selu:()=>ao,separableConv2d:()=>Ni,setdiff1dAsync:()=>$p,sigmoid:()=>Ss,sign:()=>Wp,signal:()=>xv,sin:()=>lo,sinh:()=>co,slice:()=>he,slice1d:()=>po,slice2d:()=>da,slice3d:()=>Ci,slice4d:()=>cr,softmax:()=>Yt,softplus:()=>Rn,spaceToBatchND:()=>Ti,sparseToDense:()=>fa,spectral:()=>wv,split:()=>ls,sqrt:()=>He,square:()=>ye,squaredDifference:()=>Ri,squaredDifferenceStrict:()=>US,squeeze:()=>En,stack:()=>Xe,step:()=>kn,stridedSlice:()=>zp,sub:()=>X,subStrict:()=>$S,sum:()=>te,tan:()=>Bp,tanh:()=>Zn,tensor:()=>ze,tensor1d:()=>Fe,tensor2d:()=>ts,tensor3d:()=>Pp,tensor4d:()=>cs,tensor5d:()=>ab,tensor6d:()=>lb,tile:()=>js,topk:()=>jp,transpose:()=>se,truncatedNormal:()=>Oi,unsortedSegmentSum:()=>Vp,unstack:()=>nt,variable:()=>Gp,where:()=>at,whereAsync:()=>uo,zeros:()=>Ie,zerosLike:()=>ne});const wv={fft:Li,ifft:Qn,rfft:Ai,irfft:Zr},xv={hammingWindow:HS,hannWindow:qh,frame:Yh,stft:qS},ks={flipLeftRight:KS,resizeNearestNeighbor:ov,resizeBilinear:rv,rotateWithOffset:XS,cropAndResize:YS,nonMaxSuppression:JS,nonMaxSuppressionAsync:ev,nonMaxSuppressionWithScore:tv,nonMaxSuppressionWithScoreAsync:sv,nonMaxSuppressionPadded:nv,nonMaxSuppressionPaddedAsync:iv},Zh={bandPart:av,gramSchmidt:lv,qr:pv},Lv={absoluteDifference:uv,computeWeightedLoss:ss,cosineDistance:hv,hingeLoss:dv,huberLoss:mv,logLoss:fv,meanSquaredError:gv,sigmoidCrossEntropy:yv,softmaxCrossEntropy:bv};aS(ub);const Hp={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Qh=4;async function NF(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((y,b)=>y+b.length,0)+Qh*h.length,m=new Uint8Array(d);let f=0;for(let y=0;y<h.length;y++){const b=h[y],S=new Uint8Array(new Uint32Array([b.length]).buffer);m.set(S,f),f+=Qh,m.set(b,f),f+=b.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:AF(r),specs:s}}function hb(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=Hp[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 y=m[f];p[f]=y*u.scale+u.min}}else if(u.dtype==="float16")n===void 0&&(n=CF()),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 y=m[f];p[f]=Math.round(y*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+Qh))[0];i+=Qh;const m=new Uint8Array(e.slice(i,i+d));p.push(m),i+=d}}else{const u=Hp[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 b=0;b<d.length;b++)d[b]=p[b*2],m[b]=p[b*2+1];const f=ze(d,l,"float32"),y=ze(m,l,"float32");s[o]=Ze(f,y)}else throw new Error(`Unsupported dtype in weight '${o}': ${a}`);i+=c*u}a!=="complex64"&&(s[o]=ze(p,l,a))}return s}function AF(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 RF=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function Sv(e){return RF?Buffer.byteLength(e):new Blob([e]).size}function qp(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 db(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 Yp(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:Sv(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:Sv(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function OF(){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 EF(){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 kF(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function CF(){const e=OF(),t=EF(),s=kF();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 Rt{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Rt.instance==null&&(Rt.instance=new Rt()),Rt.instance}static registerSaveRouter(e){Rt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Rt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Rt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Rt.getHandlers(e,"load",t)}static getHandlers(e,t,s){const n=[],i=t==="load"?Rt.getInstance().loadRouters:Rt.getInstance().saveRouters;return i.forEach(r=>{const o=r(e,s);o!==null&&n.push(o)}),n}}const _F=e=>Rt.registerSaveRouter(e),DF=e=>Rt.registerLoadRouter(e),FF=e=>Rt.getSaveHandlers(e),MF=(e,t)=>Rt.getLoadHandlers(e,t);const ba="://";class _n{constructor(){this.managers={}}static getInstance(){return _n.instance==null&&(_n.instance=new _n()),_n.instance}static registerManager(e,t){v(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(ba)&&(e=e.slice(0,e.indexOf(ba))),v(e.length>0,()=>"scheme must not be an empty string.");const s=_n.getInstance();v(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 ed(e){if(e.indexOf(ba)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${_n.getSchemes().join(",")}`);return{scheme:e.split(ba)[0],path:e.split(ba)[1]}}async function vv(e,t,s=!1){v(e!==t,()=>`Old path and new path are the same: '${e}'`);const n=Rt.getLoadHandlers(e);v(n.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),v(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${e}.`);const i=n[0],r=Rt.getSaveHandlers(t);v(r.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),v(r.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${t}.`);const o=r[0],a=ed(e).scheme,l=ed(e).path,c=a===ed(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 Tv(){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+ba+i;t[r]=n[i]}}return t}async function Iv(e){const t=ed(e),s=_n.getManager(t.scheme);return s.removeModel(t.path)}async function Av(e,t){const s=!1;return vv(e,t,s)}async function Nv(e,t){const s=!0;return vv(e,t,s)}const UF="model",$F=".json",WF=".weights.bin";function Cv(e){return new Promise(t=>setTimeout(t)).then(e)}class wa{constructor(e){if(!$().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(wa.URL_SCHEME)&&(e=e.slice(wa.URL_SCHEME.length)),(e==null||e.length===0)&&(e=UF),this.modelTopologyFileName=e+$F,this.weightDataFileName=e+WF}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 Cv(()=>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 Cv(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Yp(e)}}}}wa.URL_SCHEME="downloads://";class zF{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=y=>{const b=y.target.result,S=u.indexOf(m);h[S]=b,h.indexOf(null)===-1&&s({modelTopology:a,weightSpecs:p,weightData:qp(h),format:o.format,generatedBy:o.generatedBy,convertedBy:o.convertedBy,userDefinedMetadata:o.userDefinedMetadata})},f.onerror=y=>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=>db(r.name)),i={};for(const r of e)r.paths.forEach(o=>{const a=db(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 PF=e=>$().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(wa.URL_SCHEME))?BF(e.slice(wa.URL_SCHEME.length)):null;Rt.registerSaveRouter(PF);function BF(e="model"){return new wa(e)}function jF(e){return new zF(e)}function mb(e,t,s,n){o(e),s=s==null?0:s,n=n==null?1:n,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){v(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function a(l,c){v(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),v(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),v(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(r))}async function fb(e,t){t==null&&(t={});const s=t.fetchFunc==null?$().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 mb(n,t.onProgress,i,r),a=o.map(u=>u.arrayBuffer()),l=.5,c=1,p=t.onProgress==null?await Promise.all(a):await mb(a,t.onProgress,l,c);return p}async function VF(e,t="",s,n){const i=o=>fb(o,{requestInit:n}),r=Rv(i);return r(e,t,s)}function Rv(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(y=>{const b="quantization"in y?y.quantization.dtype:y.dtype,S=Hp[b]*We(y.shape),x=()=>{i[m]=!0,r[m]==null&&(r[m]=[]),r[m].push({manifestEntry:y,groupOffset:f,sizeBytes:S})};n!=null?n.forEach((I,A)=>{I===y.name&&(x(),o[A]=!0)}):x(),a.push(y.name),f+=S})}),!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 I=0;I<m;I++)f+=p[h+I].byteLength;const y=new ArrayBuffer(f),b=new Uint8Array(y);let S=0;for(let I=0;I<m;I++){const A=new Uint8Array(p[h+I]);b.set(A,S),S+=A.byteLength}const x=r[d];x.forEach(I=>{const A=y.slice(I.groupOffset,I.groupOffset+I.sizeBytes),k=hb(A,[I.manifestEntry]);for(const R in k)u[R]=k[R]}),h+=m}),u}}const GF="application/octet-stream",HF="application/json";class gb{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,t.fetchFunc!=null?(v(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=$().platform.fetch,v(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&v(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:HF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:GF}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Yp(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(p){let u=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?u+=" 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.":u+=" Please make sure the server is serving valid JSON for this request.",new Error(u)}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 p=await this.loadWeights(n);[l,c]=p}return{modelTopology:s,weightSpecs:l,weightData:c,userDefinedMetadata:a,generatedBy:i,convertedBy:r,format:o}}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[s,n]=qF(t),i=this.weightPathPrefix||s,r=[];for(const l of e)r.push(...l.weights);const o=[];e.forEach(l=>{l.paths.forEach(c=>{o.push(i+c+n)})});const a=await fb(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[r,qp(a)]}}gb.URL_SCHEME_REGEX=/^https?:\/\//;function qF(e){const t=e.lastIndexOf("/"),s=e.lastIndexOf("?"),n=e.substring(0,t),i=s>t?e.substring(s):"";return[n+"/",i]}function yb(e){return e.match(gb.URL_SCHEME_REGEX)!=null}const Ov=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let s=!0;if(Array.isArray(e)?s=e.every(n=>yb(n)):s=yb(e),s)return bb(e,t)}return null};Rt.registerSaveRouter(Ov);Rt.registerLoadRouter(Ov);function bb(e,t){return new gb(e,t)}function YF(e,t){return bb(e,t)}class wb{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class KF{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function XF(e,t,s,n){if(arguments.length===1){const i=e.modelTopology!=null||e.weightSpecs!=null;return i?new wb(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 wb({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 wb({modelTopology:e,weightSpecs:t,weightData:s,trainingConfig:n})}function JF(e){return new KF(e)}const Ot={};Re(Ot,{browserFiles:()=>jF,browserHTTPRequest:()=>YF,concatenateArrayBuffers:()=>qp,copyModel:()=>Av,decodeWeights:()=>hb,encodeWeights:()=>NF,fromMemory:()=>XF,getLoadHandlers:()=>MF,getModelArtifactsInfoForJSON:()=>Yp,getSaveHandlers:()=>FF,http:()=>bb,isHTTPScheme:()=>yb,listModels:()=>Tv,loadWeights:()=>VF,moveModel:()=>Nv,registerLoadRouter:()=>DF,registerSaveRouter:()=>_F,removeModel:()=>Iv,weightsLoaderFactory:()=>Rv,withSaveHandler:()=>JF});function ZF(e,t,s){const n=g(e,"labels","confusionMatrix"),i=g(t,"predictions","confusionMatrix");v(s==null||s>0&&Number.isInteger(s),()=>`If provided, numClasses must be a positive integer, but got ${s}`),v(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),v(i.rank===1,()=>`Expected the rank of predictions to be 1, but got ${i.rank}`),v(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.`),v(s>0&&Number.isInteger(s),()=>`numClasses is required to be a positive integer, but got ${s}`);const r=On(K(n,"int32"),s),o=On(K(i,"int32"),s),a=se(r);return K(Le(a,o),"int32")}const QF=L({confusionMatrix_:ZF});const Ev={};Re(Ev,{confusionMatrix:()=>QF});const pr={};Re(pr,{fromPixels:()=>sM,toPixels:()=>tM});let xa;function eM(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=qc(ta,T.backendName);if(a!=null){const d={pixels:e},m={numChannels:t};return T.runKernel(ta,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)&&(xa==null&&(xa=document.createElement("canvas").getContext("2d")),xa.canvas.width=l,xa.canvas.height=c,xa.drawImage(e,0,0,l,c),p=xa.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 Pp(u,h,"int32")}async function tM(e,t){let s=g(e,"img","toPixels");if(!(e instanceof ue)){const y=s;s=K(y,"int32"),y.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}`);const o=await s.data(),a=an(s),l=st(s),c=await Promise.all([a.data(),l.data()]),p=c[0],u=c[1],h=p[0],d=u[0];if(a.dispose(),l.dispose(),s.dtype==="float32"){if(h<0||d>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but got range [${h} - ${d}].`)}else if(s.dtype==="int32"){if(h<0||d>255)throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but got range [${h} - ${d}].`)}else throw new Error(`Unsupported type for toPixels: ${s.dtype}. Please use float32 or int32 tensors.`);const m=s.dtype==="float32"?255:1,f=new Uint8ClampedArray(i*n*4);for(let y=0;y<n*i;++y){let b,S,x,I;r===1?(b=o[y]*m,S=o[y]*m,x=o[y]*m,I=255):r===3?(b=o[y*3]*m,S=o[y*3+1]*m,x=o[y*3+2]*m,I=255):r===4&&(b=o[y*4]*m,S=o[y*4+1]*m,x=o[y*4+2]*m,I=o[y*4+3]*m);const A=y*4;f[A+0]=Math.round(b),f[A+1]=Math.round(S),f[A+2]=Math.round(x),f[A+3]=Math.round(I)}if(t!=null){t.width=i,t.height=n;const y=t.getContext("2d"),b=new ImageData(f,i,n);y.putImageData(b,0,0)}return s!==e&&s.dispose(),f}const sM=L({fromPixels_:eM});const kv={};Re(kv,{prepareAndValidate:()=>_v});function _v(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=[...qn(e.shape).map(c=>c/a),1].slice(0,n);return[o,i,a,l]}const P={};Re(P,{Serializable:()=>xb,SerializationMap:()=>yo,registerClass:()=>Ts});class xb{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class yo{constructor(){this.classNameMap={}}static getMap(){return yo.instance==null&&(yo.instance=new yo()),yo.instance}static register(e){yo.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Ts(e){v(e.className!=null,()=>"Class being registered does not have the static className property defined."),v(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),v(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),yo.register(e)}const Lb="2.3.0";class fs extends xb{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 Uh(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(fs,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class bo extends fs{constructor(e,t,s=null){super();this.learningRate=e,this.rho=t,this.epsilon=s,this.accumulatedGrads=[],this.accumulatedUpdates=[],s==null&&(this.epsilon=T.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=T.registeredVariables[s],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${s}/accum_grad`,variable:N(()=>ne(i).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${s}/accum_var`,variable:N(()=>ne(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;N(()=>{const c=W(C(a,this.rho),C(ye(o),1-this.rho)),p=C(J(He(W(l,this.epsilon)),He(W(a,this.epsilon))),o),u=W(C(l,this.rho),C(ye(p),1-this.rho));a.assign(c),l.assign(u);const h=W(C(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)}}bo.className="Adadelta";Ts(bo);class wo extends fs{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=T.registeredVariables[s];if(this.accumulatedGrads[n]==null){const a=!1;this.accumulatedGrads[n]={originalName:`${s}/accumulator`,variable:N(()=>Ft(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;N(()=>{const a=W(o,ye(r));o.assign(a);const l=W(C(J(r,He(W(a,T.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)}}wo.className="Adagrad";Ts(wo);class xo extends fs{constructor(e,t,s,n=null){super();this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],N(()=>{this.accBeta1=j(t).variable(),this.accBeta2=j(s).variable()}),n==null&&(this.epsilon=T.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);N(()=>{const s=X(1,this.accBeta1),n=X(1,this.accBeta2);t.forEach((i,r)=>{const o=T.registeredVariables[i],a=!1;this.accumulatedFirstMoment[r]==null&&(this.accumulatedFirstMoment[r]={originalName:`${i}/m`,variable:N(()=>ne(o).variable(a))}),this.accumulatedSecondMoment[r]==null&&(this.accumulatedSecondMoment[r]={originalName:`${i}/v`,variable:N(()=>ne(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=W(C(c,this.beta1),C(l,1-this.beta1)),h=W(C(p,this.beta2),C(ye(l),1-this.beta2)),d=J(u,s),m=J(h,n);c.assign(u),p.assign(h);const f=W(C(J(d,W(He(m),this.epsilon)),-this.learningRate),o);o.assign(f)}),this.accBeta1.assign(C(this.accBeta1,this.beta1)),this.accBeta2.assign(C(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),N(()=>{this.accBeta1.assign(qt(this.beta1,this.iterations_+1)),this.accBeta2.assign(qt(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)}}xo.className="Adam";Ts(xo);class Lo extends fs{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=[],N(()=>{this.iteration=j(0).variable(),this.accBeta1=j(t).variable()}),n==null&&(this.epsilon=T.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);N(()=>{const s=X(1,this.accBeta1),n=J(-this.learningRate,W(C(this.iteration,this.decay),1));t.forEach((i,r)=>{const o=T.registeredVariables[i],a=!1;this.accumulatedFirstMoment[r]==null&&(this.accumulatedFirstMoment[r]={originalName:`${i}/m`,variable:ne(o).variable(a)}),this.accumulatedWeightedInfNorm[r]==null&&(this.accumulatedWeightedInfNorm[r]={originalName:`${i}/v`,variable:ne(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=W(C(c,this.beta1),C(l,1-this.beta1)),h=C(p,this.beta2),d=Je(l),m=Wt(h,d);c.assign(u),p.assign(m);const f=W(C(J(n,s),J(u,W(m,this.epsilon))),o);o.assign(f)}),this.iteration.assign(W(this.iteration,1)),this.accBeta1.assign(C(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)}}Lo.className="Adamax";Ts(Lo);class Ei extends fs{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=T.registeredVariables[s];N(()=>{const o=W(C(this.c,i),r);r.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=gt(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)}}Ei.className="SGD";Ts(Ei);class So extends Ei{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=T.registeredVariables[s];if(this.accumulations[n]==null){const a=!1;this.accumulations[n]={originalName:`${s}/momentum`,variable:N(()=>ne(i).variable(a))}}const r=this.accumulations[n].variable,o=Array.isArray(e)?e[n].tensor:e[s];if(o==null)return;N(()=>{let a;const l=W(C(this.m,r),o);this.useNesterov?a=W(C(this.c,W(o,C(l,this.m))),i):a=W(C(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)}}So.className="Momentum";Ts(So);class vo extends fs{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=T.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=T.registeredVariables[s],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${s}/rms`,variable:N(()=>ne(i).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${s}/momentum`,variable:N(()=>ne(i).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${s}/mg`,variable:N(()=>ne(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;N(()=>{const c=W(C(a,this.decay),C(ye(o),1-this.decay));if(this.centered){const p=this.accumulatedMeanGrads[n].variable,u=W(C(p,this.decay),C(o,1-this.decay)),h=J(C(o,this.learningRate),He(X(c,W(ye(u),this.epsilon)))),d=W(C(l,this.momentum),h);a.assign(c),p.assign(u),l.assign(d);const m=X(i,d);i.assign(m)}else{const p=W(C(a,this.decay),C(ye(o),1-this.decay)),u=W(C(l,this.momentum),J(C(o,this.learningRate),He(W(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)}}vo.className="RMSProp";Ts(vo);class ur{static sgd(e){return new Ei(e)}static momentum(e,t,s=!1){return new So(e,t,s)}static rmsprop(e,t=.9,s=0,n=null,i=!1){return new vo(e,t,s,n,i)}static adam(e=.001,t=.9,s=.999,n=null){return new xo(e,t,s,n)}static adadelta(e=.001,t=.95,s=null){return new bo(e,t,s)}static adamax(e=.002,t=.9,s=.999,n=null,i=0){return new Lo(e,t,s,n,i)}static adagrad(e,t=.1){return new wo(e,t)}}So,Ei,bo,wo,vo,Lo,xo;const hr={sgd:ur.sgd,momentum:ur.momentum,adadelta:ur.adadelta,adagrad:ur.adagrad,rmsprop:ur.rmsprop,adamax:ur.adamax,adam:ur.adam};const nM=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Kp(){return new Promise(e=>nM(()=>e()))}function iM(e,t,s){const n=s*(typeof e=="number"?e:e[0]),i=t*(typeof e=="number"?e:e[1]);return[n,i]}function rM(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 oM(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 aM(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 lM(e,t){const s=[0];for(let n=0;n<t;++n)s.push(e[n][0]);return s}function cM(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 Sb=1.7580993408473768,vb=1.0507009873554805;const pM=.3275911,uM=.254829592,hM=-.284496736,dM=1.421413741,mM=-1.453152027,fM=1.061405429;function gM(...e){$().getBool("IS_TEST")||console.warn(...e)}function yM(...e){$().getBool("IS_TEST")||console.log(...e)}function bM(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 wM(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 xM(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 LM(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 SM(e,t){const s=e[t*2],n=e[t*2+1];return{real:s,imag:n}}function vM(e,t,s,n){e[n*2]=t,e[n*2+1]=s}function TM(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 IM(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={};Re(U,{ERF_A1:()=>uM,ERF_A2:()=>hM,ERF_A3:()=>dM,ERF_A4:()=>mM,ERF_A5:()=>fM,ERF_P:()=>pM,PARALLELIZE_THRESHOLD:()=>Fh,SELU_SCALE:()=>vb,SELU_SCALEALPHA:()=>Sb,applyActivation:()=>fo,assertAndGetBroadcastShape:()=>Se,assertAxesAreInnerMostDims:()=>F1,assertParamsConsistent:()=>vy,assignToTypedArray:()=>vM,axesAreInnerMostDims:()=>by,calculateShapes:()=>PS,castTensor:()=>AM,combineLocations:()=>dS,complexWithEvenIndex:()=>xM,complexWithOddIndex:()=>LM,computeConv2DInfo:()=>is,computeConv3DInfo:()=>rr,computeDefaultPad:()=>Ly,computeDilation2DInfo:()=>Y1,computeOptimalWindowSize:()=>dk,computeOutAndReduceShapes:()=>wy,computeOutShape:()=>Ty,computePool2DInfo:()=>Tn,computePool3DInfo:()=>bi,convertConv2DDataFormat:()=>ir,eitherStridesOrDilationsAreOne:()=>et,expandShapeToKeepDim:()=>ft,exponent:()=>IM,exponents:()=>TM,getAxesPermutation:()=>ut,getBroadcastDims:()=>ZE,getComplexWithIndex:()=>SM,getFusedBiasGradient:()=>mo,getFusedDyActivation:()=>ho,getImageCenter:()=>iM,getInnerMostAxes:()=>Gt,getPermuted:()=>oM,getReductionAxes:()=>Ke,getReshaped:()=>rM,getReshapedPermuted:()=>aM,getSliceBeginCoords:()=>lM,getSliceSize:()=>cM,getUndoAxesPermutation:()=>Pr,linspaceImpl:()=>CM,log:()=>yM,mergeRealAndImagArrays:()=>bM,prepareAndValidate:()=>_v,prepareSplitSize:()=>ob,reshapeTensor:()=>NM,segment_util:()=>bS,shouldFuse:()=>go,splitRealAndImagArrays:()=>wM,tupleValuesAreOne:()=>Bs,upcastType:()=>wt,validateInput:()=>zh,validateUpdateShape:()=>cb,warn:()=>gM});function AM(e,t,s){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const n=Ie(e.shape),i=K(e,"float32"),r=s.complex(i,n);return n.dispose(),i.dispose(),r}if(!oy(e.dtype,t))return T.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const n=s.real(e),i=K(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 NM(e,t){return T.makeTensorFromDataId(e.dataId,t,e.dtype)}function CM(e,t,s){const n=(t-e)/(s-1),i=Yn(s,"float32");i[0]=e;for(let r=1;r<i.length;r++)i[r]=i[r-1]+n;return Fe(i,"float32")}function Dv(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 Fv(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=le(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 Mv(e,t,s,n,i){const r=t[t.length-1],[o,a]=[e.length/r,r],l=ia(s,o*n),c=ia("int32",o*n);for(let u=0;u<o;u++){const h=u*a,d=e.subarray(h,h+a),m=[];for(let S=0;S<d.length;S++)m.push({value:d[S],index:S});m.sort((S,x)=>x.value-S.value);const f=u*n,y=l.subarray(f,f+n),b=c.subarray(f,f+n);for(let S=0;S<n;S++)y[S]=m[S].value,b[S]=m[S].index}const p=t.slice();return p[p.length-1]=n,[ze(l,p,s),ze(c,p,"int32")]}const St={};Re(St,{nonMaxSuppressionV3Impl:()=>Kh,nonMaxSuppressionV4Impl:()=>Xh,nonMaxSuppressionV5Impl:()=>Jh,split:()=>Dv,tile:()=>Fv,topkImpl:()=>Mv,whereImpl:()=>Wh});const RM=1e-7,OM=1e-4;class Xp{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 Jp{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?RM:OM}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. Did you forget to import the kernel?`)}const Uv={kernelName:dl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(e,kn(K(s,"float32"),-1))}}};const $v={kernelName:ml,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=ye(K(s,"float32")),i=He(X(j(1),n));return Oe(J(e,i))}}}};const Wv={kernelName:fl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=He(X(ye(K(s,"float32")),1));return J(e,n)}}}};const zv={kernelName:Er,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Se(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 Bv={kernelName:gl,saveAllInputs:!0,gradFunc:(e,t)=>{const s={};return t.forEach((n,i)=>{s[i]=()=>e.clone()}),s}};const Pv={kernelName:yl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>ne(s)}}};const jv={kernelName:bl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>ne(s)}}};const Vv={kernelName:wl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>J(e,He(X(j(1),ye(K(s,"float32")))))}}};const Gv={kernelName:xl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=He(W(j(1),ye(K(s,"float32"))));return J(e,n)}}}};const Hv={kernelName:vl,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Se(s.shape,n.shape),r=()=>{const a=W(ye(s),ye(n));let l=C(e,J(n,a));const c=Ke(s.shape,i);return c.length>0&&(l=te(l,c)),O(l,s.shape)},o=()=>{const a=W(ye(s),ye(n));let l=Oe(C(e,J(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 qv={kernelName:Ll,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>J(e,W(ye(K(s,"float32")),1))}}};const Yv={kernelName:Sl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>J(e,X(j(1),ye(K(s,"float32"))))}}};function EM(e,t,s,n,i=[1,1,1],r,o){const a=g(e,"dy","avgPool3dBackprop"),l=g(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]])),v(c.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${c.rank}.`),v(p.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${p.rank}.`),v(et(n,i),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),o!=null&&v(De(r),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const h=y=>{const b=bi(p.shape,s,n,i,r,o);return y.avgPool3dBackprop(c,p,b)},d={dy:c,input:p},m={filterSize:s,strides:n,dilations:i,pad:r,dimRoundingMode:o},f=T.runKernelFunc(h,d,null,yg,m);return u?O(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}const Kv=L({avgPool3dBackprop_:EM});const Xv={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{filterSize:i,strides:r,dilations:o,pad:a,dimRoundingMode:l}=s,c=o==null?[1,1,1]:o;return{x:()=>Kv(e,n,i,r,c,a,l)}}};function kM(e,t,s,n,i){const r=g(e,"dy","avgPoolBackprop"),o=g(t,"input","avgPoolBackprop");v(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]])),v(l.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${l.rank}.`),v(a.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${a.rank}.`);const p=m=>{const f=Tn(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=T.runKernelFunc(p,u,null,gg,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Jv=L({avgPoolBackprop_:kM});const Zv={kernelName:Tl,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{filterSize:i,strides:r,pad:o}=s;return{x:()=>Jv(e,n,i,r,o)}}};const Qv={kernelName:Al,inputsToSave:["a","b"],gradFunc:(e,t,s)=>{const[n,i]=t,{transposeA:r,transposeB:o}=s;return!r&&!o?{a:()=>Le(e,i,!1,!0),b:()=>Le(n,e,!0,!1)}:!r&&o?{a:()=>Le(e,i,!1,!1),b:()=>Le(e,n,!0,!1)}:r&&!o?{a:()=>Le(i,e,!1,!0),b:()=>Le(n,e,!1,!1)}:{a:()=>Le(i,e,!0,!0),b:()=>Le(e,n,!0,!0)}}};const eT={kernelName:Nl,gradFunc:(e,t,s)=>{const{blockShape:n,crops:i}=s;return{x:()=>Ti(e,n,i)}}};const tT={kernelName:Cl,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 sT={kernelName:kr,gradFunc:e=>({x:()=>e.clone()})};const nT={kernelName:Rl,gradFunc:e=>({x:()=>ne(e)})};const iT={kernelName:Ol,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{clipValueMin:i,clipValueMax:r}=s;return{x:()=>at(zt(as(n,i),vs(n,r)),e,ne(e))}}};const rT={kernelName:El,saveAllInputs:!0,gradFunc:(e,t,s)=>{const n=t.map(l=>l.shape),{axis:i}=s,r=Te(i,t[0].shape)[0],o=n.map(l=>l[r]),a=ls(e,o,r);return a.map(l=>()=>l)}};const oT={kernelName:kl,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const[n,i]=t,{dilations:r,strides:o,pad:a,dataFormat:l}=s;return v(Bs(r),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`),{x:()=>ua(n.shape,e,i,o,a,l),filter:()=>ya(n,e,i.shape,o,a,l)}}};const aT={kernelName:_l,inputsToSave:["dy","filter"],gradFunc:(e,t,s)=>{const[n,i]=t,{strides:r,pad:o,dataFormat:a,dimRoundingMode:l}=s;return{dy:()=>yt(e,i,r,o,a,1,l),filter:()=>ya(e,n,i.shape,r,o,a,l)}}};function _M(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]])),v(r.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${r.shape}.`),v(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),v(s.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${s}.`),v(r.shape[4]===s[3],()=>`Error in conv3dDerFilter: depth of input ${r.shape[4]}) must match input depth in filter (${s[3]}.`),v(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=rr(r.shape,s,n,u,i);return p.conv3dDerFilter(r,o,h)},l={x:r,y:o},c={strides:n,pad:i};return T.runKernelFunc(a,l,null,xg,c)}const lT=L({conv3DBackpropFilter_:_M});const cT={kernelName:Dl,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const{dilations:n,strides:i,pad:r}=s;v(Bs(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:()=>Dh(o.shape,e,a,i,r),filter:()=>lT(o,e,a.shape,i,r)}}};const pT={kernelName:Fl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(Oe(lo(K(s,"float32"))),e)}}};const uT={kernelName:Ml,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(co(K(s,"float32")),e)}}};const hT={kernelName:Ul,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{axis:i,exclusive:r,reverse:o}=s;return{x:()=>{const a=ut([i],n.rank);let l=Xr(e,i,r,!o);return a!=null&&(l=se(l,a)),l}}}};const dT={kernelName:$l,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const{dilations:n,strides:i,pad:r,dimRoundingMode:o}=s,a=n==null?[1,1]:n;v(Bs(a),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[l,c]=t;v(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),v(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),v(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]}.`),v(et(i,a),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${a}'.`),o!=null&&v(De(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=is(l.shape,c.shape,i,a,r,o,!0);return{x:()=>Hh(l.shape,e,c,p),filter:()=>Gh(l,e,c.shape,p)}}};const mT={kernelName:_r,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:()=>T.runKernel(Qo,r,s),filter:()=>T.runKernel(ea,o,s)}}};const fT={kernelName:ui,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Se(s.shape,n.shape),r=()=>{const a=J(e,K(n,"float32")),l=Ke(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{let a=C(e,K(s,"float32"));const l=Ke(n.shape,i);l.length>0&&(a=O(te(a,l),n.shape));const c=ye(n);return Oe(J(a,K(c,"float32")))};return{a:r,b:o}}};const gT={kernelName:Wl,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t,n=r=>r.eluDer(e,s),i={dy:e,y:s};return{x:()=>T.runKernelFunc(n,i,null,Ng)}}};const yT={kernelName:zl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t,n=C(At(Oe(ye(s))),2/Math.sqrt(Math.PI));return{x:()=>C(e,n)}}};const bT={kernelName:Bl,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(e,s)}}};const wT={kernelName:Pl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(e,At(s))}}};const xT={kernelName:jl,gradFunc:e=>({x:()=>ne(e)})};const LT={kernelName:Vl,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Se(s.shape,n.shape),r=()=>{const a=J(e,K(n,"float32")),l=Ke(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{let a=C(e,K(s,"float32"));const l=Ke(n.shape,i);l.length>0&&(a=O(te(a,l),n.shape));const c=ye(n);return Oe(J(a,K(c,"float32")))};return{a:r,b:o}}};const ST={kernelName:Gl,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,s)=>{const{varianceEpsilon:n}=s,[i,r,o,a]=t,l=a==null?j(1):a,c=Ke(r.shape,i.shape),p=[];if(r.rank===1){for(let I=0;I<i.shape.length-1;++I)p.push(i.shape[I]);p.push(1)}const u=X(i,r),h=C(e,l),d=oo(W(o,j(n))),m=C(C(C(d,d),d),j(-.5)),f=()=>r.rank===1?O(C(C(e,js(O(d,[1,1,1,r.shape[0]]),p)),l),i.shape):O(C(C(e,d),l),i.shape),y=()=>{let I=C(C(d,j(-1)),h);return r.rank===1&&(I=te(I,c)),O(I,r.shape)},b=()=>{let I=C(C(m,u),h);return r.rank===1&&(I=te(I,c)),O(I,r.shape)},S=()=>{const I=C(u,d);let A=C(e,I);return r.rank===1&&(A=te(A,c)),O(A,r.shape)},x=()=>{let I=e;return r.rank===1&&(I=te(I,c)),O(I,r.shape)};return{x:f,mean:y,variance:b,scale:S,offset:x}}};const IT={kernelName:Hl,inputsToSave:["x","indices"],gradFunc:(e,t,s)=>{const[n,i]=t,{axis:r}=s,o=Te(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=vT(0,u),f=vT(u+1,u+1+d),y=TT([p,[c],h]),b=O(e,y),S=O(i,[c]),x=TT([[u],m,f]),I=se(b,x);let A=Vp(I,S,n.shape[o]);const k=Pr(x);return A=se(A,k),A};return{x:a,indices:()=>i}}};function vT(e,t){const s=[];for(let n=e;n<t;++n)s.push(n);return s}function TT(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 AT={kernelName:ql,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t;return{a:()=>ne(s),b:()=>ne(n)}}};const NT={kernelName:Yl,gradFunc:e=>({x:()=>K(e,"float32")})};const CT={kernelName:Kl,gradFunc:e=>({x:()=>ne(e)})};const RT={kernelName:Xl,gradFunc:e=>({x:()=>ne(e)})};const OT={kernelName:Jl,gradFunc:e=>({x:()=>ne(e)})};const ET={kernelName:Ql,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>J(e,W(s,1))}}};const kT={kernelName:Zl,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>J(e,K(s,"float32"))}}};const _T={kernelName:ec,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n]=t,{axis:i}=s;return{logits:()=>{const r=!0,o=At(n);return X(e,C(te(e,i,r),o))}}}};function DM(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 T.runKernelFunc(a,l,null,Bg,c)}const DT=L({localResponseNormalizationBackprop_:DM});const FT={kernelName:tc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n,i]=t,{depthRadius:r,bias:o,alpha:a,beta:l}=s;return{x:()=>DT(n,i,e,r,o,a,l)}}};function td(e,t,s,n,i){return t.rank<s.rank&&(t=O(t,ft(t.shape,n))),e.rank<s.rank&&(e=O(e,ft(e.shape,n))),{x:()=>{const r=C(e,K(Qt(s,t),e.dtype));return i==null?r:se(r,i)}}}const Tb={kernelName:hi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const n=s,{reductionIndices:i}=n,[r,o]=t,a=Te(i,r.shape),l=ut(a,r.rank),c=td(e,o,r,a,l);return{x:()=>{let p=c.x();return l!=null&&(p=se(p)),p}}}};const MT={kernelName:sc,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=()=>C(e,K(as(s,n),"float32")),r=()=>C(e,K(Si(s,n),"float32"));return{a:i,b:r}}};function FM(e,t,s,n,i,r=[1,1,1],o,a){const l=g(e,"dy","maxPool3dBackprop"),c=g(t,"input","maxPool3dBackprop"),p=g(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]])),v(u.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${u.rank}.`),v(h.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${h.rank}.`),v(d.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${d.rank}.`),v(et(i,r),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${i} and dilations '${r}'`),a!=null&&v(De(o),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const f=x=>{const I=bi(h.shape,n,i,r,o,a);return x.maxPool3dBackprop(u,h,d,I)},y={dy:u,input:h,output:d},b={filterSize:n,strides:i,dilations:r,pad:o,dimRoundingMode:a},S=T.runKernelFunc(f,y,null,jg,b);return m?O(S,[S.shape[1],S.shape[2],S.shape[3],S.shape[4]]):S}const UT=L({maxPool3dBackprop_:FM});const $T={kernelName:ic,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==null?[1,1,1]:a;return{x:()=>UT(e,n,i,r,o,p,l,c)}}};function MM(e,t,s,n,i,r,o){const a=g(e,"dy","maxPoolBackprop"),l=g(t,"input","maxPoolBackprop"),c=g(s,"output","maxPoolBackprop");v(l.rank===a.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${a.rank})`),v(a.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${a.rank}.`),v(l.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${l.rank}.`),o!=null&&v(De(r),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=d=>{const m=Tn(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 T.runKernelFunc(p,u,null,Pg,h)}const WT=L({maxPoolBackprop_:MM});const zT={kernelName:nc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n,i]=t,{filterSize:r,strides:o,pad:a}=s;return{x:()=>WT(e,n,i,r,o,a)}}};const BT={kernelName:rc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const n=s,{axis:i}=n,[r,o]=t,a=Te(i,r.shape),l=ut(a,r.rank),c=td(e,o,r,a,l);return{x:()=>{let p=c.x();return l!=null&&(p=se(p)),p}}}};const PT={kernelName:oc,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=()=>C(e,K(vs(s,n),"float32")),r=()=>C(e,K(Ct(s,n),"float32"));return{a:i,b:r}}};const jT={kernelName:ac,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Se(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=C(e,Oe(Nn(J(s,n)))),l=Ke(n.shape,i);return l.length>0?O(te(a,l),n.shape):a};return{a:r,b:o}}};const VT={kernelName:lc,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Se(s.shape,n.shape),r=()=>{const a=C(e,K(n,"float32")),l=Ke(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{const a=C(e,K(s,"float32")),l=Ke(n.shape,i);return l.length>0?O(te(a,l),n.shape):a};return{a:r,b:o}}};const GT={kernelName:cc,gradFunc:e=>({x:()=>Oe(e)})};const HT={kernelName:hc,inputsToSave:["indices"],gradFunc:(e,t)=>{const s=t[0];return{indices:()=>Ie(s.shape,"float32")}}};const qT={kernelName:uc,gradFunc:e=>({x:()=>ne(e)})};const Ib={kernelName:dc,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 YT={kernelName:mc,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[s,n,i]=t,r=s,o=n,a=Se(r.shape,o.shape),l=()=>{const p=K(o,"float32");let u=C(e,C(p,qt(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=Ct(r,0),u=at(p,Mt(r),ne(r));let h=C(e,C(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 KT={kernelName:fc,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[s,n]=t,i=Ct(s,0);return{x:()=>at(i,e,C(e,n)),alpha:()=>{let r=at(i,ne(e),C(e,s));const o=Ke(n.shape,e.shape);return o.length>0&&(r=te(r,o)),O(r,n.shape)}}}};const XT={kernelName:gc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>J(e,Oe(ye(s)))}}};const JT={kernelName:Lc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t,n=C(vs(s,6),kn(s));return{x:()=>C(e,K(n,"float32"))}}};const ZT={kernelName:yc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(e,K(kn(s),"float32"))}}};const QT={kernelName:bc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>O(e,s.shape)}}};const eI={kernelName:xc,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=()=>T.runKernelFunc(i,r,null,Kg,s);return{images:o}}};const tI={kernelName:wc,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=()=>T.runKernelFunc(i,r,null,Yg,s);return{images:o}}};const sI={kernelName:Sc,gradFunc:(e,t,s)=>{const{dims:n}=s,i=Te(n,e.shape);return{x:()=>Lt(e,i)}}};const nI={kernelName:vc,gradFunc:e=>({x:()=>ne(e)})};const iI={kernelName:Tc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Oe(J(e,C(qt(s,1.5),2)))}}};const rI={kernelName:Ic,inputsToSave:["condition"],gradFunc:(e,t)=>{const[s]=t;return{condition:()=>K(ne(s),"float32"),t:()=>C(e,K(s,e.dtype)),e:()=>C(e,K(vi(s),e.dtype))}}};const oI={kernelName:Ac,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=Ct(s,j(0)),i=j(Sb),r=j(vb),o=C(e,r),a=C(C(e,i),At(K(s,"float32")));return at(n,o,a)}}}};const aI={kernelName:Ec,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(e,C(s,X(j(1),s)))}}};const lI={kernelName:Oc,gradFunc:e=>({x:()=>ne(e)})};const cI={kernelName:Cc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(xi(K(s,"float32")),e)}}};const pI={kernelName:Rc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(Kr(K(s,"float32")),e)}}};const uI={kernelName:Nc,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{begin:i,size:r}=s,o=n.shape,[a,l]=fp(n,i,r),c=[];for(let p=0;p<e.rank;p++)c.push([a[p],o[p]-a[p]-l[p]]);return{x:()=>Ut(e,c)}}};const hI={kernelName:Uc,outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n]=t,{dim:i}=s,r=!0,o=C(e,n);return{logits:()=>X(o,C(te(o,[i],r),n))}}};const dI={kernelName:kc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(e,Ss(s))}}};const Ab={kernelName:Fc,gradFunc:(e,t,s)=>{const{blockShape:n,paddings:i}=s;return{x:()=>wi(e,n,i)}}};const Nb={kernelName:Mc,gradFunc:(e,t,s)=>{const{axis:n}=s;return{x:()=>ge(e,n)}}};const mI={kernelName:_c,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>J(e,C(He(K(s,"float32")),2))}}};const fI={kernelName:$r,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(e,C(K(s,"float32"),2))}}};const gI={kernelName:di,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=j(2),r=()=>C(e,C(i,X(s,n))),o=()=>C(e,C(i,X(n,s)));return{a:r,b:o}}};const yI={kernelName:Gc,gradFunc:e=>({x:()=>ne(e)})};const bI={kernelName:$c,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Se(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(Oe(a),n.shape)};return{a:r,b:o}}};const wI={kernelName:Dc,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,i=n.shape.slice(),{axis:r}=s,o=Te(r,n.shape);o.forEach(c=>{i[c]=1});const a=O(e,i),l=C(a,es(n.shape,"float32"));return{x:()=>l}}};const xI={kernelName:Wc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>J(e,ye(xi(s)))}}};const LI={kernelName:zc,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>C(X(j(1),ye(s)),e)}}};const SI={kernelName:Bc,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{reps:i}=s,r=()=>{let o=ne(n);if(n.rank===1)for(let a=0;a<i[0];++a)o=W(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=W(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=W(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=W(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 vI={kernelName:mi,gradFunc:(e,t,s)=>{const n=s,{perm:i}=n,r=Pr(i);return{x:()=>se(e,r)}}};const TI={kernelName:Pc,gradFunc:(e,t,s)=>{const n=s,{axis:i}=n;return{value:()=>Xe(e,i)}}};const II={kernelName:jc,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[s]=t,n=()=>UM(e,s);return{x:n}}};function UM(e,t){const s=Wt(t,ne(t)),n=Cn(e,s);let i=as(t,j(0,"int32"));const r=n.rank-i.rank;for(let a=0;a<r;++a)i=Nt(i,a+1);i=zt(i,es(n.shape,"bool"));const o=ne(n);return at(i,n,o)}const AI={kernelName:Vc,gradFunc:e=>({x:()=>ne(e)})};const $M=[Uv,$v,Wv,zv,Bv,Pv,jv,Vv,Gv,Hv,qv,Yv,Xv,Zv,Qv,eT,tT,sT,nT,iT,rT,aT,oT,cT,pT,uT,hT,dT,mT,fT,gT,yT,bT,wT,LT,xT,ST,IT,AT,NT,CT,RT,OT,ET,kT,_T,FT,Tb,Tb,MT,$T,zT,BT,PT,jT,VT,GT,HT,qT,Ib,Ib,YT,KT,XT,JT,ZT,QT,eI,tI,sI,nI,iI,rI,oI,aI,lI,cI,pI,uI,hI,dI,Ab,Ab,Nb,Nb,mI,gI,fI,yI,bI,wI,xI,LI,SI,vI,TI,II,AI];for(const e of $M)ty(e);let Cb;function vt(){return Cb==null&&(Cb=Sy().epsilon()),Cb}function gs(){return"channelsLast"}class ti extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ti.prototype)}}class Is extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Is.prototype)}}class _ extends Error{constructor(e){super(e);Object.setPrototypeOf(this,_.prototype)}}class ae extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ae.prototype)}}class Rb extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Rb.prototype)}}class WM extends Error{constructor(e){super(e);Object.setPrototypeOf(this,WM.prototype)}}function cn(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 qs(e,t){if(!e)throw new Rb(t)}function Ob(e,t){let s=0;for(const n of e)n===t&&s++;return s}function Pt(e){return e.length===1?e[0]:e}function qe(e){return Array.isArray(e)?e:[e]}function pn(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 ki(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,s)=>s.toUpperCase())}let un={};function La(e){if(e==null)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Eb(e){if(e==null||typeof e!="object")return;if(Array.isArray(e))e.forEach(t=>Eb(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:Eb(n))}}}function si(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 un)o=un[r];else if(o=t[r],o==null)throw new _(`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 _(`${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 un?[a,l]=un.className:o in t&&([a,l]=t[o]),a==null)throw new _(`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(un))c[d]=un[d];for(const d of Object.keys(s))c[d]=s[d];const p=r.config;p.customObjects=c;const u=Object.assign({},un);for(const d of Object.keys(s))un[d]=s[d];Eb(r.config);const h=l(a,r.config,s,i);return un=Object.assign({},u),h}else{const c=Object.assign({},un);for(const u of Object.keys(s))un[u]=s[u];const p=new a(r.config);return un=Object.assign({},c),p}}}function zM(e,t){return e<t?-1:e>t?1:0}function Zp(e,t){return-1*zM(e,t)}function hn(e){if(e==null)return e;const t=[];for(const s of e)t.indexOf(s)===-1&&t.push(s);return t}function NI(e){if(e==null)throw new _(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function _i(e,t,s){if(s==null)return;if(e.indexOf(s)<0)throw new _(`${s} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function sd(e,t,s=0,n=Infinity){return qs(s>=0),qs(n>=s),Array.isArray(e)&&e.length>=s&&e.length<=n&&e.every(i=>typeof i===t)}function jt(e,t){Array.isArray(e)?(E.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((s,n)=>jt(s,`element ${n+1} of ${t}`))):E.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${CI(e)}.`)}function CI(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>CI(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function RI(e,t){let s=E.now(),n;const i=(...r)=>{const o=E.now();return o-s<t||(s=o,n=e(...r)),n};return i}function nd(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function kb(e,t){return N(()=>He(te(C(e,e),t,!0)))}class Qp extends P.Serializable{getConfig(){return{}}}class id extends Qp{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 N(()=>{const t=kb(e,this.axis),s=Dt(t,0,this.maxValue);return C(e,J(s,W(vt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}id.className="MaxNorm";P.registerClass(id);class rd extends Qp{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return N(()=>J(e,W(vt(),kb(e,this.axis))))}getConfig(){return{axis:this.axis}}}rd.className="UnitNorm";P.registerClass(rd);class od extends Qp{apply(e){return ke(e)}}od.className="NonNeg";P.registerClass(od);class ad extends Qp{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 N(()=>{const t=kb(e,this.axis),s=W(C(this.rate,Dt(t,this.minValue,this.maxValue)),C(1-this.rate,t));return C(e,J(s,W(vt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}ad.className="MinMaxNorm";P.registerClass(ad);const OI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Be(e){return La(e)}function EI(e,t={}){return si(e,P.SerializationMap.getMap().classNameMap,t,"constraint")}function it(e){if(e==null)return null;if(typeof e=="string"){const t=e in OI?OI[e]:e,s={className:t,config:{}};return EI(s)}else return e instanceof Qp?e:EI(e)}const _b={};Re(_b,{maxNorm:()=>BM,minMaxNorm:()=>VM,nonNeg:()=>jM,unitNorm:()=>PM});function BM(e){return new id(e)}function PM(e){return new rd(e)}function jM(){return new od()}function VM(e){return new ad(e)}const kI=["channelsFirst","channelsLast"],_I=["valid","same","causal"],DI=["max","avg"],FI=["sum","mul","concat","ave"];const Sa=new Map();function dt(e){_i(kI,"DataFormat",e)}function _s(e){_i(_I,"PaddingMode",e)}function Db(e){_i(DI,"PoolMode",e)}const eu=[],MI="/";function Dn(e,t){eu.push(e);try{const s=t();return eu.pop(),s}catch(s){throw eu.pop(),s}}function GM(){return eu.length===0?"":eu.join(MI)+MI}function ld(e){if(!UI(e))throw new Error("Not a valid tensor name: '"+e+"'");return GM()+e}function cd(e){if(!UI(e))throw new Error("Not a valid tensor name: '"+e+"'");Sa.has(e)||Sa.set(e,0);const t=Sa.get(e);if(Sa.set(e,Sa.get(e)+1),t>0){const s=`${e}_${t}`;return Sa.set(s,1),s}else return e}const HM=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function UI(e){return!!e.match(HM)}function $I(e){return e===parseInt(e.toString(),10)}function dn(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 WI(e){return e=Array.isArray(e)?new Float32Array(e):e,Fe(e)}function To(e){return an(WI(e)).dataSync()[0]}function Fn(e){return st(WI(e)).dataSync()[0]}function ps(e,t){if(t<e)throw new _(`end (${t}) < begin (${e}) is forbidden.`);const s=[];for(let n=e;n<t;++n)s.push(n);return s}function Di(e,t){return e.asType(t)}function Fi(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 zI(e,t){return N(()=>{if(e.shape.length!==2)throw new _(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);const s=Fi(e,1);return pd(s,[1,t,1])})}function BI(e){const t=[dn(e.shape)];return e.reshape(t)}function PI(e){if(e.rank<=1)throw new _(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],dn(e.shape,1)];return e.reshape(t)}function Mi(e,t,s){return N(()=>{switch(e.rank){case 1:return po(e,t,s);case 2:return da(e,[t,0],[s,e.shape[1]]);case 3:return Ci(e,[t,0,0],[s,e.shape[1],e.shape[2]]);case 4:return cr(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 _(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Fb(e,t,s){return N(()=>{switch(e.rank){case 1:return po(e,t,s);case 2:return da(e,[0,t],[e.shape[0],s]);case 3:return Ci(e,[0,0,t],[e.shape[0],e.shape[1],s]);case 4:return cr(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],s]);default:throw new _(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function tu(e,t,s,n){return N(()=>{switch(e.rank){case 1:return po(e,t,s);case 2:switch(n){case 1:return Mi(e,t,s);case 2:return Fb(e,t,s);default:throw new _(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return Mi(e,t,s);case 2:return Ci(e,[0,t,0],[e.shape[0],s,e.shape[2]]);case 3:return Fb(e,t,s);default:throw new _(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return Mi(e,t,s);case 2:return cr(e,[0,t,0,0],[e.shape[0],s,e.shape[2],e.shape[3]]);case 3:return cr(e,[0,0,t,0],[e.shape[0],e.shape[1],s,e.shape[3]]);case 4:return Fb(e,t,s);default:throw new _(`The axis is not within the rank of the tensor ${n}`)}default:throw new _(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function ud(e,t=-1){let s;return t<0&&(s=e[0].rank,s!==0?t=s:t=0),t===e[0].rank&&(t=-1),ge(e,t)}function Mb(e,t){switch(e.rank){case 1:return xp([e,t]);case 2:return Lp([e,t],0);case 3:return Sp([e,t],0);case 4:return vp([e,t],0);default:throw new _(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function pd(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new _(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return js(e,t)}function va(e,t=0,s=1,n,i){return ha(e,t,s,n,i)}function mn(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 Hs.matMul({a:e,b:t,transposeA:i,transposeB:r,bias:n?Ub(e.rank,n,gs()):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 Hs.matMul({a:e,b:t,transposeA:h,transposeB:d,bias:n?Ub(e.rank,n,gs()):null,activation:s}).reshape(u)}}function hd(e,t,s){return N(()=>(Array.isArray(t)?t=Fe(t,"int32"):t=t.toInt(),Cn(e,t,s)))}function Io(e){return C(e,e)}function Ub(e,t,s){const n=t.shape;if(t.rank!==1&&t.rank!==e)throw new _(`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 _(`Unsupported input rank by biasAdd: ${t.rank}`)}function Ys(e,t,s){return N(()=>(s==null&&(s=gs()),dt(s),e.add(Ub(e.rank,t,s))))}function jI(e,t=1){if(t!==1)throw new ae(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return An(e)}function VI(e){return N(()=>J(e,Je(e).add(1)))}function dd(e,t,s,n){return N(()=>jh(e,t,s,n))}function GI(e){return N(()=>{const t=W(.5,C(.2,e));return Dt(t,0,1)})}function Ui(e,t,s=!1){return s?e():t()}const HI=["fanIn","fanOut","fanAvg"],qI=["normal","uniform","truncatedNormal"];function qM(e){_i(HI,"FanMode",e)}function YM(e){_i(qI,"Distribution",e)}class fn extends P.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class md extends fn{apply(e,t){return Ie(e,t)}}md.className="Zeros";P.registerClass(md);class Ta extends fn{apply(e,t){return es(e,t)}}Ta.className="Ones";P.registerClass(Ta);class fd extends fn{constructor(e){super();if(typeof e!="object")throw new _(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new _(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return N(()=>C(j(this.value),es(e,t)))}getConfig(){return{value:this.value}}}fd.className="Constant";P.registerClass(fd);class gd extends fn{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 Gs(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}gd.className="RandomUniform";P.registerClass(gd);class yd extends fn{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 va(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}yd.className="RandomNormal";P.registerClass(yd);class bd extends fn{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 Oi(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}bd.className="TruncatedNormal";P.registerClass(bd);class wd extends fn{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return N(()=>{if(e.length!==2||e[0]!==e[1])throw new _("Identity matrix initializer can only be used for 2D square matrices.");return C(this.gain,ar(e[0]))})}getConfig(){return{gain:this.gain}}}wd.className="Identity";P.registerClass(wd);function KM(e,t="channelsLast"){let s,n;if(dt(t),e.length===2)s=e[0],n=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){const i=dn(e,2);s=e[1]*i,n=e[0]*i}else if(t==="channelsLast"){const i=dn(e,0,e.length-2);s=e[e.length-2]*i,n=e[e.length-1]*i}}else{const i=dn(e);s=Math.sqrt(i),n=Math.sqrt(i)}return[s,n]}class ys extends fn{constructor(e){super();if(e.scale<0)throw new _(`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,qM(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,YM(this.distribution),this.seed=e.seed}apply(e,t){const s=KM(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 Oi(e,0,o,t,this.seed)}else{const o=Math.sqrt(3*r);return Gs(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}ys.className="VarianceScaling";P.registerClass(ys);class su extends ys{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ys.className}}su.className="GlorotUniform";P.registerClass(su);class nu extends ys{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ys.className}}nu.className="GlorotNormal";P.registerClass(nu);class iu extends ys{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ys.className}}iu.className="HeNormal";P.registerClass(iu);class ru extends ys{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ys.className}}ru.className="HeUniform";P.registerClass(ru);class ou extends ys{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ys.className}}ou.className="LeCunNormal";P.registerClass(ou);class au extends ys{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ys.className}}au.className="LeCunNormal";P.registerClass(au);class xd extends fn{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 N(()=>{if(e.length!==2)throw new ae("The Orthogonal Initializer does not support non-2D shapes yet.");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=va(s,0,1,"float32");let i=Zh.gramSchmidt(n);return e[0]>e[1]&&(i=i.transpose()),C(this.gain,i)})}getConfig(){return{gain:this.gain,seed:this.seed}}}xd.className="Orthogonal";P.registerClass(xd);const YI={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 KI(e,t={}){return si(e,P.SerializationMap.getMap().classNameMap,t,"initializer")}function Me(e){return La(e)}function je(e){if(typeof e=="string"){const t=e in YI?YI[e]:e;if(t==="GlorotNormal")return new nu();if(t==="GlorotUniform")return new su();if(t==="HeNormal")return new iu();if(t==="HeUniform")return new ru();if(t==="LeCunNormal")return new ou();if(t==="LeCunUniform")return new au();{const s={};return s.className=t,s.config={},KI(s)}}else return e instanceof fn?e:KI(e)}const $b={};Re($b,{constant:()=>ZM,glorotNormal:()=>rU,glorotUniform:()=>iU,heNormal:()=>oU,heUniform:()=>aU,identity:()=>sU,leCunNormal:()=>lU,leCunUniform:()=>cU,ones:()=>JM,orthogonal:()=>pU,randomNormal:()=>eU,randomUniform:()=>QM,truncatedNormal:()=>tU,varianceScaling:()=>nU,zeros:()=>XM});function XM(){return new md()}function JM(){return new Ta()}function ZM(e){return new fd(e)}function QM(e){return new gd(e)}function eU(e){return new yd(e)}function tU(e){return new bd(e)}function sU(e){return new wd(e)}function nU(e){return new ys(e)}function iU(e){return new su(e)}function rU(e){return new nu(e)}function oU(e){return new iu(e)}function aU(e){return new ru(e)}function lU(e){return new ou(e)}function cU(e){return new au(e)}function pU(e){return new xd(e)}let uU=0;function Ld(){return uU++}const Sd={};function dr(e=""){return e in Sd||(Sd[e]=0),Sd[e]+=1,e+Sd[e].toString()}function vd(e){return Array.isArray(e)&&Array.isArray(e[0])}function Ia(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function fe(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new _(`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 _(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Aa(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 XI="Variable";class Td{constructor(e,t="float32",s=XI,n=!0,i=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Ld(),s=s==null?XI:s,this.originalName=ld(s),this.name=cd(this.originalName),this.trainable_=n,this.constraint=i,this.val=Gp(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),hU(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 hU(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function lu(e){return e.map(t=>t.read())}function Na(e){e.forEach(t=>{const s=t[0];s.write(t[1])})}class rt{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 bs{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=Ld(),r!=null&&(this.originalName=ld(r),this.name=cd(this.originalName)),this.rank=t.length}}let dU=0;class Ao{constructor(e,t){this.callArgs=t,this.id=dU++,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 mU=0;class be extends P.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=mU++,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=pn(s)+"_"+dr(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 Is(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new _(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Pt(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Pt(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ti(`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 ti(`Layer ${this.name} is not connected, no input to return.`);return Pt(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new ti(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ti(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Pt(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=qe(e),this.inputSpec==null||this.inputSpec.length===0)return;const t=qe(this.inputSpec);if(e.length!==t.length)throw new _(`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 _(`Input ${s} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${r}`);if(i.maxNDim!=null&&r>i.maxNDim)throw new _(`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 _(`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 _(`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 _(`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 _(`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=qe(e);let n=!0;for(const r of s)if(!(r instanceof bs)){n=!1;break}let i=!0;for(const r of s)if(r instanceof bs){i=!1;break}if(n===i)throw new _("Arguments to apply() must be all SymbolicTensors or all Tensors");return Dn(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const r=[];for(const o of qe(e))r.push(o.shape);this.build(Pt(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=qe(r),a=[];for(let l of o)s.indexOf(l)!==-1&&(l=l.clone()),a.push(l);if(r=Pt(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=fU(e),o=this.computeOutputShape(r);let a;const l=gU(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 bs(l,c,this,qe(e),t,this.name,p)):a=new bs(l,o,this,qe(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 ti(`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 ti(`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 Is(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Aa(this.weights)}build(e){this.built=!0}getWeights(e=!1){return lu(e?this.trainableWeights:this.weights)}setWeights(e){N(()=>{const t=this.weights;if(t.length!==e.length)throw new _(`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=lu(t);for(let i=0;i<n.length;++i){const r=n[i],o=t[i],a=e[i];if(!E.arraysEqual(r.shape,a.shape))throw new _(`Layer weight shape ${r.shape} not compatible with provided weight shape ${a.shape}`);s.push([o,a])}Na(s)})}addWeight(e,t,s,n,i,r,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new _(`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 Td(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=qe(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=qe(e);t=qe(t),s=qe(s),n=qe(n),i=Ia(i),r=Ia(r);const l=[],c=[],p=[];for(const u of a)l.push(u.sourceLayer),c.push(u.nodeIndex),p.push(u.tensorIndex);new Ao({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 fU(e){e=qe(e);const t=[];for(const s of e)t.push(s.shape);return Pt(t)}function gU(e){return"float32"}function Wb(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=Wb(o,a,l);for(const p of c)i.indexOf(p)===-1&&i.push(p)}return i}}}class $i extends be{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:dr("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 _("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 _("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new _("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 bs(this.dtype,this.batchInputShape,this,[],{},this.name);n.nodeIndex=0,n.tensorIndex=0,new Ao({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[n],outputTensors:[n],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new _(`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}}}$i.className="InputLayer";P.registerClass($i);function Id(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 _("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 $i({batchInputShape:t,name:e.name,dtype:s,sparse:e.sparse}),i=n.inboundNodes[0].outputTensors;return i[0]}async function ni(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 Ad(e){if(e==null)return;for(const t in e){const s=e[t];typeof s!="number"&&s.dispose()}}var JI;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(JI||(JI={}));const yU=125;class No{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 zb{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 bU extends No{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=N(()=>W(this.totals[n],C(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:N(()=>{const n=C(J(1,this.seen),this.totals[s]);t[s]=n,this.totals[s].dispose(),gt(t[s])})}}}class Bb extends No{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 Pb extends No{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=yU),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");E.isNumber(this.yieldEvery)&&(this.maybeWait=RI(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 ni(s),n.push(this.yield(e,t,s))),n.push(Kp()),await Promise.all(n)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await ni(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const s=[];this.epochEnd!=null&&(await ni(t),s.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&s.push(Kp()),await Promise.all(s)}async onBatchBegin(e,t){this.batchBegin!=null&&(await ni(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const s=[];this.batchEnd!=null&&(await ni(t),s.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?s.push(Kp()):E.isNumber(this.yieldEvery)&&s.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(s)}async onTrainBegin(e){this.trainBegin!=null&&(await ni(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await ni(e),await this.trainEnd(e))}}function Nd(e,t){if(e==null&&(e={}),e instanceof No)return[e];if(Array.isArray(e)&&e[0]instanceof No)return e;const s=qe(e);return s.map(n=>new Pb(n,t))}class Ks{constructor(){}static registerCallbackConstructor(e,t){E.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Ks.checkForDuplicate(t),Ks.constructors[e]==null&&(Ks.constructors[e]=[]),Ks.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Ks.constructors){const s=Ks.constructors[+t];s.forEach(n=>{if(n===e)throw new _("Duplicate callback constructor.")})}}static clear(){Ks.constructors={}}static createCallbacks(e){const t=[];for(const s in Ks.constructors){const n=+s;e>=n&&t.push(...Ks.constructors[n])}return t.map(s=>new s())}}Ks.constructors={};function Cd(e,t,s,n,i,r,o,a,l){const c=new Bb(),p=[new bU(),...Ks.createCallbacks(t)];e!=null&&p.push(...e),p.push(c);const u=new zb(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 ws(e,t={},s=!1){return si(e,P.SerializationMap.getMap().classNameMap,t,"layer",s)}function cu(e,t){return N(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));const s=te(Io(e),t,!0),n=Ft(s.shape,vt()),i=He(Wt(s,n));return J(e,i)})}function ii(e,t){return N(()=>Ge(Io(X(t,e)),-1))}function Ca(e,t){return N(()=>Ge(Je(X(t,e)),-1))}function mr(e,t){return N(()=>{const s=X(e,t),n=Dt(Je(e),vt(),Number.MAX_VALUE),i=Je(J(s,n));return C(100,Ge(i,-1))})}function wU(e,t){return N(()=>{const s=Dt(t,vt(),Number.MAX_VALUE),n=Mt(W(1,s)),i=Dt(e,vt(),Number.MAX_VALUE),r=Mt(W(1,i));return Ge(Io(X(n,r)),-1)})}function xU(e,t){return N(()=>{const s=Wt(0,X(1,C(e,t)));return Ge(Io(s),-1)})}function LU(e,t){return N(()=>{const s=Wt(0,X(1,C(e,t)));return Ge(s,-1)})}function SU(e,t){return N(()=>{const s=te(C(e,t),-1),n=st(C(X(1,e),t),-1);return Wt(0,W(1,X(n,s)))})}function vU(e,t){return N(()=>{const s=Math.log(2),n=X(t,e),i=X(W(n,Rn(C(-2,n))),s);return Ge(i,-1)})}function Co(e,t,s=!1){return N(()=>{if(s)t=Yt(t);else{const n=te(t,t.shape.length-1,!0);t=J(t,n)}return t=Dt(t,vt(),1-vt()),Oe(te(C(e.toFloat(),Mt(t)),t.shape.length-1))})}function Ra(e,t,s=!1){return N(()=>{const n=Nn(BI(e)).toInt();t=Dt(t,vt(),1-vt());const i=t.shape,r=On(n,i[i.length-1]).reshape(i);return Co(r,t,s)})}function TU(e,t){if(!E.arraysEqual(e.shape,t.shape))throw new _(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return N(()=>{const s=t.relu(),n=t.abs().neg();return s.sub(t.mul(e)).add(n.exp().log1p())})}function Oa(e,t){return N(()=>{let s;return s=Dt(t,vt(),1-vt()),s=Mt(J(s,X(1,s))),Ge(TU(e,s),-1)})}function IU(e,t){return N(()=>{const s=Dt(e,vt(),1),n=Dt(t,vt(),1);return te(C(e,Mt(J(s,n))),-1)})}function AU(e,t){return N(()=>{const s=Mt(W(vt(),t));return Ge(X(t,C(e,s)),-1)})}function pu(e,t){return N(()=>{const s=cu(e,-1),n=cu(t,-1),i=C(s,n);return Oe(te(i,-1))})}const uu={meanSquaredError:ii,meanAbsoluteError:Ca,meanAbsolutePercentageError:mr,meanSquaredLogarithmicError:wU,squaredHinge:xU,hinge:LU,categoricalHinge:SU,logcosh:vU,categoricalCrossentropy:Co,sparseCategoricalCrossentropy:Ra,binaryCrossentropy:Oa,kullbackLeiblerDivergence:IU,poisson:AU,cosineProximity:pu};function Rd(e){if(typeof e=="string"){if(e in uu)return uu[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 _(t)}else return e}function hu(e,t){return N(()=>{const s=C(.5,Bt(t)),n=Di(Ct(t,s),e.dtype);return Ge(Qt(e,n),-1)})}function du(e,t){return N(()=>Di(Qt(nr(e,-1),nr(t,-1)),"float32"))}function ZI(e,t){return N(()=>zt(e.equal(1),t.equal(1)).sum().cast("float32"))}function NU(e,t){return N(()=>zt(e.equal(1),t.equal(0)).sum().cast("float32"))}function CU(e,t){return N(()=>zt(e.equal(0),t.equal(1)).sum().cast("float32"))}function jb(e,t){return N(()=>{const s=ZI(e,t),n=CU(e,t),i=s.add(n);return at(Ct(i,0),s.div(i),0).cast("float32")})}function QI(e,t){return N(()=>{const s=ZI(e,t),n=NU(e,t),i=s.add(n);return at(Ct(i,0),s.div(i),0).cast("float32")})}function Od(e,t){return Oa(e,t)}function Ed(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)),Qt(e,t).asType("float32")}const RU=ii,OU=ii,EU=Ca,kU=Ca,_U=mr,DU=mr,mu=Co,FU=pu,Vb=Ra,kd={binaryAccuracy:hu,categoricalAccuracy:du,precision:jb,categoricalCrossentropy:mu,sparseCategoricalCrossentropy:Vb,mse:RU,MSE:OU,mae:EU,MAE:kU,mape:_U,MAPE:DU,cosine:FU};function eA(e){if(typeof e=="string"&&e in kd)return kd[e];if(typeof e!="string"&&e!=null)return e;throw new _(`Unknown metric ${e}`)}function fu(e){if(qs(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(const s of Object.keys(uu))if(uu[s]===e){t=s;break}if(t!==void 0)return t;for(const s of Object.keys(kd))if(kd[s]===e){t=s;break}return t!==void 0?t:e.name}}function tA(e){const t={Adagrad:()=>hr.adagrad(.01),Adadelta:()=>hr.adadelta(1,.95,vt()),Adam:()=>hr.adam(.001,.9,.999,vt()),Adamax:()=>hr.adamax(.002,.9,.999,vt(),0),RMSProp:()=>hr.rmsprop(.001,.9,0,vt()),SGD:()=>hr.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 _(`Unknown Optimizer ${e}`)}const sA=1*1024*1024;function Hb(e,t,s=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Gb(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>sA&&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 <= ${sA}.`)}}function Gb(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(!Gb(e[s]))return!1}return!0}else if(Array.isArray(e)){for(const t of e)if(!Gb(t))return!1;return!0}else return!1;else{const t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function nA(e,t,s,n=console.log){const i=UU(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)),_d(r,s,n),n("=".repeat(t));const a=e.layers;for(let p=0;p<a.length;++p)i?$U(a[p],s,n):WU(a[p],s,o,n),n((p===a.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const l=MU(e),c=Aa(e.nonTrainableWeights);n(`Total params: ${l+c}`),n(`Trainable params: ${l}`),n(`Non-trainable params: ${c}`),n("_".repeat(t))}function MU(e){let t;return e.collectedTrainableWeights!=null?t=Aa(e.collectedTrainableWeights):t=Aa(e.trainableWeights),t}function UU(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 _d(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 $U(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()];_d(o,t,s)}function WU(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];_d(c,t,n);for(let p=1;p<r.length;++p)_d(["","","",r[p]],t,n)}function iA(e,t,s){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof s=="string"}function Ro(e,t){if(e===null)return null;if(typeof e=="string")return ki(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];iA(t,i,r)?s.push(r):s.push(Ro(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=ki(n);s[r]=Ro(i,r)}}return s}}function Dd(e,t){if(e==null)return null;if(typeof e=="string")return pn(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];iA(t,i,r)?s.push(r):s.push(Dd(r,t))}return s}else{const s={};for(const n of Object.keys(e)){const i=e[n],r=pn(n);(n==="name"||n==="className")&&typeof i=="string"?s[r]=i:s[r]=Dd(i,n)}return s}}const fr="2.3.0";function zU(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return K(t,e.dtype)}catch(s){throw new _(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}class Wi{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Wi)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(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]=zU(e,t),this.name2Id[e.name]=e.id,s!=null&&(this.id2Mask[e.id]=s);else throw new _(`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 bs){if(this.id2Value[e.id]==null)throw new _(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{const t=this.name2Id[e];if(t==null)throw new _(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof bs){if(this.id2Value[e.id]==null)throw new _(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{const t=this.name2Id[e];if(t==null)throw new _(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&ce(this.id2Mask)}}const qb={},rA={};function Oo(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(qb[p]==null){const m=BU(o,t);u=m.sorted,h=m.recipientCounts,qb[p]=u,rA[p]=h}u=qb[p],h={},i||Object.assign(h,rA[p]);const d=new Wi(t);for(let m=0;m<u.length;++m){if(n!=null){const F=pa().numTensors;F>n.maxNumTensors&&(n.maxNumTensors=F),F<n.minNumTensors&&(n.minNumTensors=F)}const f=u[m],y=f.sourceLayer;if(y instanceof $i)continue;const b=[],S=[],x=[];let I=!1;for(const F of f.inputs){const M=d.getValue(F),B=d.getMask(F);b.push(M),S.push(B),B!=null&&(I=!0),i||(h[F.name]--,h[F.name]===0&&!t.hasKey(F)&&a.indexOf(F.name)===-1&&!M.isDisposed&&F.sourceLayer.stateful!==!0&&x.push(M))}I&&(s=s||{},s.mask=S[0]);const A=qe(y.apply(b,s));let k=null;y.supportsMasking&&(k=y.computeMask(b,S));const R=PU(f),D=Array.isArray(R)?R:[R];for(let F=0;F<D.length;++F){d.hasKey(D[F])||d.add(D[F],A[F],Array.isArray(k)?k[0]:k);const M=a.indexOf(D[F].name);M!==-1&&(l[M]=A[F])}i||ce(x)}return d.disposeMasks(),r?l:l[0]}function BU(e,t){E.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let s=[],n={};if(e.length===1){const i=oA(e[0],t);s=i.sorted,n=i.recipientMap}else{const i=new Set();for(const r of e){const{sorted:o,recipientMap:a}=oA(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:jU(n)}}function jU(e){const t={};for(const s in e)t[s]=e[s].size;return t}function oA(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 PU(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 Mn extends be{constructor(e){super({});if(this.containerNodes=new Set(),this.name=e.name,this.name==null){const b=this.getClassName().toLowerCase();this.name=dr(b)}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],hn(this.inputs).length!==this.inputs.length)throw new _(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);hn(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(b=>b.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const b of this.outputs){const S=b.sourceLayer,x=b.nodeIndex,I=b.tensorIndex;this.outputLayers.push(S),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(I)}for(const b of this.inputs){const S=b.sourceLayer,x=b.nodeIndex,I=b.tensorIndex;qs(x===0,"input layer has >1 nodes"),qs(I===0,"input layer has >1 tensors"),this.inputLayers.push(S),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(I)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;b<this.inputLayers.length;b++){const S=this.inputLayers[b];if(!(S instanceof $i))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${b} (0-based) originates from layer type ${S.getClassName()}.`);this.inputNames.push(S.name),this.feedInputShapes.push(S.batchInputShape),this.feedInputNames.push(S.name)}for(const b of this.outputLayers)this.outputNames.push(b.name);this.internalInputShapes=this.inputs.map(b=>b.shape),this.internalOutputShapes=this.outputs.map(b=>b.shape);const t={},s={},n={},i={},r={},o=[],a=(b,S,x,I,A,k)=>{(I==null||A==null||k==null)&&(I=b.sourceLayer,A=b.nodeIndex,k=b.tensorIndex);const R=I.inboundNodes[A];if(x.indexOf(R)!==-1)throw new Is(`The tensor ${b.name} at layer "${I.name}" is part of a cycle.`);if(S.indexOf(R)!==-1)return;this.containerNodes.add(Mn.nodeKey(I,A)),I.id in r||(r[I.id]=Object.keys(r).length),x.indexOf(R)===-1&&x.push(R);const D=R.inboundLayers.length;for(let F=0;F<D;F++){const M=R.inputTensors[F],B=R.inboundLayers[F],V=R.nodeIndices[F],Y=R.tensorIndices[F];a(M,S,x,B,V,Y)}for(S.push(R);x.indexOf(R)>=0;)x.splice(x.indexOf(R),1);o.push(R)},l=[],c=[];for(const b of this.outputs)a(b,l,c);const p=o.slice().reverse();for(const b of p){s[b.id]=b,b.id in t||(t[b.id]=0);let S=t[b.id];const x=n[b.outboundLayer.id]==null?0:n[b.outboundLayer.id];S=Math.max(S,x),n[b.outboundLayer.id]=S,i[b.outboundLayer.id]=b.outboundLayer,t[b.id]=S;for(let I=0;I<b.inboundLayers.length;I++){const A=b.inboundLayers[I],k=b.nodeIndices[I],R=A.inboundNodes[k],D=t[R.id]==null?0:t[R.id];t[R.id]=Math.max(S+1,D),s[R.id]=R}}const u={};for(const b in t){const S=t[b];S in u||(u[S]=[]),u[S].push(s[b])}const h={};for(const b in n){const S=n[b];S in h||(h[S]=[]),h[S].push(i[b])}let d=Object.keys(h).map(b=>parseInt(b,10)).sort(Zp);this.layers=[];for(const b of d){const S=h[b];S.sort((x,I)=>{const A=r[x.id],k=r[I.id];return A<k?-1:A>k?1:0});for(const x of S)x instanceof Mn&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=h,d=Object.keys(u).map(b=>parseInt(b,10)).sort(Zp);const m=this.inputs.slice(),f=[];for(const b of d)for(const S of u[b]){const x=S.outboundLayer;if(x!=null){for(const I of S.inputTensors)if(m.indexOf(I)===-1)throw new Is(`Graph disconnected: cannot obtain value for tensor ${I} at layer "${x.name}". The following previous layers were accessed without issue: ${f}`);for(const I of S.outputTensors)m.push(I);f.push(x.name)}}this.nodesByDepth=u;const y=this.layers.map(b=>b.name);for(const b of y){const S=y.filter(x=>x===b).length;if(S!==1)throw new Is(`The name "${b}" is used ${S} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(y))}this.outboundNodes=[],this.inboundNodes=[],new Ao({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(b=>null),outputMasks:this.outputs.map(b=>null),inputShapes:this.inputs.map(b=>b.shape),outputShapes:this.outputs.map(b=>b.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 _("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 _(`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 _(`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 _(`${r.length} of ${n} weights are not set: ${r}`)}Na(i)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${fr}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const s=Dd(this.updatedConfig());return t?JSON.stringify(s):s}call(e,t){return N(()=>{e=qe(e);const s=new Wi();for(let n=0;n<this.inputs.length;++n)s.add(this.inputs[n],e[n]);return Oo(this.outputs,s,t)})}computeMask(e,t){return N(()=>{e=qe(e);let s;return t==null?s=cn(null,e.length):s=qe(t),this.runInternalGraph(e,s)[1]})}computeOutputShape(e){const t=Ia(e);if(t.length!==this.inputLayers.length)throw new _(`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(Zp);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],y=l.nodeIndices[m],b=l.tensorIndices[m],S=`${f.name}_${y}_${b}`,x=s[S];p.push(x)}const u=c.computeOutputShape(Pt(p)),h=Ia(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];qs(a in s),i.push(s[a])}return Pt(i)}runInternalGraph(e,t){t==null&&(t=cn(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(Zp);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,y,b,S;if(c.callArgs!=null&&(m=c.callArgs),d.length===1){const[x,I]=d[0];m.mask==null&&(m.mask=I),b=qe(p.call(x,m)),S=qe(p.computeMask(x,I)),f=[x],y=[I]}else f=d.map(x=>x[0]),y=d.map(x=>x[1]),m.mask==null&&(m.mask=y),b=qe(p.call(f,m)),S=qe(p.computeMask(f,y));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 I=h[x],A=b[x],k=S[x];s[I.id]=[A,k]}}}}const i=[],r=[],o=[];for(const a of this.outputs){qs(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 Mn?1:0;for(let i=0;i<n.inboundNodes.length;i++){const r=Mn.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 _(`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 _("Provide either a layer name or layer index");for(const s of this.layers)if(s.name===e)return s;throw new _(`No such layer: ${e}`)}calculateLosses(){return N(()=>{const e=[];for(const t of this.layers)for(let s=0;s<t.inboundNodes.length;++s){const n=Mn.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=Mn.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 y=u.inboundLayers[f],b=u.nodeIndices[f],S=u.tensorIndices[f],x=Mn.nodeKey(y,b);let I=t[x];I==null&&(I=0),m.push([y.name,I,S,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=Mn.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=Mn.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,y){f.name in r?r[f.name].push(y):r[f.name]=[y]}function a(f,y){const b=[];let S;for(const x of y){const I=x[0],A=x[1],k=x[2];if(S=x[3]==null?{}:x[3],!(I in i)){o(f,y);return}const R=i[I];if(R.inboundNodes.length<=A){o(f,y);return}const D=R.inboundNodes[A];b.push(D.outputTensors[k])}b.length>0&&f.apply(Pt(b),S)}function l(f){const y=f.name,b=ws(f,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(n),i[y]=b;const S=f.inboundNodes;S.forEach(x=>{if(!(x instanceof Array))throw new _(`Corrupted configuration, expected array for nodeData: ${x}`);o(b,x)})}const c=t.name,p=t.layers;for(const f of p)l(f);for(;!NI(r);)for(const f of p){const y=i[f.name];if(y.name in r){const b=r[y.name];delete r[y.name];for(const S of b)a(y,S)}}const u=[],h=[],d=t.inputLayers;for(const f of d){const y=f[0],b=f[1],S=f[2];qs(y in i);const x=i[y],I=x.inboundNodes[b].outputTensors;u.push(I[S])}const m=t.outputLayers;for(const f of m){const y=f[0],b=f[1],S=f[2];qs(y in i);const x=i[y],I=x.inboundNodes[b].outputTensors;h.push(I[S])}return new e({inputs:u,outputs:h,name:c})}get stateful(){if(this._stateful)throw new _("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(){N(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}function VU(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 Fd(e,t){return VU(e,t,"classWeight")}async function Md(e,t,s,n){if(t!=null||n!=null)throw new Error("Support sampleWeight is not implemented yet");if(s!=null){const i=N(()=>{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])}),Fe(o,"float32")}else return null}function aA(e,t){return C(e,t)}const GU=32;function cA(e,t){let s,n;const i=t;s=i.xs,n=i.ys,E.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=lA("input",e.inputNames,s),o=lA("output",e.outputNames,n),a=r[0].shape[0];E.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)})`),E.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++)E.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++)E.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 lA(e,t,s){if(s instanceof ue)return[s];if(Array.isArray(s))return E.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 _(`The feature data generated by the dataset lacks the required ${e} key '${i}'.`);n.push(s[i])}return n}}function HU(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 uA(e,t,s){const n=s.batchesPerEpoch!=null;if(E.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),E.assert(s!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),E.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}`),E.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}`),E.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(pA(s.validationData))E.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 y=HU(s.validationData);r=y.xs,o=y.ys}const a=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let c;i?c=l.slice().concat(l.map(y=>"val_"+y)):c=l.slice();const p=Nd(s.callbacks,s.yieldEvery),u=s.verbose==null?1:s.verbose,{callbackList:h,history:d}=Cd(p,u,s.epochs,null,null,qU(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 y={};await h.onEpochBegin(m);let b=0,S=0;for(n||(f=await t.iterator());n?b<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 ${b} 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:I,ys:A}=cA(e,x.value),k={};k.batch=S,k.size=I[0].shape[0],await h.onBatchBegin(S,k);const R=[];if(s.classWeight!=null){const M=Fd(s.classWeight,e.outputNames);for(let B=0;B<M.length;++B)R.push(await Md(A[B],null,M[B]))}const D=I.concat(A).concat(R),F=a(D);ce(D);for(let M=0;M<l.length;++M){const B=l[M],V=F[M];k[B]=V,gt(V)}await h.onBatchEnd(S,k),Ad(k),S++,b++}if(n?b>=s.batchesPerEpoch:x.done){if(i){let I;pA(s.validationData)?I=qe(await e.evaluateDataset(s.validationData,{batches:s.validationBatches})):I=qe(e.evaluate(r,o,{batchSize:s.validationBatchSize==null?GU:s.validationBatchSize,verbose:0}));for(let A=0;A<e.metricsNames.length;++A)y[`val_${e.metricsNames[A]}`]=I[A]}break}if(e.stopTraining_)break}if(await h.onEpochEnd(m,y),m++,e.stopTraining_)break}return await h.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function qU(e,t){let s=null;return t.batchesPerEpoch!=null?s=t.batchesPerEpoch:Number.isFinite(e.size)&&(s=e.size),s}function pA(e){return typeof e.iterator=="function"}function YU(e){return typeof e.next=="function"}async function hA(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.");E.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=YU(t)?t:await t.iterator();let a=0,l=0;for(;n?l<s.batches:!0;){const c=await o.next();if(r=N(()=>{if(c.value){const{xs:p,ys:u}=cA(e,c.value),h=p.concat(u),d=N(()=>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 y=d[f],b=r[f];r[f]=N(()=>W(r[f],C(m,y))),l>0&&ce(b)}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]=J(r[c],a),ce(p)}return Pt(r)}function Ud(e){E.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Ea(e,t,s){return e==null?[null]:Array.isArray(e)?e.map(n=>Mi(n,t,s-t)):Mi(e,t,s-t)}function $d(e,t){return N(()=>e==null?null:Array.isArray(e)?e.map(s=>$d(s,t)):hd(e,t.dtype==="int32"?t:t.toInt()))}function Wd(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 KU(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 _("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const y=e.checkNumSamples(s,i,d,"steps_per_epoch");let b;y!=null&&(b=ps(0,y)),o==null&&(o=1);const{callbackList:S,history:x}=Cd(a,o,r,h,y,d,i,f,u);S.setModel(e),e.history=x,await S.onTrainBegin(),e.stopTraining_=!1;for(let I=h;I<r;++I){await S.onEpochBegin(I);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&&E.shuffle(b);const k=Fe(b),R=Wd(y,i);for(let D=0;D<R.length;++D){const F={};if(await S.onBatchBegin(D,F),N(()=>{const M=R[D][0],B=R[D][1],V=Mi(k,M,B-M);F.batch=D,F.size=B-M;const Y=$d(s,V),G=t(Y);for(let Z=0;Z<n.length;++Z){const q=n[Z],ee=G[Z];F[q]=ee,gt(ee)}if(D===R.length-1&&f){const Z=e.testLoop(l,c,i);for(let q=0;q<n.length;++q){const ee=n[q],Q=Z[q];gt(Q),A["val_"+ee]=Q}}}),await S.onBatchEnd(D,F),Ad(F),e.stopTraining_)break}k.dispose()}if(await S.onEpochEnd(I,A),e.stopTraining_)break}return await S.onTrainEnd(),await e.history.syncData(),e.history}async function dA(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;Ud(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 _(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);const R=!0,D=await e.standardizeUserData(o,a,null,null,R,u);l=D[0],c=D[1],f=l.concat(c)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){m=!0;const R=Math.floor(i[0].shape[0]*(1-n.validationSplit)),D=i[0].shape[0];l=Ea(i,R,D),i=Ea(i,0,R),c=Ea(r,R,D),r=Ea(r,0,R),f=l.concat(c)}else n.validationSteps!=null&&(m=!0);const y=i.concat(r).concat(p);e.checkTrainableWeightsConsistency();const b=e.makeTrainFunction(),S=e.getDedupedMetricsNames();let x,I;m?(e.makeTestFunction(),x=e.testFunction,I=S.slice().concat(S.map(R=>"val_"+R))):(x=null,f=[],I=S.slice());const A=Nd(n.callbacks,n.yieldEvery),k=await KU(e,b,y,S,u,n.epochs,n.verbose,A,x,f,n.shuffle,I,n.initialEpoch,null,null);return k}finally{e.isTraining=!1,gr(i,t),gr(r,s),gr(l,o),gr(c,a),p!=null&&ce(p)}}function Yb(e){const t=[];e instanceof ue&&(e=[e]);for(let s=0;s<e.length;++s){const n=e[s];if(n.rank===1)t.push(Fi(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 gr(e,t){if(e==null)return;const s=[];if(t instanceof ue)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 ue)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 XU(e){return e instanceof ue}function Kb(e){return Array.isArray(e)}function mA(e){return!XU(e)&&!Kb(e)}function fA(e,t,s,n=!0,i=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(Kb(e)&&e.length>0)o=!0;else if(mA(e)){for(const a in e)if(e.hasOwnProperty(a)){o=!0;break}}else o=!0;if(o)throw new _(`Error when checking model ${i} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let r;if(mA(e)){e=e,r=[];for(const o of t){if(e[o]==null)throw new _(`No data provided for "${o}". Need data for each key in: ${t}`);r.push(e[o])}}else if(Kb(e)){if(e=e,e.length!==t.length)throw new _(`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 _(`The model ${i} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);r=[e]}if(r=Yb(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 _(`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 _(`Error when checking ${i}: expected ${t[o]} to have shape [${s[o]}], but got array with shape [${a.shape}].`)}}return r}function JU(e,t,s){const n=hn(e.map(r=>r.shape[0]));n.sort();const i=hn(t.map(r=>r.shape[0]));if(i.sort(),n.length>1)throw new _(`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 _(`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&&!E.arraysEqual(n,i))throw new _(`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 ZU(e,t,s){const n=[ii,Oa,Co];for(let i=0;i<e.length;++i){const r=e[i],o=t[i],a=s[i];if(o==null)continue;if(o===Co&&r.shape[r.shape.length-1]===1)throw new _(`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 _(`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 gA(e,t,s,n=!0,i=""){let r;if(Array.isArray(e)){if(e.length!==t.length)throw new _(`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 _(`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 _(`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 _(`Error when checking ${i}: expected ${t[o]} to have shape ${JSON.stringify(s[o])} but got array with shape ${JSON.stringify(a.shape)}.`)}}}function QU(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 e$="layers-model";class gn extends Mn{constructor(e){super(e);this.isTraining=!1}summary(e,t,s=console.log){if(!this.built)throw new _("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).");nA(this,e,t,s)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=tA(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof fs))throw new _("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 _(`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(Rd(e.loss[r]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new _(`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=>Rd(o))}else{const r=Rd(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=[],Dn("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=QU(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])};Dn("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]===Oa?["accuracy","acc"].indexOf(d)!==-1?u=hu:["crossentropy","ce"].indexOf(d)!==-1&&(u=Od):this.lossFunctions[r]===Ra?["accuracy","acc"].indexOf(d)!==-1?u=Ed:["crossentropy","ce"].indexOf(d)!==-1&&(u=Vb):["accuracy","acc"].indexOf(d)!==-1?u=du:["crossentropy","ce"].indexOf(d)!==-1&&(u=mu);let y;["accuracy","acc"].indexOf(d)!==-1?y="acc":["crossentropy","ce"].indexOf(d)!==-1&&(y="ce"),h=u,p=c+y}else{const f=eA(d);h=f,p=c+fu(d)}let m;Dn(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;Ud(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 Pt(l)}finally{gr(r[0],e),gr(r[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),hA(this,e,t)}checkNumSamples(e,t,s,n="steps"){let i;if(s!=null){if(i=null,t!=null)throw new _(`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 _(`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 _("`outputs` is an empty Array, which is not allowed.");const s=Array.isArray(t),n=s?t:[t],i=this.retrieveSymbolicTensors(n),r=new Wi();if(e instanceof ue&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new _(`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 _(`No value is provided for the model's input ${a.name}`);r.add(a,l)}const o=Oo(i,r);return s?o:o[0]}retrieveSymbolicTensors(e){const t=cn(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 _(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,s=!1){return N(()=>{const n=this.checkNumSamples(e);if(s)throw new ae("Verbose predictLoop() is not implemented yet.");const i=Wd(n,t),r=this.outputs.map(o=>[]);for(let o=0;o<i.length;++o){const a=N(()=>{const l=i[o][0],c=i[o][1],p=Ea(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 Wi(u);return Oo(this.outputs,h)});a.forEach((l,c)=>r[c].push(l))}return Pt(r.map(o=>ge(o,0)))})}predict(e,t={}){const s=Yb(e);gA(s,this.inputNames,this.feedInputShapes,!1);try{const n=t.batchSize==null?32:t.batchSize;return Ud(n),this.predictLoop(s,n)}finally{gr(s,e)}}predictOnBatch(e){gA(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 Is("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===Ra?i.push(o.slice(0,o.length-1).concat([1])):i.push(o)}if(e=fA(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=fA(t,this.feedOutputNames,i,!1,"target"),JU(e,t,null),ZU(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&n!=null&&n>0&&e[0].shape[0]%n!==0)throw new _(`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=Fd(n,this.outputNames);l=[];for(let p=0;p<c.length;++p)l.push(await Md(a[p],null,c[p]))}return[o,a,l]}testLoop(e,t,s,n=0,i){return N(()=>{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=Wd(r,s),l=Fe(ps(0,r));for(let c=0;c<a.length;++c){const p=a[c][0],u=a[c][1],h=Mi(l,p,u-p),d=$d(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 y=m[f];o[f]=W(o[f],C(u-p,y))}}for(let c=0;c<o.length;++c)o[c]=J(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(Ob(e,n)>1){const r=Ob(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 Wi(p),h=Oo(this.outputs,u,{training:!0});let d;for(let m=0;m<this.lossFunctions.length;++m){const f=this.lossFunctions[m];let y=f(n[m],h[m]);i[m]!=null&&(y=aA(y,i[m]));const b=Ge(y);t.push(b),m===0?d=y:d=W(d,y)}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 y=this.metricsTensors[m][0],b=this.metricsTensors[m][1];f=Ge(y(n[b],h[b]))}gt(f),r.push(f)}return d=Ge(d),this.calculateLosses().forEach(m=>{d=W(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=>N(()=>{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 Wi(r),a=Oo(this.outputs,o);for(let l=0;l<this.lossFunctions.length;++l){const c=this.lossFunctions[l],p=Ge(c(i[l],a[l]));l===0?s=p:s=W(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=Ge(c(i[p],a[p]));t.push(u)}return t})}async fit(e,t,s={}){return dA(this,e,t,s)}async fitDataset(e,t){return uA(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),Pt(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=pa().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-pa().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=pn(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=>pn(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]=pn(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[pn(fu(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>pn(fu(e)));{const e={};for(const t in this.metrics)e[t]=pn(fu(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=Ro(e.optimizer_config),s=ws(t);let n;if(typeof e.loss=="string")n=ki(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(r=>ki(r));else if(e.loss!=null){n={};for(const r in e.loss)n[r]=ki(e.loss[r])}let i;if(Array.isArray(e.metrics))i=e.metrics.map(r=>ki(r));else if(e.metrics!=null){i={};for(const r in e.metrics)i[r]=ki(e.metrics[r])}this.compile({loss:n,metrics:i,optimizer:s})}async save(e,t){if(typeof e=="string"){const l=Ot.getSaveHandlers(e);if(l.length===0)throw new _(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new _(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new _("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const s=await Ot.encodeWeights(this.getNamedWeights(t)),n=!1,i=null,r=this.toJSON(i,n),o={modelTopology:r,format:e$,generatedBy:`TensorFlow.js tfjs-layers v${fr}`,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 Ot.encodeWeights(await this.optimizer.getWeights(),l);s.specs.push(...p),s.data=Ot.concatenateArrayBuffers([s.data,c])}if(this.userDefinedMetadata!=null){const l=!0;Hb(this.userDefinedMetadata,this.name,l),o.userDefinedMetadata=this.userDefinedMetadata}return o.weightData=s.data,o.weightSpecs=s.specs,e.save(o)}setUserDefinedMetadata(e){Hb(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}gn.className="Model";P.registerClass(gn);async function yA(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let s=e.modelTopology;s.model_config!=null&&(s=s.model_config);const n=Ro(s),i=ws(n,t);if(e.weightsManifest!=null){const r=await Ot.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 bA(e,t){if(t==null&&(t={}),typeof e=="string"){const s=Ot.getLoadHandlers(e,t);if(s.length===0)s.push(Ot.browserHTTPRequest(e,t));else if(s.length>1)throw new _(`Found more than one (${s.length}) load handlers for URL '${e}'`);e=s[0]}return t$(e,void 0,t)}async function t$(e,t,s){if(s==null&&(s={}),e.load==null)throw new _("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=ws(Ro(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 _("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:c,optimizerWeights:p}=s$(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 s$(e,t){const s=Ot.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 yr extends gn{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:dr("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 _(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof yr||e instanceof gn;let s;if(t){if(s=e,s.outputs.length!==1)throw new _("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 _("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 _("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const n=Id({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 _(`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 _("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=Wb(this.outputs[0])}this.inboundNodes=[],new Ao({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:cn(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 gn({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 Is("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 Is("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 Is("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 Is("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 _("Legacy serialization format not supported yet.");i=t}else E.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 yr))throw new ae(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(const a of i){const l=void 0,c=ws(a,l,n);n&&c.setFastWeightInitDuringBuild(!0),o.add(c)}return o}set stopTraining(e){if(this.model==null)throw new _("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 _("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}}}yr.className="Sequential";P.registerClass(yr);function wA(e){return new gn(e)}function xA(e){return new yr(e)}function LA(e,t){return t==null&&(t={}),bA(e,t)}function zd(e){return Id(e)}function SA(e,t){Ks.registerCallbackConstructor(e,t)}class Xs extends P.Serializable{getConfig(){return{}}}class vA extends Xs{apply(e,t=1){return jI(e,t)}}vA.className="elu";P.registerClass(vA);class TA extends Xs{apply(e){return ao(e)}}TA.className="selu";P.registerClass(TA);class IA extends Xs{apply(e){return ke(e)}}IA.className="relu";P.registerClass(IA);class AA extends Xs{apply(e){return N(()=>Vs(6,ke(e)))}}AA.className="relu6";P.registerClass(AA);class NA extends Xs{apply(e){return e}}NA.className="linear";P.registerClass(NA);class CA extends Xs{apply(e){return Ss(e)}}CA.className="sigmoid";P.registerClass(CA);class RA extends Xs{apply(e){return GI(e)}}RA.className="hardSigmoid";P.registerClass(RA);class OA extends Xs{apply(e){return Rn(e)}}OA.className="softplus";P.registerClass(OA);class EA extends Xs{apply(e){return VI(e)}}EA.className="softsign";P.registerClass(EA);class kA extends Xs{apply(e){return Zn(e)}}kA.className="tanh";P.registerClass(kA);class Bd extends Xs{apply(e,t=-1){return Yt(e,t)}}Bd.className="softmax";P.registerClass(Bd);class _A extends Xs{apply(e,t=-1){return to(e,t)}}_A.className="logSoftmax";P.registerClass(_A);function xs(e){return e.getClassName()}function Xb(e,t={}){return si(e,P.SerializationMap.getMap().classNameMap,t,"activation")}function Un(e){if(e==null){const t={};return t.className="linear",t.config={},Xb(t)}if(typeof e=="string"){const t={};return t.className=e,t.config={},Xb(t)}else return e instanceof Xs?e:Xb(e)}function Jb(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 DA extends P.Serializable{}class ka extends DA{constructor(e){super();Jb(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 N(()=>{let t=Ie([1]);return this.hasL1&&(t=W(t,te(C(this.l1,Je(e))))),this.hasL2&&(t=W(t,te(C(this.l2,Io(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}ka.className="L1L2";P.registerClass(ka);function FA(e){return Jb(e),new ka({l1:e!=null?e.l1:null,l2:0})}function MA(e){return Jb(e),new ka({l2:e!=null?e.l2:null,l1:0})}const UA={l1l2:"L1L2"};function Ae(e){return La(e)}function $A(e,t={}){return si(e,P.SerializationMap.getMap().classNameMap,t,"regularizer")}function Ye(e){if(e==null)return null;if(typeof e=="string"){const t=e in UA?UA[e]:e,s={className:t,config:{}};return $A(s)}else return e instanceof DA?e:$A(e)}class Pd extends be{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=fe(e);let s=ke(e);return this.maxValue!=null&&(s=Dt(s,0,this.maxValue)),s}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Pd.className="ReLU";P.registerClass(Pd);class jd extends be{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const s=fe(e);return Qr(s,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}jd.className="LeakyReLU";P.registerClass(jd);class Vd extends be{constructor(e){super(e==null?{}: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=it(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 _(`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 rt({ndim:e.length,axes:s})],this.built=!0}call(e,t){return e=fe(e),Ii(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Me(this.alphaInitializer),alphaRegularizer:Ae(this.alphaRegularizer),alphaConstraint:Be(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Vd.className="PReLU";P.registerClass(Vd);class Gd extends be{constructor(e){super(e==null?{}: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=fe(e);return An(s)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Gd.className="ELU";P.registerClass(Gd);class Hd extends be{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){const s=fe(e);return s.mul(Di(s.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Hd.className="ThresholdedReLU";P.registerClass(Hd);class qd extends be{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new Bd().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){const s=fe(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}}qd.className="Softmax";P.registerClass(qd);function Yd(e,t,s){if(typeof e=="number")return cn(e,t);if(e.length!==t)throw new _(`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(!$I(i))throw new _(`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 yn(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 gu(e,t,s,n){if(e==null)return null;if(n==="valid")e=e*t+Fn([s-t,0]);else if(n==="same")e=e*t;else throw new _(`Unsupport padding mode: ${n}.`);return e}function yu(e,t){return N(()=>(dt(t),t==="channelsFirst"?se(e,[0,2,3,1]):e))}function Zb(e,t){return N(()=>(dt(t),t==="channelsFirst"?se(e,[0,2,3,4,1]):e))}function n$(e,t,s,n=1,i="valid",r,o=1){return N(()=>{if(r==null&&(r=gs()),dt(r),e.shape.length!==3)throw new _(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new _(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(s!=null&&s.shape.length!==1)throw new _(`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=Hr(e,t,n,i==="same"?"same":"valid","NWC",o);return s!=null&&(a=Ys(a,s)),a})}function WA(e,t,s,n=[1,1],i="valid",r,o,a=null){return N(()=>{if(r==null&&(r=gs()),dt(r),e.rank!==3&&e.rank!==4)throw new _(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new _(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=yu(e,r);if(i==="causal")throw new ae("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Hs.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 i$(e,t,s,n=[1,1,1],i="valid",r,o){return N(()=>{if(r==null&&(r=gs()),dt(r),e.rank!==4&&e.rank!==5)throw new _(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new _(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let a=Zb(e,r);if(i==="causal")throw new ae("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=Yr(a,t,n,i==="same"?"same":"valid","NDHWC",o),s!=null&&(a=Ys(a,s)),r==="channelsFirst"&&(a=se(a,[0,4,1,2,3])),a})}class Kd extends be{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Kd.verifyArgs(t),this.rank=e,jt(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=Yd(t.kernelSize,e,"kernelSize"),this.strides=Yd(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,_s(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,dt(this.dataFormat),this.activation=Un(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=je(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=it(t.biasConstraint),this.biasRegularizer=Ye(t.biasRegularizer),this.activityRegularizer=Ye(t.activityRegularizer),this.dilationRate=Yd(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new _(`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 _(`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 _(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(qs("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!sd(e.kernelSize,"number",1,3))throw new _(`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:xs(this.activation),useBias:this.useBias,biasInitializer:Me(this.biasInitializer),biasRegularizer:Ae(this.biasRegularizer),activityRegularizer:Ae(this.activityRegularizer),biasConstraint:Be(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class bu extends Kd{constructor(e,t){super(e,t);this.kernel=null,bu.verifyArgs(t),this.filters=t.filters,jt(this.filters,"filters"),this.kernelInitializer=je(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=it(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 _(`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 N(()=>{e=fe(e);let s;const n=this.bias==null?null:this.bias.read(),i=nd(this.activation.getClassName());if(i!=null&&this.rank===2)s=WA(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(this.rank===1)s=n$(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)s=WA(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)s=i$(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=yn(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:Me(this.kernelInitializer),kernelRegularizer:Ae(this.kernelRegularizer),kernelConstraint:Be(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 _(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class _a extends bu{constructor(e){super(2,e);_a.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!sd(e.kernelSize,"number",1,2))throw new _(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}_a.className="Conv2D";P.registerClass(_a);class wu extends bu{constructor(e){super(3,e);wu.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 _(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}wu.className="Conv3D";P.registerClass(wu);class Xd extends _a{constructor(e){super(e);if(this.inputSpec=[new rt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new _(`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 _("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 _("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 rt({ndim:4,axes:{[t]:s}})],this.built=!0}call(e,t){return N(()=>{let s=fe(e);if(s.shape.length!==4)throw new _(`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=gu(a,u,c,this.padding),m=gu(l,h,p,this.padding),f=[i,d,m,this.filters];this.dataFormat!=="channelsLast"&&(s=se(s,[0,2,3,1]));let y=qr(s,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(y=se(y,[0,3,1,2])),this.bias!=null&&(y=Ys(y,this.bias.read(),this.dataFormat)),this.activation!=null&&(y=this.activation.apply(y)),y})}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]=gu(t[n],a,r,this.padding),t[i]=gu(t[i],l,o,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Xd.className="Conv2DTranspose";P.registerClass(Xd);class zA extends bu{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 _("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new _("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 _(`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=it(t.depthwiseConstraint),this.pointwiseInitializer=je(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Ye(t.pointwiseRegularizer),this.pointwiseConstraint=it(t.pointwiseConstraint)}build(e){if(e=Ue(e),e.length<this.rank+2)throw new _(`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 _(`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 rt({ndim:this.rank+2,axes:{[t]:s}})],this.built=!0}call(e,t){return N(()=>{e=fe(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=Ni(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(s=Ys(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=Me(this.depthwiseInitializer),e.pointwiseInitializer=Me(this.pointwiseInitializer),e.depthwiseRegularizer=Ae(this.depthwiseRegularizer),e.pointwiseRegularizer=Ae(this.pointwiseRegularizer),e.depthwiseConstraint=Be(this.depthwiseConstraint),e.pointwiseConstraint=Be(this.pointwiseConstraint),e}}zA.className="SeparableConv";class Jd extends zA{constructor(e){super(2,e)}}Jd.className="SeparableConv2D";P.registerClass(Jd);class xu extends bu{constructor(e){super(1,e);xu.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"&&!sd(e.kernelSize,"number",1,1))throw new _(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}xu.className="Conv1D";P.registerClass(xu);class Zd extends be{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 N(()=>{if(e=fe(e),this.dataFormat==="channelsLast"){const s=tu(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return tu(s,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const s=tu(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return tu(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}}Zd.className="Cropping2D";P.registerClass(Zd);class Qd extends be{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 N(()=>{let s=fe(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}}Qd.className="UpSampling2D";P.registerClass(Qd);function r$(e,t,s=[1,1],n="valid",i,r){return N(()=>{i==null&&(i=gs()),dt(i);let o=yu(e,i);if(e.rank!==4)throw new _(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new _(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=In(o,t,s,n==="same"?"same":"valid","NHWC",r),i==="channelsFirst"&&(o=se(o,[0,3,1,2])),o})}class em extends Kd{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=it(e.depthwiseConstraint),this.depthwiseRegularizer=Ye(e.depthwiseRegularizer)}build(e){if(e=Ue(e),e.length<4)throw new _(`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 _(`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 N(()=>{e=fe(e);let s=r$(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(s=Ys(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=yn(t,this.kernelSize[0],this.padding,this.strides[0]),r=yn(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=Me(this.depthwiseInitializer),e.depthwiseRegularizer=Ae(this.depthwiseRegularizer),e.depthwiseConstraint=Be(this.depthwiseRegularizer),e}}em.className="DepthwiseConv2D";P.registerClass(em);class Lu extends be{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 N(()=>{this.invokeCallHook(e,t);const s=fe(e);if(0<this.rate&&this.rate<1){const n=t.training==null?!1:t.training,i=this.getNoiseShape(s),r=Ui(()=>dd(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()}}Lu.className="Dropout";P.registerClass(Lu);class tm extends Lu{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}tm.className="SpatialDropout1D";P.registerClass(tm);class sm extends be{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,jt(this.units,"units"),this.activation=Un(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=it(e.kernelConstraint),this.biasConstraint=it(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 N(()=>{this.invokeCallHook(e,t);const s=fe(e),n=nd(this.activation.getClassName());let i;return n!=null?i=mn(s,this.kernel.read(),n,this.bias?this.bias.read():null):(i=mn(s,this.kernel.read()),this.bias!=null&&(i=Ys(i,this.bias.read())),this.activation!=null&&(i=this.activation.apply(i))),i})}getConfig(){const e={units:this.units,activation:xs(this.activation),useBias:this.useBias,kernelInitializer:Me(this.kernelInitializer),biasInitializer:Me(this.biasInitializer),kernelRegularizer:Ae(this.kernelRegularizer),biasRegularizer:Ae(this.biasRegularizer),activityRegularizer:Ae(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),biasConstraint:Be(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}sm.className="Dense";P.registerClass(sm);class nm extends be{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 _(`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],dn(e,1)]}call(e,t){return N(()=>{this.invokeCallHook(e,t);let s=fe(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 PI(s)})}getConfig(){const e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}nm.className="Flatten";P.registerClass(nm);class im extends be{constructor(e){super(e);this.supportsMasking=!0,this.activation=Un(e.activation)}call(e,t){return N(()=>{this.invokeCallHook(e,t);const s=fe(e);return this.activation.apply(s)})}getConfig(){const e={activation:xs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}im.className="Activation";P.registerClass(im);class rm extends be{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 N(()=>(e=fe(e),zI(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}rm.className="RepeatVector";P.registerClass(rm);class om extends be{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 _("Can only specifiy one unknown dimension.");else i*=l}const o=dn(e);if(r!==null){if(i===0||o%i!==0)throw new _(s);n[r]=o/i}else if(o!==i)throw new _(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 N(()=>{this.invokeCallHook(e,t);const s=fe(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}}om.className="Reshape";P.registerClass(om);class am extends be{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=ps(1,e.dims.length+1);if(!E.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 rt({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(fe(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}am.className="Permute";P.registerClass(am);class lm extends be{constructor(e){super(e==null?{}: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=fe(e),n=-1;return sr(Es(s,this.maskValue),n)}call(e,t){return N(()=>{this.invokeCallHook(e,t);const s=fe(e),n=-1,i=!0,r=sr(Es(s,this.maskValue),n,i),o=s.mul(r.asType(s.dtype));return o})}}lm.className="Masking";P.registerClass(lm);class cm extends be{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(qe(e.inputLength))}this.inputDim=e.inputDim,jt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,jt(this.outputDim,"outputDim"),this.embeddingsInitializer=je(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Ye(e.embeddingsRegularizer),this.activityRegularizer=Ye(e.activityRegularizer),this.embeddingsConstraint=it(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 N(()=>this.maskZero?(e=fe(e),Es(e,ne(e))):null)}computeOutputShape(e){if(e=Ue(e),this.inputLength==null)return[...e,this.outputDim];const t=qe(this.inputLength);if(t.length!==e.length-1)throw new _(`"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 _(`"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 N(()=>{this.invokeCallHook(e,t);let s=fe(e);s.dtype!=="int32"&&(s=Di(s,"int32"));const n=hd(this.embeddings.read(),s.as1D());return n.reshape(Ue(this.computeOutputShape(s.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Me(this.embeddingsInitializer),embeddingsRegularizer:Ae(this.embeddingsRegularizer),activityRegularizer:Ae(this.activityRegularizer),embeddingsConstraint:Be(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}cm.className="Embedding";P.registerClass(cm);class Eo extends be{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 _("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 _(`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=hn(t),t.length>1)throw new _(`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&&hn(n).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return N(()=>{if(e=e,this.reshapeRequired){const s=[],n=e.map(i=>i.rank);if(n.indexOf(null)===-1){const i=Fn(n);for(let r of e){const o=r.rank;for(let a=0;a<i-o;++a)r=Fi(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(dn(c.slice(1))));h=se(h,[1,0]),h=h.reshape(u),s.push(h),i=!0}else if(l>1){const c=ps(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(ps(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=hn(s),s.length===1?t=s.concat(t):t=[null].concat(t),t}computeMask(e,t){return N(()=>{if(t==null)return null;if(!Array.isArray(t))throw new _("`mask` should be an Array");if(!Array.isArray(e))throw new _("`inputs` should be an Array");if(t.length!==e.length)throw new _(`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:Nt(n,0));let s=t[0];for(let n=1;n<t.length-1;++n)s=zt(s,t[n]);return s})}}class pm extends Eo{constructor(e){super(e)}mergeFunction(e){return N(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=W(t,e[s]);return t})}}pm.className="Add";P.registerClass(pm);class um extends Eo{constructor(e){super(e)}mergeFunction(e){return N(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=C(t,e[s]);return t})}}um.className="Multiply";P.registerClass(um);class hm extends Eo{constructor(e){super(e)}mergeFunction(e){return N(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=W(t,e[s]);return C(1/e.length,t)})}}hm.className="Average";P.registerClass(hm);class dm extends Eo{constructor(e){super(e)}mergeFunction(e){return N(()=>{let t=e[0];for(let s=1;s<e.length;++s)t=Wt(t,e[s]);return t})}}dm.className="Maximum";P.registerClass(dm);class mm extends Eo{constructor(e){super(e)}mergeFunction(e){return N(()=>{let t=e[0];for(let s=1;s<e.length;++s)t=Vs(t,e[s]);return t})}}mm.className="Minimum";P.registerClass(mm);class fm extends Eo{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 _("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(E.arraysEqual(o,i)){r=!0;break}r||s.push(i)}if(s.length>1)throw new _("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return N(()=>ud(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new _("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 _("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new _("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new _(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return N(()=>{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(Bt(e[r]).asType("bool")):t[r].rank<e[r].rank?n.push(Nt(t[r],-1)):n.push(t[r]);const i=ge(n,this.axis);return jr(i,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}fm.className="Concatenate";P.registerClass(fm);function Su(e,t){for(;e<0;)e+=t;return e}function o$(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(E.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),E.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 N(()=>{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 gm extends Eo{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){E.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 _(`Dimension incompatibility: ${t[n[0]]} !== ${s[n[1]]}`)}mergeFunction(e){if(e.length!==2)throw new _(`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)=>Su(i,e[r].shape.length)):n=[Su(this.axes,t.shape.length),Su(this.axes,s.shape.length)],this.normalize&&(t=cu(t,n[0]),s=cu(s,n[1])),o$(t,s,n)}interpretAxes(e,t){let s;return Array.isArray(this.axes)?s=this.axes:s=[Su(this.axes,e.length),Su(this.axes,t.length)],s}computeOutputShape(e){E.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}}gm.className="Dot";P.registerClass(gm);class ym extends be{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 N(()=>{this.invokeCallHook(e,t);const s=fe(e),n=()=>va(s.shape,0,this.stddev).add(s),i=Ui(n,()=>s,t.training||!1);return i})}}ym.className="GaussianNoise";P.registerClass(ym);class bm extends be{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 N(()=>{this.invokeCallHook(e,t);const s=fe(e);if(this.rate>0&&this.rate<1){const n=()=>{const i=Math.sqrt(this.rate/(1-this.rate));return s.mul(va(s.shape,1,i))};return Ui(n,()=>s,t.training||!1)}return s})}}bm.className="GaussianDropout";P.registerClass(bm);class wm extends be{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||fe(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 N(()=>{if(this.rate<1&&this.rate>0){const s=this._getNoiseShape(e),n=()=>{const i=fe(e),r=1.6732632423543772,o=1.0507009873554805,a=-r*o;let l=as(Gs(s),this.rate);l=Di(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 Ui(n,()=>fe(e),t.training||!1)}return e})}}wm.className="AlphaDropout";P.registerClass(wm);function vu(e,t,s,n,i,r=.001){let o;if(e.rank===2)o=gp(e,t,s,n,i,r);else if(e.rank===3)o=yp(e,t,s,n,i,r);else if(e.rank===4)o=bp(e,t,s,n,i,r);else throw new ae(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function a$(e,t,s,n,i=.001){return N(()=>{const r=lr(e,n),o=r.mean,a=r.variance,l=vu(e,o,a,s,t,i);return[l,o,a]})}function l$(e,t,s,n,i=.001){return N(()=>{const r=lr(e,n),o=r.mean,a=r.variance,l=[];for(const m of ps(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=vu(e,c,p,h,u,i);return[d,o,a]})}function c$(e,t,s,n,i=.001){return E.arraysEqual(n.slice().sort(),ps(0,e.rank-1))?a$(e,t,s,n,i):l$(e,t,s,n,i)}class xm extends be{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=it(e.betaConstraint),this.gammaConstraint=it(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 _(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new rt({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 N(()=>{const s=t.training==null?!1:t.training,n=fe(e),i=n.shape,r=i.length,o=ps(0,r),a=this.axis>=0?this.axis:this.axis+r;o.splice(a,1);const l=cn(1,r);l[a]=i[a];const c=o.slice();c.sort();const p=!E.arraysEqual(c,ps(0,r).slice(0,r-1)),u=()=>{if(p){const b=this.movingMean.read().reshape(l),S=this.movingVariance.read().reshape(l),x=this.center?this.beta.read().reshape(l):null,I=this.scale?this.gamma.read().reshape(l):null;return vu(n,b,S,x,I,this.epsilon)}else return vu(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]=c$(n,this.gamma.read(),this.beta.read(),o,this.epsilon),f=(b,S,x)=>{N(()=>{const I=1-x,A=b.read(),k=A.sub(S).mul(I);b.write(A.sub(k))})},y=()=>{f(this.movingMean,d,this.momentum),f(this.movingVariance,m,this.momentum)};return y(),h})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Me(this.betaInitializer),gammaInitializer:Me(this.gammaInitializer),movingMeanInitializer:Me(this.movingMeanInitializer),movingVarianceInitializer:Me(this.movingVarianceInitializer),betaRegularizer:Ae(this.betaRegularizer),gammaRegularizer:Ae(this.gammaRegularizer),betaConstraint:Be(this.betaConstraint),gammaConstraint:Be(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}xm.className="BatchNormalization";P.registerClass(xm);class Lm extends be{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!==hn(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=fe(e),n=s.shape,i=n.length;return N(()=>{const r=!0;let{mean:o,variance:a}=lr(s,this.axis,r);const l=cn(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),vu(s,o,a,u,p,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Me(this.betaInitializer),gammaInitializer:Me(this.gammaInitializer),betaRegularizer:Ae(this.betaRegularizer),gammaRegularizer:Ae(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}Lm.className="LayerNormalization";P.registerClass(Lm);function p$(e,t,s){return N(()=>{if(e.rank!==4)throw new _(`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 _("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(s==null&&(s=gs()),s!=="channelsLast"&&s!=="channelsFirst")throw new _(`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]],Ut(e,n)})}class Sm extends be{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?gs():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 _(`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 _(`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 _(`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 rt({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 N(()=>p$(fe(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Sm.className="ZeroPadding2D";P.registerClass(Sm);function vm(e,t,s,n,i,r){return N(()=>{dt(i),Db(r),_s(n),s==null&&(s=[1,1]),n==null&&(n="valid"),i==null&&(i=gs()),r==null&&(r="max"),e=yu(e,i);let o;const a=n==="same"?"same":"valid";return r==="max"?o=lt(e,t,s,a):o=rs(e,t,s,a),i==="channelsFirst"&&(o=se(o,[0,3,1,2])),o})}function BA(e,t,s,n,i,r){return N(()=>{dt(i),Db(r),_s(n),s==null&&(s=[1,1,1]),n==null&&(n="valid"),i==null&&(i=gs()),r==null&&(r="max"),e=Zb(e,i);let o;const a=n==="same"?"same":"valid";return r==="max"?o=no(e,t,s,a):o=Gr(e,t,s,a),i==="channelsFirst"&&(o=se(o,[0,4,1,2,3])),o})}class PA extends be{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 _(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(jt(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 _(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);jt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,_s(this.padding),this.inputSpec=[new rt({ndim:3})]}computeOutputShape(e){e=Ue(e);const t=yn(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return N(()=>{this.invokeCallHook(e,t),e=Fi(fe(e),2);const s=this.poolingFunction(fe(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return En(s,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class Tm extends PA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return dt(i),_s(n),vm(e,t,s,n,i,"max")}}Tm.className="MaxPooling1D";P.registerClass(Tm);class Im extends PA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return dt(i),_s(n),vm(e,t,s,n,i,"avg")}}Im.className="AveragePooling1D";P.registerClass(Im);class jA extends be{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 _(`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];jt(this.poolSize,"poolSize"),jt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,dt(this.dataFormat),_s(this.padding),this.inputSpec=[new rt({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=yn(t,this.poolSize[0],this.padding,this.strides[0]),s=yn(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 N(()=>(this.invokeCallHook(e,t),this.poolingFunction(fe(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 Am extends jA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return dt(i),_s(n),vm(e,t,s,n,i,"max")}}Am.className="MaxPooling2D";P.registerClass(Am);class Nm extends jA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return dt(i),_s(n),vm(e,t,s,n,i,"avg")}}Nm.className="AveragePooling2D";P.registerClass(Nm);class VA extends be{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 _(`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];jt(this.poolSize,"poolSize"),jt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,dt(this.dataFormat),_s(this.padding),this.inputSpec=[new rt({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=yn(t,this.poolSize[0],this.padding,this.strides[0]),s=yn(s,this.poolSize[1],this.padding,this.strides[1]),n=yn(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 N(()=>(this.invokeCallHook(e,t),this.poolingFunction(fe(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 Cm extends VA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return dt(i),_s(n),BA(e,t,s,n,i,"max")}}Cm.className="MaxPooling3D";P.registerClass(Cm);class Rm extends VA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return dt(i),_s(n),BA(e,t,s,n,i,"avg")}}Rm.className="AveragePooling3D";P.registerClass(Rm);class GA extends be{constructor(e){super(e);this.inputSpec=[new rt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new ae()}}class Om extends GA{constructor(e){super(e||{})}call(e,t){return N(()=>{const s=fe(e);return Ge(s,1)})}}Om.className="GlobalAveragePooling1D";P.registerClass(Om);class Em extends GA{constructor(e){super(e||{})}call(e,t){return N(()=>{const s=fe(e);return st(s,1)})}}Em.className="GlobalMaxPooling1D";P.registerClass(Em);class HA extends be{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,dt(this.dataFormat),this.inputSpec=[new rt({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 km extends HA{call(e,t){return N(()=>{const s=fe(e);return this.dataFormat==="channelsLast"?Ge(s,[1,2]):Ge(s,[2,3])})}}km.className="GlobalAveragePooling2D";P.registerClass(km);class _m extends HA{call(e,t){return N(()=>{const s=fe(e);return this.dataFormat==="channelsLast"?st(s,[1,2]):st(s,[2,3])})}}_m.className="GlobalMaxPooling2D";P.registerClass(_m);function Qb(e,t,s,n){if(Array.isArray(e)){if(t!=null||s!=null)throw new _("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 ew(e,t,s,n=!1,i,r,o=!1,a=!1){return N(()=>{const l=t.shape.length;if(l<3)throw new _(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(ps(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=Nt(i,-1)),i=se(i,c)),n&&(t=Lt(t,0),i!=null&&(i=Lt(i,0)));const p=[];let u,h=s;const d=t.shape[0],m=nt(t);let f;i!=null&&(f=nt(i));for(let b=0;b<d;++b){const S=m[b],x=N(()=>e(S,h));if(i==null)u=x[0],h=x[1];else{const I=N(()=>{const A=f[b],k=Bt(A).sub(A),R=x[0].mul(A).add(h[0].mul(k)),D=h.map((F,M)=>x[1][M].mul(A).add(F.mul(k)));return{output:R,newStates:D}});u=I.output,h=I.newStates}a&&p.push(u)}let y;if(a){const b=1;y=Xe(p,b)}return[u,y,h]})}class ri extends be{constructor(e){super(e);let t;if(e.cell==null)throw new _("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Tu({cells:e.cell}):t=e.cell,t.stateSize==null)throw new _("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 rt({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 ps(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){vd(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 N(()=>{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.");vd(e)&&(e=e[0]),e=e;const s=this.stateful?e[0]:null,n=e[e.length-1];this.inputSpec[0]=new rt({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(!E.arraysEqual(this.stateSpec.map(o=>o.shape[o.shape.length-1]),r))throw new _(`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 rt({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){N(()=>{if(!this.stateful)throw new ti("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape[0];if(s==null)throw new _("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=>Ie([s,n])):this.states_=[Ie([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=>Ie([s,n])):this.states_[0]=Ie([s,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new _(`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(!E.arraysEqual(i.shape,o))throw new _(`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=>gt(n.clone()))})}apply(e,t){let s=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});const i=Qb(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 rt({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 bs;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 N(()=>{const s=t==null?null:t.mask,n=t==null?null:t.training;let i=t==null?null:t.initialState;e=fe(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 _(`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=ew(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 N(()=>{let t=Ie(e.shape);return t=te(t,[1,2]),t=Fi(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(s=>s>1?pd(t,[1,s]):t):this.cell.stateSize>1?[pd(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={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(e.numConstants=this.numConstants);const t=this.cell.getConfig();e.cell={className:this.cell.getClassName(),config:t};const s=super.getConfig();return Object.assign(e,s),e}static fromConfig(e,t,s={}){const n=t.cell,i=ws(n,s);return new e(Object.assign(t,{cell:i}))}}ri.className="RNN";P.registerClass(ri);class Da extends be{}class Iu extends Da{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,jt(this.units,"units"),this.activation=Un(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=it(e.kernelConstraint),this.recurrentConstraint=it(e.recurrentConstraint),this.biasConstraint=it(e.biasConstraint),this.dropout=To([1,Fn([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=To([1,Fn([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 N(()=>{if(e=e,e.length!==2)throw new _(`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=Fa(()=>Bt(e),this.dropout,n)),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Fa(()=>Bt(s),this.recurrentDropout,n));let i;const r=this.dropoutMask,o=this.recurrentDropoutMask;r!=null?i=mn(C(e,r),this.kernel.read()):i=mn(e,this.kernel.read()),this.bias!=null&&(i=Ys(i,this.bias.read())),o!=null&&(s=C(s,o));let a=W(i,mn(s,this.recurrentKernel.read()));return this.activation!=null&&(a=this.activation.apply(a)),[a,a]})}getConfig(){const e={units:this.units,activation:xs(this.activation),useBias:this.useBias,kernelInitializer:Me(this.kernelInitializer),recurrentInitializer:Me(this.recurrentInitializer),biasInitializer:Me(this.biasInitializer),kernelRegularizer:Ae(this.kernelRegularizer),recurrentRegularizer:Ae(this.recurrentRegularizer),biasRegularizer:Ae(this.biasRegularizer),activityRegularizer:Ae(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},t=super.getConfig();return Object.assign(e,t),e}}Iu.className="SimpleRNNCell";P.registerClass(Iu);class Dm extends ri{constructor(e){e.cell=new Iu(e),super(e)}call(e,t){return N(()=>{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})})}get units(){return this.cell.units}get activation(){return this.cell.activation}get useBias(){return this.cell.useBias}get kernelInitializer(){return this.cell.kernelInitializer}get recurrentInitializer(){return this.cell.recurrentInitializer}get biasInitializer(){return this.cell.biasInitializer}get kernelRegularizer(){return this.cell.kernelRegularizer}get recurrentRegularizer(){return this.cell.recurrentRegularizer}get biasRegularizer(){return this.cell.biasRegularizer}get kernelConstraint(){return this.cell.kernelConstraint}get recurrentConstraint(){return this.cell.recurrentConstraint}get biasConstraint(){return this.cell.biasConstraint}get dropout(){return this.cell.dropout}get recurrentDropout(){return this.cell.recurrentDropout}getConfig(){const e={units:this.units,activation:xs(this.activation),useBias:this.useBias,kernelInitializer:Me(this.kernelInitializer),recurrentInitializer:Me(this.recurrentInitializer),biasInitializer:Me(this.biasInitializer),kernelRegularizer:Ae(this.kernelRegularizer),recurrentRegularizer:Ae(this.recurrentRegularizer),biasRegularizer:Ae(this.biasRegularizer),activityRegularizer:Ae(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},t=super.getConfig();return delete t.cell,Object.assign(e,t),e}static fromConfig(e,t){return new e(t)}}Dm.className="SimpleRNN";P.registerClass(Dm);class Au extends Da{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 _("GRUCell does not support reset_after parameter set to true.");this.units=e.units,jt(this.units,"units"),this.activation=Un(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Un(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=it(e.kernelConstraint),this.recurrentConstraint=it(e.recurrentConstraint),this.biasConstraint=it(e.biasConstraint),this.dropout=To([1,Fn([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=To([1,Fn([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 N(()=>{if(e=e,e.length!==2)throw new _(`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=Fa(()=>Bt(e),this.dropout,s,3)),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Fa(()=>Bt(n),this.recurrentDropout,s,3));const i=this.dropoutMask,r=this.recurrentDropoutMask;let o,a,l;0<this.dropout&&this.dropout<1&&(e=C(e,i[0]));let c=mn(e,this.kernel.read());this.useBias&&(c=Ys(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(n=C(n,r[0]));const p=this.recurrentKernel.read(),[u,h]=ls(p,[2*this.units,this.units],p.rank-1),d=mn(n,u),[m,f,y]=ls(c,3,c.rank-1),[b,S]=ls(d,2,d.rank-1);o=this.recurrentActivation.apply(W(m,b)),a=this.recurrentActivation.apply(W(f,S));const x=mn(C(a,n),h);l=this.activation.apply(W(y,x));const I=W(C(o,n),C(W(1,Oe(o)),l));return[I,I]})}getConfig(){const e={units:this.units,activation:xs(this.activation),recurrentActivation:xs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Me(this.kernelInitializer),recurrentInitializer:Me(this.recurrentInitializer),biasInitializer:Me(this.biasInitializer),kernelRegularizer:Ae(this.kernelRegularizer),recurrentRegularizer:Ae(this.recurrentRegularizer),biasRegularizer:Ae(this.biasRegularizer),activityRegularizer:Ae(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1},t=super.getConfig();return Object.assign(e,t),e}}Au.className="GRUCell";P.registerClass(Au);class Fm extends ri{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 Au(e),super(e)}call(e,t){return N(()=>{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})})}get units(){return this.cell.units}get activation(){return this.cell.activation}get recurrentActivation(){return this.cell.recurrentActivation}get useBias(){return this.cell.useBias}get kernelInitializer(){return this.cell.kernelInitializer}get recurrentInitializer(){return this.cell.recurrentInitializer}get biasInitializer(){return this.cell.biasInitializer}get kernelRegularizer(){return this.cell.kernelRegularizer}get recurrentRegularizer(){return this.cell.recurrentRegularizer}get biasRegularizer(){return this.cell.biasRegularizer}get kernelConstraint(){return this.cell.kernelConstraint}get recurrentConstraint(){return this.cell.recurrentConstraint}get biasConstraint(){return this.cell.biasConstraint}get dropout(){return this.cell.dropout}get recurrentDropout(){return this.cell.recurrentDropout}get implementation(){return this.cell.implementation}getConfig(){const e={units:this.units,activation:xs(this.activation),recurrentActivation:xs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Me(this.kernelInitializer),recurrentInitializer:Me(this.recurrentInitializer),biasInitializer:Me(this.biasInitializer),kernelRegularizer:Ae(this.kernelRegularizer),recurrentRegularizer:Ae(this.recurrentRegularizer),biasRegularizer:Ae(this.biasRegularizer),activityRegularizer:Ae(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1},t=super.getConfig();return delete t.cell,Object.assign(e,t),e}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}Fm.className="GRU";P.registerClass(Fm);class Nu extends Da{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,jt(this.units,"units"),this.activation=Un(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Un(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=it(e.kernelConstraint),this.recurrentConstraint=it(e.recurrentConstraint),this.biasConstraint=it(e.biasConstraint),this.dropout=To([1,Fn([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=To([1,Fn([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 fn{apply(a,l){const c=i.apply([r]),p=new Ta().apply([r]),u=i.apply([r*2]);return Mb(Mb(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 N(()=>{const s=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new _(`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=Fa(()=>Bt(e),this.dropout,s,4)),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Fa(()=>Bt(n),this.recurrentDropout,s,4));const r=this.dropoutMask,o=this.recurrentDropoutMask;let a,l,c,p;0<this.dropout&&this.dropout<1&&(e=C(e,r[0]));let u=mn(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=C(n,o[0])),u=W(u,mn(n,this.recurrentKernel.read())),this.useBias&&(u=Ys(u,this.bias.read()));const[h,d,m,f]=ls(u,4,u.rank-1);a=this.recurrentActivation.apply(h),l=this.recurrentActivation.apply(d),c=W(C(l,i),C(a,this.activation.apply(m))),p=this.recurrentActivation.apply(f);const y=C(p,this.activation.apply(c));return[y,y,c]})}getConfig(){const e={units:this.units,activation:xs(this.activation),recurrentActivation:xs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Me(this.kernelInitializer),recurrentInitializer:Me(this.recurrentInitializer),biasInitializer:Me(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ae(this.kernelRegularizer),recurrentRegularizer:Ae(this.recurrentRegularizer),biasRegularizer:Ae(this.biasRegularizer),activityRegularizer:Ae(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=super.getConfig();return Object.assign(e,t),e}}Nu.className="LSTMCell";P.registerClass(Nu);class Mm extends ri{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 Nu(e),super(e)}call(e,t){return N(()=>{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})})}get units(){return this.cell.units}get activation(){return this.cell.activation}get recurrentActivation(){return this.cell.recurrentActivation}get useBias(){return this.cell.useBias}get kernelInitializer(){return this.cell.kernelInitializer}get recurrentInitializer(){return this.cell.recurrentInitializer}get biasInitializer(){return this.cell.biasInitializer}get unitForgetBias(){return this.cell.unitForgetBias}get kernelRegularizer(){return this.cell.kernelRegularizer}get recurrentRegularizer(){return this.cell.recurrentRegularizer}get biasRegularizer(){return this.cell.biasRegularizer}get kernelConstraint(){return this.cell.kernelConstraint}get recurrentConstraint(){return this.cell.recurrentConstraint}get biasConstraint(){return this.cell.biasConstraint}get dropout(){return this.cell.dropout}get recurrentDropout(){return this.cell.recurrentDropout}get implementation(){return this.cell.implementation}getConfig(){const e={units:this.units,activation:xs(this.activation),recurrentActivation:xs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Me(this.kernelInitializer),recurrentInitializer:Me(this.recurrentInitializer),biasInitializer:Me(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ae(this.kernelRegularizer),recurrentRegularizer:Ae(this.recurrentRegularizer),biasRegularizer:Ae(this.biasRegularizer),activityRegularizer:Ae(this.activityRegularizer),kernelConstraint:Be(this.kernelConstraint),recurrentConstraint:Be(this.recurrentConstraint),biasConstraint:Be(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=super.getConfig();return delete t.cell,Object.assign(e,t),e}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}Mm.className="LSTM";P.registerClass(Mm);class Tu extends Da{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 N(()=>{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){vd(e)&&(e=e[0]),e=e;let t;this.cells.forEach((s,n)=>{Dn(`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=[];for(const n of this.cells)e.push({className:n.getClassName(),config:n.getConfig()});const t={cells:e},s=super.getConfig();return Object.assign(t,s),t}static fromConfig(e,t,s={}){const n=[];for(const i of t.cells)n.push(ws(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 lu(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]])}Na(t)}}Tu.className="StackedRNNCells";P.registerClass(Tu);function Fa(e,t,s=null,n=1){function i(){return dd(e(),t)}if(n>1){const r=[];for(let o=0;o<n;o++)r.push(Ui(i,e,s));return r.map(o=>gt(o.clone()))}else return gt(Ui(i,e,s).clone())}class qA extends be{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=ws(n,s);delete t.layer;const r={layer:i};return Object.assign(r,t),new e(r)}}class Um extends qA{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=Ue(e),e.length<3)throw new _(`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 N(()=>{e=fe(e);const s=(r,o)=>{const a=fe(this.layer.call(r,t));return[a,[]]},n=ew(s,e,[],!1,null,null,!1,!0),i=n[1];return i})}}Um.className="TimeDistributed";P.registerClass(Um);function u$(e){_i(FI,"BidirectionalMergeMode",e)}const h$="concat";class $m extends qA{constructor(e){super(e);const t=e.layer.getConfig(),s={};s.className=e.layer.getClassName(),s.config=t,this.forwardLayer=ws(s),t.goBackwards=!(t.goBackwards===!0);const n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=ws(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?h$:e.mergeMode,u$(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()):Pt(n)}apply(e,t){let s=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});const i=Qb(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 _("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 rt({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 bs;for(const l of r)if(l instanceof bs!==a)throw new _("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 N(()=>{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=Lt(i,1));let o;return this.mergeMode==="concat"?o=ud([n,i]):this.mergeMode==="sum"?o=W(n,i):this.mergeMode==="ave"?o=C(.5,W(n,i)):this.mergeMode==="mul"?o=C(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){Dn(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Dn(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=ws(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)}}$m.className="Bidirectional";P.registerClass($m);const tw={};Re(tw,{Layer:()=>be,RNN:()=>ri,RNNCell:()=>Da,activation:()=>C$,add:()=>U$,alphaDropout:()=>bW,average:()=>$$,averagePooling1d:()=>sw,averagePooling2d:()=>nw,averagePooling3d:()=>iw,avgPool1d:()=>q$,avgPool2d:()=>K$,avgPool3d:()=>J$,avgPooling1d:()=>Y$,avgPooling2d:()=>X$,avgPooling3d:()=>Z$,batchNormalization:()=>V$,bidirectional:()=>pW,concatenate:()=>W$,conv1d:()=>x$,conv2d:()=>L$,conv2dTranspose:()=>S$,conv3d:()=>v$,cropping2D:()=>I$,dense:()=>R$,depthwiseConv2d:()=>N$,dot:()=>j$,dropout:()=>O$,elu:()=>m$,embedding:()=>M$,flatten:()=>k$,gaussianDropout:()=>yW,gaussianNoise:()=>gW,globalAveragePooling1d:()=>Q$,globalAveragePooling2d:()=>eW,globalMaxPool1d:()=>hW,globalMaxPool2d:()=>dW,globalMaxPooling1d:()=>YA,globalMaxPooling2d:()=>KA,gru:()=>sW,gruCell:()=>nW,input:()=>zd,inputLayer:()=>d$,layerNormalization:()=>G$,leakyReLU:()=>g$,lstm:()=>iW,lstmCell:()=>rW,masking:()=>wW,maxPool1d:()=>mW,maxPool2d:()=>fW,maxPooling1d:()=>XA,maxPooling2d:()=>JA,maxPooling3d:()=>tW,maximum:()=>z$,minimum:()=>B$,multiply:()=>P$,permute:()=>F$,prelu:()=>y$,reLU:()=>f$,repeatVector:()=>_$,reshape:()=>D$,rnn:()=>lW,separableConv2d:()=>T$,simpleRNN:()=>oW,simpleRNNCell:()=>aW,softmax:()=>b$,spatialDropout1d:()=>E$,stackedRNNCells:()=>cW,thresholdedReLU:()=>w$,timeDistributed:()=>uW,upSampling2d:()=>A$,zeroPadding2d:()=>H$});function d$(e){return new $i(e)}function m$(e){return new Gd(e)}function f$(e){return new Pd(e)}function g$(e){return new jd(e)}function y$(e){return new Vd(e)}function b$(e){return new qd(e)}function w$(e){return new Hd(e)}function x$(e){return new xu(e)}function L$(e){return new _a(e)}function S$(e){return new Xd(e)}function v$(e){return new wu(e)}function T$(e){return new Jd(e)}function I$(e){return new Zd(e)}function A$(e){return new Qd(e)}function N$(e){return new em(e)}function C$(e){return new im(e)}function R$(e){return new sm(e)}function O$(e){return new Lu(e)}function E$(e){return new tm(e)}function k$(e){return new nm(e)}function _$(e){return new rm(e)}function D$(e){return new om(e)}function F$(e){return new am(e)}function M$(e){return new cm(e)}function U$(e){return new pm(e)}function $$(e){return new hm(e)}function W$(e){return new fm(e)}function z$(e){return new dm(e)}function B$(e){return new mm(e)}function P$(e){return new um(e)}function j$(e){return new gm(e)}function V$(e){return new xm(e)}function G$(e){return new Lm(e)}function H$(e){return new Sm(e)}function sw(e){return new Im(e)}function q$(e){return sw(e)}function Y$(e){return sw(e)}function nw(e){return new Nm(e)}function K$(e){return nw(e)}function X$(e){return nw(e)}function iw(e){return new Rm(e)}function J$(e){return iw(e)}function Z$(e){return iw(e)}function Q$(e){return new Om(e)}function eW(e){return new km(e)}function YA(e){return new Em(e)}function KA(e){return new _m(e)}function XA(e){return new Tm(e)}function JA(e){return new Am(e)}function tW(e){return new Cm(e)}function sW(e){return new Fm(e)}function nW(e){return new Au(e)}function iW(e){return new Mm(e)}function rW(e){return new Nu(e)}function oW(e){return new Dm(e)}function aW(e){return new Iu(e)}function lW(e){return new ri(e)}function cW(e){return new Tu(e)}function pW(e){return new $m(e)}function uW(e){return new Um(e)}const hW=YA,dW=KA,mW=XA,fW=JA;function gW(e){return new ym(e)}function yW(e){return new bm(e)}function bW(e){return new wm(e)}function wW(e){return new lm(e)}const rw={};Re(rw,{MAPE:()=>OW,MSE:()=>_W,binaryAccuracy:()=>xW,binaryCrossentropy:()=>LW,categoricalAccuracy:()=>vW,categoricalCrossentropy:()=>TW,cosineProximity:()=>NW,mape:()=>EW,meanAbsoluteError:()=>CW,meanAbsolutePercentageError:()=>RW,meanSquaredError:()=>kW,mse:()=>DW,precision:()=>IW,recall:()=>AW,sparseCategoricalAccuracy:()=>SW});function xW(e,t){return hu(e,t)}function LW(e,t){return Od(e,t)}function SW(e,t){return Ed(e,t)}function vW(e,t){return du(e,t)}function TW(e,t){return mu(e,t)}function IW(e,t){return jb(e,t)}function AW(e,t){return QI(e,t)}function NW(e,t){return pu(e,t)}function CW(e,t){return Ca(e,t)}function RW(e,t){return mr(e,t)}function OW(e,t){return mr(e,t)}function EW(e,t){return mr(e,t)}function kW(e,t){return ii(e,t)}function _W(e,t){return ii(e,t)}function DW(e,t){return ii(e,t)}const ow={};Re(ow,{modelFromJSON:()=>yA});const aw={};Re(aw,{l1:()=>MW,l1l2:()=>FW,l2:()=>UW});function FW(e){return new ka(e)}function MW(e){return FA(e)}function UW(e){return MA(e)}class lw extends No{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof gn))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function Wm(e,t){return e<t}function ZA(e,t){return e>t}class cw extends lw{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=Wm:this.mode==="max"?this.monitorFunc=ZA:this.monitor.indexOf("acc")!==-1?this.monitorFunc=ZA:this.monitorFunc=Wm,this.monitorFunc===Wm&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Wm?Infinity:-Infinity}async onEpochEnd(e,t){await ni(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 $W(e){return new cw(e)}const QA={earlyStopping:$W};var bn;(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"})(bn||(bn={}));var eN;(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={}))})(eN||(eN={}));const pw={};function tN(e,t){const s={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};pw[e]=s}function zm(e){return pw[e]}function sN(e){delete pw[e]}function w(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]:E.toNestedArray(l.shape,c)}const r=t.attrParams[e];return r&&r.value}function Vt(e,t,s){const[n,i]=As(e),r=s.currentContextIds.find(o=>!!t[Bm(n,o)]);return r!==void 0?t[Bm(n,r)][i]:void 0}function nN(e,t,s){return t[Bm(e,s.currentContextId)]}function $n(e,t){const[s,n]=As(e);return[Bm(s,t&&t.currentContextId),n]}function Bm(e,t){return t?`${e}-${t}`:e}function As(e){const t=e.split(":");if(t.length===1)return[e,0];const s=t[0];return[s,Number(t[t.length-1])]}function Cu(e,t,s){let n=w("pad",e,t,s);if(n==="explicit"){n=w("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 Wn(e){return e.kept?e:Ps(e)}const uw={};Re(uw,{json:()=>WW});const WW=[{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 hw={};Re(hw,{json:()=>zW});const zW=[{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 dw={};Re(dw,{json:()=>BW});const BW=[{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 mw={};Re(mw,{json:()=>PW});const PW=[{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 fw={};Re(fw,{json:()=>jW});const jW=[{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 gw={};Re(gw,{json:()=>VW});const VW=[{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 yw={};Re(yw,{json:()=>GW});const GW=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]}];const bw={};Re(bw,{json:()=>HW});const HW=[{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 ww={};Re(ww,{json:()=>qW});const qW=[{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 xw={};Re(xw,{json:()=>YW});const YW=[{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 Lw={};Re(Lw,{json:()=>KW});const KW=[{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 Sw={};Re(Sw,{json:()=>XW});const XW=[{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 vw={};Re(vw,{json:()=>JW});const JW=[{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 Tw={};Re(Tw,{json:()=>ZW});const ZW=[{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 Iw={};Re(Iw,{json:()=>QW});const QW=[{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 Aw={};Re(Aw,{json:()=>ez});const ez=[{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 rN{static get Instance(){return this._instance||(this._instance=new this())}constructor(){const e=[uw,hw,dw,mw,fw,gw,yw,xw,ww,bw,Lw,Sw,vw,Tw,Iw,Aw],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=s.reduce((h,d)=>(h[d.name]=this.mapNode(d),d.op.startsWith("Placeholder")&&n.push(h[d.name]),d.op==="Const"&&i.push(h[d.name]),h),{});let o=[];const a=[];let l={},c={};t!=null&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const p=Object.keys(r);p.forEach(h=>{const d=r[h];d.inputNames.forEach(m=>{const[f]=$n(m);d.inputs.push(r[f]),r[f].children.push(d)})}),Object.keys(c).length===0?p.forEach(h=>{const d=r[h];d.children.length===0&&a.push(d)}):Object.keys(c).forEach(h=>{const[d]=$n(h),m=r[d];m!=null&&(m.signatureKey=c[h],a.push(m))}),Object.keys(l).length>0?Object.keys(l).forEach(h=>{const[d]=$n(h),m=r[d];m&&(m.signatureKey=l[h],o.push(m))}):o=n;let u={};return e.library!=null&&e.library.function!=null&&(u=e.library.function.reduce((h,d)=>(h[d.signature.name]=this.mapFunction(d),h),{})),{nodes:r,inputs:o,outputs:a,weights:i,placeholders:n,signature:t,functions:u}}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,s)=>(t[e[s].name]=s,t),{})}mapNode(e){const t=zm(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=Pm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Pm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"string[]":o=Km(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Km(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number":o=Vm(e.attr,i.tfName,i.defaultValue||0),o===void 0&&!!i.tfDeprecatedName&&(o=Vm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number[]":o=Ym(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Ym(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool":o=jm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=jm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool[]":o=Jm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Jm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape":o=qm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=qm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape[]":o=Xm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Xm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype":o=Gm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Gm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype[]":o=Hm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Hm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"func":o=iN(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=iN(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]=$n(p.name),h={name:u,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Nw(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]=$n(h);u.inputs.push(i[d]),i[d].children.push(u)})});const l=e.ret;e.signature.outputArg.forEach(p=>{const[u,h]=$n(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 tz(e){const t=$().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 oN(e,t){const s=Array.isArray(e)?String.fromCharCode.apply(null,e):tz(e);return t?s:s.toLowerCase()}function Pm(e,t,s,n=!1){const i=e[t];return i!=null?oN(i.s,n):s}function jm(e,t,s){const n=e[t];return n?n.b:s}function Vm(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 Nw(e){typeof e=="string"&&(e=bn[e]);switch(e){case bn.DT_FLOAT:return"float32";case bn.DT_INT32:case bn.DT_INT64:case bn.DT_INT8:case bn.DT_UINT8:return"int32";case bn.DT_BOOL:return"bool";case bn.DT_DOUBLE:return"float32";case bn.DT_STRING:return"string";default:return null}}function iN(e,t,s){const n=e[t];return n&&n.func?n.func.name:s}function Gm(e,t,s){const n=e[t];return n&&n.type?Nw(n.type):s}function Hm(e,t,s){const n=e[t];return n&&n.list&&n.list.type?n.list.type.map(i=>Nw(i)):s}function aN(e){return e.unknownRank?void 0:e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function qm(e,t,s){const n=e[t];return n&&n.shape?aN(n.shape):s}function Ym(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 Km(e,t,s,n=!1){const i=e[t];return i&&i.list&&i.list.s?i.list.s.map(r=>oN(r,n)):s}function Xm(e,t,s){const n=e[t];return n&&n.list&&n.list.shape?n.list.shape.map(i=>aN(i)):s}function Jm(e,t,s){const n=e[t];return n&&n.list&&n.list.b?n.list.b:s}class lN{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 Vm(this.node.rawAttrs,e,t);if(s.s!=null)return Pm(this.node.rawAttrs,e,t);if(s.b!=null)return jm(this.node.rawAttrs,e,t);if(s.shape!=null)return qm(this.node.rawAttrs,e,t);if(s.type!=null)return Gm(this.node.rawAttrs,e,t);if(s.list!=null){if(s.list.i!=null||s.list.f!=null)return Ym(this.node.rawAttrs,e,t);if(s.list.s!=null)return Km(this.node.rawAttrs,e,t);if(s.list.shape!=null)return Xm(this.node.rawAttrs,e,t);if(s.list.b!=null)return Jm(this.node.rawAttrs,e,t);if(s.list.type!=null)return Hm(this.node.rawAttrs,e,t)}return t}}const cN=(e,t,s)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[W(w("a",e,t,s),w("b",e,t,s))];case"AddN":return[op(w("tensors",e,t,s))];case"FloorMod":case"Mod":return[io(w("a",e,t,s),w("b",e,t,s))];case"Mul":return[C(w("a",e,t,s),w("b",e,t,s))];case"RealDiv":case"Div":return[J(w("a",e,t,s),w("b",e,t,s))];case"DivNoNan":return[Ap(w("a",e,t,s),w("b",e,t,s))];case"FloorDiv":return[Jr(w("a",e,t,s),w("b",e,t,s))];case"Sub":return[X(w("a",e,t,s),w("b",e,t,s))];case"Minimum":return[Vs(w("a",e,t,s),w("b",e,t,s))];case"Maximum":return[Wt(w("a",e,t,s),w("b",e,t,s))];case"Pow":return[qt(w("a",e,t,s),w("b",e,t,s))];case"SquaredDifference":return[Ri(w("a",e,t,s),w("b",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const pN=(e,t,s)=>{switch(e.op){case"Abs":case"ComplexAbs":return[Je(w("x",e,t,s))];case"Acos":return[ip(w("x",e,t,s))];case"Acosh":return[rp(w("x",e,t,s))];case"Asin":return[lp(w("x",e,t,s))];case"Asinh":return[cp(w("x",e,t,s))];case"Atan":return[pp(w("x",e,t,s))];case"Atan2":return[up(w("x",e,t,s),w("y",e,t,s))];case"Atanh":return[hp(w("x",e,t,s))];case"Ceil":return[wp(w("x",e,t,s))];case"Complex":return[Ze(w("real",e,t,s),w("imag",e,t,s))];case"Cos":return[xi(w("x",e,t,s))];case"Cosh":return[Kr(w("x",e,t,s))];case"Elu":return[An(w("x",e,t,s))];case"Erf":return[Np(w("x",e,t,s))];case"Exp":return[At(w("x",e,t,s))];case"Expm1":return[Cp(w("x",e,t,s))];case"Floor":return[Nn(w("x",e,t,s))];case"Log":return[Mt(w("x",e,t,s))];case"Log1p":return[eo(w("x",e,t,s))];case"Imag":return[Ht(w("x",e,t,s))];case"Neg":return[Oe(w("x",e,t,s))];case"Reciprocal":return[Fp(w("x",e,t,s))];case"Real":return[$t(w("x",e,t,s))];case"Relu":return[ke(w("x",e,t,s))];case"Round":return[Up(w("x",e,t,s))];case"Selu":return[ao(w("x",e,t,s))];case"Sigmoid":return[Ss(w("x",e,t,s))];case"Sin":return[lo(w("x",e,t,s))];case"Sign":return[Wp(w("x",e,t,s))];case"Sinh":return[co(w("x",e,t,s))];case"Softplus":return[Rn(w("x",e,t,s))];case"Sqrt":return[He(w("x",e,t,s))];case"Square":return[ye(w("x",e,t,s))];case"Tanh":return[Zn(w("x",e,t,s))];case"Tan":return[Bp(w("x",e,t,s))];case"Relu6":case"ClipByValue":return[Dt(w("x",e,t,s),w("clipValueMin",e,t,s),w("clipValueMax",e,t,s))];case"Rsqrt":return[oo(Vt(e.inputNames[0],t,s))];case"Prod":return[ro(w("x",e,t,s),w("axes",e,t,s))];case"LeakyRelu":return[Qr(w("x",e,t,s),w("alpha",e,t,s))];case"Prelu":return[Ii(w("x",e,t,s),w("alpha",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Ds(e,t,s=""){E.assert(sz(e,t),()=>s+` Shapes ${e} and ${t} must match`)}function sz(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 uN{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),gt(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(){this.tensors.forEach(e=>e.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),Ds(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,gt(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 Ds(this.elementShape,s[0].shape,"TensorArray shape mismatch: "),Xe(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 Ds(this.elementShape,s[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${s[0].shape})`),ge(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,nt(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=[];N(()=>{t=t.reshape([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]=he(t,c,p).reshape(this.elementShape)}return r});const o=[];for(let a=0;a<e.length;a++)o[a]=a;this.writeMany(o,r)}}class Ru{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}`);Ds(t,i.shape,"TensorList shape mismatch: "),gt(i)}),this.idTensor=j(0),this.maxNumElements=n,gt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Ru([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(){this.tensors.forEach(e=>e.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 Ds(e,this.elementShape,"TensorList shape mismatch: "),N(()=>{const n=this.tensors.map(i=>i.reshape(e));return Xe(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 Ds(s.shape,e,"TensorList shape mismatch: "),s.reshape(e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ds(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");gt(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 Ds(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.`);Ds(this.elementShape,t.shape,"TensorList shape mismatch: "),gt(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 Ds(this.elementShape,s,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?ze([],[0].concat(this.elementShape)):N(()=>{const n=e.map(i=>this.tensors[i].reshape(s));return Xe(n,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Ds(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?ze([],[0].concat(this.elementShape)):N(()=>{const s=this.tensors.map(n=>n.reshape(t));return ge(s,0)})}}function hN(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);Ds(i,t,"TensorList shape mismatch: ");const r=e.unstack();return new Ru(r,t,n)}function dN(e,t,s){return new Ru([],e,t,s)}function mN(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 Ru([],s,e.dtype,n),o=nt(e,0);return t.forEach((a,l)=>{r.setItem(a,o[l])}),r}function fN(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=N(()=>{const l=[];e=e.reshape([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]=he(e,u,h).reshape(s)}return e.dispose(),l}),a=new Ru([],s,e.dtype,t.length);for(let l=0;l<o.length;l++)a.setItem(l,o[l]);return a}const gN=async(e,t,s)=>{switch(e.op){case"If":case"StatelessIf":{const n=w("thenBranch",e,t,s),i=w("elseBranch",e,t,s),r=w("cond",e,t,s),o=w("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=w("body",e,t,s),i=w("cond",e,t,s),r=w("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=w("pred",e,t,s);return[Wn(n)]}case"Switch":{const n=w("pred",e,t,s);let i=w("data",e,t,s);return i.kept||(i=Wn(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[Wn(i)]}return}case"Enter":{const n=w("frameName",e,t,s),i=w("tensor",e,t,s);return s.enterFrame(n),[Wn(i)]}case"Exit":{const n=w("tensor",e,t,s);return s.exitFrame(),[Wn(n)]}case"NextIteration":{const n=w("tensor",e,t,s);return s.nextIteration(),[Wn(n)]}case"TensorArrayV3":{const n=w("size",e,t,s),i=w("dtype",e,t,s),r=w("elementShape",e,t,s),o=w("dynamicSize",e,t,s),a=w("clearAfterRead",e,t,s),l=w("identicalElementShapes",e,t,s),c=w("name",e,t,s),p=new uN(c,i,n,r,l,o,a);return s.addTensorArray(p),[p.idTensor,j(1)]}case"TensorArrayWriteV3":{const n=w("tensorArrayId",e,t,s),i=w("index",e,t,s),r=w("tensor",e,t,s),o=s.getTensorArray(n.id);return o.write(i,r),[o.idTensor]}case"TensorArrayReadV3":{const n=w("tensorArrayId",e,t,s),i=w("index",e,t,s),r=s.getTensorArray(n.id);return[r.read(i)]}case"TensorArrayGatherV3":{const n=w("tensorArrayId",e,t,s),i=w("indices",e,t,s),r=w("dtype",e,t,s),o=s.getTensorArray(n.id);return[o.gather(i,r)]}case"TensorArrayScatterV3":{const n=w("tensorArrayId",e,t,s),i=w("indices",e,t,s),r=w("tensor",e,t,s),o=s.getTensorArray(n.id);return o.scatter(i,r),[o.idTensor]}case"TensorArrayConcatV3":{const n=w("tensorArrayId",e,t,s),i=s.getTensorArray(n.id),r=w("dtype",e,t,s);return[i.concat(r)]}case"TensorArraySplitV3":{const n=w("tensorArrayId",e,t,s),i=w("tensor",e,t,s),r=w("lengths",e,t,s),o=s.getTensorArray(n.id);return o.split(r,i),[o.idTensor]}case"TensorArraySizeV3":{const n=w("tensorArrayId",e,t,s),i=s.getTensorArray(n.id);return[j(i.size(),"int32")]}case"TensorArrayCloseV3":{const n=w("tensorArrayId",e,t,s),i=s.getTensorArray(n.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const n=w("tensorListId",e,t,s),i=w("index",e,t,s),r=w("tensor",e,t,s),o=s.getTensorList(n.id);return o.setItem(i,r),[o.idTensor]}case"TensorListGetItem":{const n=w("tensorListId",e,t,s),i=w("index",e,t,s),r=w("elementShape",e,t,s),o=w("elementDType",e,t,s),a=s.getTensorList(n.id);return[a.getItem(i,r,o)]}case"TensorListScatterV2":case"TensorListScatter":{const n=w("indices",e,t,s),i=w("tensor",e,t,s),r=w("elementShape",e,t,s),o=w("numElements",e,t,s),a=mN(i,n,r,o);return s.addTensorList(a),[a.idTensor]}case"TensorListReserve":{const n=w("elementShape",e,t,s),i=w("elementDType",e,t,s),r=w("numElements",e,t,s),o=dN(n,i,r);return s.addTensorList(o),[o.idTensor]}case"TensorListGather":{const n=w("tensorListId",e,t,s),i=w("indices",e,t,s),r=w("elementShape",e,t,s),o=w("elementDType",e,t,s),a=s.getTensorList(n.id);return[a.gather(i,o,r)]}case"TensorListStack":{const n=w("tensorListId",e,t,s),i=w("elementShape",e,t,s),r=w("elementDType",e,t,s),o=w("numElements",e,t,s),a=s.getTensorList(n.id);return[a.stack(i,r,o)]}case"TensorListFromTensor":{const n=w("tensor",e,t,s),i=w("elementShape",e,t,s),r=w("elementDType",e,t,s),o=hN(n,i,r);return s.addTensorList(o),[o.idTensor]}case"TensorListConcat":{const n=w("tensorListId",e,t,s),i=s.getTensorList(n.id),r=w("dtype",e,t,s),o=w("elementShape",e,t,s);return[i.concat(r,o)]}case"TensorListPushBack":{const n=w("tensorListId",e,t,s),i=w("tensor",e,t,s),r=s.getTensorList(n.id);return r.pushBack(i),[r.idTensor]}case"TensorListPopBack":{const n=w("tensorListId",e,t,s),i=w("elementShape",e,t,s),r=w("elementDType",e,t,s),o=s.getTensorList(n.id);return[o.popBack(i,r)]}case"TensorListSplit":{const n=w("tensor",e,t,s),i=w("elementShape",e,t,s),r=w("lengths",e,t,s),o=fN(n,r,i);return s.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function yN(e,t,s){const[n,i]=w("fusedOps",e,t,s),r=n==="biasadd",o=i==="prelu",a=n==="fusedbatchnorm",l=w("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=w("strides",e,t,s),p=Cu(e,t,s),u=w("dataFormat",e,t,s).toUpperCase(),h=w("dilations",e,t,s),[d,m]=w("args",e,t,s);return{stride:c,pad:p,dataFormat:u,dilations:h,biasArg:d,preluArg:m,activationFunc:i}}const bN=(e,t,s)=>{switch(e.op){case"Conv1D":{const n=w("stride",e,t,s),i=w("pad",e,t,s),r=w("dataFormat",e,t,s).toUpperCase(),o=w("dilation",e,t,s);return[Hr(w("x",e,t,s),w("filter",e,t,s),n,i,r,o)]}case"Conv2D":{const n=w("strides",e,t,s),i=Cu(e,t,s),r=w("dataFormat",e,t,s).toUpperCase(),o=w("dilations",e,t,s);return[yt(w("x",e,t,s),w("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}=yN(e,t,s);return[Hs.conv2d({x:w("x",e,t,s),filter:w("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}=yN(e,t,s);return[Hs.depthwiseConv2d({x:w("x",e,t,s),filter:w("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=w("outputShape",e,t,s),i=w("strides",e,t,s),r=Cu(e,t,s);return[qr(w("x",e,t,s),w("filter",e,t,s),n,[i[1],i[2]],r)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const n=w("strides",e,t,s),i=Cu(e,t,s),r=w("dilations",e,t,s),o=w("dataFormat",e,t,s).toUpperCase();return[In(w("input",e,t,s),w("filter",e,t,s),[n[1],n[2]],i,o,[r[1],r[2]])]}case"Conv3D":{const n=w("strides",e,t,s),i=w("pad",e,t,s),r=w("dataFormat",e,t,s).toUpperCase(),o=w("dilations",e,t,s);return[Yr(w("x",e,t,s),w("filter",e,t,s),[n[1],n[2],n[3]],i,r,[o[1],o[2],o[3]])]}case"AvgPool":{const n=w("strides",e,t,s),i=w("pad",e,t,s),r=w("kernelSize",e,t,s);return[rs(w("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i)]}case"MaxPool":{const n=w("strides",e,t,s),i=w("pad",e,t,s),r=w("kernelSize",e,t,s);return[lt(w("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i)]}case"MaxPoolWithArgmax":{const n=w("strides",e,t,s),i=w("pad",e,t,s),r=w("kernelSize",e,t,s),o=w("includeBatchInIndex",e,t,s),{result:a,indexes:l}=kp(w("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i,o);return[a,l]}case"AvgPool3D":{const n=w("strides",e,t,s),i=w("pad",e,t,s),r=w("kernelSize",e,t,s);return[Gr(w("x",e,t,s),[r[1],r[2],r[3]],[n[1],n[2],n[3]],i)]}case"MaxPool3D":{const n=w("strides",e,t,s),i=w("pad",e,t,s),r=w("kernelSize",e,t,s);return[no(w("x",e,t,s),[r[1],r[2],r[3]],[n[1],n[2],n[3]],i)]}case"Dilation2D":{const n=w("strides",e,t,s),i=w("pad",e,t,s),r=w("dilations",e,t,s),o=n[1],a=n[2],l=r[1],c=r[2];return[Ip(w("x",e,t,s),w("filter",e,t,s),[o,a],i,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const wN=(e,t,s)=>{switch(e.op){case"Fill":{const n=w("shape",e,t,s),i=w("dtype",e,t,s),r=w("value",e,t,s);return[Ft(n,r,i)]}case"LinSpace":{const n=w("start",e,t,s),i=w("stop",e,t,s),r=w("num",e,t,s);return[Rp(n,i,r)]}case"Multinomial":{const n=w("logits",e,t,s),i=w("numSamples",e,t,s),r=w("seed",e,t,s);return[_p(n,i,r)]}case"OneHot":{const n=w("indices",e,t,s),i=w("depth",e,t,s),r=w("onValue",e,t,s),o=w("offValue",e,t,s);return[On(n,i,r,o)]}case"Ones":return[es(w("shape",e,t,s),w("dtype",e,t,s))];case"OnesLike":return[Bt(w("x",e,t,s))];case"RandomUniform":return[Gs(w("shape",e,t,s),w("minval",e,t,s),w("maxval",e,t,s),w("dtype",e,t,s))];case"Range":{const n=w("start",e,t,s),i=w("stop",e,t,s),r=w("step",e,t,s);return[ei(n,i,r,w("dtype",e,t,s))]}case"TruncatedNormal":{const n=w("shape",e,t,s),i=w("mean",e,t,s),r=w("stdDev",e,t,s),o=w("seed",e,t,s);return[Oi(n,i,r,w("dtype",e,t,s),o)]}case"Zeros":return[Ie(w("shape",e,t,s),w("dtype",e,t,s))];case"ZerosLike":return[ne(w("x",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Cw(e,t,s){const n=w("boxes",e,t,s),i=w("scores",e,t,s),r=w("maxOutputSize",e,t,s),o=w("iouThreshold",e,t,s),a=w("scoreThreshold",e,t,s),l=w("softNmsSigma",e,t,s);return{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}}const xN=async(e,t,s)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}=Cw(e,t,s),c=await ks.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}=Cw(e,t,s),l=w("padToMaxOutputSize",e,t,s),c=await ks.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}=Cw(e,t,s);return[await ks.nonMaxSuppressionAsync(n,i,r,o,a)]}case"Where":{const n=w("condition",e,t,s).asType("bool"),i=[await uo(n)];return n.dispose(),i}case"ListDiff":return $p(w("x",e,t,s),w("y",e,t,s));default:throw TypeError(`Node type ${e.op} is not implemented`)}};const LN=(e,t,s)=>{switch(e.op){case"TopKV2":{const n=w("x",e,t,s),i=w("k",e,t,s),r=w("sorted",e,t,s),o=jp(n,i,r);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const SN=(e,t,s)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const n=w("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=w("x",e,t,s);return[Wn(c)]}case"IdentityN":return w("x",e,t,s).map(c=>Wn(c));case"Snapshot":const i=w("x",e,t,s);return[Wn(i)];case"Shape":return[Fe(w("x",e,t,s).shape,"int32")];case"ShapeN":return w("x",e,t,s).map(c=>Fe(c.shape));case"Size":return[j(w("x",e,t,s).size,"int32")];case"Rank":return[j(w("x",e,t,s).rank,"int32")];case"NoOp":return[j(1)];case"Print":const r=w("x",e,t,s),o=w("data",e,t,s),a=w("message",e,t,s),l=w("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 vN=(e,t,s)=>{switch(e.op){case"ResizeBilinear":{const n=w("images",e,t,s),i=w("size",e,t,s),r=w("alignCorners",e,t,s);return[ks.resizeBilinear(n,[i[0],i[1]],r)]}case"ResizeNearestNeighbor":{const n=w("images",e,t,s),i=w("size",e,t,s),r=w("alignCorners",e,t,s);return[ks.resizeNearestNeighbor(n,[i[0],i[1]],r)]}case"CropAndResize":{const n=w("image",e,t,s),i=w("boxes",e,t,s),r=w("boxInd",e,t,s),o=w("cropSize",e,t,s),a=w("method",e,t,s),l=w("extrapolationValue",e,t,s);return[ks.cropAndResize(n,i,r,o,a,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const TN=(e,t,s)=>{switch(e.op){case"Equal":return[Qt(w("a",e,t,s),w("b",e,t,s))];case"NotEqual":return[Es(w("a",e,t,s),w("b",e,t,s))];case"Greater":return[Ct(w("a",e,t,s),w("b",e,t,s))];case"GreaterEqual":return[as(w("a",e,t,s),w("b",e,t,s))];case"Less":return[Si(w("a",e,t,s),w("b",e,t,s))];case"LessEqual":return[vs(w("a",e,t,s),w("b",e,t,s))];case"LogicalAnd":return[zt(w("a",e,t,s),w("b",e,t,s))];case"LogicalNot":return[vi(w("a",e,t,s))];case"LogicalOr":return[so(w("a",e,t,s),w("b",e,t,s))];case"Select":case"SelectV2":return[at(w("condition",e,t,s),w("a",e,t,s),w("b",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const IN=(e,t,s)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Le(w("a",e,t,s),w("b",e,t,s),w("transposeA",e,t,s),w("transposeB",e,t,s))];case"Transpose":return[se(w("x",e,t,s),w("perm",e,t,s))];case"_FusedMatMul":const[n,i]=w("fusedOps",e,t,s),r=n==="biasadd",o=i==="prelu",a=w("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]=w("args",e,t,s);return[Hs.matMul({a:w("a",e,t,s),b:w("b",e,t,s),transposeA:w("transposeA",e,t,s),transposeB:w("transposeB",e,t,s),bias:l,activation:i,preluActivationWeights:c})];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const AN=(e,t,s)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[on(w("x",e,t,s),w("mean",e,t,s),w("variance",e,t,s),w("offset",e,t,s),w("scale",e,t,s),w("epsilon",e,t,s))];case"FusedBatchNormV3":return[on(w("x",e,t,s),w("mean",e,t,s),w("variance",e,t,s),w("offset",e,t,s),w("scale",e,t,s),w("epsilon",e,t,s))];case"LRN":return[Op(w("x",e,t,s),w("radius",e,t,s),w("bias",e,t,s),w("alpha",e,t,s),w("beta",e,t,s))];case"Softmax":return[Yt(w("x",e,t,s))];case"LogSoftmax":return[to(w("x",e,t,s))];case"SparseToDense":return[fa(w("sparseIndices",e,t,s),w("outputShape",e,t,s),w("sparseValues",e,t,s),w("defaultValue",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const NN=(e,t,s)=>{switch(e.op){case"Max":{const n=w("axis",e,t,s),i=w("keepDims",e,t,s);return[st(w("x",e,t,s),n,i)]}case"Mean":{const n=w("axis",e,t,s),i=w("keepDims",e,t,s);return[Ge(w("x",e,t,s),n,i)]}case"Min":{const n=w("axis",e,t,s),i=w("keepDims",e,t,s);return[an(w("x",e,t,s),n,i)]}case"Sum":{const n=w("axis",e,t,s),i=w("keepDims",e,t,s);return[te(w("x",e,t,s),n,i)]}case"All":{const n=w("axis",e,t,s),i=w("keepDims",e,t,s);return[jr(w("x",e,t,s),n,i)]}case"Any":{const n=w("axis",e,t,s),i=w("keepDims",e,t,s);return[sr(w("x",e,t,s),n,i)]}case"ArgMax":{const n=w("axis",e,t,s);return[nr(w("x",e,t,s),n)]}case"ArgMin":{const n=w("axis",e,t,s);return[ap(w("x",e,t,s),n)]}case"Prod":{const n=w("axis",e,t,s),i=w("keepDims",e,t,s);return[ro(w("x",e,t,s),n,i)]}case"Cumsum":{const n=w("axis",e,t,s),i=w("exclusive",e,t,s),r=w("reverse",e,t,s);return[Xr(w("x",e,t,s),n,i,r)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const CN=(e,t,s)=>{switch(e.op){case"ConcatV2":case"Concat":{const n=w("n",e,t,s),i=w("axis",e,t,s);let r=w("tensors",e,t,s);return r=r.slice(0,n),[ge(r,i)]}case"GatherV2":case"Gather":{const n=w("axis",e,t,s),i=w("x",e,t,s),r=w("indices",e,t,s);return[Cn(i,r.asType("int32"),n)]}case"ReverseV2":case"Reverse":{const n=w("axis",e,t,s),i=w("x",e,t,s);return[Lt(i,n)]}case"Slice":{const n=w("begin",e,t,s),i=w("size",e,t,s);return[he(w("x",e,t,s),n,i)]}case"StridedSlice":{const n=w("begin",e,t,s),i=w("end",e,t,s),r=w("strides",e,t,s),o=w("beginMask",e,t,s),a=w("endMask",e,t,s),l=w("ellipsisMask",e,t,s),c=w("newAxisMask",e,t,s),p=w("shrinkAxisMask",e,t,s),u=w("x",e,t,s);return[zp(u,n,i,r,o,a,l,c,p)]}case"Pack":return N(()=>{const n=w("axis",e,t,s),i=w("tensors",e,t,s),r=i[0].shape,o=i[0].squeeze().shape,a=i.map(l=>{const c=E.arraysEqual(l.shape,r);if(!c&&!E.arraysEqual(l.squeeze().shape,o))throw new Error("the input tensors shape does not match");return c?l:l.reshape(r)});return[Xe(a,n)]});case"Unpack":{const n=w("axis",e,t,s),i=w("tensor",e,t,s);return nt(i,n)}case"Tile":{const n=w("reps",e,t,s);return[js(w("x",e,t,s),n)]}case"Split":case"SplitV":{const n=w("axis",e,t,s),i=w("numOrSizeSplits",e,t,s),r=w("x",e,t,s);return ls(r,i,n)}case"ScatterNd":{const n=w("indices",e,t,s),i=w("values",e,t,s),r=w("shape",e,t,s);return[Bh(n,i,r)]}case"GatherNd":{const n=w("x",e,t,s),i=w("indices",e,t,s);return[Ph(n,i)]}case"SparseToDense":{const n=w("sparseIndices",e,t,s),i=w("outputShape",e,t,s),r=w("sparseValues",e,t,s),o=w("defaultValue",e,t,s);return[fa(n,r,i,r.dtype===o.dtype?o:o.asType(r.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const RN=(e,t,s)=>{switch(e.op){case"FFT":return[Li(w("x",e,t,s))];case"IFFT":return[Qn(w("x",e,t,s))];case"RFFT":return[Ai(w("x",e,t,s))];case"IRFFT":return[Zr(w("x",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const ON=(e,t,s)=>{switch(e.op){case"Cast":return[K(w("x",e,t,s),w("dtype",e,t,s))];case"ExpandDims":{const n=w("axis",e,t,s);return[Nt(w("x",e,t,s),n)]}case"Squeeze":{const n=w("axis",e,t,s);return[En(w("x",e,t,s),n)]}case"Reshape":return[O(w("x",e,t,s),w("shape",e,t,s))];case"PadV2":case"Pad":return[Ut(w("x",e,t,s),w("padding",e,t,s),w("constantValue",e,t,s))];case"SpaceToBatchND":{const n=w("blockShape",e,t,s),i=w("paddings",e,t,s);return[Ti(w("x",e,t,s),n,i)]}case"BatchToSpaceND":{const n=w("blockShape",e,t,s),i=w("crops",e,t,s);return[wi(w("x",e,t,s),n,i)]}case"DepthToSpace":{const n=w("blockSize",e,t,s),i=w("dataFormat",e,t,s).toUpperCase();return[Tp(w("x",e,t,s),n,i)]}case"BroadcastTo":return[or(w("x",e,t,s),w("shape",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Rw(e,t,s){const n=((i,r,o)=>{switch(i.category){case"arithmetic":return N(()=>cN(i,r,o));case"basic_math":return N(()=>pN(i,r,o));case"control":return gN(i,r,o);case"convolution":return N(()=>bN(i,r,o));case"creation":return N(()=>wN(i,r,o));case"dynamic":return xN(i,r,o);case"evaluation":return N(()=>LN(i,r,o));case"image":return N(()=>vN(i,r,o));case"graph":return N(()=>SN(i,r,o));case"logical":return N(()=>TN(i,r,o));case"matrices":return N(()=>IN(i,r,o));case"normalization":return N(()=>AN(i,r,o));case"reduction":return N(()=>NN(i,r,o));case"slice_join":return N(()=>CN(i,r,o));case"spectral":return N(()=>RN(i,r,o));case"transformation":return N(()=>ON(i,r,o));case"custom":const a=zm(i.op);if(a&&a.customExecutor)return a.customExecutor(new lN(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 Ow{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(){for(const e in this.tensorArrayMap)this.tensorArrayMap[e].clearAndClose();for(const e in this.tensorListMap)this.tensorListMap[e].clearAndClose()}}function kw(e,t,s){const n=new Set(),i=[];let r=null,o=null;const a=new Set(),l=Object.keys(e).map(p=>As(p)[0]),c=[...t];for(;c.length>0;){const p=c.pop();if((Ew(p)||nz(p))&&(r==null&&(r=p,o=r.children.map(u=>u.name).filter(u=>n.has(u)))),n.add(p.name),s[p.name]!=null)continue;if(l.indexOf(p.name)!==-1)continue;if(p.inputs.length===0){i.push(p.name);continue}p.inputs.forEach(u=>{if(a.has(u.name))return;a.add(u.name),c.push(u)})}return{inputs:e,outputs:t,usedNodes:n,missingInputs:i,dynamicNode:r,syncInputs:o}}function EN(e,t,s){const{usedNodes:n,inputs:i}=s,r=[],o=Object.keys(i).map(c=>As(c)[0]).map(c=>e.nodes[c]);o.forEach(c=>{n.has(c.name)&&r.push(c)}),e.weights.forEach(c=>{n.has(c.name)&&r.push(c)});const a=new Set(),l=[];for(;r.length>0;){const c=r.pop();a.add(c.name),t[c.name]||l.push(c),c.children.forEach(p=>{!a.has(p.name)&&n.has(p.name)&&p.inputs.every(u=>a.has(u.name))&&r.push(p)})}return l}const iz=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],rz=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function Ew(e){return iz.indexOf(e.op)>=0}function nz(e){return rz.indexOf(e.op)>=0}class _w{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._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(s=>{this._functionExecutorMap[s]=new _w(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=kw(e,t,this.weightMap),{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 EN(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(c=>this.graph.nodes[As(c)[0]]),i=t.map(c=>this.graph.nodes[As(c)[0]]),r=this.getCompilationKey(n,i);let o=this.compiledMap.get(r);o==null&&(o=this.compile(e,i),this.compiledMap.set(r,o));const a={},l={};return N(()=>{const c=new Ow(this.weightMap,a,l,this.functionExecutorMap),p=Object.assign({},this.weightMap);Object.keys(e).forEach(d=>{const[m,f]=As(d),y=[];y[f]=e[d],p[m]=y});const u=this.getFrozenTensorIds(p),h={};for(let d=0;d<o.length;d++){const m=o[d];if(!p[m.name]){const f=Rw(m,p,c);if(f instanceof Promise)throw new Error(`The execution of the op '${m.op}' returned a promise. Please use model.executeAsync() instead.`);p[m.name]=f,this.checkTensorForDisposal(m.name,m,p,c,u,t,h)}}return this.parent==null&&c.dispose(),t.map(d=>Vt(d,p,c))})}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=nN(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 Ow(this.weightMap,n,i,this.functionExecutorMap),o=await this.executeWithControlFlow(e,r,t,s),a=t.map(p=>Vt(p,o,r)),l=new Set(a.map(p=>p.id)),c=new Set(Object.keys(e).map(p=>e[p].id));return Object.keys(o).forEach(p=>{const u=o[p];u.forEach(h=>{h&&!h.isDisposed&&!l.has(h.id)&&!c.has(h.id)&&this.weightIds.indexOf(h.id)===-1&&h.dispose()})}),this.parent==null&&r.dispose(),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(b=>this.graph.nodes[As(b)[0]]),o=s.map(b=>this.graph.nodes[As(b)[0]]),{usedNodes:a,missingInputs:l,dynamicNode:c,syncInputs:p}=kw(e,o,this.weightMap),u=[...r,...this.graph.weights].map(b=>({node:b,contexts:t.currentContext})),h=Object.assign({},this.weightMap);Object.keys(e).forEach(b=>{const[S,x]=As(b),I=[];I[x]=e[b],h[S]=I});const d={},m=this.getFrozenTensorIds(h),f={};for(;u.length>0;){const b=this.processStack(r,u,t,h,f,m,s,d,a);await Promise.all(b)}c==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=o.filter(b=>!Ew(b)&&!Vt(b.name,h,t)).map(b=>b.name);if(y.length>0){let b="";throw c!=null&&(b=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${i}]. Consider providing the following inputs: [${l}]. ${b}`)}return h}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"&&w("isConstant",p.node,n,s)&&([u]=$n(p.node.name,s)),e.indexOf(p.node)===-1){const h=Rw(p.node,n,s);u||([u]=$n(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]=$n(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]=As(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);E.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&&E.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]=As(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]=As(t);if(!this.graph.nodes[s])throw new Error(`The output '${t}' is not found in the graph`)})}}const oz="?tfjs-format=file",az="model.json";class Dw{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=Ot.browserHTTPRequest(e,this.loadOptions);else{const t=Ot.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Ot.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=Ot.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);return this.executor=new _w(rN.Instance.transformGraph(t,s)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),!0}async save(e,t){if(typeof e=="string"){const s=Ot.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 ue)&&!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()}}async function kN(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}${az}${oz}`));const s=new Dw(e,t);return await s.load(),s}const Zm="2.3.0";function _N(e,t){return Qm(e,t)}function Qm(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(br(e)){const r=Array.isArray(e)?[]:{};n.add(e);for(const o in e){const a=e[o],l=Qm(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 FN(e,t=Fw){return DN(e,t)}function DN(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(br(n)){const r=Array.isArray(n)?[]:{};s.add(n);for(const o in n){const a=e.map(c=>c[o]),l=DN(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 Fw(e){return e===null?null:br(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function ef(e,t){const s=new Map();Qm(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=Qm(e,t,s);return n}function br(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof ue))}function MN(e){return e==null||lz(e)||Array.isArray(e)||typeof e=="object"&&e instanceof ue||E.isTypedArray(e)}function lz(e){return e===null||typeof e!="object"&&typeof e!="function"}function UN(e){return _N(e,cz)}function cz(e){return e instanceof ue?{value:e.clone(),recurse:!1}:br(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class tf{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 sf extends tf{constructor(){super(sf.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}}sf.INITIAL_CAPACITY=32;const $N=nl(il());function Mw(e){return new pz(e)}function Ou(e){return new uz(e)}function zN(e,t){return new WN(e,t)}function BN(e,t=zi.FAIL){return new hz(e,t)}class Tt{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 wz(this,e)}filter(e){return new yz(this,e)}map(e){return new bz(this,e)}mapAsync(e){return new PN(this,e)}serialMapAsync(e){return new PN(this,e).serial()}flatmap(e){return new xz(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 gz(this,e,t)}columnMajorBatch(e,t=!0,s=Fw){const n=this.rowMajorBatch(e,t);return n.map(i=>FN(i,s))}concatenate(e,t){return new WN(Mw([this,e]),t)}take(e){return e<0||e==null?this:new fz(this,e)}skip(e){return e<0||e==null?this:new mz(this,e)}prefetch(e){return new jN(this,e)}shuffle(e,t){return new Lz(this,e,t)}serial(){return new dz(this)}}class pz extends Tt{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:UN(e),done:!1}}}class uz extends Tt{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 dz extends Tt{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 mz extends Tt{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 fz extends Tt{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 gz extends Tt{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 yz extends Tt{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 bz extends Tt{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=rn.getTensorsInContainer(e.value),s=this.transform(e.value),n=rn.getTensorsInContainer(s);for(const i of t)rn.isTensorInList(i,n)||i.dispose();return{value:s,done:!1}}}class wz extends Tt{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 PN extends Tt{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=rn.getTensorsInContainer(e.value),s=await this.transform(e.value),n=rn.getTensorsInContainer(s);for(const i of t)rn.isTensorInList(i,n)||i.dispose();return{value:s,done:!1}}}class Eu extends Tt{constructor(){super();this.outputQueue=new sf(),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 xz extends Eu{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=rn.getTensorsInContainer(e.value),s=this.transform(e.value),n=rn.getTensorsInContainer(s);this.outputQueue.pushAll(s);for(const i of t)rn.isTensorInList(i,n)||i.dispose();return!0}}class WN extends Tt{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 zi;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(zi||(zi={}));class hz extends Tt{constructor(e,t=zi.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 Tt){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 ef(this.iterators,n);if(t===s)return{value:null,done:!0};if(s>0)switch(this.mismatchMode){case zi.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case zi.SHORTEST:return{value:null,done:!0};case zi.LONGEST:default:}return this.count++,{value:i,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class jN extends Tt{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new tf(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 Lz extends jN{constructor(e,t,s){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=$N.alea(s||E.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 VN=nl(il());class Bi{constructor(){this.size=null}batch(e,t=!0){const s=this;E.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),Ns(async()=>(await s.iterator()).columnMajorBatch(e,t,Sz),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,Ns(async()=>(await t.iterator()).concatenate(await e.iterator()),s)}filter(e){const t=this;let s;return this.size===Infinity?s=Infinity:s=null,Ns(async()=>(await t.iterator()).filter(n=>N(()=>e(n))),s)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return Ns(async()=>(await t.iterator()).map(s=>N(()=>e(s))),this.size)}mapAsync(e){const t=this;return Ns(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 Ns(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,Ns(async()=>{const n=Ou(async()=>({value:await t.iterator(),done:!1}));return zN(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,Ns(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=VN.alea(t||E.now().toString());return Ns(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,Ns(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()}}Bi.MAX_BUFFER_SIZE=1e4;function Ns(e,t=null){return new class extends Bi{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}()}function GN(e){return Ns(async()=>Mw(e),e.length)}function HN(e){if(!br(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 Ns(async()=>{const s=await ef(e,n=>{if(n instanceof Bi)return{value:n.iterator(),recurse:!1};if(br(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return BN(s,zi.SHORTEST)},t)}function Sz(e){if(e===null)return null;const t=e[0];if(MN(t)){const s=vz(e);return{value:s,recurse:!1}}return{value:null,recurse:!0}}function vz(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof ue?Xe(e):ze(e)}class nf extends Bi{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 rf='"',ku=Symbol("out"),qN=Symbol("field"),of=Symbol("quote"),Uw=Symbol("quoteafterquote"),YN=Symbol("quoteinquote");class af extends Bi{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 nf(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(E.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&&E.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(E.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 rf:n=o+1,r=of;break;case this.delimiter:if(n=o+1,this.delimiter===" "&&this.delimWhitespace)break;s.push(""),r=ku;break;default:r=qN,n=o;break}break;case qN:switch(e.charAt(o)){case this.delimiter:s.push(e.substring(n,o)),r=ku,n=o+1;break;default:}break;case of:switch(e.charAt(o)){case rf:r=Uw;break;default:}break;case Uw:switch(e.charAt(o)){case this.delimiter:s.push(e.substring(n,o-1)),r=ku,n=o+1;break;case rf:r=of;break;default:r=YN;break}break;case YN:switch(e.charAt(o)){case rf:r=of;break;default:}break;default:}if(r===Uw?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 $w extends Tt{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($().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");const t=new $w(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(E.sizeFromShape(t));return s.set(e,s.length-e.length),ze(s,t)}}class Ww extends Tt{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=Fe([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=ts([r,i,a,o],[1,4])}else this.cropBox=ts([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if($().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 Ww(e,t);return await s.start(),s}async start(){this.webcamConfig.facingMode&&E.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=pr.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 N(()=>{const t=e.toFloat().expandDims(0);let s;s=ks.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 lf{}class zw extends Tt{split(e){return new Tz(this,e)}}class Tz extends zw{constructor(e,t){super();this.upstream=e,this.impl=new Iz(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class Iz extends Eu{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 KN extends Tt{decodeUTF8(){return new Az(this)}}class Az extends zw{constructor(e){super();this.upstream=e,this.impl=new Nz(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class Nz extends Eu{constructor(e){super();if(this.upstream=e,$().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:t}=dL();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 $().get("IS_BROWSER")?s=this.decoder.decode(t,{stream:!0}):s=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(s),!0}}class cf extends KN{constructor(e,t={}){super();this.file=e,this.options=t,E.assert(e instanceof Uint8Array||($().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 XN(e,t={}){let s,n;typeof e=="string"?s=e:(s=e.url,n=Cz(e));const i=await E.fetch(s,n);if(i.ok){const r=new Uint8Array(await i.arrayBuffer());return new cf(r,t)}else throw new Error(i.statusText)}const Cz=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 pf(e){return typeof e=="string"&&e.substr(0,7)==="file://"}class uf extends lf{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(pf(this.input)&&$().get("IS_NODE")){const e=mL();this.input=e.readFileSync(this.input.substr(7))}return new cf(this.input,this.options)}}class hf extends lf{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return pf(this.url)?new uf(this.url,this.fileOptions).iterator():XN(this.url,this.fileOptions)}}function JN(e,t={}){return new af(new hf(e),t)}function ZN(e){const t=Ou(e);return Ns(async()=>t)}function QN(e){return Ns(async()=>{const t=await e();return Ou(()=>t.next())})}async function eC(e,t){return Ww.create(e,t)}async function tC(e){return $w.create(e)}const df="2.3.0";const Bw={};Re(Bw,{CSVDataset:()=>af,Dataset:()=>Bi,FileDataSource:()=>uf,TextLineDataset:()=>nf,URLDataSource:()=>hf,array:()=>GN,csv:()=>JN,func:()=>ZN,generator:()=>QN,microphone:()=>tC,version_data:()=>df,webcam:()=>eC,zip:()=>HN});function H(e,t){Array.isArray(e)||(e=[e]),e.forEach(s=>{s!=null&&E.assert(s.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}function _u(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=le(i.outShape,s),y=f.values,b=i.outShape[1]*i.outShape[2]*i.outShape[3],S=i.outShape[2]*i.outShape[3],x=i.outShape[3];for(let I=0;I<i.batchSize;++I){const A=I*b,k=I*n[0];for(let R=0;R<i.inChannels;++R)for(let D=0;D<i.outHeight;++D){const F=D*o-h,M=Math.max(0,F),B=Math.min(i.inHeight,p+F),V=A+D*S;for(let Y=0;Y<i.outWidth;++Y){const G=Y*a-d,Z=Math.max(0,G),q=Math.min(i.inWidth,u+G);let ee=m,Q=0,ie=0;for(let de=M;de<B;de+=l){const pe=k+de*n[1];for(let me=Z;me<q;me+=c){const we=pe+me*n[2],$e=e[we+R];r==="max"&&$e>ee?ee=$e:r==="avg"&&(Q+=$e,ie++)}if(isNaN(ee))break}const re=V+Y*x+R;y[re]=r==="avg"?Q/ie:ee}}}return f}function mf(e,t,s,n,i=!1,r=!1){const o=le(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=le(t,s,e);for(let y=0;y<n.batchSize;++y)for(let b=0;b<n.inChannels;++b)for(let S=0;S<n.outHeight;++S){const x=S*a-d;let I=x;for(;I<0;)I+=c;const A=Math.min(n.inHeight,u+x);for(let k=0;k<n.outWidth;++k){const R=k*l-m;let D=R;for(;D<0;)D+=p;const F=Math.min(n.inWidth,h+R);let M=Number.NEGATIVE_INFINITY,B=-1;for(let V=I;V<A;V+=c){const Y=V-x;for(let G=D;G<F;G+=p){const Z=G-R,q=f.get(y,V,G,b);q>M&&(M=q,i?B=r?((y*n.inHeight+V)*n.inWidth+G)*n.inChannels+b:(V*n.inWidth+G)*n.inChannels+b:B=Y*h+Z)}}o.set(B,y,S,k,b)}}return o}const sC=nl(il());const Rz=St.nonMaxSuppressionV3Impl,Oz=St.split,Ez=St.tile,kz=St.topkImpl,_z=St.whereImpl;function Pw(e,t,s,n){if(s==="linear")return e.linear(t);if(s==="relu")return e.relu(t);if(s==="elu")return e.elu(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 jw extends Jp{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Xp(this,os())}write(e,t,s){this.firstUse&&(this.firstUse=!1,$().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}),n}move(e,t,s,n){this.data.set(e,{values:t,dtype:n})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensors: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=>E.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return le(e.shape,e.dtype,s)}makeOutput(e,t,s){const n=this.write(e,t,s);return os().makeTensorFromDataId(n,t,s,this)}disposeData(e){if(this.data.has(e)){const{complexTensors:t}=this.data.get(e);t!=null&&(t.real.dispose(),t.imag.dispose()),this.data.delete(e)}}async time(e){const t=E.now();e();const s=E.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."]}}complex(e,t){const s=this.makeOutput(null,e.shape,"complex64"),n=this.data.get(s.dataId);return n.complexTensors={real:os().keep(e.clone()),imag:os().keep(t.clone())},s}real(e){const t=this.data.get(e.dataId);return t.complexTensors.real.clone()}imag(e){const t=this.data.get(e.dataId);return t.complexTensors.imag.clone()}slice(e,t,s){H(e,"slice");const n=Jn.isSliceContinous(e.shape,t,s);if(n){const o=Jn.computeFlatOffset(t,e.strides),a=E.sizeFromShape(s),l=this.readSync(e.dataId);return ze(l.subarray(o,o+a),s,e.dtype)}const i=le(s,e.dtype),r=this.bufferSync(e);for(let o=0;o<i.size;++o){const a=i.indexToLoc(o),l=a.map((c,p)=>c+t[p]);i.values[o]=r.get(...l)}return i.toTensor()}stridedSlice(e,t,s,n){H(e,"stridedSlice");const i=Jn.computeOutShape(t,s,n);if(i.some(a=>a===0))return ze([],i);const r=le(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=le([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]=this.slice(e,r,o).reshape(n);return a}reverse(e,t){H(e,"reverse");const s=le(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()}concat(e,t){if(e[0].dtype==="complex64"){const o=e.map(l=>$t(l)),a=e.map(l=>Ht(l));return Ze(this.concat(o,t),this.concat(a,t))}const s=e.map(o=>{const a=E.sizeFromShape(o.shape.slice(t));return o.as2D(-1,a)}),n=U.computeOutShape(s.map(o=>o.shape),1),i=le(n,e[0].dtype).values;if(s[0].shape[0]===1){let o=0;s.forEach(a=>{i.set(this.readSync(a.dataId),o),o+=a.size})}else{let o=0;s.forEach(a=>{const l=this.readSync(a.dataId);let c=0;for(let p=0;p<a.shape[0];++p){const u=p*n[1]+o;for(let h=0;h<a.shape[1];++h)i[u+h]=l[c++]}o+=a.shape[1]})}const r=U.computeOutShape(e.map(o=>o.shape),t);return ze(i,r,e[0].dtype)}neg(e){return H(e,"neg"),this.multiply(j(-1),e)}add(e,t){return e.dtype==="complex64"||t.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),(s,n,i,r)=>({real:s+i,imag:n+r})):this.broadcastedBinaryOp(e,t,wt(e.dtype,t.dtype),(s,n)=>s+n)}addN(e){H(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),s=le(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=E.parseAxisParam([t],e.shape),n=st(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 J(o,a)}subtract(e,t){return e.dtype==="complex64"||t.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),(s,n,i,r)=>({real:s-i,imag:n-r})):this.broadcastedBinaryOp(e,t,wt(e.dtype,t.dtype),(s,n)=>s-n)}pow(e,t){return H([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.pow(s,n))}batchMatMul(e,t,s,n){H([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]],y=r*o,b=le([a,r,o],e.dtype),S=b.values,x=this.blockSize;for(let I=0;I<a;I++)for(let A=0;A<r;A+=x)for(let k=0;k<o;k+=x)for(let R=0;R<i;R+=x){const D=Math.min(A+x,r),F=Math.min(k+x,o),M=Math.min(R+x,i);for(let B=A;B<D;B++)for(let V=k;V<F;V++){let Y=0;for(let G=R;G<M;G++)Y+=l[I*p+B*u+G*h]*c[G*d+V*m+I*f];S[I*y+(B*o+V)]+=Y}}return b.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=this.add(a,i)),r&&(a=Pw(this,a,r,o)),a}multiply(e,t){return e.dtype==="complex64"||t.dtype==="complex64"?this.broadcastedBinaryComplexOp(e.cast("complex64"),t.cast("complex64"),(s,n,i,r)=>({real:s*i-n*r,imag:s*r+n*i})):this.broadcastedBinaryOp(e,t,wt(e.dtype,t.dtype),(s,n)=>s*n)}floorDiv(e,t){H([e,t],"floorDiv");const s=(i,r)=>Math.floor(i/r),n="int32";return this.broadcastedBinaryOp(e,t,n,s)}sum(e,t){H(e,"sum"),U.assertAxesAreInnerMostDims("sum",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=wt(e.dtype,"int32"),r=Ie(s,i),o=E.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){H(e,"sum");const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=wt(e.dtype,"int32"),r=Ie(s,i),o=E.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){H(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=Qt(o,t).asType("float32"),l=a.mul(e).sum(0);n.push(l)}return Xe(n)}argMin(e,t){H(e,"argMin");const s=[t];U.assertAxesAreInnerMostDims("argMin",s,e.rank);const[n,i]=U.computeOutAndReduceShapes(e.shape,s),r=Ie(n,"int32"),o=E.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){H(e,"argMax");const s=[t];U.assertAxesAreInnerMostDims("argMax",s,e.rank);const[n,i]=U.computeOutAndReduceShapes(e.shape,s),r=Ie(n,"int32"),o=E.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(H(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=wt(e.dtype,"int32"),r=Ie(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 H([e,t],"equal"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s===n?1:0)}notEqual(e,t){return H([e,t],"notEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s!==n?1:0)}less(e,t){return H([e,t],"less"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s<n?1:0)}lessEqual(e,t){return H([e,t],"lessEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s<=n?1:0)}greater(e,t){return H([e,t],"greater"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s>n?1:0)}greaterEqual(e,t){return H([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s>=n?1:0)}logicalNot(e){H(e,"logicalNot");const t=this.readSync(e.dataId),s=new Uint8Array(t.length);for(let n=0;n<t.length;++n)s[n]=t[n]?0:1;return this.makeOutput(s,e.shape,"bool")}logicalAnd(e,t){return H([e,t],"logicalAnd"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s&&n)}logicalOr(e,t){return H([e,t],"logicalOr"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s||n)}select(e,t,s){H([e,t,s],"select");const n=this.readSync(e.dataId),i=this.readSync(t.dataId),r=this.readSync(s.dataId),o=Ie(t.shape,wt(t.dtype,s.dtype)),a=this.readSync(o.dataId);let l=0;const c=e.rank===0||e.rank>1||t.rank===1?1:E.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){H([e],"where");const t=this.readSync(e.dataId);return _z(e.shape,t)}topk(e,t,s){H(e,"topk");const n=this.readSync(e.dataId);return kz(n,e.shape,e.dtype,t,s)}min(e,t){H(e,"min"),U.assertAxesAreInnerMostDims("min",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=Ie(s,e.dtype),r=E.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 H([e,t],"minimum"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.min(s,n))}mod(e,t){return H([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 H([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.max(s,n))}all(e,t){H(e,"all"),U.assertAxesAreInnerMostDims("all",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=Ie(s,e.dtype),r=E.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){H(e,"any"),U.assertAxesAreInnerMostDims("any",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=Ie(s,e.dtype),r=E.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 H([e,t],"squaredDifference"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>{const i=s-n;return i*i})}ceil(e){H(e,"ceil");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n)s[n]=Math.ceil(t[n]);return this.makeOutput(s,e.shape,"float32")}floor(e){H(e,"floor");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n)s[n]=Math.floor(t[n]);return this.makeOutput(s,e.shape,"float32")}sign(e){H(e,"x");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n)t[n]<0?s[n]=-1:t[n]>0?s[n]=1:s[n]=0;return this.makeOutput(s,e.shape,"float32")}isNaN(e){H(e,"x");const t=this.readSync(e.dataId),s=new Uint8Array(t.length);for(let n=0;n<t.length;++n)Number.isNaN(t[n])&&(s[n]=1);return this.makeOutput(s,e.shape,"bool")}isInf(e){H(e,"x");const t=this.readSync(e.dataId),s=new Uint8Array(t.length);for(let n=0;n<t.length;++n)Math.abs(t[n])===Infinity&&(s[n]=1);return this.makeOutput(s,e.shape,"bool")}isFinite(e){H(e,"x");const t=this.readSync(e.dataId),s=new Uint8Array(t.length);for(let n=0;n<t.length;++n)Number.isFinite(t[n])&&(s[n]=1);return this.makeOutput(s,e.shape,"bool")}round(e){H(e,"round");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n){const i=Math.floor(t[n]);t[n]-i<.5?s[n]=Math.floor(t[n]):t[n]-i>.5?s[n]=Math.ceil(t[n]):i%2===0?s[n]=i:s[n]=i+1}return this.makeOutput(s,e.shape,"float32")}exp(e){H(e,"exp");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n)s[n]=Math.exp(t[n]);return this.makeOutput(s,e.shape,"float32")}expm1(e){H(e,"expm1");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n)s[n]=Math.expm1(t[n]);return this.makeOutput(s,e.shape,"float32")}log(e){H(e,"log");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n){const i=t[n];s[n]=Math.log(i)}return this.makeOutput(s,e.shape,"float32")}log1p(e){H(e,"log1p");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n){const i=t[n];s[n]=Math.log1p(i)}return this.makeOutput(s,e.shape,"float32")}sqrt(e){H(e,"sqrt");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n){const i=t[n];s[n]=Math.sqrt(i)}return this.makeOutput(s,e.shape,"float32")}rsqrt(e){H(e,"rsqrt");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n){const i=t[n];s[n]=1/Math.sqrt(i)}return this.makeOutput(s,e.shape,"float32")}reciprocal(e){H(e,"reciprocal");const t=this.readSync(e.dataId),s=new Float32Array(t.length);for(let n=0;n<t.length;++n)s[n]=1/t[n];return this.makeOutput(s,e.shape,"float32")}linear(e){return e}relu(e){H(e,"relu");const t=Ie(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){H(e,"relu");const t=Ie(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 H([e,t],"prelu"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>s<0?n*s:s)}elu(e){H(e,"elu");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n){const i=s[n];i>=0?t[n]=i:t[n]=Math.exp(i)-1}return this.makeOutput(t,e.shape,"float32")}eluDer(e,t){H([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")}selu(e){H(e,"selu");const t=U.SELU_SCALEALPHA,s=U.SELU_SCALE,n=new Float32Array(e.size),i=this.readSync(e.dataId);for(let r=0;r<i.length;++r){const o=i[r];o>=0?n[r]=s*o:n[r]=t*(Math.exp(o)-1)}return this.makeOutput(n,e.shape,"float32")}clip(e,t,s){H(e,"clip");const n=new Float32Array(e.size),i=this.readSync(e.dataId);for(let r=0;r<i.length;++r){const o=i[r];n[r]=o>s?s:o<t?t:o}return this.makeOutput(n,e.shape,"float32")}abs(e){const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.abs(s[n]);return this.makeOutput(t,e.shape,"float32")}complexAbs(e){const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<e.size;++n){const i=s[n*2],r=s[n*2+1];t[n]=Math.hypot(i,r)}return this.makeOutput(t,e.shape,"float32")}int(e){H(e,"int");const t=new Int32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=s[n];return this.makeOutput(t,e.shape,"int32")}sigmoid(e){H(e,"sigmoid");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=1/(1+Math.exp(-s[n]));return this.makeOutput(t,e.shape,"float32")}softplus(e){H(e,"softplus");const t=11920928955078125e-23,s=Math.log(t)+2,n=new Float32Array(e.size),i=this.readSync(e.dataId);for(let r=0;r<i.length;++r){const o=i[r]>-s,a=i[r]<s,l=Math.exp(i[r]);let c;a?c=l:o?c=i[r]:c=Math.log(1+l),n[r]=c}return this.makeOutput(n,e.shape,"float32")}sin(e){H(e,"sin");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.sin(s[n]);return this.makeOutput(t,e.shape,"float32")}cos(e){H(e,"cos");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.cos(s[n]);return this.makeOutput(t,e.shape,"float32")}tan(e){H(e,"tan");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.tan(s[n]);return this.makeOutput(t,e.shape,"float32")}asin(e){H(e,"asin");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.asin(s[n]);return this.makeOutput(t,e.shape,"float32")}acos(e){H(e,"acos");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.acos(s[n]);return this.makeOutput(t,e.shape,"float32")}atan(e){H(e,"atan");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.atan(s[n]);return this.makeOutput(t,e.shape,"float32")}atan2(e,t){return H([e,t],"atan2"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.atan2(s,n))}sinh(e){H(e,"sinh");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.sinh(s[n]);return this.makeOutput(t,e.shape,"float32")}cosh(e){H(e,"cosh");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.cosh(s[n]);return this.makeOutput(t,e.shape,"float32")}tanh(e){H(e,"tanh");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=E.tanh(s[n]);return this.makeOutput(t,e.shape,"float32")}asinh(e){H(e,"asinh");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.asinh(s[n]);return this.makeOutput(t,e.shape,"float32")}acosh(e){H(e,"acosh");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.acosh(s[n]);return this.makeOutput(t,e.shape,"float32")}atanh(e){H(e,"atanh");const t=new Float32Array(e.size),s=this.readSync(e.dataId);for(let n=0;n<s.length;++n)t[n]=Math.atanh(s[n]);return this.makeOutput(t,e.shape,"float32")}erf(e){H(e,"erf");const t=new Float32Array(e.size),s=this.readSync(e.dataId),n=U.ERF_P,i=U.ERF_A1,r=U.ERF_A2,o=U.ERF_A3,a=U.ERF_A4,l=U.ERF_A5;for(let c=0;c<s.length;++c){const p=Math.sign(s[c]),u=Math.abs(s[c]),h=1/(1+n*u);t[c]=p*(1-((((l*h+a)*h+o)*h+r)*h+i)*h*Math.exp(-u*u))}return this.makeOutput(t,e.shape,"float32")}step(e,t=0){H(e,"step");const s=new Float32Array(e.size),n=this.readSync(e.dataId);for(let i=0;i<n.length;++i){const r=n[i];isNaN(r)?s[i]=NaN:s[i]=r>0?1:t}return this.makeOutput(s,e.shape,"float32")}fusedConv2d({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){let o=this.conv2d(e,t,s);return n&&(o=this.add(o,n)),i&&(o=Pw(this,o,i,r)),o}conv2d(e,t,s){H([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=le(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],y=c?p.strides[1]:p.strides[2],b=c?p.strides[2]:1,S=c?1:p.strides[1],x=this.readSync(e.dataId),I=this.readSync(t.dataId),A=p.values;for(let k=0;k<s.batchSize;++k){const R=k*u,D=k*f;for(let F=0;F<s.outHeight;++F){const M=D+F*y,B=F*s.strideHeight-l;for(let V=0;V<n;V++){const Y=B+V*r;if(Y<0||Y>=s.inHeight)continue;const G=V*t.strides[0],Z=R+Y*h;for(let q=0;q<s.outWidth;++q){const ee=M+q*b,Q=q*s.strideWidth-a;for(let ie=0;ie<i;ie++){const re=Q+ie*o;if(re<0||re>=s.inWidth)continue;const de=G+ie*t.strides[1],pe=Z+re*d;let me=de;for(let we=0;we<s.inChannels;++we){const $e=x[pe+we*m];for(let Pe=0;Pe<s.outChannels;++Pe)A[ee+Pe*S]+=$e*I[me+Pe];me+=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=le(s.outShape,e.dtype),d=this.readSync(e.dataId),m=this.readSync(t.dataId),f=h.values;for(let y=0;y<s.batchSize;++y){const b=y*e.strides[0],S=y*h.strides[0];for(let x=0;x<s.outDepth;++x){const I=S+x*h.strides[1],A=x*s.strideDepth-c;for(let k=0;k<n;k++){const R=A+k*o;if(R<0||R>=s.inDepth)continue;const D=k*t.strides[0],F=b+R*e.strides[1];for(let M=0;M<s.outHeight;++M){const B=I+M*h.strides[2],V=M*s.strideHeight-u;for(let Y=0;Y<i;Y++){const G=V+Y*a;if(G<0||G>=s.inHeight)continue;const Z=D+Y*t.strides[1],q=F+G*e.strides[2];for(let ee=0;ee<s.outWidth;++ee){const Q=B+ee*s.outChannels,ie=ee*s.strideWidth-p;for(let re=0;re<r;re++){const de=ie+re*l;if(de<0||de>=s.inWidth)continue;const pe=Z+re*t.strides[2],me=q+de*s.inChannels;let we=pe;for(let $e=0;$e<s.inChannels;++$e){const Pe=d[me+$e];for(let ct=0;ct<s.outChannels;++ct)f[Q+ct]+=Pe*m[we+ct];we+=s.outChannels}}}}}}}}return h.toTensor()}conv2dDerInput(e,t,s){H([e,t],"conv2dDerInput");const n=le(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:y,outHeight:b,outWidth:S,strideHeight:x,strideWidth:I,dataFormat:A}=s,k=u-1-s.padInfo.top,R=h-1-s.padInfo.left,D=A==="channelsLast",F=n.strides[0],M=D?n.strides[1]:n.strides[2],B=D?n.strides[2]:1,V=D?1:n.strides[1],Y=e.strides[0],G=D?e.strides[1]:e.strides[2],Z=D?e.strides[2]:1,q=D?1:e.strides[1];for(let ee=0;ee<p;++ee)for(let Q=0;Q<d;++Q)for(let ie=0;ie<m;++ie){const re=ie-k,de=Math.max(0,Math.ceil(re/x)),pe=Math.min(b,(u+re)/x);for(let me=0;me<f;++me){const we=me-R,$e=Math.max(0,Math.ceil(we/I)),Pe=Math.min(S,(h+we)/I);let ct=0;for(let Rs=de;Rs<pe;++Rs){const xn=Rs*x-re;for(let kt=$e;kt<Pe;++kt){const Us=kt*I-we,ci=Y*ee+G*Rs+Z*kt,Ln=a*(u-1-xn)+l*(h-1-Us)+c*Q;for(let Os=0;Os<y;++Os){const tn=r[ci+q*Os],sl=o[Ln+Os];ct+=tn*sl}}}const Jt=F*ee+M*ie+B*me+V*Q;i[Jt]=ct}}return n.toTensor()}conv3dDerInput(e,t,s){const n=le(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,y,b,S]=t.strides,{batchSize:x,filterDepth:I,filterHeight:A,filterWidth:k,inChannels:R,inDepth:D,inHeight:F,inWidth:M,outChannels:B,outDepth:V,outHeight:Y,outWidth:G,strideDepth:Z,strideHeight:q,strideWidth:ee}=s,Q=I-1-s.padInfo.front,ie=A-1-s.padInfo.top,re=k-1-s.padInfo.left;for(let de=0;de<x;++de)for(let pe=0;pe<R;++pe)for(let me=0;me<D;++me){const we=me-Q,$e=Math.max(0,Math.ceil(we/Z)),Pe=Math.min(V,(I+we)/Z);for(let ct=0;ct<F;++ct){const Jt=ct-ie,Rs=Math.max(0,Math.ceil(Jt/q)),xn=Math.min(Y,(A+Jt)/q);for(let kt=0;kt<M;++kt){const Us=kt-re,ci=Math.max(0,Math.ceil(Us/ee)),Ln=Math.min(G,(k+Us)/ee);let Os=0;for(let tn=$e;tn<Pe;++tn){const sl=tn*Z-we;for(let Bo=Rs;Bo<xn;++Bo){const Po=Bo*q-Jt;for(let jo=ci;jo<Ln;++jo){const Jf=jo*ee-Us,Zf=p*de+u*tn+h*Bo+d*jo,MO=f*(I-1-sl)+y*(A-1-Po)+b*(k-1-Jf)+S*pe;for(let qu=0;qu<B;++qu){const UO=c[Zf+qu],$O=m[MO+qu];Os+=UO*$O}}}}i[r*de+o*me+a*ct+l*kt+pe]=Os}}}return n.toTensor()}conv2dDerFilter(e,t,s){H([e,t],"conv2dDerFilter");const n=s.strideHeight,i=s.strideWidth,r=s.filterHeight,o=s.filterWidth,a=s.dataFormat==="channelsLast",l=le(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 y=0;y<o;++y){const b=Math.max(0,Math.ceil((c-y)/i)),S=Math.min(s.outWidth,(s.inWidth+c-y)/i);for(let x=0;x<s.inChannels;++x)for(let I=0;I<s.outChannels;++I){let A=0;for(let k=0;k<s.batchSize;++k)for(let R=m;R<f;++R){const D=d+R*n-p;for(let F=b;F<S;++F){const M=y+F*i-c;a?A+=u.get(k,D,M,x)*h.get(k,R,F,I):A+=u.get(k,x,D,M)*h.get(k,I,R,F)}}l.set(A,d,y,x,I)}}}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=le(s.filterShape,"float32"),p=c.values,[u,h,d,m]=c.strides,f=this.readSync(t.dataId),[y,b,S,x]=t.strides,I=this.readSync(e.dataId),[A,k,R,D]=e.strides,F=s.padInfo.front,M=s.padInfo.left,B=s.padInfo.top;for(let V=0;V<o;++V){const Y=Math.max(0,Math.ceil((F-V)/n)),G=Math.min(s.outDepth,(s.inDepth+F-V)/n),Z=V*u;for(let q=0;q<a;++q){const ee=Math.max(0,Math.ceil((B-q)/i)),Q=Math.min(s.outHeight,(s.inHeight+B-q)/i),ie=q*h+Z;for(let re=0;re<l;++re){const de=Math.max(0,Math.ceil((M-re)/r)),pe=Math.min(s.outWidth,(s.inWidth+M-re)/r),me=re*d+ie;for(let we=0;we<s.inChannels;++we){const $e=we*m+me;for(let Pe=0;Pe<s.outChannels;++Pe){let ct=0;for(let Jt=0;Jt<s.batchSize;++Jt){const Rs=Jt*A,xn=Jt*y;for(let kt=Y;kt<G;++kt){const Us=V+kt*n-F,ci=Us*k+Rs,Ln=kt*b+xn;for(let Os=ee;Os<Q;++Os){const tn=q+Os*i-B,sl=tn*R+ci,Bo=Os*S+Ln;for(let Po=de;Po<pe;++Po){const jo=re+Po*r-M,Jf=jo*D+sl,Zf=Po*x+Bo;ct+=I[Jf+we]*f[Zf+Pe]}}}}p[$e+Pe]=ct}}}}}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=this.add(o,n)),i&&(o=Pw(this,o,i,r)),o}depthwiseConv2D(e,t,s){H([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=le(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],y=m*p.strides[0];for(let b=0;b<s.outHeight;++b){const S=y+b*p.strides[1],x=b*s.strideHeight-a;for(let I=0;I<n;++I){const A=x+I*r;if(A<0||A>=s.inHeight)continue;const k=I*t.strides[0],R=f+A*e.strides[1];for(let D=0;D<s.outWidth;++D){const F=S+D*p.strides[2],M=D*s.strideWidth-l;for(let B=0;B<i;++B){const V=M+B*o;if(V<0||V>=s.inWidth)continue;const Y=k+B*t.strides[1],G=R+V*s.inChannels;let Z=F,q=Y;for(let ee=0;ee<s.inChannels;++ee){const Q=u[G+ee];for(let ie=0;ie<c;++ie)d[Z+ie]+=Q*h[q+ie];Z+=c,q+=c}}}}}}return p.toTensor()}depthwiseConv2DDerInput(e,t,s){H([e,t],"depthwiseConv2DDerInput");const n=le(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:y,filterHeight:b,filterWidth:S,inChannels:x,inHeight:I,inWidth:A,outChannels:k,outHeight:R,outWidth:D,strideHeight:F,strideWidth:M}=s,B=b-1-s.padInfo.top,V=S-1-s.padInfo.left,Y=k/x;for(let G=0;G<y;++G)for(let Z=0;Z<x;++Z)for(let q=0;q<I;++q){const ee=q-B,Q=Math.max(0,Math.ceil(ee/F)),ie=Math.min(R,(b+ee)/F);for(let re=0;re<A;++re){const de=re-V,pe=Math.max(0,Math.ceil(de/M)),me=Math.min(D,(S+de)/M);let we=0;for(let $e=Q;$e<ie;++$e){const Pe=$e*F-ee;for(let ct=pe;ct<me;++ct){const Jt=ct*M-de,Rs=c*G+p*$e+u*ct,xn=d*(b-1-Pe)+m*(S-1-Jt)+f*Z;for(let kt=0;kt<Y;++kt){const Us=Z*Y+kt,ci=l[Rs+Us],Ln=h[xn+kt];we+=ci*Ln}}}i[r*G+o*q+a*re+Z]=we}}return n.toTensor()}depthwiseConv2DDerFilter(e,t,s){H([e,t],"depthwiseConv2DDerFilter");const n=s.strideHeight,i=s.strideWidth,r=s.filterHeight,o=s.filterWidth,a=le(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 y=0;y<o;++y){const b=Math.max(0,Math.ceil((l-y)/i)),S=Math.min(s.outWidth,(s.inWidth+l-y)/i);for(let x=0;x<s.outChannels;++x){const I=Math.trunc(x/p),A=x%p;let k=0;for(let R=0;R<s.batchSize;++R)for(let D=m;D<f;++D){const F=d+D*n-c;for(let M=b;M<S;++M){const B=y+M*i-l;k+=u.get(R,F,B,I)*h.get(R,D,M,x)}}a.set(k,d,y,I,A)}}}return a.toTensor()}tile(e,t){return H(e,"tile"),Ez(this.bufferSync(e),t)}pad(e,t,s){H(e,"pad");const n=t.map((a,l)=>a[0]+e.shape[l]+a[1]),i=t.map(a=>a[0]),r=this.bufferSync(e),o=le(n,e.dtype);s!==0&&o.values.fill(s);for(let a=0;a<e.size;a++){const l=r.indexToLoc(a),c=l.map((p,u)=>p+i[u]);o.set(r.get(...l),...c)}return o.toTensor()}gather(e,t,s){H([e,t],"gather");const n=e.shape.slice(),i=this.readSync(t.dataId);n[s]=i.length;const r=le(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){H([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)}spaceToBatchND(e,t,s){H([e],"spaceToBatchND");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)}maxPool(e,t){H(e,"maxPool");const s=this.readSync(e.dataId);return _u(s,e.shape,e.dtype,e.strides,t,"max").toTensor()}maxPoolBackprop(e,t,s,n){H([t,s],"maxPoolBackprop");const i=this.readSync(t.dataId),r=le(n.outShape,t.dtype,mf(i,t.shape,t.dtype,n).values),o=n.strideHeight,a=n.strideWidth,l=n.dilationHeight,c=n.dilationWidth,p=n.effectiveFilterHeight,u=n.effectiveFilterWidth,h=u-1-n.padInfo.left,d=p-1-n.padInfo.top,m=le(t.shape,"float32"),f=this.bufferSync(e);for(let y=0;y<n.batchSize;++y)for(let b=0;b<n.inChannels;++b)for(let S=0;S<n.inHeight;++S)for(let x=0;x<n.inWidth;++x){const I=S-d,A=x-h;let k=0;for(let R=0;R<p;R+=l){const D=(I+R)/o;if(D<0||D>=n.outHeight||Math.floor(D)!==D)continue;for(let F=0;F<u;F+=c){const M=(A+F)/a;if(M<0||M>=n.outWidth||Math.floor(M)!==M)continue;const B=p*u-1-r.get(y,D,M,b),V=R*u+F,Y=B===V?1:0;if(Y===0)continue;const G=f.get(y,D,M,b);k+=G*Y}}m.set(k,y,S,x,b)}return m.toTensor()}avgPoolBackprop(e,t,s){H([e,t],"avgPoolBackprop");const n=s.strideHeight,i=s.strideWidth,r=s.filterHeight,o=s.filterWidth,a=s.dilationHeight,l=s.dilationWidth,c=s.effectiveFilterHeight,p=s.effectiveFilterWidth,u=p-1-s.padInfo.left,h=c-1-s.padInfo.top,d=le(t.shape,"float32"),m=1/(r*o),f=this.bufferSync(e);for(let y=0;y<s.batchSize;++y)for(let b=0;b<s.inChannels;++b)for(let S=0;S<s.inHeight;++S)for(let x=0;x<s.inWidth;++x){const I=S-h,A=x-u;let k=0;for(let R=0;R<c;R+=a){const D=(I+R)/n;if(D<0||D>=s.outHeight||Math.floor(D)!==D)continue;for(let F=0;F<p;F+=l){const M=(A+F)/i;if(M<0||M>=s.outWidth||Math.floor(M)!==M)continue;const B=f.get(y,D,M,b);k+=B}}d.set(k*m,y,S,x,b)}return d.toTensor()}pool3d(e,t,s){H(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,y=this.readSync(e.dataId),b=le(t.outShape,e.dtype),S=b.values,x=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],I=t.outShape[2]*t.outShape[3]*t.outShape[4],A=t.outShape[3]*t.outShape[4],k=t.outShape[4];for(let R=0;R<t.batchSize;++R){const D=R*x,F=R*e.strides[0];for(let M=0;M<t.inChannels;++M)for(let B=0;B<t.outDepth;++B){const V=B*n-h;let Y=V;for(;Y<0;)Y+=o;const G=Math.min(t.inDepth,c+V),Z=D+B*I;for(let q=0;q<t.outHeight;++q){const ee=q*i-d;let Q=ee;for(;Q<0;)Q+=a;const ie=Math.min(t.inHeight,p+ee),re=Z+q*A;for(let de=0;de<t.outWidth;++de){const pe=de*r-m;let me=pe;for(;me<0;)me+=l;const we=Math.min(t.inWidth,u+pe),$e=re+de*k;let Pe=f,ct=0,Jt=0;for(let xn=Y;xn<G;xn+=o){const kt=F+xn*e.strides[1];for(let Us=Q;Us<ie;Us+=a){const ci=kt+Us*e.strides[2];for(let Ln=me;Ln<we;Ln+=l){const Os=ci+Ln*e.strides[3],tn=y[Os+M];if(s==="max"&&tn>Pe?Pe=tn:s==="avg"&&(ct+=tn,Jt++),isNaN(Pe))break}if(isNaN(Pe))break}if(isNaN(Pe))break}const Rs=$e+M;S[Rs]=s==="avg"?ct/Jt:Pe}}}}return b.toTensor()}avgPool3d(e,t){return H(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()}avgPool3dBackprop(e,t,s){H([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,y=m-1-s.padInfo.left,b=d-1-s.padInfo.top,S=le(t.shape,"float32"),x=1/(o*a*l),I=this.bufferSync(e);for(let A=0;A<s.batchSize;++A)for(let k=0;k<s.inChannels;++k)for(let R=0;R<s.inDepth;++R)for(let D=0;D<s.inHeight;++D)for(let F=0;F<s.inWidth;++F){const M=R-f,B=D-b,V=F-y;let Y=0;for(let G=0;G<h;G+=c){const Z=(M+G)/n;if(Z<0||Z>=s.outDepth||Math.floor(Z)!==Z)continue;for(let q=0;q<d;q+=p){const ee=(B+q)/i;if(ee<0||ee>=s.outHeight||Math.floor(ee)!==ee)continue;for(let Q=0;Q<m;Q+=u){const ie=(V+Q)/r;if(ie<0||ie>=s.outWidth||Math.floor(ie)!==ie)continue;const re=I.get(A,Z,ee,ie,k);Y+=re}}}S.set(Y*x,A,R,D,F,k)}return S.toTensor()}maxPool3d(e,t){return H(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()}maxPool3dPositions(e,t){const s=le(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 y=0;y<t.batchSize;++y)for(let b=0;b<t.inChannels;++b)for(let S=0;S<t.outDepth;++S){const x=S*n-h;let I=x;for(;I<0;)I+=o;const A=Math.min(t.inDepth,c+x);for(let k=0;k<t.outHeight;++k){const R=k*i-d;let D=R;for(;D<0;)D+=a;const F=Math.min(t.inHeight,p+R);for(let M=0;M<t.outWidth;++M){const B=M*r-m;let V=B;for(;V<0;)V+=l;const Y=Math.min(t.inWidth,u+B);let G=Number.NEGATIVE_INFINITY,Z=-1;for(let q=I;q<A;q+=o){const ee=q-x;for(let Q=D;Q<F;Q+=a){const ie=Q-R;for(let re=V;re<Y;re+=l){const de=re-B,pe=f.get(y,q,Q,re,b);pe>=G&&(G=pe,Z=ee*p*u+ie*p+de)}}}s.set(Z,y,S,k,M,b)}}}return s.toTensor()}maxPool3dBackprop(e,t,s,n){H([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,y=h-1-n.padInfo.top,b=le(t.shape,"float32"),S=this.bufferSync(i),x=this.bufferSync(e);for(let I=0;I<n.batchSize;++I)for(let A=0;A<n.inChannels;++A)for(let k=0;k<n.inDepth;++k)for(let R=0;R<n.inHeight;++R)for(let D=0;D<n.inWidth;++D){const F=k-m,M=R-y,B=D-f;let V=0;for(let Y=0;Y<u;Y+=l){const G=(F+Y)/r;if(G<0||G>=n.outDepth||Math.floor(G)!==G)continue;for(let Z=0;Z<h;Z+=c){const q=(M+Z)/o;if(q<0||q>=n.outHeight||Math.floor(q)!==q)continue;for(let ee=0;ee<d;ee+=p){const Q=(B+ee)/a;if(Q<0||Q>=n.outWidth||Math.floor(Q)!==Q)continue;const ie=u*h*d-1-S.get(I,G,q,Q,A),re=Y*h*d+Z*d+ee,de=ie===re?1:0;if(de===0)continue;const pe=x.get(I,G,q,Q,A);V+=pe*de}}}b.set(V,I,k,R,D,A)}return b.toTensor()}cast(e,t){return U.castTensor(e,t,this)}reshape(e,t){return U.reshapeTensor(e,t)}avgPool(e,t){H(e,"avgPool"),H(e,"maxPool");const s=this.readSync(e.dataId);return _u(s,e.shape,e.dtype,e.strides,t,"avg").toTensor().toFloat()}resizeBilinear(e,t,s,n){H(e,"resizeBilinear");const[i,r,o,a]=e.shape,l=this.readSync(e.dataId),c=new Float32Array(E.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 y=0;y<t;y++){const b=d*y,S=Math.floor(b),x=b-S,I=Math.min(r-1,Math.ceil(b)),A=f*e.strides[0]+S*e.strides[1],k=f*e.strides[0]+I*e.strides[1];for(let R=0;R<s;R++){const D=m*R,F=Math.floor(D),M=D-F,B=Math.min(o-1,Math.ceil(D)),V=A+F*e.strides[2],Y=k+F*e.strides[2],G=A+B*e.strides[2],Z=k+B*e.strides[2];for(let q=0;q<a;q++){const ee=l[V+q],Q=l[Y+q],ie=l[G+q],re=l[Z+q],de=ee+(ie-ee)*M,pe=Q+(re-Q)*M,me=de+(pe-de)*x;c[h++]=me}}}return ze(c,[i,t,s,a])}resizeBilinearBackprop(e,t,s){H([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 y=0;y<n;y++){const b=y*t.strides[0];for(let S=0;S<a;S++){const x=S*h,I=Math.floor(x),A=Math.min(Math.ceil(x),i-1),k=b+I*t.strides[1],R=b+A*t.strides[1],D=x-I,F=1-D;for(let M=0;M<l;M++){const B=M*d,V=Math.floor(B),Y=Math.min(Math.ceil(B),r-1),G=B-V,Z=1-G,q=k+V*t.strides[2],ee=k+Y*t.strides[2],Q=R+V*t.strides[2],ie=R+Y*t.strides[2],re=F*Z,de=F*G,pe=D*Z,me=D*G;for(let we=0;we<o;we++){const $e=m[f++];c[q+we]+=$e*re,c[ee+we]+=$e*de,c[Q+we]+=$e*pe,c[ie+we]+=$e*me}}}}return cs(c,[n,r,i,o],t.dtype)}resizeNearestNeighbor(e,t,s,n){H(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 y=f*e.strides[0];for(let b=0;b<t;b++){const S=h*b,x=Math.min(r-1,n?Math.round(S):Math.floor(S)),I=y+x*e.strides[1];for(let A=0;A<s;A++){const k=d*A,R=Math.min(o-1,n?Math.round(k):Math.floor(k)),D=I+R*e.strides[2];for(let F=0;F<a;F++){const M=l[D+F];c[m++]=M}}}}return ze(c,[i,t,s,a],e.dtype)}resizeNearestNeighborBackprop(e,t,s){H([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,y=1/m,b=Math.ceil(f)*2+2,S=Math.ceil(y)*2+2;for(let x=0;x<n;x++){const I=x*t.strides[0];for(let A=0;A<i;A++){const k=I+A*t.strides[1],R=Math.floor(A*f),D=Math.floor(R-b/2);for(let F=0;F<r;F++){const M=k+F*t.strides[2],B=Math.floor(F*y),V=Math.floor(B-S/2);for(let Y=0;Y<o;Y++){let G=0;for(let Z=0;Z<b;Z++){const q=Z+D;if(q<0||q>=a)continue;const ee=I+q*e.strides[1],Q=q*d,ie=Math.min(i-1,s?Math.round(Q):Math.floor(Q));if(A!==ie)continue;for(let re=0;re<S;re++){const de=re+V;if(de<0||de>=l)continue;const pe=ee+de*e.strides[2],me=de*m,we=Math.min(r-1,s?Math.round(me):Math.floor(me));F===we&&(G+=p[pe+Y])}}c[M+Y]=G}}}}return cs(c,t.shape,t.dtype)}batchNorm(e,t,s,n,i,r){H([e,t,s,i,n],"batchNorm");const o=this.readSync(e.dataId),a=this.readSync(t.dataId),l=this.readSync(s.dataId),c=i?this.readSync(i.dataId):new Float32Array([1]),p=n?this.readSync(n.dataId):new Float32Array([0]),u=new Float32Array(o.length),h=p.length,d=c.length,m=l.length,f=a.length;let y=0,b=0,S=0,x=0;for(let I=0;I<o.length;++I)u[I]=p[y++]+(o[I]-a[b++])*c[S++]/Math.sqrt(l[x++]+r),y>=h&&(y=0),b>=f&&(b=0),S>=d&&(S=0),x>=m&&(x=0);return cs(u,e.shape)}localResponseNormalization4D(e,t,s,n,i){H(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 y=a[d];f+=y*y}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 cs(c,e.shape)}LRNGrad(e,t,s,n,i,r,o){H(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),y=d-m+Math.min(a,m+n+1);let b=0;for(let S=f;S<y;S++)b+=Math.pow(c[S],2);b=r*b+i;for(let S=f;S<y;S++){let x=-2*r*o*c[S]*p[d]/b;d===S&&(x+=Math.pow(b,-o)),x*=l[d],u[S]+=x}}return cs(u,e.shape)}multinomial(e,t,s,n){H(e,"multinomial");const i=t?e:Yt(e),r=i.shape[0],o=i.shape[1],a=Ie([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=sC.alea(n.toString()),m=p*s;for(let f=0;f<s;++f){const y=d();l[m+f]=h.length;for(let b=0;b<h.length;b++)if(y<h[b]){l[m+f]=b;break}}}return a}oneHot(e,t,s,n){H(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 ts(i,[e.size,t],"int32")}nonMaxSuppression(e,t,s,n,i){H(e,"nonMaxSuppression");const r=this.readSync(e.dataId),o=this.readSync(t.dataId);return Rz(r,o,s,n,i)}fft(e){return this.fftBatch(e,!1)}ifft(e){return this.fftBatch(e,!0)}fftBatch(e,t){const s=e.shape[0],n=e.shape[1],i=le(e.shape,"float32"),r=le(e.shape,"float32"),o=$t(e).as2D(s,n),a=Ht(e).as2D(s,n);for(let c=0;c<s;c++){const p=o.slice([c,0],[1,n]),u=a.slice([c,0],[1,n]),h=Ze(p,u),d=this.readSync(this.fftImpl(h,t).dataId);for(let m=0;m<n;m++){const f=U.getComplexWithIndex(d,m);i.values[c*n+m]=f.real,r.values[c*n+m]=f.imag}}const l=Ze(i.toTensor(),r.toTensor());return l.as2D(s,n)}fftImpl(e,t){const s=e.as1D(),n=s.size;if(this.isExponentOf2(n)){let i=this.fftRadix2(s,n,t).as2D(e.shape[0],e.shape[1]);return t&&(i=Ze($t(i).div(j(n)),Ht(i).div(j(n)))),i}else{const i=this.readSync(e.dataId),r=this.fourierTransformByMatmul(i,n,t),o=U.splitRealAndImagArrays(r);return Ze(o.real,o.imag).as2D(e.shape[0],e.shape[1])}}isExponentOf2(e){return(e&e-1)===0}fftRadix2(e,t,s){if(t===1)return e;const n=this.readSync(e.dataId),i=t/2,r=U.complexWithEvenIndex(n);let o=Ze(r.real,r.imag).as1D();const a=U.complexWithOddIndex(n);let l=Ze(a.real,a.imag).as1D();o=this.fftRadix2(o,i,s),l=this.fftRadix2(l,i,s);const c=U.exponents(t,s),p=Ze(c.real,c.imag).mul(l),u=o.add(p),h=o.sub(p),d=$t(u).concat($t(h)),m=Ht(u).concat(Ht(h));return Ze(d,m).as1D()}fourierTransformByMatmul(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}depthToSpace(e,t,s){E.assert(s==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${s}`),E.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),y=m%t;for(let b=0;b<l;++b){const S=Math.floor(b/t),x=b%t,I=(y*t+x)*c;for(let A=0;A<c;++A){const k=A+I,R=k+o*(S+r*(f+i*d));u[h++]=p[R]}}}return cs(u,[n,a,l,c])}broadcastedBinaryOp(e,t,s,n){const i=U.assertAndGetBroadcastShape(e.shape,t.shape),r=le(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 y=u.locToIndex(f),b=m.slice(-t.rank);c.forEach(x=>b[x]=0);const S=h.locToIndex(b);p[d]=n(o[y],a[S])}}return r.toTensor()}broadcastedBinaryComplexOp(e,t,s){const n=U.assertAndGetBroadcastShape(e.shape,t.shape),i=le(n,"float32"),r=le(n,"float32"),o=this.readSync(e.dataId),a=this.readSync(t.dataId),l=U.getBroadcastDims(e.shape,n),c=U.getBroadcastDims(t.shape,n),p=i.values,u=r.values;if(l.length+c.length===0)for(let h=0;h<p.length;h++){const d=h%o.length,m=h%a.length,f=s(o[d*2],o[d*2+1],a[m*2],a[m*2+1]);p[h]=f.real,u[h]=f.imag}else{const h=this.bufferSync(this.data.get(e.dataId).complexTensors.real),d=this.bufferSync(this.data.get(t.dataId).complexTensors.real);for(let m=0;m<p.length;m++){const f=i.indexToLoc(m),y=f.slice(-e.rank);l.forEach(A=>y[A]=0);const b=h.locToIndex(y),S=f.slice(-t.rank);c.forEach(A=>S[A]=0);const x=d.locToIndex(S),I=s(o[b*2],o[b*2+1],a[x*2],a[x*2+1]);p[m]=I.real,u[m]=I.imag}}return this.complex(i.toTensor(),r.toTensor())}split(e,t,s){return Oz(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=le([p,u,h,c],"float32"),m=this.readSync(t.dataId),f=this.readSync(s.dataId),y=this.readSync(e.dataId),b=e.strides,S=d.strides;for(let x=0;x<p;x++){const I=x*4,A=m[I],k=m[I+1],R=m[I+2],D=m[I+3],F=f[x];if(F>=o)continue;const M=u>1?(R-A)*(a-1)/(u-1):0,B=h>1?(D-k)*(l-1)/(h-1):0;for(let V=0;V<u;V++){const Y=u>1?A*(a-1)+V*M:.5*(A+R)*(a-1);if(Y<0||Y>a-1){for(let G=0;G<h;G++)for(let Z=0;Z<c;Z++){const q=Z+G*S[2]+V*S[1]+x*S[0];d.values[q]=r}continue}if(i==="bilinear"){const G=Math.floor(Y),Z=Math.ceil(Y),q=Y-G;for(let ee=0;ee<h;ee++){const Q=h>1?k*(l-1)+ee*B:.5*(k+D)*(l-1);if(Q<0||Q>l-1){for(let pe=0;pe<c;pe++){const me=pe+ee*S[2]+V*S[1]+x*S[0];d.values[me]=r}continue}const ie=Math.floor(Q),re=Math.ceil(Q),de=Q-ie;for(let pe=0;pe<c;pe++){let me=pe+ie*b[2]+G*b[1]+F*b[0];const we=y[me];me=pe+re*b[2]+G*b[1]+F*b[0];const $e=y[me];me=pe+ie*b[2]+Z*b[1]+F*b[0];const Pe=y[me];me=pe+re*b[2]+Z*b[1]+F*b[0];const ct=y[me],Jt=we+($e-we)*de,Rs=Pe+(ct-Pe)*de;me=pe+ee*S[2]+V*S[1]+x*S[0],d.values[me]=Jt+(Rs-Jt)*q}}}else for(let G=0;G<h;++G){const Z=h>1?k*(l-1)+G*B:.5*(k+D)*(l-1);if(Z<0||Z>l-1){for(let Q=0;Q<c;Q++){const ie=Q+G*S[2]+V*S[1]+x*S[0];d.values[ie]=r}continue}const q=Math.round(Z),ee=Math.round(Y);for(let Q=0;Q<c;Q++){const ie=Q+q*b[2]+ee*b[1]+F*b[0],re=Q+G*S[2]+V*S[1]+x*S[0];d.values[re]=y[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 fi([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||E.inferDtype(t);const n=E.getArrayFromDType(s,E.sizeFromShape(e));return n.fill(t),os().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=E.getArrayFromDType(e.dtype,E.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 fi(p,t.dtype);d.values.fill(this.readSync(l.dataId)[0]);for(let m=0;m<r;m++){const f=[];let y=0;for(let b=0;b<o;b++){const S=u[m*o+b];f.push(S),y+=S*a[b]}if(y<0||y>=n/i)throw new Error(`Invalid indices: ${f} does not index into ${s}`);for(let b=0;b<i;b++)c?d.values[y*i+b]+=h[m*i+b]:d.values[y*i+b]=t.rank===0?h[0]:h[m*i+b]}return d.toTensor().reshape(s)}}function ff(e,t,s,n){const i=E.getTypedArrayFromDType(n,E.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}function Ma(e,t,s,n,i){const r=t.length,o=E.sizeFromShape(t),a=E.computeStrides(t),l=E.computeStrides(i),c=E.getTypedArrayFromDType(s,E.sizeFromShape(i));for(let p=0;p<o;++p){const u=E.indexToLoc(p,r,a),h=new Array(u.length);for(let m=0;m<h.length;m++)h[m]=u[n[m]];const d=E.locToIndex(h,r,l);c[d]=e[p]}return c}const Vw={};Re(Vw,{maxImpl:()=>ff,transposeImpl:()=>Ma});const Gw="2.3.0";dp("cpu",()=>new jw(),1);const nC={kernelName:_r,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=E.toNestedArray(n.shape,l.data.get(n.dataId).values),p=E.toNestedArray(i.shape,l.data.get(i.dataId).values),{batchSize:u,inHeight:h,inWidth:d,inChannels:m,outHeight:f,outWidth:y,padInfo:b,strideHeight:S,strideWidth:x,filterHeight:I,filterWidth:A,dilationHeight:k,dilationWidth:R,outShape:D}=U.computeDilation2DInfo(n.shape,i.shape,r,o,"NHWC",a),F=E.makeZerosNestedTypedArray(D,n.dtype);for(let B=0;B<u;++B)for(let V=0;V<f;++V){const Y=V*S-b.top;for(let G=0;G<y;++G){const Z=G*x-b.left;for(let q=0;q<m;++q){let ee=Number.MIN_SAFE_INTEGER;for(let Q=0;Q<I;++Q){const ie=Y+Q*k;if(ie>=0&&ie<h)for(let re=0;re<A;++re){const de=Z+re*R;if(de>=0&&de<d){const pe=c[B][ie][de][q]+p[Q][re][q];pe>ee&&(ee=pe)}}}F[B][V][G][q]=ee}}}const M=l.write(E.toTypedArray(F,n.dtype),D,n.dtype);return{dataId:M,shape:D,dtype:n.dtype}}};const iC={kernelName:ea,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=E.toNestedArray(n.shape,c.data.get(n.dataId).values),u=E.toNestedArray(i.shape,c.data.get(i.dataId).values),{batchSize:h,inHeight:d,inWidth:m,inChannels:f,outHeight:y,outWidth:b,padInfo:S,strideHeight:x,strideWidth:I,filterHeight:A,filterWidth:k,dilationHeight:R,dilationWidth:D,outShape:F}=U.computeDilation2DInfo(n.shape,i.shape,o,a,"NHWC",l);E.assert(r.rank===F.length,()=>`Error in ${ea}, dy must have the same rank as output ${F.length}, but got ${r.rank}`);const M=E.toNestedArray(F,c.data.get(r.dataId).values),B=E.makeZerosNestedTypedArray(i.shape,i.dtype);for(let Y=0;Y<h;++Y)for(let G=0;G<y;++G){const Z=G*x-S.top;for(let q=0;q<b;++q){const ee=q*I-S.left;for(let Q=0;Q<f;++Q){let ie=Number.MIN_SAFE_INTEGER,re=0,de=0;for(let pe=0;pe<A;++pe){const me=Z+pe*R;if(me>=0&&me<d)for(let we=0;we<k;++we){const $e=ee+we*D;if($e>=0&&$e<m){const Pe=p[Y][me][$e][Q]+u[pe][we][Q];Pe>ie&&(ie=Pe,re=pe,de=we)}}}B[re][de][Q]+=M[Y][G][q][Q]}}}const V=c.write(E.toTypedArray(B,n.dtype),i.shape,i.dtype);return{dataId:V,shape:i.shape,dtype:i.dtype}}};const rC={kernelName:Qo,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=E.toNestedArray(n.shape,c.data.get(n.dataId).values),u=E.toNestedArray(i.shape,c.data.get(i.dataId).values),{batchSize:h,inHeight:d,inWidth:m,inChannels:f,outHeight:y,outWidth:b,padInfo:S,strideHeight:x,strideWidth:I,filterHeight:A,filterWidth:k,dilationHeight:R,dilationWidth:D,outShape:F}=U.computeDilation2DInfo(n.shape,i.shape,o,a,"NHWC",l);E.assert(r.rank===F.length,()=>`Error in ${Qo}, dy must have the same rank as output ${F.length}, but got ${r.rank}`);const M=E.toNestedArray(F,c.data.get(r.dataId).values),B=E.makeZerosNestedTypedArray(n.shape,n.dtype);for(let Y=0;Y<h;++Y)for(let G=0;G<y;++G){const Z=G*x-S.top;for(let q=0;q<b;++q){const ee=q*I-S.left;for(let Q=0;Q<f;++Q){let ie=Number.MIN_SAFE_INTEGER,re=Z<0?0:Z,de=ee<0?0:ee;for(let pe=0;pe<A;++pe){const me=Z+pe*R;if(me>=0&&me<d)for(let we=0;we<k;++we){const $e=ee+we*D;if($e>=0&&$e<m){const Pe=p[Y][me][$e][Q]+u[pe][we][Q];Pe>ie&&(ie=Pe,re=me,de=$e)}}}B[Y][re][de][Q]+=M[Y][G][q][Q]}}}const V=c.write(E.toTypedArray(B,n.dtype),n.shape,n.dtype);return{dataId:V,shape:n.shape,dtype:n.dtype}}};function gf(e,t){return{kernelName:e,backendName:"cpu",kernelFunc:({inputs:s,backend:n})=>{const{a:i,b:r}=s,o=n;H([i,r],e);const a=o.data.get(i.dataId).values,l=o.data.get(r.dataId).values,[c,p]=t(i.shape,r.shape,a,l,i.dtype),u=o.write(c,p,i.dtype);return{dataId:u,shape:p,dtype:i.dtype}}}}function yf(e){return(t,s,n,i,r)=>{const o=U.assertAndGetBroadcastShape(t,s),a=o.length,l=E.computeStrides(o),c=E.sizeFromShape(o),p=E.getTypedArrayFromDType(r,c),u=t.length,h=s.length,d=E.computeStrides(t),m=E.computeStrides(s),f=U.getBroadcastDims(t,o),y=U.getBroadcastDims(s,o);if(f.length+y.length===0)for(let b=0;b<p.length;++b)p[b]=e(n[b%n.length],i[b%i.length]);else for(let b=0;b<p.length;++b){const S=E.indexToLoc(b,a,l),x=S.slice(-u);f.forEach(R=>x[R]=0);const I=E.locToIndex(x,u,d),A=S.slice(-h);y.forEach(R=>A[R]=0);const k=E.locToIndex(A,h,m);p[b]=e(n[I],i[k])}return[p,o]}}const oC=yf((e,t)=>e/t);const aC=gf(ui,oC);const lC={kernelName:Dr,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,i=s,r=E.getTypedArrayFromDType(n.dtype,E.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 y=0;y<l;y++){const b=y*c;for(let S=0;S<c;S++){const x=[o,m,y,S],I=x[2],A=Math.round(l-I),k=d+f+b+S;let R=p[k];if(A>=0&&A<l){const D=A*c,F=d+f+D+S;R=p[F]}r[k]=R}}}}const u=i.write(r,n.shape,n.dtype);return{dataId:u,shape:n.shape,dtype:n.dtype}}};const cC={kernelName:hi,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=E.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 I=0;I<x.length;I++)x[I]=a[u[I]];h=Ma(h,a,n.dtype,u,x),p=U.getInnerMostAxes(p.length,l),a=x}H(n,"max"),U.assertAxesAreInnerMostDims("max",p,l);const[d,m]=U.computeOutAndReduceShapes(a,p),f=E.sizeFromShape(m),y=ff(h,f,d,n.dtype),b=o.write(y,d,n.dtype);let S=d;if(r){const x=U.expandShapeToKeepDim(d,c);S=x}return{dataId:b,shape:S,dtype:n.dtype}}};function pC(e,t,s,n,i){const r=E.computeStrides(t),o=_u(e,t,s,r,i,"max"),a=mf(e,t,s,i,!0,n);return[o.values,a.values]}const uC={kernelName:Fr,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{filterSize:i,strides:r,pad:o,includeBatchInIndex:a}=t,l=s;H(n,"MaxPoolWithArgmax");const c=l.data.get(n.dataId).values,p=U.computePool2DInfo(n.shape,i,r,[1,1],o),[u,h]=pC(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 Dz=St.nonMaxSuppressionV4Impl,hC={kernelName:Mr,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;H(n,"NonMaxSuppressionPadded");const p=c.data.get(n.dataId).values,u=c.data.get(i.dataId).values,{selectedIndices:h,validOutputs:d}=Dz(p,u,r,o,a,l);return[h,d]}};const Fz=St.nonMaxSuppressionV5Impl,dC={kernelName:Ur,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;H(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:y,selectedScores:b}=Fz(p,u,h,d,m,f);return[y,b]}};const mC={kernelName:Wr,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,{radians:i,fillValue:r,center:o}=t,a=s,l=E.getTypedArrayFromDType(n.dtype,E.sizeFromShape(n.shape)),[c,p,u,h]=n.shape,[d,m]=U.getImageCenter(o,p,u),f=255,y=Math.sin(i),b=Math.cos(i),S=a.data.get(n.dataId).values;for(let I=0;I<c;I++){const A=I*u*p*h;for(let k=0;k<p;k++){const R=k*(u*h);for(let D=0;D<u;D++){const F=D*h;for(let M=0;M<h;M++){const B=[c,k,D,M],V=B[2],Y=B[1];let G=(V-d)*b-(Y-m)*y,Z=(V-d)*y+(Y-m)*b;G=Math.round(G+d),Z=Math.round(Z+m);let q=r;if(typeof r!="number"&&(M===3?q=f:q=r[M]),G>=0&&G<u&&Z>=0&&Z<p){const Q=Z*(u*h),ie=G*h,re=A+Q+ie+M;q=S[re]}const ee=A+R+F+M;l[ee]=q}}}}const x=a.write(l,n.shape,n.dtype);return{dataId:x,shape:n.shape,dtype:n.dtype}}};const fC={kernelName:$r,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:s}=e,n=t;H(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 Mz=yf((e,t)=>{const s=e-t;return s*s}),gC=gf(di,Mz);const yC={kernelName:mi,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{perm:i}=t,r=s;H(n,"transpose");const o=n.shape.length,a=new Array(o);for(let u=0;u<a.length;u++)a[u]=n.shape[i[u]];const l=r.data.get(n.dataId).values,c=Ma(l,n.shape,n.dtype,i,a),p=r.write(c,a,n.dtype);return{dataId:p,shape:a,dtype:n.dtype}}};const Uz=[nC,rC,iC,aC,lC,uC,cC,hC,dC,mC,fC,gC,yC];for(const e of Uz)Yc(e);const ko={},Hw={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function qw(e,t){ko[e]=t}function Js(e){e in ko||(ko[e]=$z(e));const t=ko[e];return t.isContextLost()?(delete ko[e],Js(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),ko[e])}function Wz(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 $z(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=Wz(e);return t.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete ko[e]},!1),e===1?t.getContext("webgl",Hw)||t.getContext("experimental-webgl",Hw):t.getContext("webgl2",Hw)}var wr;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(wr||(wr={}));var ns;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(ns||(ns={}));var Kt;(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"})(Kt||(Kt={}));function _o(e,t){return[t,e]}function bC(e,t){return e*t}function xr(e){const t=E.sizeFromShape(e),s=Math.ceil(t/4);return E.sizeToSquarishShape(s)}function oi(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function wC(e,t){const[s,n]=oi(e,t);return s*n*4}function Du(e,t){const s=e;let n,i,r,o,a,l,c,p,u,h;return $().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 oe(e,t){const s=t();return $().getBool("DEBUG")&&zz(e),s}function zz(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+Bz(e,t))}const Pz=596e-10,jz=65504;function xC(e){return!!($().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||Pz<Math.abs(e)&&Math.abs(e)<jz)}function Bz(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 Fu(e,t){return Pi(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function LC(e,t){const s=Pi(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(oe(e,()=>e.shaderSource(s,t)),oe(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 SC(e,t){const s=Pi(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(oe(e,()=>e.shaderSource(s,t)),oe(e,()=>e.compileShader(s)),e.getShaderParameter(s,e.COMPILE_STATUS)===!1)throw Vz(t,e.getShaderInfoLog(s)),new Error("Failed to compile fragment shader.");return s}const Gz=/ERROR: [0-9]+:([0-9]+):/g;function Vz(e,t){const s=Gz.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)=>E.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 ${E.rightPad(c[0],a)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join(`
`))}function vC(e){return Pi(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function TC(e,t){if(oe(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 bf(e,t){if(oe(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function IC(e,t){const s=Pi(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return oe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),oe(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),s}function AC(e,t){const s=Pi(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return oe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,s)),oe(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),s}function NC(e){return Pi(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function CC(e,t){const s=$().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 RC(e){return Pi(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Yw(e,t,s,n,i,r,o){const a=e.getAttribLocation(t,s);return a===-1?!1:(oe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),oe(e,()=>e.vertexAttribPointer(a,i,e.FLOAT,!1,r,o)),oe(e,()=>e.enableVertexAttribArray(a)),!0)}function qz(e,t,s){Hz(e,s),oe(e,()=>e.activeTexture(e.TEXTURE0+s)),oe(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function OC(e,t,s){return Pi(e,()=>e.getUniformLocation(t,s),'uniform "'+s+'" not present in program.')}function EC(e,t,s){return e.getUniformLocation(t,s)}function kC(e,t,s,n){oe(e,()=>qz(e,t,n)),oe(e,()=>e.uniform1i(s,n))}function wf(e,t,s){oe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,s)),oe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Kw(e,t){oe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),oe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Mu(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Yz(e,t))}function Yz(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 Pi(e,t,s){const n=oe(e,()=>t());if(n==null)throw new Error(s);return n}function Hz(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 Lr(e,t=2){return E.sizeFromShape(e.slice(0,e.length-t))}function Sr(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 xf(e){let t=[1,1,1];const s=e.length===0||e.length===1&&e[0]===1;return s||(t=[Lr(e),...Sr(e)]),t}function _C(e,t=!1){let s=$().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(s=s*2,e=e.map((i,r)=>r>=e.length-2?E.nearestLargerEven(e[r]):e[r]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=E.squeezeShape(e);e=i.newShape}let n=E.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=Lr(e);let r=2,o=2;return e.length&&([r,o]=Sr(e)),n=i*(r/2)*(o/2),E.sizeToSquarishShape(n).map(a=>a*2)}return E.sizeToSquarishShape(n)}function Lf(e){return e%2===0}function vr(e,t){if(e=e.slice(-2),t=t.slice(-2),E.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(Lf(s)&&Lf(n)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Lf(e[0])&&Lf(t[0])}let Xw,Jw;function DC(e){if(Xw==null){const t=Js(e);Xw=t.getParameter(t.MAX_TEXTURE_SIZE)}return Xw}function FC(e){if(Jw==null){const t=Js(e);Jw=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Jw)}function MC(e){if(e===0)return 0;let t;const s=Js(e);return Zs(s,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Zs(s,"EXT_disjoint_timer_query")?t=1:t=0,t}function Zs(e,t){const s=e.getExtension(t);return s!=null}function Zw(e){try{const t=Js(e);if(t!=null)return!0}catch(t){return!1}return!1}function UC(e){if(e===0)return!1;const t=Js(e);if(e===1){if(!Zs(t,"OES_texture_float"))return!1}else if(!Zs(t,"EXT_color_buffer_float"))return!1;const s=Qw(t);return s}function $C(e){if(e===0)return!1;const t=Js(e);if(e===1){if(!Zs(t,"OES_texture_float"))return!1;if(!Zs(t,"WEBGL_color_buffer_float"))return!1}else{if(Zs(t,"EXT_color_buffer_float"))return Qw(t);const n="EXT_color_buffer_half_float";if(Zs(t,n)){const i=t.getExtension(n);return Kz(t,i)}return!1}const s=Qw(t);return s}function Qw(e){const t=Du(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 Kz(e,t){const s=Du(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 WC(e){if(e!==2)return!1;const t=Js(e),s=t.fenceSync!=null;return s}const ve=$();ve.registerFlag("HAS_WEBGL",()=>ve.getNumber("WEBGL_VERSION")>0);ve.registerFlag("WEBGL_VERSION",()=>Zw(2)?2:Zw(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",()=>DC(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>FC(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=ve.getNumber("WEBGL_VERSION");return e===0?0:MC(e)});ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>ve.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!la.isMobile());ve.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>UC(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",()=>$C(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_FENCE_API_ENABLED",()=>WC(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}.`)});class zC{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 BC{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 PC{constructor(e,t,s){this.variableNames=["A"];const n=e.windowSize,i=e.batchSize,r=e.inSize,o=Math.ceil(r/n);s||this.variableNames.push("bestIndicesA"),this.outputShape=[i,o];const a=t==="max"?">":"<",l=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 = ${l};
float candidate = getA(batch, inIdx);
if (candidate ${a} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}}function ex(e,t){return["x","y","z","w","u","v"].slice(0,t).map(s=>`${e}.${s}`)}function Et(e,t){return t===1?[e]:ex(e,t)}function jC(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 ot(){let e,t,s,n,i,r,o,a,l,c;return $().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 zn(e,t,s="index"){const n=E.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 Ua(e){const t=E.computeStrides(e).map(s=>s.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}const Sf=`
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:VC}=U;function GC(e,t,s,n){const i=[];e.forEach(m=>{const f=E.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=>Xz(m,t,n)).join(`
`),a=t.texShape,l=ot(),c=Qz(l);let p,u,h=sB(l);t.isPacked?(p=Jz(t.logicalShape,a),u=tB(l)):(p=Zz(t.logicalShape,a),u=eB(l)),n&&(h+=nB);const d=[h,c,u,r,p,o,s].join(`
`);return d}function $a(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return iB(e);case 1:return rB(e);case 2:return oB(e);case 3:return aB(e);case 4:return lB(e);case 5:return cB(e);case 6:return pB(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function HC(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return uB(e);case 1:return hB(e);case 2:return dB(e);case 3:return mB(e);default:return fB(e)}}function Xz(e,t,s=!1){let n="";s?n+=HC(e):n+=$a(e);const i=e.shapeInfo.logicalShape,r=t.logicalShape;return i.length<=r.length&&(s?n+=gB(e,t):n+=yB(e,t)),n}function Jz(e,t){switch(e.length){case 0:return qC();case 1:return bB(e,t);case 2:return LB(e,t);case 3:return wB(e,t);default:return xB(e,t)}}function Zz(e,t){switch(e.length){case 0:return qC();case 1:return SB(e,t);case 2:return NB(e,t);case 3:return vB(e,t);case 4:return TB(e,t);case 5:return IB(e,t);case 6:return AB(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function Qz(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function eB(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function tB(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function sB(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);
}
${CB}
${RB}
${OB}
`;return t}const CB=`
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);
}
`,RB=`
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);
}
`,OB=`
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);
}
`,nB=`
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 qC(){return`
int getOutputCoords() {
return 0;
}
`}function bB(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 SB(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 wB(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 vB(e,t){const s=zn(["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 xB(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 TB(e,t){const s=zn(["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 IB(e,t){const s=zn(["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 AB(e,t){const s=zn(["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 LB(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(E.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 NB(e,t){return E.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 Do(e){return`offset${e}`}function uB(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1),n=ot();return`
vec4 ${s}() {
return ${n.texture2D}(${t}, halfCR);
}
`}function iB(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=Do(t);return`
float ${s}() {
vec2 uv = uvFromFlat(${r}, ${o}, ${a});
return sampleTexture(${t}, uv);
}
`}function hB(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=ot();return`
vec4 ${s}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${r.texture2D}(${t}, uv);
}
`}function rB(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${s}(int index) {
${Wa(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=Do(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 dB(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=ot();if(i!=null&&E.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 oB(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&&E.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}=E.squeezeShape(t),a=r;if(a.length<t.length){const u=za(e,a),h=["row","col"];return`
${$a(u)}
float ${n}(int row, int col) {
return ${n}(${Ba(h,o)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${Wa(e)}
}
`;const l=i[0],c=i[1],p=Do(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 mB(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=za(e,u),m=["b","row","col"];return`
${HC(d)}
vec4 ${n}(int b, int row, int col) {
return ${n}(${Ba(m,h)});
}
`}const o=r[0],a=r[1],l=Math.ceil(t[2]/2),c=l*Math.ceil(t[1]/2),p=ot();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 aB(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}=E.squeezeShape(t),l=o;if(l.length<t.length){const m=za(e,l),f=["row","col","depth"];return`
${$a(m)}
float ${n}(int row, int col, int depth) {
return ${n}(${Ba(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)));
${Wa(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=Do(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 fB(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=ot();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 lB(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}=E.squeezeShape(t);if(a.length<t.length){const m=za(e,a),f=["row","col","depth","depth2"];return`
${$a(m)}
float ${n}(int row, int col, int depth, int depth2) {
return ${n}(${Ba(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)));
${Wa(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=Do(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 cB(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}=E.squeezeShape(t);if(l.length<t.length){const f=za(e,l),y=["row","col","depth","depth2","depth3"];return`
${$a(f)}
float ${n}(int row, int col, int depth, int depth2, int depth3) {
return ${n}(${Ba(y,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;
${Wa(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=Do(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 pB(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),{newShape:i,keptDims:r}=E.squeezeShape(t);if(i.length<t.length){const y=za(e,i),b=["row","col","depth","depth2","depth3","depth4"];return`
${$a(y)}
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${n}(${Ba(b,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)));
${Wa(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=Do(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 Wa(e){const t=e.name,s=E.sizeFromShape(e.shapeInfo.logicalShape);return s<2?`return ${t};`:`
for (int i = 0; i < ${s}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function gB(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=VC(e.shapeInfo.logicalShape,t.logicalShape),l=Ce(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(S=>`coords.${u[S+c]} = 0;`).join(`
`);let h="";o<2&&r>0?h="coords":h=e.shapeInfo.logicalShape.map((S,x)=>`coords.${u[x+c]}`).join(", ");let d="return outputValue;";const m=E.sizeFromShape(e.shapeInfo.logicalShape),f=m===1,y=E.sizeFromShape(t.logicalShape),b=y===1;if(r===1&&!f&&!b)d=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(f&&!b)o===1?d=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:d=`
return vec4(outputValue.x);
`;else if(a.length){const S=r-2,x=r-1;a.indexOf(S)>-1&&a.indexOf(x)>-1?d="return vec4(outputValue.x);":a.indexOf(S)>-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 yB(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&&E.arraysEqual(o,r))return`
float ${i}() {
return sampleTexture(${s}, resultUV);
}
`;const c=Ce(l),p=VC(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,y)=>`coords.${d[y+u]}`).join(", "),`
float ${i}() {
${c} coords = getOutputCoords();
${h}
return get${n}(${m});
}
`}function Ce(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 za(e,t){const s=JSON.parse(JSON.stringify(e));return s.shapeInfo.logicalShape=t,s}function Ba(e,t){return t.map(s=>e[s]).join(", ")}class YC{constructor(e,t,s,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,E.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=Ce(a),c=Et("coords",a);let p,u;if(r===1){u=a+1;const R=Ce(u);p=`
${R} sourceLocR = ${R}(${c.join()}, 0);
++${c[a-1]};
${R} sourceLocG = ${R}(${c.join()}, 0);
++${c[a-2]};
${R} sourceLocA = ${R}(${c.join()}, 0);
--${c[a-1]};
${R} sourceLocB = ${R}(${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(R=>"int "+R),f=Et("sourceLocR",u-1).concat("inIdx.r"),y=Et("sourceLocG",u-1).concat("inIdx.g"),b=Et("sourceLocB",u-1).concat("inIdx.b"),S=Et("sourceLocA",u-1).concat("inIdx.a"),x=s==="max"?"greaterThan":"lessThan",I=n?"":`
inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
getBestIndicesAChannel(${y.join()}),
getBestIndicesAChannel(${b.join()}),
getBestIndicesAChannel(${S.join()})));`,A=`vec4(
getAChannel(${f.join()}),
hasNextCol ? getAChannel(${y.join()}) : 0.,
hasNextRow ? getAChannel(${b.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${S.join()}) : 0.)`,k=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()}));
}
${k}
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;
${I}
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 KC{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 XC{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,y=1/(t*s*n);this.userCode=`
const ivec3 pads = ivec3(${d}, ${m}, ${f});
const float avgMultiplier = float(${y});
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);
}
`}}class JC{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 ZC{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 tx={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class sx{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 nx=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,vf="return a + b;",Tf="return a - b;",ix="return a * b;",QC=`
if (a == b) {
return 1.0;
};
return a / b;`,e0=`
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;
}
`,t0=`
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);
`,s0="return float(a == b);",n0="return float(a != b);",i0="return float(a < b);",r0="return float(a <= b);",o0="return float(a > b);",a0="return float(a >= b);",l0="return float(a >= 1.0 && b >= 1.0);",c0="return float(a >= 1.0 || b >= 1.0);",p0=nx+`
return max(a, b);
`,u0=nx+`
return min(a, b);
`,h0=`if (b == 0.0) return NAN;
return mod(a, b);`,d0=nx+`
return atan(a, b);
`,m0="return (b >= 1.0) ? a : a * (b + 1.0);",rx="return (a < 0.) ? b * a : a;";class mt{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 Uu=`
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;
`,f0=`
// 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;
`,g0=`
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);
`,y0=`
// 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));
`+Uu+`
return result;
`,ox=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,b0=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,w0=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Uu+`
return result;
`,x0=`
return vec4(equal(a, b));
`,L0=`
return vec4(notEqual(a, b));
`,S0=`
return vec4(lessThan(a, b));
`,v0=`
return vec4(lessThanEqual(a, b));
`,T0=`
return vec4(greaterThan(a, b));
`,I0=`
return vec4(greaterThanEqual(a, b));
`,A0=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,N0=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,C0=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Uu+`
return result;
`,R0=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Uu+`
return result;
`,O0=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+Uu+`
return result;
`;class Qs{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||E.sizeFromShape(this.outputShape)===1)r=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{const o=Ce(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=Et("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 E0{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 k0{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 _0{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 D0{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 F0{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=Ce(n),r=Et("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}(${If(o,l,f)}),
vec2(${If(c,l,f)}));
}`}const h=a.length,d=a[a.length-1];u+=`
return getChannel(
getT${h}(${If(o,l,d)}),
vec2(${If(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 If(e,t,s){const n=e.indexOf(t),i=e.map((r,o)=>o===n?`${r} - ${s}`:r);return i.join()}class M0{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 U0{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 $0{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 W0{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 z0{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 B0{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 ax{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,y=m?2:3,b=m?3:1;let S="",x="";s&&(n?S=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}`:S=`
float activation(float x) {
${s}
}
`,x="result = activation(result);");const I=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${S}
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${i}, ${r});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${b}];
ivec2 xRCCorner =
ivec2(coords[${f}], coords[${y}]) * 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;
${I}
${x}
setOutput(result);
}
`}}class P0{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 lx{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="",y="";s&&(n?f=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}`:f=`
float activation(float x) {
${s}
}
`,y="result = activation(result);");const b=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;
${b}
${y}
setOutput(result);
}
`}}class cx{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 I=0;I<d;I++)f+=`
vec4 xTexelR${x}C${I*2} = vec4(0.);
vec4 wR${x}C${I} = vec4(0.);
vec4 xR${x}C${I} = vec4(0.);`;for(let x=0;x<h;x++)for(let I=0;I<m;I++){const A=I*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 k=a%2===0?E.nearestLargerEven(u):u;u%2===0&&a%2===1||u%2!==0&&a%2!==1?(f+=`
xCOffset = xC + ${a%2} + ${k};
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 + ${k};
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 I=0;I<d;I++)f+=`dotProd += xR${x}C${I} * wR${x}C${I};`;let y="",b="";s&&(n?y=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${s}
}`:y=`vec4 activation(vec4 x) {
${s}
}`,b="result = activation(result);");const S=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${y}
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;
${S}
${b}
setOutput(result);
}
`}}class j0{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,y,b]=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}`],[S,x,I]=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(${S});
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 = ${y};
float width_scale = ${x};
float in_y = ${b};
if( in_y < 0.0 || in_y > ${d} ) {
setOutput(float(${i}));
return;
}
float in_x = ${I};
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 px{constructor(e,t,s){this.variableNames=["x"],this.outputShape=e;const n=e.length,i=t?"0.0":`getX(${V0(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() {
${Ce(n)} coords = getOutputCoords();
int end = ${G0(n,"coords")};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${o}) {
int idx = ${a};
${G0(n,"coords")} = idx;
val += getX(${V0(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 V0(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 G0(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 H0{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=wr.DENSE;const t=xr(e),s=ot();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${zn(["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 q0{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=wr.DENSE;const t=xr(e),s=ot();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${zn(["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 Y0{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 K0{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 X0{constructor(e){this.variableNames=["A"],this.outTexUsage=ns.DOWNLOAD;const t=ot();this.outputShape=e,this.userCode=`
${Sf}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}}class J0{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ns.DOWNLOAD;const t=ot();this.outputShape=e,this.userCode=`
${Sf}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}}class Z0{constructor(e,t,s=!1){this.variableNames=["A"];const n=ot(),[i,r]=t;this.outputShape=e;let o="result";s&&(o="floor(result * 255. + 0.5)"),this.userCode=`
${Ua(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 Q0{constructor(e,t,s=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const n=ot(),[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=`
${Ua(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 ux={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"};class hx{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 eR{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 tR{constructor(e,t,s){this.variableNames=["A","indices"];const n=e.slice();n[s]=t,this.outputShape=n,this.rank=n.length;const i=Ce(this.rank),r=EB(e,s);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`}}function EB(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 sR{constructor(e,t,s){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=s;const n=Ce(t.length),i=Ce(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 nR(e){const t=ot(),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 LC(e,s)}function iR(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 IC(e,t)}function rR(e){const t=new Uint16Array([0,1,2,2,1,3]);return AC(e,t)}function $u(e,t,s,n,i,r){CC(t,s);const o=NC(e),a=e.TEXTURE_2D;return oe(e,()=>e.bindTexture(a,o)),oe(e,()=>e.texParameteri(a,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),oe(e,()=>e.texParameteri(a,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),oe(e,()=>e.texParameteri(a,e.TEXTURE_MIN_FILTER,e.NEAREST)),oe(e,()=>e.texParameteri(a,e.TEXTURE_MAG_FILTER,e.NEAREST)),oe(e,()=>e.texImage2D(a,0,n,t,s,0,i,r,null)),oe(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function dx(e){return e.internalFormatFloat}function oR(e,t,s,n){const[i,r]=_o(t,s);return $u(e,i,r,dx(n),n.textureFormatFloat,e.FLOAT)}function mx(e){return e.internalFormatHalfFloat}function aR(e,t,s,n){const[i,r]=_o(t,s);return $u(e,i,r,mx(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function fx(e){return e.downloadTextureFormat}function lR(e,t,s,n){const[i,r]=_o(t,s);return $u(e,i,r,fx(n),e.RGBA,e.UNSIGNED_BYTE)}function gx(e){return e.internalFormatPackedFloat}function cR(e,t,s,n){const[i,r]=oi(t,s);return $u(e,i,r,gx(n),e.RGBA,e.FLOAT)}function yx(e){return e.internalFormatPackedHalfFloat}function pR(e,t,s,n){const[i,r]=oi(t,s);return $u(e,i,r,yx(n),e.RGBA,n.textureTypeHalfFloat)}function uR(e,t,s){const n=0,i=3*4,r=3*4+2*4;oe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s));const o=Yw(e,t,"clipSpacePos",s,3,r,n);return o&&Yw(e,t,"uv",s,2,r,i)}function hR(e,t,s,n,i,r){oe(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),oe(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,s,n,0,e.RGBA,a,o)),oe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function dR(e,t,s){oe(e,()=>e.bindTexture(e.TEXTURE_2D,t)),s.data instanceof Uint8Array?oe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s.width,s.height,0,e.RGBA,e.UNSIGNED_BYTE,s.data)):oe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s)),oe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function mR(e,t,s,n){const i=e.createBuffer();oe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const r=4,o=4,a=r*o*t*s;return oe(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ)),oe(e,()=>e.readPixels(0,0,s,t,e.RGBA,e.FLOAT,0)),oe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function fR(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 gR(e,t,s,n){const[i,r]=_o(t,s),o=4,a=new Uint8Array(bC(t*s,o));return oe(e,()=>e.readPixels(0,0,i,r,n.downloadTextureFormat,e.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function yR(e,t,s,n,i,r,o,a){const l=e,c=new Float32Array(wC(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 bR(e,t,s){const n=new Float32Array(t*s*4);return oe(e,()=>e.readPixels(0,0,s,t,e.RGBA,e.FLOAT,n)),n}class bx{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=$().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,qw(t,e)):this.gl=Js(t);let s="WEBGL_color_buffer_float";const n="EXT_color_buffer_half_float";if($().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",r="OES_texture_half_float";if(this.textureFloatExtension=Fu(this.gl,i),Zs(this.gl,r))this.textureHalfFloatExtension=Fu(this.gl,r);else if($().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),Zs(this.gl,n))this.colorBufferHalfFloatExtension=Fu(this.gl,n);else if($().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",Zs(this.gl,s))this.colorBufferFloatExtension=this.gl.getExtension(s);else if(Zs(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=iR(this.gl),this.indexBuffer=rR(this.gl),this.framebuffer=RC(this.gl),this.textureConfig=Du(this.gl,this.textureHalfFloatExtension)}get debug(){return $().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;oe(e,()=>e.finish()),oe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),oe(e,()=>e.deleteFramebuffer(this.framebuffer)),oe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),oe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),oe(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),oR(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),aR(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),lR(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),dR(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,s,n){this.throwIfDisposed(),hR(this.gl,e,t,s,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),pR(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),cR(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Kw(this.gl,this.framebuffer),this.outputTexture=null),oe(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,s){return this.downloadMatrixDriver(e,()=>gR(this.gl,t,s,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,s,n,i,r){return yR(this.gl,e,t,s,n,i,r,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return fR(this.gl,e,t)}createBufferFromTexture(e,t,s){this.bindTextureToFrameBuffer(e);const n=mR(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($().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 $().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),s=()=>this.isQueryAvailable(t,$().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):s=()=>!0;return{query:t,isFencePassed:s}}downloadMatrixFromPackedTexture(e,t,s){return this.downloadMatrixDriver(e,()=>bR(this.gl,t,s))}createProgram(e){this.throwIfDisposed();const t=this.gl,s=SC(t,e),n=nR(t),i=vC(t);return oe(t,()=>t.attachShader(i,n)),oe(t,()=>t.attachShader(i,s)),TC(t,i),this.debug&&bf(t,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=uR(t,this.program,this.vertexBuffer)),i}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&oe(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&bf(this.gl,this.program),oe(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,s=!0){return this.throwIfDisposed(),s?OC(this.gl,e,t):EC(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),oe(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(),kC(this.gl,e,t,s)}setOutputMatrixTexture(e,t,s){this.setOutputMatrixTextureDriver(e,s,t)}setOutputPackedMatrixTexture(e,t,s){this.throwIfDisposed();const[n,i]=oi(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&&bf(this.gl,this.program),Mu(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),oe(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),oe(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Fu(this.gl,$().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($().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($().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 E.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,$().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,$().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=kB(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;E.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),wf(this.gl,e,this.framebuffer),this.debug&&Mu(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(wf(this.gl,this.outputTexture,this.framebuffer),this.debug&&Mu(this.gl)):Kw(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;wf(n,e,this.framebuffer),this.debug&&Mu(n),this.outputTexture=e,oe(n,()=>n.viewport(0,0,t,s)),oe(n,()=>n.scissor(0,0,t,s))}setOutputMatrixWriteRegionDriver(e,t,s,n){this.throwIfDisposed(),oe(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 kB(e){let t=0;for(;t<e.length;++t){const s=e[t]();if(!s)break}return t-1}function wR(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=GC(r,a,i,t.packedInputs),c=e.createProgram(l);let p=null;const u=e.getUniformLocation(c,"NAN",!1);$().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 xR(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(!E.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(!E.arraysEqual(a,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${l} must match`)})}function LR(e,t,s,n,i){xR(t.inShapeInfos,s),xR([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),$().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(E.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 SR(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 vR{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=ot(),y=u==="channelsLast",b=y?0:1,S=y?1:2;let x="";for(let I=0;I<=1;I++)for(let A=0;A<=1;A++)x+=`
blockIndex = rc.y + ${A};
pos = rc.x + ${I};
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
offsetY = int(blockIndex / (${l})) * ${o} - ${d};
d0 = offsetY + ${p} * (pos / ${m});
if(d0 < ${t[b]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${l}.) * ${r}. - ${h}.);
d1 = offsetX + ${c} * (int(mod(float(pos), ${m}.) / ${i}.));
if(d1 < ${t[S]} && d1 >= 0) {
ch = int(mod(float(pos), ${i}.));
if (${y}) {
innerDims = vec2(d1, ch);
result[${I*2+A}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${I*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 TR{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 IR{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 AR{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 NR{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 CR{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 Af{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 RR{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 OR{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 ER{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=Et("rc",t),n=Ce(t),i=_B(t,e,s),r=DB(t,e[e.length-1],e[e.length-2],s),o=FB(e,s);this.userCode=`
void main() {
${n} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${r}
setOutput(vec4(${o}));
}
}
`}}}function MB(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 _B(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 DB(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 FB(e,t){const s=e.length,n=MB(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 kR{constructor(e,t,s){this.variableNames=["x"],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);const n=e.length,i=Ce(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 _R{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=Ce(n),r=t.map(m=>m[0]).join(","),o=t.map((m,f)=>m[0]+e[f]).join(","),a=Et("rc",n),l=Et("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 Fo{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`,y=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let b="0.0";if(m||(b="-1.0 / 1e-20"),s){const R=">=";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 ${R} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?i?f:y:`wR * ${u} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const S="max";let x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / count");const I=Math.floor(r/4)*4,A=r%4,k=`
if (${m}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${S}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${h}, ${d});
const float initializationValue = ${b};
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(${b});
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 < ${I}; 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)
);
${k}
}
int xC = xCCorner + ${I};
if (${A===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${k}
} else if (${A===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
initializationValue,
initializationValue
);
${k}
} 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
);
${k}
}
}
setOutput(${x});
}
`}}class Nf{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,y=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;const S=t==="avg";let x="0.0";if(S||(x="-1.0 / 1e-20"),s){const F=">=";this.userCode=`
const ivec3 strides =
ivec3(${o}, ${a}, ${l});
const ivec3 pads = ivec3(${f}, ${y}, ${b});
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 ${F} 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 I="max";let A=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(A="avgValue / count");const k=Math.floor(r/4)*4,R=r%4,D=`
if (${S}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${I}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${o}, ${a}, ${l});
const ivec3 pads = ivec3(${f}, ${y}, ${b});
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 < ${k}; 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)
);
${D}
}
int xC = xCCorner + ${k};
if (${R===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${D}
} else if (${R===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
initializationValue,
initializationValue
);
${D}
} else if (${R===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
);
${D}
}
}
setOutput(${A});
}
}
`}}class Cf{constructor(e,t){this.variableNames=["x"];const s=e.windowSize,n=e.batchSize,i=e.inSize,r=Math.ceil(i/s);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 Rf{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=`
${UB(t)}
${Ua(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${s}
setOutput(result);
}
`}}function UB(e){const t=zn(["r","c","d"],e);return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
`}class DR{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 FR{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 MR{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 UR{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 $R{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 WR{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=Ce(s);this.userCode=`
void main() {
${r} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}}class zR{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=Et("rc",s),i=`${n[s-1]} + 1 < ${this.outputShape[s-1]}`,r=`${n[s-2]} + 1 < ${this.outputShape[s-2]}`,o=Ce(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((b,S)=>h(S,d)),f=m.join(","),y=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${y}))`}function h(d,m){return t.indexOf(d)!==-1&&e[d]!==1?`${e[d]} - ${m[d]} - 1`:`${m[d]}`}}}class wx{constructor(e,t,s,n,i,r,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=r;const a=Ce(i.length),l=Ce(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 BR{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 PR{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=Ce(s);this.userCode=`
void main() {
${r} resRC = getOutputCoords();
float cVal = getC(${n});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
`}}class jR{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Ce(this.rank),s=`uniform int start[${this.rank}];`,n=$B(this.rank);let i;const r=e.map((o,a)=>`sourceLoc.${xx[a]} = start[${a}] + coords.${xx[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 xx=["x","y","z","w","u","v"];function $B(e){if(e===1)return"sourceLoc";if(e<=6)return xx.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class VR{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Ce(this.rank),s=Et("coords",this.rank),n=Et("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 GR{constructor(e,t,s){this.variableNames=["x"],this.outputShape=s;const n=s.length,i=Ce(s.length),r=Ce(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 KR{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=qR(t,s),i=YR(e,n,s);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const r=HR(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===Kt.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===Kt.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===Kt.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===Kt.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===Kt.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=qR(s,n),r=YR(t,i,n);r in this.freeTextures||(this.freeTextures[r]=[]);const o=HR(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,n),a=$().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 WB(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 HR(e,t,s,n,i){const r=zB(t,n);let o;if(i){const[l,c]=oi(e[0],e[1]);o=l*c}else{const[l,c]=_o(e[0],e[1]);o=l*c}const a=WB(s,r);return o*a}function zB(e,t){switch(e){case Kt.PACKED_2X2_FLOAT32:return gx(t);case Kt.PACKED_2X2_FLOAT16:return yx(t);case Kt.UNPACKED_FLOAT32:return dx(t);case Kt.UNPACKED_FLOAT16:return mx(t);case Kt.PACKED_4X1_UNSIGNED_BYTE:return fx(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function BB(e){return $().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Kt.PACKED_2X2_FLOAT32:Kt.UNPACKED_FLOAT32:e?Kt.PACKED_2X2_FLOAT16:Kt.UNPACKED_FLOAT16}function qR(e,t){if(e===ns.UPLOAD)return Kt.PACKED_2X2_FLOAT32;if(e===ns.RENDER||e==null)return BB(t);if(e===ns.DOWNLOAD||e===ns.PIXELS)return Kt.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function YR(e,t,s){return`${e[0]}_${e[1]}_${t}_${s}`}class XR{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=Ce(this.rank),i=PB(e);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function PB(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 Bn="if (isnan(x)) return x;",JR="return x;",Lx="return abs(x);",Sx=Bn+`
return (x < 0.0) ? 0.0 : x;
`,vx=Bn+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,Tx="return (x >= 0.0) ? x : (exp(x) - 1.0);",ZR=`
// 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 QR(e=0){return Bn+`
return x > 0.0 ? 1.0 : float(${e});
`}const Ix="return -x;",Ax="return ceil(x);",Nx="return floor(x);",e2=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,t2="return float(isnan(x));",s2="return float(isinf(x));",n2="return float(!isnan(x) && !isinf(x));",i2=`
// 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;
}
}
`,Cx="return exp(x);",Rx="return exp(x) - 1.0;",r2=`if (x < 0.0) return NAN;
return log(x);`,o2="return log(1.0 + x);",a2="return sqrt(x);",l2="return inversesqrt(x);",c2="return 1.0 / (1.0 + exp(-1.0 * x));",p2=`
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;
`,u2=Bn+`
return sin(x);
`,h2=Bn+`
return cos(x);
`,d2="return tan(x);",m2=Bn+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,f2=Bn+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,g2=Bn+`
return atan(x);
`,y2=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,b2=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,w2=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,x2=Bn+"return log(x + sqrt(x * x + 1.0));",L2=Bn+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,S2=Bn+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,v2=`
// 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));
`,T2="return x * x;",I2="return 1.0 / x;",A2="return float(!(x >= 1.0));",N2="return float(int(x));",Wu="return x;";const C2="return x;",R2=`
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;
`,Ox=`
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;
`,Ex=`
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;
`,kx=`
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 Pa{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 O2{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,s=Et("rc",t),n=Ce(t),i=jC(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:E2}=U,jB=St.split,VB=St.tile,GB=St.topkImpl,HB=St.whereImpl,qB=1e-7,YB=1e-4,Of={};function KB(e){return e in Of||(Of[e]={}),Of[e]}function Ef(e,t=!1){if(e==="linear")return t?C2:JR;if(e==="relu")return t?Ox:Sx;if(e==="elu")return t?kx:Tx;if(e==="relu6")return t?Ex:vx;if(e==="prelu")return t?ox:rx;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const XB=128,JB=600;function ZB(){return $().global.screen==null?1024:$().global.screen.height*$().global.screen.width*window.devicePixelRatio*JB/1024/1024}const k2=1e3;class _x extends Jp{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,!$().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Js($().getNumber("WEBGL_VERSION"));this.binaryCache=KB($().getNumber("WEBGL_VERSION")),this.gpgpu=new bx(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 KR(this.gpgpu),this.numMBBeforeWarning=ZB(),this.texData=new Xp(this,os())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,s){if(($().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||$().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:ns.UPLOAD}),n}move(e,t,s,n){if($().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:ns.UPLOAD})}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 Pa(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.disposeData(h.dataId),d}if(s!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return s;const l=this.activeTimers!=null;let c;l&&(c=E.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+=E.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 Pa(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.disposeData(m.dataId),f}if(s!=null)return this.convertAndCacheOnCPU(e);if(!$().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&$().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"&&$().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);const d=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(d.texture,...xr(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=E.sizeFromShape(n);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,d)}c!=null&&this.disposeData(c.dataId);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(!xC(s))throw $().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=E.sizeFromShape(t);if($().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const u=this.decode(e),h=this.texData.get(u.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(h.texture,...xr(t)).subarray(0,i);return this.disposeData(u.dataId),d}const r=$().getBool("WEBGL_PACK")&&n===!0,o=r?xf(t):t,a=r?new J0(o):new X0(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.disposeData(l.dataId),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=E.flatten(this.activeTimers.map(a=>a.query)).filter(a=>a!=null),r=E.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($().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const a=await Promise.all(i);o.kernelMs=E.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 $().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:E.now(),endMs:null}}endTimer(e){return $().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=E.now(),e)}async getQueryTime(e){if($().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 $().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=os().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=XB){const s=this.getCPUBackend();return!this.warnedAboutCPUBackend&&s==null&&!$().getBool("IS_TEST")&&(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&&E.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:os().keep(e.clone()),imag:os().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]))return this.cpuBackend.slice(e,t,s);if(E.sizeFromShape(s)===0)return ze([],s,e.dtype);const{isPacked:n}=this.texData.get(e.dataId),i=Jn.isSliceContinous(e.shape,t,s);if(n||!i){const r=$().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new VR(s):new jR(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=Jn.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){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.stridedSlice(e,t,s,n);const i=Jn.computeOutShape(t,s,n);if(i.some(o=>o===0))return ze([],i);const r=new GR(t,n,i);return this.compileAndRun(r,[e])}reverse(e,t){const s=$().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new zR(e.shape,t):new WR(e.shape,t);return this.compileAndRun(s,[e])}concat(e,t){if(e[0].dtype==="complex64"){const o=e.map(l=>$t(l)),a=e.map(l=>Ht(l));return Ze(this.concat(o,t),this.concat(a,t))}if(this.shouldExecuteOnCPU(e))return this.cpuBackend.concat(e,t);if(e.length===1)return e[0];if(e.length>$().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($().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){const o=new F0(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,E.sizeFromShape(o.shape.slice(t)))),i=new D0(n.map(o=>o.shape)),r=this.compileAndRun(i,n);return r.reshape(s)}neg(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if($().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ix,e.dtype);const t=new _e(e.shape,Ix);return this.compileAndRun(t,[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>k2){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=wt(e.dtype,t.dtype),c=new Af(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=wt(e.dtype,t.dtype),u=i!=null,h=o!=null,d=r?Ef(r,!0):null,m=new Af(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 n=this.texData.get(e.dataId),i=this.texData.get(t.dataId),r=new sx(tx.REAL,e.shape,t.shape),o=new sx(tx.IMAG,e.shape,t.shape),a=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag),this.makeComplexComponentTensorInfo(t,i.complexTensors.real),this.makeComplexComponentTensorInfo(t,i.complexTensors.imag)],l=this.compileAndRun(r,a),c=this.compileAndRun(o,a),p=this.complex(l,c);return l.dispose(),c.dispose(),p}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,ix,e.dtype);const s=new mt(ix,e.shape,t.shape);return this.compileAndRun(s,[e,t],e.dtype)}batchNorm(e,t,s,n,i,r){const o=[e,t,s];let a=null;n!=null&&(a=n.shape,o.push(n));let l=null;if(i!=null&&(l=i.shape,o.push(i)),$().getBool("WEBGL_PACK_NORMALIZATION")){const p=new ZC(e.shape,t.shape,s.shape,a,l,r);return this.compileAndRun(p,o)}const c=new JC(e.shape,t.shape,s.shape,a,l,r);return this.compileAndRun(c,o)}localResponseNormalization4D(e,t,s,n,i){const r=$().getBool("WEBGL_PACK_NORMALIZATION")?new AR(e.shape,t,s,n,i):new TR(e.shape,t,s,n,i);return this.compileAndRun(r,[e])}LRNGrad(e,t,s,n,i,r,o){const a=new IR(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=>E.decodeString(o)),r=le(e.shape,e.dtype,i);return VB(r,t)}const s=new XR(e.shape,t);return this.compileAndRun(s,[e])}pad(e,t,s){const n=$().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _R(e.shape,t,s):new kR(e.shape,t,s);return this.compileAndRun(n,[e])}gather(e,t,s){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.gather(e,t,s);const n=new tR(e.shape,t.size,s);return this.compileAndRun(n,[e,t])}batchToSpaceND(e,t,s){E.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){E.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={windowSize:r,inSize:i,batchSize:n},a=new Cf(o,t),l=this.compileAndRun(a,[e],s);return l.shape[1]===1?l:this.reduce(l,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},a=new PC(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 YC(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=E.sizeFromShape(n),r=e.as2D(-1,i),o=tp(e.dtype);return this.reduce(r,"sum",o).reshape(s)}prod(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.prod(e,t);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=E.sizeFromShape(n),r=e.as2D(-1,i),o=tp(e.dtype);return this.reduce(r,"prod",o).reshape(s)}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=E2.computeOutShape(r.shape,n,s),a=E.sizeFromShape([r.shape[n]]),l=r.as2D(-1,a),c=tp(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=E2.segOpComputeOptimalWindowSize(o,i),l={windowSize:a,inSize:o,batchSize:r,numSegments:i},c=new BR(l,t),p=this.compileAndRun(c,[e,s],n);return p.shape[1]===i?p:(s=ei(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),!$().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){const[i,r]=U.computeOutAndReduceShapes(e.shape,n),o=E.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 px(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 px(e.shape,s,n),a=r;r=this.compileAndRun(o,[r]),a.dispose()}return r}equal(e,t){if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,x0,"bool");const s=new mt(s0,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}notEqual(e,t){if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,L0,"bool");const s=new mt(n0,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}less(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.less(e,t);if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,S0,"bool");const s=new mt(i0,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}lessEqual(e,t){if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,v0,"bool");const s=new mt(r0,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}greater(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.greater(e,t);if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,T0,"bool");const s=new mt(o0,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}greaterEqual(e,t){if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,I0,"bool");const s=new mt(a0,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}logicalNot(e){const t=new _e(e.shape,A2);return this.compileAndRun(t,[e])}logicalAnd(e,t){if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,A0,"bool");const s=new mt(l0,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}logicalOr(e,t){if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,N0,"bool");const s=new mt(c0,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}select(e,t,s){const n=new PR(e.rank,t.shape,t.rank);return this.compileAndRun(n,[e,t,s],wt(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 HB(e.shape,t)}topk(e,t,s){const n=e.dataSync();return GB(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=E.sizeFromShape(n),r=e.as2D(-1,i);return this.reduce(r,"min",r.dtype).reshape(s)}minimum(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.minimum(e,t);const s=$().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Qs(R0,e.shape,t.shape):new mt(u0,e.shape,t.shape);return this.compileAndRun(s,[e,t])}mod(e,t){const s=$().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Qs(O0,e.shape,t.shape):new mt(h0,e.shape,t.shape);return this.compileAndRun(s,[e,t])}maximum(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.maximum(e,t);const s=$().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Qs(C0,e.shape,t.shape):new mt(p0,e.shape,t.shape);return this.compileAndRun(s,[e,t])}all(e,t){U.assertAxesAreInnerMostDims("all",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=E.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=E.sizeFromShape(n),r=e.as2D(-1,i);return this.reduce(r,"any",r.dtype).reshape(s)}floorDiv(e,t){const s=e0,n="int32";if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,g0,n);const i=new mt(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,vf);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.add(e,t);const s=wt(e.dtype,t.dtype);if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,vf,s);const n=new mt(vf,e.shape,t.shape);return this.compileAndRun(n,[e,t],s)}packedUnaryOp(e,t,s){const n=new Pa(e.shape,t);return this.compileAndRun(n,[e],s)}packedBinaryOp(e,t,s,n,i=!1){const r=new Qs(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 mt(s,e.shape,t.shape);return this.compileAndRun(d,[u,h],wt(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>$().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)=>wt(r,o)),s=e.map(r=>r.shape),n=$().getBool("WEBGL_PACK"),i=n?new BC(e[0].shape,s):new zC(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,Tf);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.subtract(e,t);const s=wt(e.dtype,t.dtype);if($().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,Tf,e.dtype);const n=new mt(Tf,e.shape,t.shape);return this.compileAndRun(n,[e,t],s)}pow(e,t){const s=$().getBool("WEBGL_PACK_BINARY_OPERATIONS"),n=s?new Qs(y0,e.shape,t.shape):new mt(t0,e.shape,t.shape),i=wt(e.dtype,t.dtype);return this.compileAndRun(n,[e,t],i)}ceil(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if($().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ax,e.dtype);const t=new _e(e.shape,Ax);return this.compileAndRun(t,[e])}floor(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if($().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Nx,e.dtype);const t=new _e(e.shape,Nx);return this.compileAndRun(t,[e])}sign(e){const t=new _e(e.shape,e2);return this.compileAndRun(t,[e])}isNaN(e){const t=new _e(e.shape,t2);return this.compileAndRun(t,[e],"bool")}isInf(e){const t=new _e(e.shape,s2);return this.compileAndRun(t,[e],"bool")}isFinite(e){const t=new _e(e.shape,n2);return this.compileAndRun(t,[e],"bool")}round(e){const t=new _e(e.shape,i2);return this.compileAndRun(t,[e])}exp(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if($().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Cx,e.dtype);const t=new _e(e.shape,Cx);return this.compileAndRun(t,[e])}expm1(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if($().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Rx,e.dtype);const t=new _e(e.shape,Rx);return this.compileAndRun(t,[e])}softmax(e,t){const s=E.parseAxisParam([t],e.shape),n=st(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 J(o,a)}log(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if($().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,R2,e.dtype);const t=new _e(e.shape,r2);return this.compileAndRun(t,[e])}log1p(e){const t=new _e(e.shape,o2);return this.compileAndRun(t,[e])}sqrt(e){const t=new _e(e.shape,a2);return this.compileAndRun(t,[e])}rsqrt(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);const t=new _e(e.shape,l2);return this.compileAndRun(t,[e])}reciprocal(e){const t=new _e(e.shape,I2);return this.compileAndRun(t,[e])}relu(e){let t;return $().getBool("WEBGL_PACK")?t=new Pa(e.shape,Ox):t=new _e(e.shape,Sx),this.compileAndRun(t,[e])}relu6(e){let t;return $().getBool("WEBGL_PACK")?t=new Pa(e.shape,Ex):t=new _e(e.shape,vx),this.compileAndRun(t,[e])}prelu(e,t){const s=$().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Qs(ox,e.shape,t.shape):new mt(rx,e.shape,t.shape);return this.compileAndRun(s,[e,t])}elu(e){if($().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,kx,e.dtype);const t=new _e(e.shape,Tx);return this.compileAndRun(t,[e])}eluDer(e,t){const s=$().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Qs(b0,e.shape,t.shape):new mt(m0,e.shape,t.shape);return this.compileAndRun(s,[e,t])}selu(e){const t=new _e(e.shape,ZR);return this.compileAndRun(t,[e])}int(e){const t=new _e(e.shape,N2);return this.compileAndRun(t,[e],"int32")}clip(e,t,s){let n;$().getBool("WEBGL_PACK_CLIP")?n=new k0(e.shape):n=new E0(e.shape);const i=n.getCustomSetupFunc(t,s);return this.compileAndRun(n,[e],null,i)}abs(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if($().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Lx,e.dtype);const t=new _e(e.shape,Lx);return this.compileAndRun(t,[e])}complexAbs(e){const t=this.texData.get(e.dataId),s=new _0(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,c2);return this.compileAndRun(t,[e])}softplus(e){const t=new _e(e.shape,p2);return this.compileAndRun(t,[e])}sin(e){const t=new _e(e.shape,u2);return this.compileAndRun(t,[e])}cos(e){const t=new _e(e.shape,h2);return this.compileAndRun(t,[e])}tan(e){const t=new _e(e.shape,d2);return this.compileAndRun(t,[e])}asin(e){const t=new _e(e.shape,m2);return this.compileAndRun(t,[e])}acos(e){const t=new _e(e.shape,f2);return this.compileAndRun(t,[e])}atan(e){const t=new _e(e.shape,g2);return this.compileAndRun(t,[e])}atan2(e,t){const s=$().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Qs(w0,e.shape,t.shape):new mt(d0,e.shape,t.shape);return this.compileAndRun(s,[e,t])}sinh(e){const t=new _e(e.shape,y2);return this.compileAndRun(t,[e])}cosh(e){const t=new _e(e.shape,b2);return this.compileAndRun(t,[e])}tanh(e){const t=new _e(e.shape,w2);return this.compileAndRun(t,[e])}asinh(e){const t=new _e(e.shape,x2);return this.compileAndRun(t,[e])}acosh(e){const t=new _e(e.shape,L2);return this.compileAndRun(t,[e])}atanh(e){const t=new _e(e.shape,S2);return this.compileAndRun(t,[e])}erf(e){const t=new _e(e.shape,v2);return this.compileAndRun(t,[e])}step(e,t){const s=new _e(e.shape,QR(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>k2,f=o[2]%2!==0&&!!a.isPacked;if(m||!$().getBool("WEBGL_LAZILY_UNPACK")||!$().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!f){const k=u?o[0]*o[1]*o[2]:o[0]*o[2]*o[3],R=this.reshape(e,[1,k,s.inChannels]),D=this.reshape(t,[1,s.inChannels,s.outChannels]);return this.reshape(this.fusedBatchMatMul({a:R,b:D,transposeA:h,transposeB:d,bias:n,activation:i,preluActivationWeights:r}),s.outShape)}const y=u?o[0]*o[1]*(o[2]+1):o[0]*o[2]*(o[3]+1),b={dataId:e.dataId,shape:[1,y,s.inChannels],dtype:e.dtype},S=a.shape;a.shape=a.shape.slice(),a.shape[a.shape.length-2]++,E.assert(vr(a.shape,b.shape),()=>`packed reshape ${a.shape} to ${b.shape} isn't free`);const x=this.reshape(t,[1,s.inChannels,s.outChannels]),I=this.fusedBatchMatMul({a:b,b:x,transposeA:h,transposeB:d,bias:n,activation:i,preluActivationWeights:r}),A=this.texData.get(I.dataId);return E.assert(A.isPacked,()=>"batchMatMul result is expected to be packed"),a.shape=S,A.shape=s.outShape,os().makeTensorFromDataId(I.dataId,s.outShape,I.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],y=!0,b=!1,S=e.squeeze([0]),x=t.reshape([1,d,-1]),I=new vR(f,S.shape,s),A=this.compileAndRun(I,[S]).reshape([1,f[0],f[1]]),k=n!=null,R=r!=null,D=i?Ef(i,!0):null,F=new Af(A.shape,[1,m,s.outChannels],y,b,k,D,R),M=[A,x];n&&M.push(n),R&&M.push(r);const B=this.compileAndRun(F,M);return h?B.reshape([1,p,c,s.outChannels]):B.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($().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?Ef(i,!1):null,c=new ax(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($().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,s);const n=new ax(s);return this.compileAndRun(n,[e,t])}conv2dDerInput(e,t,s){const n=new U0(s);return this.compileAndRun(n,[e,t])}conv2dDerFilter(e,t,s){const n=new M0(s);return this.compileAndRun(n,[e,t])}fusedDepthwiseConv2D({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){const o=$().getBool("WEBGL_PACK_DEPTHWISECONV")&&s.strideWidth<=2&&s.outChannels/s.inChannels===1,a=i?Ef(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 cx(s,c,a,p),this.compileAndRun(u,l)):(u=new lx(s,c,a,p),this.compileAndRun(u,l))}depthwiseConv2D(e,t,s){let n;return $().getBool("WEBGL_PACK_DEPTHWISECONV")&&s.strideWidth<=2&&s.outChannels/s.inChannels===1?(n=new cx(s),this.compileAndRun(n,[e,t])):(n=new lx(s),this.compileAndRun(n,[e,t]))}depthwiseConv2DDerInput(e,t,s){const n=new B0(s);return this.compileAndRun(n,[e,t])}depthwiseConv2DDerFilter(e,t,s){const n=new z0(s);return this.compileAndRun(n,[e,t])}conv3d(e,t,s){const n=new P0(s);return this.compileAndRun(n,[e,t])}conv3dDerInput(e,t,s){const n=new W0(s);return this.compileAndRun(n,[e,t])}conv3dDerFilter(e,t,s){const n=new $0(s);return this.compileAndRun(n,[e,t])}maxPool(e,t){const s=new Fo(t,"max",!1);return this.compileAndRun(s,[e])}avgPool(e,t){const s=new Fo(t,"avg",!1);return this.compileAndRun(s,[e],"float32")}maxPoolBackprop(e,t,s,n){const i=!0,r=new Fo(n,"max",i),o=this.compileAndRun(r,[t]),a=new NR(n),l=this.compileAndRun(a,[e,o],t.dtype);return o.dispose(),l}avgPoolBackprop(e,t,s){const n=new KC(s);return this.compileAndRun(n,[e],t.dtype)}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 Nf(t,"avg",!1);return this.compileAndRun(s,[e],"float32")}avgPool3dBackprop(e,t,s){const n=new XC(s);return this.compileAndRun(n,[e],t.dtype)}maxPool3d(e,t){const s=new Nf(t,"max",!1);return this.compileAndRun(s,[e],"float32")}maxPool3dBackprop(e,t,s,n){const i=!0,r=new Nf(n,"max",i),o=this.compileAndRun(r,[t]),a=new CR(n),l=this.compileAndRun(a,[e,o],t.dtype);return o.dispose(),l}reshape(e,t){const s=this.texData.get(e.dataId);if(s.isPacked&&!vr(e.shape,t)&&!(s.texture!==null&&vr(s.shape,t))){const n=this.packedReshape(e,t);return os().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}return U.reshapeTensor(e,t)}resizeBilinear(e,t,s,n){const i=$().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new MR(e.shape,t,s,n):new FR(e.shape,t,s,n);return this.compileAndRun(i,[e],"float32")}resizeBilinearBackprop(e,t,s){const n=new DR(e,t,s);return this.compileAndRun(n,[e])}resizeNearestNeighbor(e,t,s,n){const i=new $R(e.shape,t,s,n);return this.compileAndRun(i,[e])}resizeNearestNeighborBackprop(e,t,s){const n=new UR(e,t,s);return this.compileAndRun(n,[e])}multinomial(e,t,s,n){const i=t?e:Yt(e),r=i.shape[0],o=i.shape[1],a=new RR(r,o,s),l=a.getCustomSetupFunc(n);return this.compileAndRun(a,[i],"int32",l)}oneHot(e,t,s,n){const i=new OR(e.size,t,s,n);return this.compileAndRun(i,[e])}diag(e){const t=new K0(e.size);return this.compileAndRun(t,[e])}cropAndResize(e,t,s,n,i,r){const o=new j0(e.shape,t.shape,n,i,r);return this.compileAndRun(o,[e,t,s],"float32")}depthToSpace(e,t,s){E.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 Y0(p,t,s);return this.compileAndRun(u,[e])}split(e,t,s){return jB(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 wx(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 wx(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 hx(ux.REAL,e.shape,t),i=new hx(ux.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 sR(n,a,[r,o]),u=this.compileAndRun(p,[c,l]);return u.reshape(i)}fill(e,t,s){if(s=s||E.inferDtype(t),s==="string"){const n=E.getArrayFromDType(s,E.sizeFromShape(e));return n.fill(t),os().makeTensor(n,e,s,this)}else{const n=new eR(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){const s=this.write(null,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t){const{dataId:s}=this.makeTensorInfo(e,t);return os().makeTensorFromDataId(s,e,t,this)}unpackTensor(e){const t=new O2(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new ER(e.shape),s=!0;return this.runWebGLProgram(t,[e],e.dtype,null,s)}packedReshape(e,t){const s=[Lr(e.shape),...Sr(e.shape)],n={dtype:e.dtype,shape:s,dataId:e.dataId},i=[Lr(t),...Sr(t)],r=new Rf(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=xf(n);let o;s?o=new q0(r):o=new H0(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===wr.DENSE){const m=xr(e.outputShape);o.texShape=m.map(f=>f*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),E.sizeFromShape(r.shape)===0)return o.values=E.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&&E.sizeFromShape(m.shape)<=$().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&&!vr(f.shape,m.shape)){const y=m,b=m.shape;m.shape=f.shape,m=this.packedReshape(m,b),a.push(m),f=this.texData.get(m.dataId),y.shape=b}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=SR(e,l,c),u=this.getAndSaveBinary(p,()=>wR(this.gpgpu,e,l,c)),h=this.activeTimers!=null;let d;if(h&&(d=this.startTimer()),LR(this.gpgpu,u,l,c,n),a.forEach(m=>this.disposeData(m.dataId)),h&&(d=this.endTimer(d),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(d)})),!$().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&i===!1){const m=this.unpackTensor(r);return this.disposeData(r.dataId),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 os().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(!$().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=N(()=>{if(!$().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=$().getBool("DEBUG");$().set("DEBUG",!1);const t=this.abs(j(1e-8)).dataSync()[0];if($().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?qB:YB}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=E.now());let p=t.texShape;if(p==null&&(p=_C(s,a),t.texShape=p),i!=null){const u=xf(s);let h,d=p[1],m=p[0];const f=i instanceof Uint8Array;a?([d,m]=oi(p[0],p[1]),h=new Q0(u,[m,d],f)):h=new Z0(u,[m,d],f);const y=this.makeTensorInfo([m,d],n);f?this.texData.get(y.dataId).usage=ns.PIXELS:this.texData.get(y.dataId).usage=ns.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),d,m,i);const b=!0,S=this.runWebGLProgram(h,[y],n,null,b),x=this.texData.get(S.dataId);t.texture=x.texture,t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,this.disposeData(y.dataId),this.texData.delete(S.dataId),t.values=null,l&&(this.uploadWaitMs+=E.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=QB(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]*E.bytesPerElement(t)}}function QB(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 Dx="2.3.0";function _2(){$().set("WEBGL_FORCE_F16_TEXTURES",!0)}la.isBrowser()&&dp("webgl",()=>new _x(),2);const a3e={forceHalfFloat:_2};function D2(e,t,s){let n=new mt(QC,e.shape,t.shape);$().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&(n=new Qs(f0,e.shape,t.shape,!0));const i=s.runWebGLProgram(n,[e,t],"float32");return i}const F2={kernelName:ui,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{a:s,b:n}=e,i=t;return D2(s,n,i)}};class M2{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 U2={kernelName:Dr,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:s}=e,n=t,i=new M2(s.shape),r=n.runWebGLProgram(i,[s],s.dtype);return r}};class $2{constructor(e){this.variableNames=["A"];const t=ot(),[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 W2{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=ot(),[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 z2={kernelName:ta,backendName:"webgl",kernelFunc:eP};let ja;function eP(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)&&(ja==null&&(ja=document.createElement("canvas").getContext("2d")),ja.canvas.width=l,ja.canvas.height=c,ja.drawImage(i,0,0,l,c),i=ja.canvas);const h=s.makeTensorInfo(p,"int32");s.texData.get(h.dataId).usage=ns.PIXELS,s.gpgpu.uploadPixelDataToTexture(s.getTexture(h.dataId),i);const d=$().getBool("WEBGL_PACK")?new W2(u):new $2(u),m=s.runWebGLProgram(d,[h],"int32");return s.disposeData(h.dataId),m}const{maxImpl:B2,transposeImpl:kf}=Vw;function Fx(e,t,s,n){const[i,r]=e.shape,o=U.computeOptimalWindowSize(r),a={windowSize:o,inSize:r,batchSize:i},l=new Cf(a,s),c=n.runWebGLProgram(l,[e],t);return c.shape[1]===1?c:Fx(c,t,s,n)}function tP(e,t,s){const n=[Lr(e.shape),...Sr(e.shape)],i={dtype:e.dtype,shape:n,dataId:e.dataId},r=[Lr(t),...Sr(t)],o=new Rf(r,n),a=!0,l=s.runWebGLProgram(o,[i],e.dtype,null,a);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function Mx(e,t,s){const n=s.texData.get(e.dataId);return n.isPacked&&!vr(e.shape,t)&&!(n.texture!==null&&vr(n.shape,t))?tP(e,t,s):{dataId:e.dataId,shape:t,dtype:e.dtype}}function P2(e,t,s,n){const i=E.sizeFromShape(t),r=E.sizeFromShape(e.shape),o=r/i,a=Mx(e,[o,i],n),l=Fx(a,e.dtype,"max",n);return a.dataId!==e.dataId&&n.disposeData(a.dataId),Mx(l,s,n)}class j2{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=Ce(this.rank),i=sP(t);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function sP(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 V2{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=Ce(this.rank),i=ex("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 _f(e,t,s){const n=$().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new V2(e.shape,t):new j2(e.shape,t);return s.runWebGLProgram(n,[e],e.dtype)}const G2={kernelName:hi,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=E.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 S=o.texData.get(d.dataId),x=S.values,I=new Array(a);for(let R=0;R<I.length;R++)I[R]=n.shape[p[R]];const A=kf(x,n.shape,n.dtype,p,I);d=o.makeTensorInfo(I,n.dtype);const k=o.texData.get(d.dataId);k.values=A}else d=_f(n,p,o);c=U.getInnerMostAxes(c.length,a)}U.assertAxesAreInnerMostDims("max",c,a);const[m,f]=U.computeOutAndReduceShapes(d.shape,c);let y=m;r&&(y=U.expandShapeToKeepDim(m,l));let b;if(h){const S=o.texData.get(d.dataId),x=S.values,I=B2(x,E.sizeFromShape(f),y,n.dtype);b=o.makeTensorInfo(y,n.dtype);const A=o.texData.get(b.dataId);A.values=I}else b=P2(d,f,y,o);return u&&o.disposeData(d.dataId),b}};function H2(e,t,s,n){let i=new Fo(s,"max",!1);const r=n.runWebGLProgram(i,[e],"float32");i=new Fo(s,"max",!0,!0,t);const o=n.runWebGLProgram(i,[e],"float32");return[r,o]}const q2={kernelName:Fr,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{filterSize:i,strides:r,pad:o,includeBatchInIndex:a}=t,l=s;E.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);const c=[1,1];E.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]=H2(n,a,p,l);return[u,h]}};const Y2={kernelName:pc,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 St.nonMaxSuppressionV3Impl(c,p,u,h,d)}};const nP=St.nonMaxSuppressionV4Impl,K2={kernelName:Mr,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}=nP(p,u,r,o,a,l);return[h,d]}};const iP=St.nonMaxSuppressionV5Impl,X2={kernelName:Ur,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:y,selectedScores:b}=iP(p,u,h,d,m,f);return[y,b]}};class J2{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 Z2={kernelName:Wr,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,{radians:i,fillValue:r,center:o}=t,a=s,l=new J2(n.shape,i,r,o),c=a.runWebGLProgram(l,[n],n.dtype);return c}};const Q2={kernelName:$r,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{x:s}=e,n=t,i=new _e(s.shape,T2);return n.runWebGLProgram(i,[s],s.dtype)}};const eO={kernelName:di,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{a:s,b:n}=e,i="return (a - b) * (a - b);",r=t,o=$().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Qs(i,s.shape,n.shape):new mt(i,s.shape,n.shape);return r.compileAndRun(o,[s,n])}};const tO={kernelName:mi,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=kf(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=_f(n,i,r);return l}};const rP=[G2,U2,z2,F2,q2,Y2,K2,X2,Z2,Q2,eO,tO];for(const e of rP)Yc(e);const sO="2.3.0";const Xu={};Re(Xu,{Abs:()=>dl,Acos:()=>ml,Acosh:()=>fl,AdadeltaOptimizer:()=>bo,AdagradOptimizer:()=>wo,AdamOptimizer:()=>xo,AdamaxOptimizer:()=>Lo,Add:()=>Er,AddN:()=>gl,All:()=>mg,Any:()=>fg,ArgMax:()=>yl,ArgMin:()=>bl,Asin:()=>wl,Asinh:()=>xl,Atan:()=>Ll,Atan2:()=>vl,Atanh:()=>Sl,AvgPool:()=>Tl,AvgPool3D:()=>Il,AvgPool3DBackprop:()=>yg,AvgPoolBackprop:()=>gg,BatchMatMul:()=>Al,BatchToSpaceND:()=>Nl,BroadcastTo:()=>Cl,Callback:()=>lw,CallbackList:()=>zb,Cast:()=>kr,Ceil:()=>Rl,ClipByValue:()=>Ol,Complex:()=>bg,Concat:()=>El,Conv2D:()=>kl,Conv2DBackpropFilter:()=>wg,Conv2DBackpropInput:()=>_l,Conv3D:()=>Dl,Conv3DBackpropFilterV2:()=>xg,Conv3DBackpropInputV2:()=>Lg,Cos:()=>Fl,Cosh:()=>Ml,CropAndResize:()=>Sg,Cumsum:()=>Ul,CustomCallback:()=>Pb,DataStorage:()=>Xp,DepthToSpace:()=>vg,DepthwiseConv2dNative:()=>$l,DepthwiseConv2dNativeBackpropFilter:()=>Tg,DepthwiseConv2dNativeBackpropInput:()=>Ig,Diag:()=>Ag,Dilation2D:()=>_r,Dilation2DBackpropFilter:()=>ea,Dilation2DBackpropInput:()=>Qo,Div:()=>ui,ENV:()=>pg,EarlyStopping:()=>cw,Elu:()=>Wl,EluGrad:()=>Ng,Environment:()=>cg,Equal:()=>Cg,Erf:()=>zl,Exp:()=>Bl,Expm1:()=>Pl,FFT:()=>Rg,Fill:()=>Og,FlipLeftRight:()=>Dr,Floor:()=>jl,FloorDiv:()=>Vl,FromPixels:()=>ta,FusedBatchNorm:()=>Gl,FusedConv2D:()=>Ih,FusedDepthwiseConv2D:()=>Ah,GatherNd:()=>Eg,GatherV2:()=>Hl,GraphModel:()=>Dw,Greater:()=>kg,GreaterEqual:()=>ql,History:()=>Bb,IFFT:()=>_g,Identity:()=>Yl,Imag:()=>Dg,InputSpec:()=>rt,IsFinite:()=>Kl,IsInf:()=>Xl,IsNan:()=>Jl,KernelBackend:()=>Jp,LRN:()=>tc,LRNBackprop:()=>Bg,LayerVariable:()=>Td,LayersModel:()=>gn,Less:()=>Fg,LessEqual:()=>Mg,LinSpace:()=>Ug,Log:()=>Zl,Log1p:()=>Ql,LogSoftmax:()=>ec,LogicalAnd:()=>$g,LogicalNot:()=>Wg,LogicalOr:()=>zg,Max:()=>hi,MaxPool:()=>nc,MaxPool3D:()=>ic,MaxPool3DBackprop:()=>jg,MaxPoolBackprop:()=>Pg,MaxPoolWithArgmax:()=>Fr,Maximum:()=>sc,Mean:()=>e1,Min:()=>rc,Minimum:()=>oc,Mod:()=>ac,MomentumOptimizer:()=>So,Multiply:()=>lc,Negate:()=>cc,NonMaxSuppressionV3:()=>pc,NonMaxSuppressionV4:()=>Mr,NonMaxSuppressionV5:()=>Ur,NotEqual:()=>Vg,OneHot:()=>hc,OnesLike:()=>uc,Optimizer:()=>fs,PadV2:()=>dc,Pool:()=>t1,Pow:()=>mc,Prelu:()=>fc,Prod:()=>Gg,RMSPropOptimizer:()=>vo,RNN:()=>ri,Range:()=>Hg,Rank:()=>uy,Real:()=>qg,Reciprocal:()=>gc,Reduction:()=>ht,Relu:()=>yc,Relu6:()=>Lc,Reshape:()=>bc,ResizeBilinear:()=>xc,ResizeBilinearGrad:()=>Kg,ResizeNearestNeighbor:()=>wc,ResizeNearestNeighborGrad:()=>Yg,Reverse:()=>Sc,RotateWithOffset:()=>Wr,Round:()=>vc,Rsqrt:()=>Tc,SGDOptimizer:()=>Ei,ScatterNd:()=>Xg,SelectV2:()=>Ic,Selu:()=>Ac,Sequential:()=>yr,Sigmoid:()=>Ec,Sign:()=>Oc,Sin:()=>Cc,Sinh:()=>Rc,Slice:()=>Nc,Softmax:()=>Uc,Softplus:()=>kc,SpaceToBatchND:()=>Fc,SparseToDense:()=>Jg,SplitV:()=>Mc,Sqrt:()=>_c,Square:()=>$r,SquaredDifference:()=>di,Step:()=>Gc,StridedSlice:()=>Zg,Sub:()=>$c,Sum:()=>Dc,SymbolicTensor:()=>bs,Tan:()=>Wc,Tanh:()=>zc,Tensor:()=>ue,TensorBuffer:()=>fi,Tile:()=>Bc,TopK:()=>Qg,Transpose:()=>mi,Unpack:()=>Pc,UnsortedSegmentSum:()=>jc,Variable:()=>Xn,ZerosLike:()=>Vc,_FusedMatMul:()=>Th,abs:()=>Je,acos:()=>ip,acosh:()=>rp,add:()=>W,addN:()=>op,addStrict:()=>OS,all:()=>jr,any:()=>sr,argMax:()=>nr,argMin:()=>ap,asin:()=>lp,asinh:()=>cp,atan:()=>pp,atan2:()=>up,atanh:()=>hp,avgPool:()=>rs,avgPool3d:()=>Gr,backend:()=>Sy,backend_util:()=>U,basicLSTMCell:()=>_y,batchNorm:()=>on,batchNorm2d:()=>gp,batchNorm3d:()=>yp,batchNorm4d:()=>bp,batchToSpaceND:()=>wi,booleanMaskAsync:()=>vS,broadcastTo:()=>or,browser:()=>pr,buffer:()=>le,callbacks:()=>QA,cast:()=>K,ceil:()=>wp,clipByValue:()=>Dt,clone:()=>Ps,complex:()=>Ze,concat:()=>ge,concat1d:()=>xp,concat2d:()=>Lp,concat3d:()=>Sp,concat4d:()=>vp,constraints:()=>_b,conv1d:()=>Hr,conv2d:()=>yt,conv2dTranspose:()=>qr,conv3d:()=>Yr,conv3dTranspose:()=>Dy,cos:()=>xi,cosh:()=>Kr,cosineWindow:()=>ga,cumsum:()=>Xr,customGrad:()=>ms,data:()=>Bw,deprecationWarn:()=>xt,depthToSpace:()=>Tp,depthwiseConv2d:()=>In,deregisterOp:()=>sN,device_util:()=>la,diag:()=>Fy,dilation2d:()=>Ip,disableDeprecationWarnings:()=>sE,dispose:()=>ce,disposeVariables:()=>nE,div:()=>J,divNoNan:()=>Ap,divStrict:()=>ES,dot:()=>My,dropout:()=>jh,elu:()=>An,enableDebugMode:()=>tE,enableProdMode:()=>eE,enclosingPowerOfTwo:()=>Vh,engine:()=>os,env:()=>$,equal:()=>Qt,equalStrict:()=>TS,erf:()=>Np,exp:()=>At,expandDims:()=>Nt,expm1:()=>Cp,eye:()=>ar,fft:()=>Li,fill:()=>Ft,findBackend:()=>cE,findBackendFactory:()=>pE,floor:()=>Nn,floorDiv:()=>Jr,fused:()=>Hs,gather:()=>Cn,gatherND:()=>Ph,gather_util:()=>kv,getBackend:()=>aE,getGradient:()=>Nh,getKernel:()=>qc,getKernelsForBackend:()=>Ch,grad:()=>Dk,grads:()=>Fk,greater:()=>Ct,greaterEqual:()=>as,greaterEqualStrict:()=>IS,greaterStrict:()=>AS,ifft:()=>Qn,imag:()=>Ht,image:()=>ks,inTopKAsync:()=>GS,initializers:()=>$b,input:()=>zd,io:()=>Ot,irfft:()=>Zr,isFinite:()=>$y,isInf:()=>Wy,isNaN:()=>zy,keep:()=>gt,kernel_impls:()=>St,layers:()=>tw,leakyRelu:()=>Qr,less:()=>Si,lessEqual:()=>vs,lessEqualStrict:()=>NS,lessStrict:()=>CS,linalg:()=>Zh,linspace:()=>Rp,loadGraphModel:()=>kN,loadLayersModel:()=>LA,localResponseNormalization:()=>Op,log:()=>Mt,log1p:()=>eo,logSigmoid:()=>By,logSoftmax:()=>to,logSumExp:()=>Ep,logicalAnd:()=>zt,logicalNot:()=>vi,logicalOr:()=>so,logicalXor:()=>Py,losses:()=>Lv,matMul:()=>Le,math:()=>Ev,max:()=>st,maxPool:()=>lt,maxPool3d:()=>no,maxPoolWithArgmax:()=>kp,maximum:()=>Wt,maximumStrict:()=>kS,mean:()=>Ge,memory:()=>pa,metrics:()=>rw,min:()=>an,minimum:()=>Vs,minimumStrict:()=>_S,mod:()=>io,modStrict:()=>DS,model:()=>wA,models:()=>ow,moments:()=>lr,movingAverage:()=>zS,mul:()=>C,mulStrict:()=>FS,multiRNNCell:()=>jy,multinomial:()=>_p,neg:()=>Oe,nextFrame:()=>Kp,norm:()=>ma,notEqual:()=>Es,notEqualStrict:()=>RS,oneHot:()=>On,ones:()=>es,onesLike:()=>Bt,op:()=>L,outerProduct:()=>Vy,pad:()=>Ut,pad1d:()=>Gy,pad2d:()=>Hy,pad3d:()=>qy,pad4d:()=>Yy,pool:()=>Ky,pow:()=>qt,powStrict:()=>MS,prelu:()=>Ii,print:()=>Xy,prod:()=>ro,profile:()=>iE,rand:()=>Jy,randomGamma:()=>tb,randomNormal:()=>ha,randomUniform:()=>Gs,range:()=>ei,ready:()=>oE,real:()=>$t,reciprocal:()=>Fp,registerBackend:()=>dp,registerCallbackConstructor:()=>SA,registerGradient:()=>ty,registerKernel:()=>Yc,registerOp:()=>tN,regularizers:()=>aw,relu:()=>ke,relu6:()=>Mp,removeBackend:()=>lE,reshape:()=>O,reverse:()=>Lt,reverse1d:()=>sb,reverse2d:()=>nb,reverse3d:()=>ib,reverse4d:()=>rb,rfft:()=>Ai,round:()=>Up,rsqrt:()=>oo,scalar:()=>j,scatterND:()=>Bh,scatter_util:()=>BS,selu:()=>ao,separableConv2d:()=>Ni,sequential:()=>xA,serialization:()=>P,setBackend:()=>mS,setPlatform:()=>uE,setdiff1dAsync:()=>$p,sigmoid:()=>Ss,sign:()=>Wp,signal:()=>xv,sin:()=>lo,sinh:()=>co,slice:()=>he,slice1d:()=>po,slice2d:()=>da,slice3d:()=>Ci,slice4d:()=>cr,slice_util:()=>Jn,softmax:()=>Yt,softplus:()=>Rn,spaceToBatchND:()=>Ti,sparseToDense:()=>fa,spectral:()=>wv,split:()=>ls,sqrt:()=>He,square:()=>ye,squaredDifference:()=>Ri,squaredDifferenceStrict:()=>US,squeeze:()=>En,stack:()=>Xe,step:()=>kn,stridedSlice:()=>zp,sub:()=>X,subStrict:()=>$S,sum:()=>te,sumOutType:()=>tp,tan:()=>Bp,tanh:()=>Zn,tensor:()=>ze,tensor1d:()=>Fe,tensor2d:()=>ts,tensor3d:()=>Pp,tensor4d:()=>cs,tensor5d:()=>ab,tensor6d:()=>lb,tensor_util:()=>rn,test_util:()=>wS,tidy:()=>N,tile:()=>js,time:()=>rE,topk:()=>jp,train:()=>hr,transpose:()=>se,truncatedNormal:()=>Oi,unregisterGradient:()=>n1,unregisterKernel:()=>s1,unsortedSegmentSum:()=>Vp,unstack:()=>nt,upcastType:()=>wt,util:()=>E,valueAndGrad:()=>Mk,valueAndGrads:()=>Uk,variable:()=>Gp,variableGrads:()=>Uh,version:()=>oP,version_converter:()=>Zm,version_core:()=>Lb,version_layers:()=>fr,where:()=>at,whereAsync:()=>uo,zeros:()=>Ie,zerosLike:()=>ne});const oP={"tfjs-core":Lb,"tfjs-backend-cpu":Gw,"tfjs-backend-webgl":Dx,"tfjs-data":df,"tfjs-layers":fr,"tfjs-converter":Zm,tfjs:sO};function ji(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 Ls{constructor(e,t){if(!Pn(e)||!Pn(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 Ls(1/this.width,1/this.height)}}const Zu={};Re(Zu,{computeReshapedDimensions:()=>Wx,getCenterPoint:()=>Wo,isDimensions:()=>Ff,isEven:()=>Df,isFloat:()=>$x,isTensor:()=>Mo,isTensor1D:()=>aP,isTensor2D:()=>Ux,isTensor3D:()=>Uo,isTensor4D:()=>en,isValidNumber:()=>Pn,isValidProbablitiy:()=>Va,range:()=>ai,round:()=>$o});function Mo(e,t){return e instanceof ue&&e.shape.length===t}function aP(e){return Mo(e,1)}function Ux(e){return Mo(e,2)}function Uo(e){return Mo(e,3)}function en(e){return Mo(e,4)}function $x(e){return e%1!==0}function Df(e){return e%2===0}function $o(e,t=2){const s=Math.pow(10,t);return Math.floor(e*s)/s}function Ff(e){return e&&e.width&&e.height}function Wx({width:e,height:t},s){const n=s/Math.max(t,e);return new Ls(Math.round(e*n),Math.round(t*n))}function Wo(e){return e.reduce((t,s)=>t.add(s),new Ee(0,0)).div(new Ee(e.length,e.length))}function ai(e,t,s){return Array(e).fill(0).map((n,i)=>t+i*s)}function Pn(e){return!!e&&e!==Infinity&&e!==-Infinity&&!isNaN(e)||e===0}function Va(e){return Pn(e)&&0<=e&&e<=1}class Ee{constructor(e,t){this._x=e,this._y=t}get x(){return this._x}get y(){return this._y}add(e){return new Ee(this.x+e.x,this.y+e.y)}sub(e){return new Ee(this.x-e.x,this.y-e.y)}mul(e){return new Ee(this.x*e.x,this.y*e.y)}div(e){return new Ee(this.x/e.x,this.y/e.y)}abs(){return new Ee(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 Ee(Math.floor(this.x),Math.floor(this.y))}}class tt{constructor(e,t=!0){const s=e||{},n=[s.left,s.top,s.right,s.bottom].every(Pn),i=[s.x,s.y,s.width,s.height].every(Pn);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];tt.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(Pn)}static assertIsValidBox(e,t,s=!1){if(!tt.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 Ee(this.left,this.top)}get topRight(){return new Ee(this.right,this.top)}get bottomLeft(){return new Ee(this.left,this.bottom)}get bottomRight(){return new Ee(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 tt({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 tt({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 tt({x:e,y:t,width:s,height:n})}rescale(e){const t=Ff(e)?e.width:e,s=Ff(e)?e.height:e;return new tt({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 tt({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 tt({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 tt({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 tt({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 Zo extends tt{constructor(e,t,s,n,i=!1){super({left:e,top:t,right:s,bottom:n},i)}}class Or{constructor(e,t,s,n,i){this._imageDims=new Ls(i.width,i.height),this._score=e,this._classScore=t,this._className=s,this._box=new tt(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 tt(this._box).rescale(this.imageDims.reverse())}forSize(e,t){return new Or(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:t})}}class bt extends Or{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 bt(s,n,i)}}function ih(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 nh(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 Zo(n,i,r,o)}function sh(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(ih(u,h,n))}i=i.filter((c,p)=>l[p]<=s)}return r}function sn(e,t){return N(()=>{const[s,n,i]=t,r=Ft([...e.shape.slice(0,3),1],s),o=Ft([...e.shape.slice(0,3),1],n),a=Ft([...e.shape.slice(0,3),1],i),l=ge([r,o,a],3);return X(e,l)})}function th(e,t=!1){return N(()=>{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,Ft(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=>h.toFloat());return ge(u,o)})}function wL(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 Ho(e){return 1/(1+Math.exp(-e))}function xL(e){return Math.log(e/(1-e))}class Sh extends tt{constructor(e,t,s,n,i=!1){super({x:e,y:t,width:s,height:n},i)}}const lP=.5,cP=.43,pP=.45;class Ws{constructor(e,t,s=new Ee(0,0)){const{width:n,height:i}=t;this._imgDims=new Ls(n,i),this._shift=s,this._positions=e.map(r=>r.mul(new Ee(n,i)).add(s))}get shift(){return new Ee(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 Ee(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 Ee(e,t))}shiftByPoint(e){return this.shiftBy(e.x,e.y)}align(e,t={}){if(e){const i=e instanceof bt?e.box.floor():new tt(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/pP),a=Wo(e),l=Math.floor(Math.max(0,a.x-lP*o)),c=Math.floor(Math.max(0,a.y-cP*o));return new Sh(l,c,Math.min(o,this.imageWidth+l),Math.min(o,this.imageHeight+c))}alignMinBbox(e){const t=nh(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class GL extends Ws{getRefPointsForAlignment(){const e=this.positions;return[e[0],e[1],Wo([e[3],e[4]])]}}class Jo extends Ws{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(Wo)}}class hl{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?` (${$o(this.distance)})`:""}`}}class ul extends tt{constructor(e,t){super(e);this._label=t}static assertIsValidLabeledBox(e,t){if(tt.assertIsValidBox(e,t),!Pn(e.label))throw new Error(`${t} - expected property label (${e.label}) to be a number`)}get label(){return this._label}}class tr{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 tr(e.label,t)}}class VL extends ul{constructor(e,t,s,n){super(e,t);this._score=s,this._classScore=n}static assertIsValidPredictedBox(e,t){if(ul.assertIsValidLabeledBox(e,t),!Va(e.score)||!Va(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 Sn(e){return e.detection instanceof bt}function Xi(e,t){const s={detection:t};return Object.assign({},e,s)}function zx(){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 Mf(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 Bx(){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=Mf();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 Px(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const jx=nl(gL());let Xt;function uP(){if(!Xt)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Xt}function Vx(e){Xt=e}function Gx(){if(Px())return Vx(zx());if(jx.isNodejs())return Vx(Bx())}function hP(e){if(Xt||Gx(),!Xt)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:t=Xt.Canvas,Image:s=Xt.Image}=e;Xt.Canvas=t,Xt.Image=s,Xt.createCanvasElement=e.createCanvasElement||(()=>new t()),Xt.createImageElement=e.createImageElement||(()=>new s()),Xt.ImageData=e.ImageData||Xt.ImageData,Xt.Video=e.Video||Xt.Video,Xt.fetch=e.fetch||Xt.fetch,Xt.readFile=e.readFile||Xt.readFile}const Ve={getEnv:uP,setEnv:Vx,initialize:Gx,createBrowserEnv:zx,createFileSystem:Mf,createNodejsEnv:Bx,monkeyPatch:hP,isBrowser:Px,isNodejs:jx.isNodejs};Gx();function Zi(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=Zi(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 li;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(li||(li={}));class Uf{constructor(e={}){const{anchorPosition:t,backgroundColor:s,fontColor:n,fontSize:i,fontStyle:r,padding:o}=e;this.anchorPosition=t||li.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 Ga{constructor(e,t,s={}){this.text=typeof e=="string"?[e]:e instanceof Ga?e.text:e,this.anchor=t,this.options=new Uf(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===li.BOTTOM_RIGHT||s===li.TOP_RIGHT,i=s===li.BOTTOM_LEFT||s===li.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=Zi(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 nO{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:li.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Uf(Object.assign({},r,i))}}class Hx{constructor(e,t={}){this.box=new tt(e),this.options=new nO(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 Ga([l],{x:i-n/2,y:r},this.options.drawLabelOptions).draw(e)}}function dP(e,t){const s=Array.isArray(t)?t:[t];s.forEach(n=>{const i=n instanceof bt?n.score:Sn(n)?n.detection.score:void 0,r=n instanceof bt?n.box:Sn(n)?n.detection.box:new tt(n),o=i?`${$o(i)}`:void 0;new Hx(r,{label:o}).draw(e)})}function Ko(e){const{Image:t,Video:s}=Ve.getEnv();return e instanceof t&&e.complete||e instanceof s&&e.readyState>=3}function Lh(e){return new Promise((t,s)=>{if(e instanceof Ve.getEnv().Canvas||Ko(e))return t();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 xh(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 Qi(e){const{Image:t,Video:s}=Ve.getEnv();return e instanceof t?new Ls(e.naturalWidth,e.naturalHeight):e instanceof s?new Ls(e.videoWidth,e.videoHeight):new Ls(e.width,e.height)}function Rr({width:e,height:t}){const{createCanvasElement:s}=Ve.getEnv(),n=s();return n.width=e,n.height=t,n}function Xo(e,t){const{ImageData:s}=Ve.getEnv();if(!(e instanceof s)&&!Ko(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:n,height:i}=t||Qi(e),r=Rr({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 bh(e,t){const s=t||Ve.getEnv().createCanvasElement(),[n,i,r]=e.shape.slice(en(e)?1:0),o=N(()=>e.as3D(n,i,r).toInt());return await pr.toPixels(o,s),o.dispose(),s}function pl(e){const{Image:t,Canvas:s,Video:n}=Ve.getEnv();return e instanceof t||e instanceof s||e instanceof n}function yh(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=Qi(e),o=t/Math.max(r.height,r.width),a=o*r.width,l=o*r.height,c=Rr({width:t,height:t}),p=e instanceof i?e:Xo(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 pi{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(Uo(s)){this._imageTensors[n]=s,this._inputDimensions[n]=s.shape;return}if(en(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:Xo(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 ai(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 Wx({width:t,height:s},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,N(()=>{const s=ai(this.batchSize,0,1).map(i=>{const r=this.getInput(i);if(r instanceof ue){let o=en(r)?r:r.expandDims();return o=th(o,t),(o.shape[1]!==e||o.shape[2]!==e)&&(o=ks.resizeBilinear(o,[e,e])),o.as3D(e,e,3)}if(r instanceof Ve.getEnv().Canvas)return pr.fromPixels(yh(r,e,t));throw new Error(`toBatchTensor - at batchIdx ${i}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${r}`)}),n=Xe(s.map(i=>i.toFloat())).as4D(this.batchSize,e,e,3);return n})}}async function pt(e){if(e instanceof pi)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(Zi);return n.forEach((i,r)=>{if(!pl(i)&&!Uo(i)&&!en(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(en(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=>pl(i)&&Lh(i))),new pi(n,Array.isArray(e))}async function Nr(e,t){const{Canvas:s}=Ve.getEnv();let n=e;if(!(e instanceof s)){const o=await pt(e);if(o.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const a=o.getInput(0);n=a instanceof s?a:await bh(a)}const i=us(n),r=t.map(o=>o instanceof bt?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=Rr({width:l,height:c});return us(p).putImageData(i.getImageData(o,a,l,c),0,0),p})}async function Cr(e,t){if(!Uo(e)&&!en(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(en(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return N(()=>{const[s,n,i]=e.shape.slice(en(e)?1:0),r=t.map(a=>a instanceof bt?a.forSize(n,s).box:a).map(a=>a.clipAtImageBorders(n,s)),o=r.map(({x:a,y:l,width:c,height:p})=>Ci(e.as3D(s,n,i),[l,a,0],[p,c,i]));return o})}async function er(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 jL(e){const t=await er(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 xh(s)}async function wh(e){return(await er(e)).json()}async function PL(e){return new Float32Array(await(await er(e)).arrayBuffer())}function $f(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 gh(e,t){const{manifestUri:s,modelBaseUri:n}=$f(e,t),i=await wh(s);return Ot.loadWeights(i,n)}function BL(e,t,s=!1){const{width:n,height:i}=s?Qi(t):t;return e.width=n,e.height=i,{width:n,height:i}}class hs{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 Xn)}getFrozenParams(){return this.getParamList().filter(e=>!(e.tensor instanceof Xn))}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 gh(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}=$f(e,this.getDefaultModelName()),i=l=>Promise.all(l.map(c=>t(c).then(p=>p.buffer))),r=Ot.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 ue))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:s,objProp:n}}}function Cs(e,t,s){return N(()=>{let n=Ni(e,t.depthwise_filter,t.pointwise_filter,s,"same");return n=W(n,t.bias),n})}function Wf(e,t,s=!1){return N(()=>{const n=ke(s?W(yt(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):Cs(e,t.conv0,[2,2])),i=Cs(n,t.conv1,[1,1]),r=ke(W(n,i)),o=Cs(r,t.conv2,[1,1]);return ke(W(n,W(i,o)))})}function zu(e,t,s=!1,n=!0){return N(()=>{const i=ke(s?W(yt(e,t.conv0.filters,n?[2,2]:[1,1],"same"),t.conv0.bias):Cs(e,t.conv0,n?[2,2]:[1,1])),r=Cs(i,t.conv1,[1,1]),o=ke(W(i,r)),a=Cs(o,t.conv2,[1,1]),l=ke(W(i,W(r,a))),c=Cs(l,t.conv3,[1,1]);return ke(W(i,W(r,W(a,c))))})}function zf(e,t,s="same",n=!1){return N(()=>{const i=W(yt(e,t.filters,[1,1],s),t.bias);return n?ke(i):i})}function Fs(e,t){Object.keys(e).forEach(s=>{t.some(n=>n.originalPath===s)||e[s].dispose()})}function Ha(e,t){return function(s,n,i,r){const o=cs(e(s*n*i*i),[i,i,s,n]),a=Fe(e(n));return t.push({paramPath:`${r}/filters`},{paramPath:`${r}/bias`}),{filters:o,bias:a}}}function Bf(e,t){return function(s,n,i){const r=ts(e(s*n),[s,n]),o=Fe(e(n));return t.push({paramPath:`${i}/weights`},{paramPath:`${i}/bias`}),{weights:r,bias:o}}}class qx{constructor(e,t,s){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=s}}function qa(e,t){return function(s,n,i){const r=cs(e(3*3*s),[3,3,s,1]),o=cs(e(s*n),[1,1,s,n]),a=Fe(e(n));return t.push({paramPath:`${i}/depthwise_filter`},{paramPath:`${i}/pointwise_filter`},{paramPath:`${i}/bias`}),new qx(r,o,a)}}function Ya(e){return function(t){const s=e(`${t}/depthwise_filter`,4),n=e(`${t}/pointwise_filter`,4),i=e(`${t}/bias`,1);return new qx(s,n,i)}}function wn(e,t){return function(s,n,i){const r=e[s];if(!Mo(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 Ms(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 Pf(e,t){const s=Ha(e,t),n=qa(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 iO(e){const t=[],{extractWeights:s,getRemainingWeights:n}=Ms(e),{extractDenseBlock4Params:i}=Pf(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 jf(e){return function(t){const s=e(`${t}/filters`,4),n=e(`${t}/bias`,1);return{filters:s,bias:n}}}function Vf(e,t){const s=wn(e,t),n=jf(s),i=Ya(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 rO(e){const t=[],{extractDenseBlock4Params:s}=Vf(e,t),n={dense0:s("dense0",!0),dense1:s("dense1"),dense2:s("dense2"),dense3:s("dense3")};return Fs(e,t),{params:n,paramMappings:t}}class Gf extends hs{constructor(){super("FaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return N(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=sn(s,n).div(j(255));let r=zu(i,t.dense0,!0);return r=zu(r,t.dense1),r=zu(r,t.dense2),r=zu(r,t.dense3),r=rs(r,[7,7],[2,2],"valid"),r})}async forward(e){return this.forwardInput(await pt(e))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(e){return rO(e)}extractParams(e){return iO(e)}}function Bu(e,t){return N(()=>W(Le(e,t.weights),t.bias))}function oO(e,t,s){const n=[],{extractWeights:i,getRemainingWeights:r}=Ms(e),o=Bf(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 aO(e){const t=[],s=wn(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 Fs(e,t),{params:i,paramMappings:t}}function Hf(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 qf extends hs{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 N(()=>{const s=e instanceof pi?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 oO(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:s}=Hf(e);return this.faceFeatureExtractor.loadFromWeightMap(t),aO(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 dh=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class Ji{constructor(e){if(e.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${e.length}`);dh.forEach((t,s)=>{this[t]=e[s]})}asSortedArray(){return dh.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}}class mh extends qf{constructor(e=new Gf()){super("FaceExpressionNet",e)}forwardInput(e){return N(()=>Yt(this.runNet(e)))}async forward(e){return this.forwardInput(await pt(e))}async predictExpressions(e){const t=await pt(e),s=await this.forwardInput(t),n=await Promise.all(nt(s).map(async r=>{const o=await r.data();return r.dispose(),o}));s.dispose();const i=n.map(r=>new Ji(r));return t.isBatchInput?i:i[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function uh(e){return e.expressions instanceof Ji}function al(e,t){const s={expressions:t};return Object.assign({},e,s)}function mP(e,t,s=.1,n){const i=Array.isArray(t)?t:[t];i.forEach(r=>{const o=r instanceof Ji?r:uh(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=Sn(r)?r.detection.box.bottomLeft:n||new Ee(0,0),p=new Ga(l.map(u=>`${u.expression} (${$o(u.probability)})`),c);p.draw(e)})}function Ki(e){return Sn(e)&&e.landmarks instanceof Ws&&e.unshiftedLandmarks instanceof Ws&&e.alignedRect instanceof bt}function Ar(e,t){const{box:s}=e.detection,n=t.shiftBy(s.x,s.y),i=n.align(),{imageDims:r}=e.detection,o=new bt(e.detection.score,i.rescale(r.reverse()),r),a={landmarks:n,unshiftedLandmarks:t,alignedRect:o};return Object.assign({},e,a)}class lO{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 cO{constructor(e,t={}){this.faceLandmarks=e,this.options=new lO(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 Jo&&(t.strokeStyle=r,t.lineWidth=i,ji(t,this.faceLandmarks.getJawOutline()),ji(t,this.faceLandmarks.getLeftEyeBrow()),ji(t,this.faceLandmarks.getRightEyeBrow()),ji(t,this.faceLandmarks.getNose()),ji(t,this.faceLandmarks.getLeftEye(),!0),ji(t,this.faceLandmarks.getRightEye(),!0),ji(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 fP(e,t){const s=Array.isArray(t)?t:[t];s.forEach(n=>{const i=n instanceof Ws?n:Ki(n)?n.landmarks:void 0;if(!i)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new cO(i).draw(e)})}const Ju={};Re(Ju,{AnchorPosition:()=>li,DrawBox:()=>Hx,DrawBoxOptions:()=>nO,DrawFaceLandmarks:()=>cO,DrawFaceLandmarksOptions:()=>lO,DrawTextField:()=>Ga,DrawTextFieldOptions:()=>Uf,drawContour:()=>ji,drawDetections:()=>dP,drawFaceExpressions:()=>mP,drawFaceLandmarks:()=>fP});function gP(e,t){const s=Ha(e,t),n=qa(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 pO(e,t){const s=[],{extractWeights:n,getRemainingWeights:i}=Ms(e),{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:a,extractMainBlockParams:l}=gP(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={};ai(t,0,1).forEach(b=>{d[`main_block_${b}`]=l(128,`middle_flow/main_block_${b}`)});const m=a(128,256,"exit_flow/reduction_block"),f=o(256,512,"exit_flow/separable_conv"),y={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:y}}}function yP(e,t){const s=wn(e,t),n=jf(s),i=Ya(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 uO(e,t){const s=[],{extractConvParams:n,extractSeparableConvParams:i,extractReductionBlockParams:r,extractMainBlockParams:o}=yP(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={};ai(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 Fs(e,s),{params:{entry_flow:p,middle_flow:u,exit_flow:m},paramMappings:s}}function hO(e,t,s){return W(yt(e,t.filters,s,"same"),t.bias)}function Yx(e,t,s=!0){let n=s?ke(e):e;return n=Cs(n,t.separable_conv0,[1,1]),n=Cs(ke(n),t.separable_conv1,[1,1]),n=lt(n,[3,3],[2,2],"same"),n=W(n,hO(e,t.expansion_conv,[2,2])),n}function bP(e,t){let s=Cs(ke(e),t.separable_conv0,[1,1]);return s=Cs(ke(s),t.separable_conv1,[1,1]),s=Cs(ke(s),t.separable_conv2,[1,1]),s=W(s,e),s}class dO extends hs{constructor(e){super("TinyXception");this._numMainBlocks=e}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyXception - load model before inference");return N(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=sn(s,n).div(j(256));let r=ke(hO(i,t.entry_flow.conv_in,[2,2]));return r=Yx(r,t.entry_flow.reduction_block_0,!1),r=Yx(r,t.entry_flow.reduction_block_1),ai(this._numMainBlocks,0,1).forEach(o=>{r=bP(r,t.middle_flow[`main_block_${o}`])}),r=Yx(r,t.exit_flow.reduction_block),r=ke(Cs(r,t.exit_flow.separable_conv,[1,1])),r})}async forward(e){return this.forwardInput(await pt(e))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(e){return uO(e,this._numMainBlocks)}extractParams(e){return pO(e,this._numMainBlocks)}}function mO(e){const t=[],{extractWeights:s,getRemainingWeights:n}=Ms(e),i=Bf(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 fO(e){const t=[],s=wn(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 Fs(e,t),{params:i,paramMappings:t}}var Vn;(function(e){e.FEMALE="female",e.MALE="male"})(Vn||(Vn={}));class vh extends hs{constructor(e=new dO(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 N(()=>{const s=e instanceof pi?this.faceFeatureExtractor.forwardInput(e):e,n=rs(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 N(()=>{const{age:t,gender:s}=this.runNet(e);return{age:t,gender:Yt(s)}})}async forward(e){return this.forwardInput(await pt(e))}async predictAgeAndGender(e){const t=await pt(e),s=await this.forwardInput(t),n=nt(s.age),i=nt(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?Vn.MALE:Vn.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 mO(e)}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:s}=Hf(e);return this.faceFeatureExtractor.loadFromWeightMap(t),fO(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 Yf extends qf{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 N(()=>{const r=(p,u)=>Xe([Ft([68],p),Ft([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(Ft([i,136],t)).sub(Xe(Array.from(Array(i),(p,u)=>r(a(u),l(u))))).div(Xe(Array.from(Array(i),(p,u)=>r(n[u].width,n[u].height))));return c})}forwardInput(e){return N(()=>{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 pt(e))}async detectLandmarks(e){const t=await pt(e),s=N(()=>nt(this.forwardInput(t))),n=await Promise.all(s.map(async(i,r)=>{const o=Array.from(await i.data()),a=o.filter((c,p)=>Df(p)),l=o.filter((c,p)=>!Df(p));return new Jo(Array(68).fill(0).map((c,p)=>new Ee(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 Yo extends Yf{constructor(e=new Gf()){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function gO(e){const t=[],{extractDenseBlock3Params:s}=Vf(e,t),n={dense0:s("dense0",!0),dense1:s("dense1"),dense2:s("dense2")};return Fs(e,t),{params:n,paramMappings:t}}function yO(e){const t=[],{extractWeights:s,getRemainingWeights:n}=Ms(e),{extractDenseBlock3Params:i}=Pf(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 bO extends hs{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return N(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=sn(s,n).div(j(255));let r=Wf(i,t.dense0,!0);return r=Wf(r,t.dense1),r=Wf(r,t.dense2),r=rs(r,[14,14],[2,2],"valid"),r})}async forward(e){return this.forwardInput(await pt(e))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(e){return gO(e)}extractParams(e){return yO(e)}}class hh extends Yf{constructor(e=new bO()){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class zL extends Yo{}function wO(e,t){return W(C(e,t.weights),t.biases)}function Kx(e,t,s,n,i="same"){const{filters:r,bias:o}=t.conv;let a=yt(e,r,s,i);return a=W(a,o),a=wO(a,t.scale),n?ke(a):a}function xO(e,t){return Kx(e,t,[1,1],!0)}function Xx(e,t){return Kx(e,t,[1,1],!1)}function Kf(e,t){return Kx(e,t,[2,2],!0,"valid")}function wP(e,t){function s(a,l,c){const p=e(a),u=p.length/(l*c*c);if($x(u))throw new Error(`depth has to be an integer: ${u}, weights.length: ${p.length}, numFilters: ${l}, filterSize: ${c}`);return N(()=>se(cs(p,[l,u,c,c]),[2,3,1,0]))}function n(a,l,c,p){const u=s(a,l,c),h=Fe(e(l));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/bias`}),{filters:u,bias:h}}function i(a,l){const c=Fe(e(a)),p=Fe(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 LO(e){const{extractWeights:t,getRemainingWeights:s}=Ms(e),n=[],{extractConvLayerParams:i,extractResidualLayerParams:r}=wP(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"),y=r(147456,128,3,"conv128_2"),b=r(589824,256,3,"conv256_down",!0),S=r(589824,256,3,"conv256_1"),x=r(589824,256,3,"conv256_2"),I=r(589824,256,3,"conv256_down_out"),A=N(()=>se(ts(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 k={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:y,conv256_down:b,conv256_1:S,conv256_2:x,conv256_down_out:I,fc:A};return{params:k,paramMappings:n}}function xP(e,t){const s=wn(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 SO(e){const t=[],{extractConvLayerParams:s,extractResidualLayerParams:n}=xP(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"),y=n("conv256_1"),b=n("conv256_2"),S=n("conv256_down_out"),x=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!Ux(x))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${x}`);const I={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:y,conv256_2:b,conv256_down_out:S,fc:x};return Fs(e,t),{params:I,paramMappings:t}}function jn(e,t){let s=xO(e,t.conv1);return s=Xx(s,t.conv2),s=W(s,e),s=ke(s),s}function Pu(e,t){let s=Kf(e,t.conv1);s=Xx(s,t.conv2);let n=rs(e,2,2,"valid");const i=Ie(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=Ie(a);s=ge([s,l],1);const c=[...s.shape];c[2]=1;const p=Ie(c);s=ge([s,p],2)}return n=r?ge([n,i],3):n,s=W(n,s),s=ke(s),s}class qo extends hs{constructor(){super("FaceRecognitionNet")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return N(()=>{const s=e.toBatchTensor(150,!0).toFloat(),n=[122.782,117.001,104.298],i=sn(s,n).div(j(256));let r=Kf(i,t.conv32_down);r=lt(r,3,2,"valid"),r=jn(r,t.conv32_1),r=jn(r,t.conv32_2),r=jn(r,t.conv32_3),r=Pu(r,t.conv64_down),r=jn(r,t.conv64_1),r=jn(r,t.conv64_2),r=jn(r,t.conv64_3),r=Pu(r,t.conv128_down),r=jn(r,t.conv128_1),r=jn(r,t.conv128_2),r=Pu(r,t.conv256_down),r=jn(r,t.conv256_1),r=jn(r,t.conv256_2),r=Pu(r,t.conv256_down_out);const o=r.mean([1,2]),a=Le(o,t.fc);return a})}async forward(e){return this.forwardInput(await pt(e))}async computeFaceDescriptor(e){const t=await pt(e),s=N(()=>nt(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 SO(e)}extractParams(e){return LO(e)}}function WL(e){const t=new qo();return t.extractWeights(e),t}function ll(e,t){const s={descriptor:t};return Object.assign({},e,s)}function $L(e){return typeof e.age=="number"}function cl(e,t){const s={age:t};return Object.assign({},e,s)}function UL(e){return(e.gender===Vn.MALE||e.gender===Vn.FEMALE)&&Va(e.genderProbability)}function ol(e,t,s){const n={gender:t,genderProbability:s};return Object.assign({},e,n)}class nn{async then(e){return e(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}async function zo(e,t,s,n,i=({alignedRect:r})=>r){const r=e.map(l=>Ki(l)?i(l):l.detection),o=n||(t instanceof ue?await Cr(t,r):await Nr(t,r)),a=await s(o);return o.forEach(l=>l instanceof ue&&l.dispose()),a}async function Ka(e,t,s,n,i){return zo([e],t,async r=>s(r[0]),n,i)}const Xf=e=>typeof e=="number";function Qu(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(!Xf(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=>Xf(t.x)&&Xf(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(Xf)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Xa(e){return N(()=>{const t=C(e,j(.10000000149011612));return W(ke(X(e,t)),t)})}function Vi(e,t){return N(()=>{let s=Ut(e,[[0,0],[1,1],[1,1],[0,0]]);return s=yt(s,t.conv.filters,[1,1],"valid"),s=X(s,t.bn.sub),s=C(s,t.bn.truediv),s=W(s,t.conv.bias),Xa(s)})}function Gi(e,t){return N(()=>{let s=Ut(e,[[0,0],[1,1],[1,1],[0,0]]);return s=Ni(s,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),s=W(s,t.bias),Xa(s)})}function LP(e,t){const s=Ha(e,t);function n(o,a){const l=Fe(e(o)),c=Fe(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=qa(e,t);return{extractConvParams:s,extractConvWithBatchNormParams:i,extractSeparableConvParams:r}}function vO(e,t,s,n){const{extractWeights:i,getRemainingWeights:r}=Ms(e),o=[],{extractConvParams:a,extractConvWithBatchNormParams:l,extractSeparableConvParams:c}=LP(i,o);let p;if(t.withSeparableConvs){const[u,h,d,m,f,y,b,S,x]=n,I=t.isFirstLayerConv2d?a(u,h,3,"conv0"):c(u,h,"conv0"),A=c(h,d,"conv1"),k=c(d,m,"conv2"),R=c(m,f,"conv3"),D=c(f,y,"conv4"),F=c(y,b,"conv5"),M=S?c(b,S,"conv6"):void 0,B=x?c(S,x,"conv7"):void 0,V=a(x||S||b,5*s,1,"conv8");p={conv0:I,conv1:A,conv2:k,conv3:R,conv4:D,conv5:F,conv6:M,conv7:B,conv8:V}}else{const[u,h,d,m,f,y,b,S,x]=n,I=l(u,h,"conv0"),A=l(h,d,"conv1"),k=l(d,m,"conv2"),R=l(m,f,"conv3"),D=l(f,y,"conv4"),F=l(y,b,"conv5"),M=l(b,S,"conv6"),B=l(S,x,"conv7"),V=a(x,5*s,1,"conv8");p={conv0:I,conv1:A,conv2:k,conv3:R,conv4:D,conv5:F,conv6:M,conv7:B,conv8:V}}if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{params:p,paramMappings:o}}function SP(e,t){const s=wn(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=Ya(s);return{extractConvParams:i,extractConvWithBatchNormParams:r,extractSeparableConvParams:o}}function TO(e,t){const s=[],{extractConvParams:n,extractConvWithBatchNormParams:i,extractSeparableConvParams:r}=SP(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 Fs(e,s),{params:o,paramMappings:s}}var eh;(function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"})(eh||(eh={}));class Vo{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 Ja extends hs{constructor(e){super("TinyYolov2");Qu(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=Vi(e,t.conv0);return s=lt(s,[2,2],[2,2],"same"),s=Vi(s,t.conv1),s=lt(s,[2,2],[2,2],"same"),s=Vi(s,t.conv2),s=lt(s,[2,2],[2,2],"same"),s=Vi(s,t.conv3),s=lt(s,[2,2],[2,2],"same"),s=Vi(s,t.conv4),s=lt(s,[2,2],[2,2],"same"),s=Vi(s,t.conv5),s=lt(s,[2,2],[1,1],"same"),s=Vi(s,t.conv6),s=Vi(s,t.conv7),zf(s,t.conv8,"valid",!1)}runMobilenet(e,t){let s=this.config.isFirstLayerConv2d?Xa(zf(e,t.conv0,"valid",!1)):Gi(e,t.conv0);return s=lt(s,[2,2],[2,2],"same"),s=Gi(s,t.conv1),s=lt(s,[2,2],[2,2],"same"),s=Gi(s,t.conv2),s=lt(s,[2,2],[2,2],"same"),s=Gi(s,t.conv3),s=lt(s,[2,2],[2,2],"same"),s=Gi(s,t.conv4),s=lt(s,[2,2],[2,2],"same"),s=Gi(s,t.conv5),s=lt(s,[2,2],[1,1],"same"),s=t.conv6?Gi(s,t.conv6):s,s=t.conv7?Gi(s,t.conv7):s,zf(s,t.conv8,"valid",!1)}forwardInput(e,t){const{params:s}=this;if(!s)throw new Error("TinyYolov2 - load model before inference");return N(()=>{let n=e.toBatchTensor(t,!1).toFloat();return n=this.config.meanRgb?sn(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 pt(e),t)}async detect(e,t={}){const{inputSize:s,scoreThreshold:n}=new Vo(t),i=await pt(e),r=await this.forwardInput(i,s),o=N(()=>nt(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=sh(c.map(f=>f.rescale(s)),p,this.config.iouThreshold,!0),m=d.map(f=>new Or(p[f],u[f],h[f],c[f],a));return m}getDefaultModelName(){return""}extractParamsFromWeigthMap(e){return TO(e,this.config)}extractParams(e){const t=this.config.filterSizes||Ja.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 vO(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]=N(()=>{const y=e.reshape([l,l,c,this.boxEncodingSize]),b=y.slice([0,0,0,0],[l,l,c,4]),S=y.slice([0,0,0,4],[l,l,c,1]),x=this.withClassScores?Yt(y.slice([0,0,0,5],[l,l,c,this.config.classes.length]),3):j(0);return[b,S,x]}),d=[],m=await u.array(),f=await p.array();for(let y=0;y<l;y++)for(let b=0;b<l;b++)for(let S=0;S<c;S++){const x=Ho(m[y][b][S][0]);if(!s||x>s){const I=(b+Ho(f[y][b][S][0]))/l*o,A=(y+Ho(f[y][b][S][1]))/l*a,k=Math.exp(f[y][b][S][2])*this.config.anchors[S].x/l*o,R=Math.exp(f[y][b][S][3])*this.config.anchors[S].y/l*a,D=I-k/2,F=A-R/2,M={row:y,col:b,anchor:S},{classScore:B,label:V}=this.withClassScores?await this.extractPredictedClass(h,M):{classScore:1,label:0};d.push({box:new Zo(D,F,D+k,F+R),score:x,classScore:x*B,label:V,...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)}}Ja.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];const IO=.4,AO=[new Ee(1.603231,2.094468),new Ee(6.041143,7.080126),new Ee(2.882459,3.518061),new Ee(4.266906,5.178857),new Ee(9.041765,10.66308)],NO=[117.001,114.697,97.404];class Ir extends Ja{constructor(){const e={withSeparableConvs:!0,iouThreshold:IO,classes:["face"],anchors:AO,meanRgb:NO,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 bt(n.score,n.relativeBox,{width:n.imageWidth,height:n.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}const CO=.4,RO=[new Ee(.738768,.874946),new Ee(2.42204,2.65704),new Ee(4.30971,7.04493),new Ee(10.246,4.59428),new Ee(12.6868,11.8741)],OO=[new Ee(1.603231,2.094468),new Ee(6.041143,7.080126),new Ee(2.882459,3.518061),new Ee(4.266906,5.178857),new Ee(9.041765,10.66308)],EO=[117.001,114.697,97.404],kO="tiny_yolov2_model",_O="tiny_yolov2_separable_conv_model";class Go extends Ja{constructor(e=!0){const t=Object.assign({},{withSeparableConvs:e,iouThreshold:CO,classes:["face"]},e?{anchors:OO,meanRgb:EO}:{anchors:RO,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 bt(n.score,n.relativeBox,{width:n.imageWidth,height:n.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?_O:kO}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}function yL(e,t=!0){const s=new Go(t);return s.extractWeights(e),s}const Qe={tinyFaceDetector:new Ir(),tinyYolov2:new Go(),faceLandmark68Net:new Yo(),faceLandmark68TinyNet:new hh(),faceRecognitionNet:new qo(),faceExpressionNet:new mh(),ageGenderNet:new vh()},LL=(e,t)=>Qe.tinyFaceDetector.locateFaces(e,t),og=e=>Qe.faceLandmark68Net.detectLandmarks(e),SL=e=>Qe.faceLandmark68TinyNet.detectLandmarks(e),vL=e=>Qe.faceRecognitionNet.computeFaceDescriptor(e),TL=e=>Qe.faceExpressionNet.predictExpressions(e),IL=e=>Qe.ageGenderNet.predictAgeAndGender(e),ag=e=>Qe.tinyFaceDetector.load(e),AL=e=>Qe.tinyYolov2.load(e),NL=e=>Qe.faceLandmark68Net.load(e),CL=e=>Qe.faceLandmark68TinyNet.load(e),RL=e=>Qe.faceRecognitionNet.load(e),OL=e=>Qe.faceExpressionNet.load(e),EL=e=>Qe.ageGenderNet.load(e),kL=ag,_L=Ir,DL=og;class DO extends nn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.extractedFaces=s}}class Gu extends DO{async run(){const e=await this.parentTask,t=await zo(e,this.input,async s=>await Promise.all(s.map(n=>Qe.faceExpressionNet.predictExpressions(n))),this.extractedFaces);return e.map((s,n)=>al(s,t[n]))}withAgeAndGender(){return new ju(this,this.input)}}class Hu extends DO{async run(){const e=await this.parentTask;if(!e)return;const t=await Ka(e,this.input,s=>Qe.faceExpressionNet.predictExpressions(s),this.extractedFaces);return al(e,t)}withAgeAndGender(){return new Vu(this,this.input)}}class el extends Gu{withAgeAndGender(){return new Za(this,this.input)}withFaceDescriptors(){return new qi(this,this.input)}}class tl extends Hu{withAgeAndGender(){return new Qa(this,this.input)}withFaceDescriptor(){return new Yi(this,this.input)}}class FO extends nn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.extractedFaces=s}}class ju extends FO{async run(){const e=await this.parentTask,t=await zo(e,this.input,async s=>await Promise.all(s.map(n=>Qe.ageGenderNet.predictAgeAndGender(n))),this.extractedFaces);return e.map((s,n)=>{const{age:i,gender:r,genderProbability:o}=t[n];return cl(ol(s,r,o),i)})}withFaceExpressions(){return new Gu(this,this.input)}}class Vu extends FO{async run(){const e=await this.parentTask;if(!e)return;const{age:t,gender:s,genderProbability:n}=await Ka(e,this.input,i=>Qe.ageGenderNet.predictAgeAndGender(i),this.extractedFaces);return cl(ol(e,s,n),t)}withFaceExpressions(){return new Hu(this,this.input)}}class Za extends ju{withFaceExpressions(){return new el(this,this.input)}withFaceDescriptors(){return new qi(this,this.input)}}class Qa extends Vu{withFaceExpressions(){return new tl(this,this.input)}withFaceDescriptor(){return new Yi(this,this.input)}}class ph extends nn{constructor(e,t){super();this.parentTask=e,this.input=t}}class qi extends ph{async run(){const e=await this.parentTask,t=await zo(e,this.input,s=>Promise.all(s.map(n=>Qe.faceRecognitionNet.computeFaceDescriptor(n))),null,s=>s.landmarks.align(null,{useDlibAlignment:!0}));return t.map((s,n)=>ll(e[n],s))}withFaceExpressions(){return new el(this,this.input)}withAgeAndGender(){return new Za(this,this.input)}}class Yi extends ph{async run(){const e=await this.parentTask;if(!e)return;const t=await Ka(e,this.input,s=>Qe.faceRecognitionNet.computeFaceDescriptor(s),null,s=>s.landmarks.align(null,{useDlibAlignment:!0}));return ll(e,t)}withFaceExpressions(){return new tl(this,this.input)}withAgeAndGender(){return new Qa(this,this.input)}}class Hi extends Vo{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class ah extends nn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.useTinyLandmarkNet=s}get landmarkNet(){return this.useTinyLandmarkNet?Qe.faceLandmark68TinyNet:Qe.faceLandmark68Net}}class lh extends ah{async run(){const e=await this.parentTask,t=e.map(i=>i.detection),s=this.input instanceof ue?await Cr(this.input,t):await Nr(this.input,t),n=await Promise.all(s.map(i=>this.landmarkNet.detectLandmarks(i)));return s.forEach(i=>i instanceof ue&&i.dispose()),e.map((i,r)=>Ar(i,n[r]))}withFaceExpressions(){return new el(this,this.input)}withAgeAndGender(){return new Za(this,this.input)}withFaceDescriptors(){return new qi(this,this.input)}}class ch extends ah{async run(){const e=await this.parentTask;if(!e)return;const{detection:t}=e,s=this.input instanceof ue?await Cr(this.input,[t]):await Nr(this.input,[t]),n=await this.landmarkNet.detectLandmarks(s[0]);return s.forEach(i=>i instanceof ue&&i.dispose()),Ar(e,n)}withFaceExpressions(){return new tl(this,this.input)}withAgeAndGender(){return new Qa(this,this.input)}withFaceDescriptor(){return new Yi(this,this.input)}}class rh extends nn{constructor(e,t=new Hi()){super();this.input=e,this.options=t}}class rl extends rh{async run(){const{input:e,options:t}=this,s=t instanceof Hi?n=>Qe.tinyFaceDetector.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=>Xi({},s)))})}withFaceLandmarks(e=!1){return new lh(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new Gu(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new ju(this.runAndExtendWithFaceDetections(),this.input)}}class oh extends rh{async run(){const e=await new rl(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?Xi({},t):void 0)})}withFaceLandmarks(e=!1){return new ch(this.runAndExtendWithFaceDetection(),this.input,e)}withFaceExpressions(){return new Hu(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Vu(this.runAndExtendWithFaceDetection(),this.input)}}function FL(e,t=new Hi()){return new oh(e,t)}function ML(e,t=new Hi()){return new rl(e,t)}function fh(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 lg{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 tr)return r;if(r instanceof Float32Array)return new tr(i(),[r]);if(r.descriptor&&r.descriptor instanceof Float32Array)return new tr(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=>fh(s,e)).reduce((s,n)=>s+n,0)/(t.length||1)}matchDescriptor(e){return this.labeledDescriptors.map(({descriptors:t,label:s})=>new hl(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 hl("unknown",t.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(e=>e.toJSON())}}static fromJSON(e){const t=e.labeledDescriptors.map(s=>tr.fromJSON(s));return new lg(t,e.distanceThreshold)}}function bL(e){const t=new Ir();return t.extractWeights(e),t}function rg(e,t){const{width:s,height:n}=new Ls(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=>rg(i,{width:s,height:n}));if(Ki(e)){const i=e.detection.forSize(s,n),r=e.unshiftedLandmarks.forSize(i.box.width,i.box.height);return Ar(Xi(e,i),r)}return Sn(e)?Xi(e,e.detection.forSize(s,n)):e instanceof Ws||e instanceof bt?e.forSize(s,n):e}return HL();})();
/**
* @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. 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.min.js.map