(window.webpackJsonp=window.webpackJsonp||[]).push([[61],{"1uat":function(d,V,O){(function(y,l,M){d.exports=V=l(O("Ib8C"),O("MlIO"))})(this,function(y){return function(){var l=y,M=l.lib,D=M.Hasher,A=l.x64,x=A.Word,v=A.WordArray,h=l.algo;function p(){return x.create.apply(x,arguments)}var c=[p(1116352408,3609767458),p(1899447441,602891725),p(3049323471,3964484399),p(3921009573,2173295548),p(961987163,4081628472),p(1508970993,3053834265),p(2453635748,2937671579),p(2870763221,3664609560),p(3624381080,2734883394),p(310598401,1164996542),p(607225278,1323610764),p(1426881987,3590304994),p(1925078388,4068182383),p(2162078206,991336113),p(2614888103,633803317),p(3248222580,3479774868),p(3835390401,2666613458),p(4022224774,944711139),p(264347078,2341262773),p(604807628,2007800933),p(770255983,1495990901),p(1249150122,1856431235),p(1555081692,3175218132),p(1996064986,2198950837),p(2554220882,3999719339),p(2821834349,766784016),p(2952996808,2566594879),p(3210313671,3203337956),p(3336571891,1034457026),p(3584528711,2466948901),p(113926993,3758326383),p(338241895,168717936),p(666307205,1188179964),p(773529912,1546045734),p(1294757372,1522805485),p(1396182291,2643833823),p(1695183700,2343527390),p(1986661051,1014477480),p(2177026350,1206759142),p(2456956037,344077627),p(2730485921,1290863460),p(2820302411,3158454273),p(3259730800,3505952657),p(3345764771,106217008),p(3516065817,3606008344),p(3600352804,1432725776),p(4094571909,1467031594),p(275423344,851169720),p(430227734,3100823752),p(506948616,1363258195),p(659060556,3750685593),p(883997877,3785050280),p(958139571,3318307427),p(1322822218,3812723403),p(1537002063,2003034995),p(1747873779,3602036899),p(1955562222,1575990012),p(2024104815,1125592928),p(2227730452,2716904306),p(2361852424,442776044),p(2428436474,593698344),p(2756734187,3733110249),p(3204031479,2999351573),p(3329325298,3815920427),p(3391569614,3928383900),p(3515267271,566280711),p(3940187606,3454069534),p(4118630271,4000239992),p(116418474,1914138554),p(174292421,2731055270),p(289380356,3203993006),p(460393269,320620315),p(685471733,587496836),p(852142971,1086792851),p(1017036298,365543100),p(1126000580,2618297676),p(1288033470,3409855158),p(1501505948,4234509866),p(1607167915,987167468),p(1816402316,1246189591)],m=[];(function(){for(var g=0;g<80;g++)m[g]=p()})();var C=h.SHA512=D.extend({_doReset:function(){this._hash=new v.init([new x.init(1779033703,4089235720),new x.init(3144134277,2227873595),new x.init(1013904242,4271175723),new x.init(2773480762,1595750129),new x.init(1359893119,2917565137),new x.init(2600822924,725511199),new x.init(528734635,4215389547),new x.init(1541459225,327033209)])},_doProcessBlock:function(g,T){for(var B=this._hash.words,F=B[0],J=B[1],H=B[2],K=B[3],Y=B[4],W=B[5],U=B[6],_=B[7],te=F.high,q=F.low,w=J.high,X=J.low,ne=H.high,he=H.low,le=K.high,_e=K.low,se=Y.high,be=Y.low,j=W.high,Q=W.low,L=U.high,re=U.low,de=_.high,ee=_.low,xe=te,Ne=q,Le=w,Ge=X,Qe=ne,Te=he,nt=le,Ye=_e,Pe=se,ke=be,Be=j,ot=Q,ve=L,ge=re,$e=de,pe=ee,Z=0;Z<80;Z++){var k,$,Re=m[Z];if(Z<16)$=Re.high=g[T+Z*2]|0,k=Re.low=g[T+Z*2+1]|0;else{var Ae=m[Z-15],Xe=Ae.high,rt=Ae.low,lt=(Xe>>>1|rt<<31)^(Xe>>>8|rt<<24)^Xe>>>7,bt=(rt>>>1|Xe<<31)^(rt>>>8|Xe<<24)^(rt>>>7|Xe<<25),Tt=m[Z-2],xt=Tt.high,Et=Tt.low,Nt=(xt>>>19|Et<<13)^(xt<<3|Et>>>29)^xt>>>6,at=(Et>>>19|xt<<13)^(Et<<3|xt>>>29)^(Et>>>6|xt<<26),Bt=m[Z-7],mr=Bt.high,rr=Bt.low,Sr=m[Z-16],Lr=Sr.high,Dr=Sr.low;k=bt+rr,$=lt+mr+(k>>>0>>0?1:0),k=k+at,$=$+Nt+(k>>>0>>0?1:0),k=k+Dr,$=$+Lr+(k>>>0>>0?1:0),Re.high=$,Re.low=k}var Ar=Pe&Be^~Pe&ve,et=ke&ot^~ke&ge,Xn=xe&Le^xe&Qe^Le&Qe,Nr=Ne&Ge^Ne&Te^Ge&Te,No=(xe>>>28|Ne<<4)^(xe<<30|Ne>>>2)^(xe<<25|Ne>>>7),Kn=(Ne>>>28|xe<<4)^(Ne<<30|xe>>>2)^(Ne<<25|xe>>>7),co=(Pe>>>14|ke<<18)^(Pe>>>18|ke<<14)^(Pe<<23|ke>>>9),Cr=(ke>>>14|Pe<<18)^(ke>>>18|Pe<<14)^(ke<<23|Pe>>>9),lo=c[Z],_n=lo.high,fo=lo.low,nr=pe+Cr,hr=$e+co+(nr>>>0>>0?1:0),nr=nr+et,hr=hr+Ar+(nr>>>0>>0?1:0),nr=nr+fo,hr=hr+_n+(nr>>>0>>0?1:0),nr=nr+k,hr=hr+$+(nr>>>0>>0?1:0),cr=Kn+Nr,nn=No+Xn+(cr>>>0>>0?1:0);$e=ve,pe=ge,ve=Be,ge=ot,Be=Pe,ot=ke,ke=Ye+nr|0,Pe=nt+hr+(ke>>>0>>0?1:0)|0,nt=Qe,Ye=Te,Qe=Le,Te=Ge,Le=xe,Ge=Ne,Ne=nr+cr|0,xe=hr+nn+(Ne>>>0>>0?1:0)|0}q=F.low=q+Ne,F.high=te+xe+(q>>>0>>0?1:0),X=J.low=X+Ge,J.high=w+Le+(X>>>0>>0?1:0),he=H.low=he+Te,H.high=ne+Qe+(he>>>0>>0?1:0),_e=K.low=_e+Ye,K.high=le+nt+(_e>>>0>>0?1:0),be=Y.low=be+ke,Y.high=se+Pe+(be>>>0>>0?1:0),Q=W.low=Q+ot,W.high=j+Be+(Q>>>0>>0?1:0),re=U.low=re+ge,U.high=L+ve+(re>>>0>>0?1:0),ee=_.low=ee+pe,_.high=de+$e+(ee>>>0>>0?1:0)},_doFinalize:function(){var g=this._data,T=g.words,B=this._nDataBytes*8,F=g.sigBytes*8;T[F>>>5]|=128<<24-F%32,T[(F+128>>>10<<5)+30]=Math.floor(B/4294967296),T[(F+128>>>10<<5)+31]=B,g.sigBytes=T.length*4,this._process();var J=this._hash.toX32();return J},clone:function(){var g=D.clone.call(this);return g._hash=this._hash.clone(),g},blockSize:1024/32});l.SHA512=D._createHelper(C),l.HmacSHA512=D._createHmacHelper(C)}(),y.SHA512})},"2LEM":function(d,V,O){d.exports=O.p+"static/checkPeople.d3191bb4.jpg"},"2U/9":function(d,V,O){"use strict";var y=O("VTBJ"),l=O("rePB"),M=O("Ff2n"),D=O("1OyB"),A=O("vuIU"),x=O("Ji7U"),v=O("LK+K"),h=O("q1tI"),p=O.n(h),c=O("Zm9Q"),m=O("TSYQ"),C=O.n(m),g=["className","prefixCls","style","active","status","iconPrefix","icon","wrapperStyle","stepNumber","disabled","description","title","subTitle","progressDot","stepIcon","tailContent","icons","stepIndex","onStepClick","onClick"];function T(K){return typeof K=="string"}var B=function(K){Object(x.a)(W,K);var Y=Object(v.a)(W);function W(){var U;return Object(D.a)(this,W),U=Y.apply(this,arguments),U.onClick=function(){var _=U.props,te=_.onClick,q=_.onStepClick,w=_.stepIndex;te&&te.apply(void 0,arguments),q(w)},U}return Object(A.a)(W,[{key:"renderIconNode",value:function(){var _,te=this.props,q=te.prefixCls,w=te.progressDot,X=te.stepIcon,ne=te.stepNumber,he=te.status,le=te.title,_e=te.description,se=te.icon,be=te.iconPrefix,j=te.icons,Q,L=C()("".concat(q,"-icon"),"".concat(be,"icon"),(_={},Object(l.a)(_,"".concat(be,"icon-").concat(se),se&&T(se)),Object(l.a)(_,"".concat(be,"icon-check"),!se&&he==="finish"&&(j&&!j.finish||!j)),Object(l.a)(_,"".concat(be,"icon-cross"),!se&&he==="error"&&(j&&!j.error||!j)),_)),re=h.createElement("span",{className:"".concat(q,"-icon-dot")});return w?typeof w=="function"?Q=h.createElement("span",{className:"".concat(q,"-icon")},w(re,{index:ne-1,status:he,title:le,description:_e})):Q=h.createElement("span",{className:"".concat(q,"-icon")},re):se&&!T(se)?Q=h.createElement("span",{className:"".concat(q,"-icon")},se):j&&j.finish&&he==="finish"?Q=h.createElement("span",{className:"".concat(q,"-icon")},j.finish):j&&j.error&&he==="error"?Q=h.createElement("span",{className:"".concat(q,"-icon")},j.error):se||he==="finish"||he==="error"?Q=h.createElement("span",{className:L}):Q=h.createElement("span",{className:"".concat(q,"-icon")},ne),X&&(Q=X({index:ne-1,status:he,title:le,description:_e,node:Q})),Q}},{key:"render",value:function(){var _,te=this.props,q=te.className,w=te.prefixCls,X=te.style,ne=te.active,he=te.status,le=he===void 0?"wait":he,_e=te.iconPrefix,se=te.icon,be=te.wrapperStyle,j=te.stepNumber,Q=te.disabled,L=te.description,re=te.title,de=te.subTitle,ee=te.progressDot,xe=te.stepIcon,Ne=te.tailContent,Le=te.icons,Ge=te.stepIndex,Qe=te.onStepClick,Te=te.onClick,nt=Object(M.a)(te,g),Ye=C()("".concat(w,"-item"),"".concat(w,"-item-").concat(le),q,(_={},Object(l.a)(_,"".concat(w,"-item-custom"),se),Object(l.a)(_,"".concat(w,"-item-active"),ne),Object(l.a)(_,"".concat(w,"-item-disabled"),Q===!0),_)),Pe=Object(y.a)({},X),ke={};return Qe&&!Q&&(ke.role="button",ke.tabIndex=0,ke.onClick=this.onClick),h.createElement("div",Object.assign({},nt,{className:Ye,style:Pe}),h.createElement("div",Object.assign({onClick:Te},ke,{className:"".concat(w,"-item-container")}),h.createElement("div",{className:"".concat(w,"-item-tail")},Ne),h.createElement("div",{className:"".concat(w,"-item-icon")},this.renderIconNode()),h.createElement("div",{className:"".concat(w,"-item-content")},h.createElement("div",{className:"".concat(w,"-item-title")},re,de&&h.createElement("div",{title:typeof de=="string"?de:void 0,className:"".concat(w,"-item-subtitle")},de)),L&&h.createElement("div",{className:"".concat(w,"-item-description")},L))))}}]),W}(h.Component),F=["prefixCls","style","className","children","direction","type","labelPlacement","iconPrefix","status","size","current","progressDot","stepIcon","initial","icons","onChange"],J=function(K){Object(x.a)(W,K);var Y=Object(v.a)(W);function W(){var U;return Object(D.a)(this,W),U=Y.apply(this,arguments),U.onStepClick=function(_){var te=U.props,q=te.onChange,w=te.current;q&&w!==_&&q(_)},U}return Object(A.a)(W,[{key:"render",value:function(){var _,te=this,q=this.props,w=q.prefixCls,X=q.style,ne=X===void 0?{}:X,he=q.className,le=q.children,_e=q.direction,se=q.type,be=q.labelPlacement,j=q.iconPrefix,Q=q.status,L=q.size,re=q.current,de=q.progressDot,ee=q.stepIcon,xe=q.initial,Ne=q.icons,Le=q.onChange,Ge=Object(M.a)(q,F),Qe=se==="navigation",Te=de?"vertical":be,nt=C()(w,"".concat(w,"-").concat(_e),he,(_={},Object(l.a)(_,"".concat(w,"-").concat(L),L),Object(l.a)(_,"".concat(w,"-label-").concat(Te),_e==="horizontal"),Object(l.a)(_,"".concat(w,"-dot"),!!de),Object(l.a)(_,"".concat(w,"-navigation"),Qe),_));return p.a.createElement("div",Object.assign({className:nt,style:ne},Ge),Object(c.a)(le).map(function(Ye,Pe){var ke=xe+Pe,Be=Object(y.a)({stepNumber:"".concat(ke+1),stepIndex:ke,key:ke,prefixCls:w,iconPrefix:j,wrapperStyle:ne,progressDot:de,stepIcon:ee,icons:Ne,onStepClick:Le&&te.onStepClick},Ye.props);return Q==="error"&&Pe===re-1&&(Be.className="".concat(w,"-next-error")),Ye.props.status||(ke===re?Be.status=Q:ke>>31}var K=(C<<5|C>>>27)+F+v[J];J<20?K+=(g&T|~g&B)+1518500249:J<40?K+=(g^T^B)+1859775393:J<60?K+=(g&T|g&B|T&B)-1894007588:K+=(g^T^B)-899497514,F=B,B=T,T=g<<30|g>>>2,g=C,C=K}m[0]=m[0]+C|0,m[1]=m[1]+g|0,m[2]=m[2]+T|0,m[3]=m[3]+B|0,m[4]=m[4]+F|0},_doFinalize:function(){var p=this._data,c=p.words,m=this._nDataBytes*8,C=p.sigBytes*8;return c[C>>>5]|=128<<24-C%32,c[(C+64>>>9<<4)+14]=Math.floor(m/4294967296),c[(C+64>>>9<<4)+15]=m,p.sigBytes=c.length*4,this._process(),this._hash},clone:function(){var p=A.clone.call(this);return p._hash=this._hash.clone(),p}});l.SHA1=A._createHelper(h),l.HmacSHA1=A._createHmacHelper(h)}(),y.SHA1})},4:function(d,V){},5:function(d,V){},"5hvy":function(d,V,O){(function(y,l,M){d.exports=V=l(O("Ib8C"),O("MlIO"))})(this,function(y){return function(l){var M=y,D=M.lib,A=D.WordArray,x=D.Hasher,v=M.x64,h=v.Word,p=M.algo,c=[],m=[],C=[];(function(){for(var B=1,F=0,J=0;J<24;J++){c[B+5*F]=(J+1)*(J+2)/2%64;var H=F%5,K=(2*B+3*F)%5;B=H,F=K}for(var B=0;B<5;B++)for(var F=0;F<5;F++)m[B+5*F]=F+(2*B+3*F)%5*5;for(var Y=1,W=0;W<24;W++){for(var U=0,_=0,te=0;te<7;te++){if(Y&1){var q=(1<>>24)&16711935|(Y<<24|Y>>>8)&4278255360,W=(W<<8|W>>>24)&16711935|(W<<24|W>>>8)&4278255360;var U=J[K];U.high^=W,U.low^=Y}for(var _=0;_<24;_++){for(var te=0;te<5;te++){for(var q=0,w=0,X=0;X<5;X++){var U=J[te+5*X];q^=U.high,w^=U.low}var ne=g[te];ne.high=q,ne.low=w}for(var te=0;te<5;te++)for(var he=g[(te+4)%5],le=g[(te+1)%5],_e=le.high,se=le.low,q=he.high^(_e<<1|se>>>31),w=he.low^(se<<1|_e>>>31),X=0;X<5;X++){var U=J[te+5*X];U.high^=q,U.low^=w}for(var be=1;be<25;be++){var q,w,U=J[be],j=U.high,Q=U.low,L=c[be];L<32?(q=j<>>32-L,w=Q<>>32-L):(q=Q<>>64-L,w=j<>>64-L);var re=g[m[be]];re.high=q,re.low=w}var de=g[0],ee=J[0];de.high=ee.high,de.low=ee.low;for(var te=0;te<5;te++)for(var X=0;X<5;X++){var be=te+5*X,U=J[be],xe=g[be],Ne=g[(te+1)%5+5*X],Le=g[(te+2)%5+5*X];U.high=xe.high^~Ne.high&Le.high,U.low=xe.low^~Ne.low&Le.low}var U=J[0],Ge=C[_];U.high^=Ge.high,U.low^=Ge.low}},_doFinalize:function(){var B=this._data,F=B.words,J=this._nDataBytes*8,H=B.sigBytes*8,K=this.blockSize*32;F[H>>>5]|=1<<24-H%32,F[(l.ceil((H+1)/K)*K>>>5)-1]|=128,B.sigBytes=F.length*4,this._process();for(var Y=this._state,W=this.cfg.outputLength/8,U=W/8,_=[],te=0;te>>24)&16711935|(w<<24|w>>>8)&4278255360,X=(X<<8|X>>>24)&16711935|(X<<24|X>>>8)&4278255360,_.push(X),_.push(w)}return new A.init(_,W)},clone:function(){for(var B=x.clone.call(this),F=B._state=this._state.slice(0),J=0;J<25;J++)F[J]=F[J].clone();return B}});M.SHA3=x._createHelper(T),M.HmacSHA3=x._createHmacHelper(T)}(Math),y.SHA3})},6:function(d,V){},7:function(d,V){},"7Cbv":function(d,V,O){"use strict";var y=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),l=new Uint8Array(16);function M(){if(!y)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return y(l)}var D=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function A(g){return typeof g=="string"&&D.test(g)}for(var x=A,v=[],h=0;h<256;++h)v.push((h+256).toString(16).substr(1));function p(g){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,B=(v[g[T+0]]+v[g[T+1]]+v[g[T+2]]+v[g[T+3]]+"-"+v[g[T+4]]+v[g[T+5]]+"-"+v[g[T+6]]+v[g[T+7]]+"-"+v[g[T+8]]+v[g[T+9]]+"-"+v[g[T+10]]+v[g[T+11]]+v[g[T+12]]+v[g[T+13]]+v[g[T+14]]+v[g[T+15]]).toLowerCase();if(!x(B))throw TypeError("Stringified UUID is invalid");return B}var c=p;function m(g,T,B){g=g||{};var F=g.random||(g.rng||M)();if(F[6]=F[6]&15|64,F[8]=F[8]&63|128,T){B=B||0;for(var J=0;J<16;++J)T[B+J]=F[J];return T}return c(F)}var C=V.a=m},"7ixt":function(d,V,O){"use strict";O.d(V,"a",function(){return M});var y={adjustX:1,adjustY:1},l=[0,0],M={left:{points:["cr","cl"],overflow:y,offset:[-4,0],targetOffset:l},right:{points:["cl","cr"],overflow:y,offset:[4,0],targetOffset:l},top:{points:["bc","tc"],overflow:y,offset:[0,-4],targetOffset:l},bottom:{points:["tc","bc"],overflow:y,offset:[0,4],targetOffset:l},topLeft:{points:["bl","tl"],overflow:y,offset:[0,-4],targetOffset:l},leftTop:{points:["tr","tl"],overflow:y,offset:[-4,0],targetOffset:l},topRight:{points:["br","tr"],overflow:y,offset:[0,-4],targetOffset:l},rightTop:{points:["tl","tr"],overflow:y,offset:[4,0],targetOffset:l},bottomRight:{points:["tr","br"],overflow:y,offset:[0,4],targetOffset:l},rightBottom:{points:["bl","br"],overflow:y,offset:[4,0],targetOffset:l},bottomLeft:{points:["tl","bl"],overflow:y,offset:[0,4],targetOffset:l},leftBottom:{points:["br","bl"],overflow:y,offset:[-4,0],targetOffset:l}},D=M},"8KZw":function(d,V,O){"use strict";(function(y,l){O.d(V,"a",function(){return M});function M(){return typeof y=="object"&&!0&&typeof d!="undefined"&&typeof l!="undefined"&&!!l.version}}).call(this,O("IyRk"),O("Q2Ig"))},"9OqN":function(d,V,O){(function(y,l,M){d.exports=V=l(O("Ib8C"),O("OLod"))})(this,function(y){return y.mode.CTR=function(){var l=y.lib.BlockCipherMode.extend(),M=l.Encryptor=l.extend({processBlock:function(D,A){var x=this._cipher,v=x.blockSize,h=this._iv,p=this._counter;h&&(p=this._counter=h.slice(0),this._iv=void 0);var c=p.slice(0);x.encryptBlock(c,0),p[v-1]=p[v-1]+1|0;for(var m=0;m=0)continue;if(!Object.prototype.propertyIsEnumerable.call(se,Q))continue;j[Q]=se[Q]}}return j}function x(se,be){if(se==null)return{};var j={},Q=Object.keys(se),L,re;for(re=0;re=0)continue;j[L]=se[L]}return j}function v(se,be){if(!(se instanceof be))throw new TypeError("Cannot call a class as a function")}function h(se,be){for(var j=0;j>6),be+=String.fromCharCode(128|Q&63)):Q<55296||Q>=57344?(be+=String.fromCharCode(224|Q>>12),be+=String.fromCharCode(128|Q>>6&63),be+=String.fromCharCode(128|Q&63)):(j++,Q=65536+((Q&1023)<<10|se.charCodeAt(j)&1023),be+=String.fromCharCode(240|Q>>18),be+=String.fromCharCode(128|Q>>12&63),be+=String.fromCharCode(128|Q>>6&63),be+=String.fromCharCode(128|Q&63))}return be}var W={size:128,level:"L",bgColor:"#FFFFFF",fgColor:"#000000",includeMargin:!1},U={},_=4,te=.1;function q(se){var be=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,j=[];return se.forEach(function(Q,L){var re=null;Q.forEach(function(de,ee){if(!de&&re!==null){j.push("M".concat(re+be," ").concat(L+be,"h").concat(ee-re,"v1H").concat(re+be,"z")),re=null;return}if(ee===Q.length-1){if(!de)return;re===null?j.push("M".concat(ee+be,",").concat(L+be," h1v1H").concat(ee+be,"z")):j.push("M".concat(re+be,",").concat(L+be," h").concat(ee+1-re,"v1H").concat(re+be,"z"));return}de&&re===null&&(re=ee)})}),j.join("")}function w(se,be){return se.slice().map(function(j,Q){return Q=be.y+be.h?j:j.map(function(L,re){return re=be.x+be.w?L:!1})})}function X(se,be){var j=se.imageSettings,Q=se.size,L=se.includeMargin;if(j==null)return null;var re=L?_:0,de=be.length+re*2,ee=Math.floor(Q*te),xe=de/Q,Ne=(j.width||ee)*xe,Le=(j.height||ee)*xe,Ge=j.x==null?be.length/2-Ne/2:j.x*xe,Qe=j.y==null?be.length/2-Le/2:j.y*xe,Te=null;if(j.excavate){var nt=Math.floor(Ge),Ye=Math.floor(Qe),Pe=Math.ceil(Ne+Ge-nt),ke=Math.ceil(Le+Qe-Ye);Te={x:nt,y:Ye,w:Pe,h:ke}}return{x:Ge,y:Qe,h:Le,w:Ne,excavation:Te}}var ne=function(){try{new Path2D().addPath(new Path2D)}catch(se){return!1}return!0}(),he=function(se){g(be,se);function be(){var j,Q;v(this,be);for(var L=arguments.length,re=new Array(L),de=0;de>>24)&16711935|(m[g]<<24|m[g]>>>8)&4278255360;var T=this._X=[m[0],m[3]<<16|m[2]>>>16,m[1],m[0]<<16|m[3]>>>16,m[2],m[1]<<16|m[0]>>>16,m[3],m[2]<<16|m[1]>>>16],B=this._C=[m[2]<<16|m[2]>>>16,m[0]&4294901760|m[1]&65535,m[3]<<16|m[3]>>>16,m[1]&4294901760|m[2]&65535,m[0]<<16|m[0]>>>16,m[2]&4294901760|m[3]&65535,m[1]<<16|m[1]>>>16,m[3]&4294901760|m[0]&65535];this._b=0;for(var g=0;g<4;g++)c.call(this);for(var g=0;g<8;g++)B[g]^=T[g+4&7];if(C){var F=C.words,J=F[0],H=F[1],K=(J<<8|J>>>24)&16711935|(J<<24|J>>>8)&4278255360,Y=(H<<8|H>>>24)&16711935|(H<<24|H>>>8)&4278255360,W=K>>>16|Y&4294901760,U=Y<<16|K&65535;B[0]^=K,B[1]^=W,B[2]^=Y,B[3]^=U,B[4]^=K,B[5]^=W,B[6]^=Y,B[7]^=U;for(var g=0;g<4;g++)c.call(this)}},_doProcessBlock:function(m,C){var g=this._X;c.call(this),x[0]=g[0]^g[5]>>>16^g[3]<<16,x[1]=g[2]^g[7]>>>16^g[5]<<16,x[2]=g[4]^g[1]>>>16^g[7]<<16,x[3]=g[6]^g[3]>>>16^g[1]<<16;for(var T=0;T<4;T++)x[T]=(x[T]<<8|x[T]>>>24)&16711935|(x[T]<<24|x[T]>>>8)&4278255360,m[C+T]^=x[T]},blockSize:128/32,ivSize:64/32});function c(){for(var m=this._X,C=this._C,g=0;g<8;g++)v[g]=C[g];C[0]=C[0]+1295307597+this._b|0,C[1]=C[1]+3545052371+(C[0]>>>0>>0?1:0)|0,C[2]=C[2]+886263092+(C[1]>>>0>>0?1:0)|0,C[3]=C[3]+1295307597+(C[2]>>>0>>0?1:0)|0,C[4]=C[4]+3545052371+(C[3]>>>0>>0?1:0)|0,C[5]=C[5]+886263092+(C[4]>>>0>>0?1:0)|0,C[6]=C[6]+1295307597+(C[5]>>>0>>0?1:0)|0,C[7]=C[7]+3545052371+(C[6]>>>0>>0?1:0)|0,this._b=C[7]>>>0>>0?1:0;for(var g=0;g<8;g++){var T=m[g]+C[g],B=T&65535,F=T>>>16,J=((B*B>>>17)+B*F>>>15)+F*F,H=((T&4294901760)*T|0)+((T&65535)*T|0);h[g]=J^H}m[0]=h[0]+(h[7]<<16|h[7]>>>16)+(h[6]<<16|h[6]>>>16)|0,m[1]=h[1]+(h[0]<<8|h[0]>>>24)+h[7]|0,m[2]=h[2]+(h[1]<<16|h[1]>>>16)+(h[0]<<16|h[0]>>>16)|0,m[3]=h[3]+(h[2]<<8|h[2]>>>24)+h[1]|0,m[4]=h[4]+(h[3]<<16|h[3]>>>16)+(h[2]<<16|h[2]>>>16)|0,m[5]=h[5]+(h[4]<<8|h[4]>>>24)+h[3]|0,m[6]=h[6]+(h[5]<<16|h[5]>>>16)+(h[4]<<16|h[4]>>>16)|0,m[7]=h[7]+(h[6]<<8|h[6]>>>24)+h[5]|0}l.Rabbit=D._createHelper(p)}(),y.Rabbit})},ELcG:function(d,V,O){(function(y,l){d.exports=V=l(O("Ib8C"))})(this,function(y){/** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */return function(l){var M=y,D=M.lib,A=D.WordArray,x=D.Hasher,v=M.algo,h=A.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),p=A.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),c=A.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),m=A.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),C=A.create([0,1518500249,1859775393,2400959708,2840853838]),g=A.create([1352829926,1548603684,1836072691,2053994217,0]),T=v.RIPEMD160=x.extend({_doReset:function(){this._hash=A.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(W,U){for(var _=0;_<16;_++){var te=U+_,q=W[te];W[te]=(q<<8|q>>>24)&16711935|(q<<24|q>>>8)&4278255360}var w=this._hash.words,X=C.words,ne=g.words,he=h.words,le=p.words,_e=c.words,se=m.words,be,j,Q,L,re,de,ee,xe,Ne,Le;de=be=w[0],ee=j=w[1],xe=Q=w[2],Ne=L=w[3],Le=re=w[4];for(var Ge,_=0;_<80;_+=1)Ge=be+W[U+he[_]]|0,_<16?Ge+=B(j,Q,L)+X[0]:_<32?Ge+=F(j,Q,L)+X[1]:_<48?Ge+=J(j,Q,L)+X[2]:_<64?Ge+=H(j,Q,L)+X[3]:Ge+=K(j,Q,L)+X[4],Ge=Ge|0,Ge=Y(Ge,_e[_]),Ge=Ge+re|0,be=re,re=L,L=Y(Q,10),Q=j,j=Ge,Ge=de+W[U+le[_]]|0,_<16?Ge+=K(ee,xe,Ne)+ne[0]:_<32?Ge+=H(ee,xe,Ne)+ne[1]:_<48?Ge+=J(ee,xe,Ne)+ne[2]:_<64?Ge+=F(ee,xe,Ne)+ne[3]:Ge+=B(ee,xe,Ne)+ne[4],Ge=Ge|0,Ge=Y(Ge,se[_]),Ge=Ge+Le|0,de=Le,Le=Ne,Ne=Y(xe,10),xe=ee,ee=Ge;Ge=w[1]+Q+Ne|0,w[1]=w[2]+L+Le|0,w[2]=w[3]+re+de|0,w[3]=w[4]+be+ee|0,w[4]=w[0]+j+xe|0,w[0]=Ge},_doFinalize:function(){var W=this._data,U=W.words,_=this._nDataBytes*8,te=W.sigBytes*8;U[te>>>5]|=128<<24-te%32,U[(te+64>>>9<<4)+14]=(_<<8|_>>>24)&16711935|(_<<24|_>>>8)&4278255360,W.sigBytes=(U.length+1)*4,this._process();for(var q=this._hash,w=q.words,X=0;X<5;X++){var ne=w[X];w[X]=(ne<<8|ne>>>24)&16711935|(ne<<24|ne>>>8)&4278255360}return q},clone:function(){var W=x.clone.call(this);return W._hash=this._hash.clone(),W}});function B(W,U,_){return W^U^_}function F(W,U,_){return W&U|~W&_}function J(W,U,_){return(W|~U)^_}function H(W,U,_){return W&_|U&~_}function K(W,U,_){return W^(U|~_)}function Y(W,U){return W<>>32-U}M.RIPEMD160=x._createHelper(T),M.HmacRIPEMD160=x._createHmacHelper(T)}(Math),y.RIPEMD160})},ETIr:function(d,V,O){(function(y,l){d.exports=V=l(O("Ib8C"))})(this,function(y){return function(){var l=y,M=l.lib,D=M.WordArray,A=l.enc,x=A.Base64={stringify:function(h){var p=h.words,c=h.sigBytes,m=this._map;h.clamp();for(var C=[],g=0;g>>2]>>>24-g%4*8&255,B=p[g+1>>>2]>>>24-(g+1)%4*8&255,F=p[g+2>>>2]>>>24-(g+2)%4*8&255,J=T<<16|B<<8|F,H=0;H<4&&g+H*.75>>6*(3-H)&63));var K=m.charAt(64);if(K)for(;C.length%4;)C.push(K);return C.join("")},parse:function(h){var p=h.length,c=this._map,m=this._reverseMap;if(!m){m=this._reverseMap=[];for(var C=0;C>>6-g%4*2,F=T|B;m[C>>>2]|=F<<24-C%4*8,C++}return D.create(m,C)}}(),y.enc.Base64})},"F+F2":function(d,V,O){(function(y,l){d.exports=V=l(O("Ib8C"))})(this,function(y){return function(){if(typeof ArrayBuffer!="function")return;var l=y,M=l.lib,D=M.WordArray,A=D.init,x=D.init=function(v){if(v instanceof ArrayBuffer&&(v=new Uint8Array(v)),(v instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&v instanceof Uint8ClampedArray||v instanceof Int16Array||v instanceof Uint16Array||v instanceof Int32Array||v instanceof Uint32Array||v instanceof Float32Array||v instanceof Float64Array)&&(v=new Uint8Array(v.buffer,v.byteOffset,v.byteLength)),v instanceof Uint8Array){for(var h=v.byteLength,p=[],c=0;c>>2]|=v[c]<<24-c%4*8;A.call(this,p,h)}else A.apply(this,arguments)};x.prototype=D}(),y.lib.WordArray})},GRuw:function(d,V,O){(function(y,l,M){d.exports=V=l(O("Ib8C"),O("lPiR"))})(this,function(y){return function(){var l=y,M=l.lib,D=M.WordArray,A=l.algo,x=A.SHA256,v=A.SHA224=x.extend({_doReset:function(){this._hash=new D.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var h=x._doFinalize.call(this);return h.sigBytes-=4,h}});l.SHA224=x._createHelper(v),l.HmacSHA224=x._createHmacHelper(v)}(),y.SHA224})},GfqC:function(d,V,O){"use strict";var y=O("q1tI"),l=O.n(y),M=O("TSYQ"),D=O.n(M);function A(L,re){var de="cannot "+L.method+" "+L.action+" "+re.status+"'",ee=new Error(de);return ee.status=re.status,ee.method=L.method,ee.url=L.action,ee}function x(L){var re=L.responseText||L.response;if(!re)return re;try{return JSON.parse(re)}catch(de){return re}}function v(L){var re=new XMLHttpRequest;L.onProgress&&re.upload&&(re.upload.onprogress=function(Ne){Ne.total>0&&(Ne.percent=Ne.loaded/Ne.total*100),L.onProgress(Ne)});var de=new FormData;L.data&&Object.keys(L.data).forEach(function(xe){var Ne=L.data[xe];if(Array.isArray(Ne)){Ne.forEach(function(Le){de.append(xe+"[]",Le)});return}de.append(xe,L.data[xe])}),L.file instanceof Blob?de.append(L.filename,L.file,L.file.name):de.append(L.filename,L.file),re.onerror=function(Ne){L.onError(Ne)},re.onload=function(){return re.status<200||re.status>=300?L.onError(A(L,re),x(re)):L.onSuccess(x(re),re)},re.open(L.method,L.action,!0),L.withCredentials&&"withCredentials"in re&&(re.withCredentials=!0);var ee=L.headers||{};return ee["X-Requested-With"]!==null&&re.setRequestHeader("X-Requested-With","XMLHttpRequest"),Object.keys(ee).forEach(function(xe){ee[xe]!==null&&re.setRequestHeader(xe,ee[xe])}),re.send(de),{abort:function(){re.abort()}}}var h=+new Date,p=0;function c(){return"rc-upload-"+h+"-"+ ++p}function m(L,re){return L.indexOf(re,L.length-re.length)!==-1}var C=function(L,re){if(L&&re){var de=Array.isArray(re)?re:re.split(","),ee=L.name||"",xe=L.type||"",Ne=xe.replace(/\/.*$/,"");return de.some(function(Le){var Ge=Le.trim();return Ge.charAt(0)==="."?m(ee.toLowerCase(),Ge.toLowerCase()):/\/\*$/.test(Ge)?Ne===Ge.replace(/\/.*$/,""):xe===Ge})}return!0};function g(L,re){var de=L.createReader(),ee=[];function xe(){de.readEntries(function(Ne){var Le=Array.prototype.slice.apply(Ne);ee=ee.concat(Le);var Ge=!Le.length;Ge?re(ee):xe()})}xe()}var T=function(re,de,ee){var xe=function Ne(Le,Ge){Ge=Ge||"",Le.isFile?Le.file(function(Qe){ee(Qe)&&(Le.fullPath&&!Qe.webkitRelativePath&&(Object.defineProperties(Qe,{webkitRelativePath:{writable:!0}}),Qe.webkitRelativePath=Le.fullPath.replace(/^\//,""),Object.defineProperties(Qe,{webkitRelativePath:{writable:!1}})),de([Qe]))}):Le.isDirectory&&g(Le,function(Qe){Qe.forEach(function(Te){Ne(Te,""+Ge+Le.name+"/")})})};re.forEach(function(Ne){xe(Ne.webkitGetAsEntry())})},B=T,F=Object.assign||function(L){for(var re=1;re=0)continue;if(!Object.prototype.hasOwnProperty.call(L,ee))continue;de[ee]=L[ee]}return de}function W(L,re){if(!(L instanceof re))throw new TypeError("Cannot call a class as a function")}function U(L,re){if(!L)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return re&&(typeof re=="object"||typeof re=="function")?re:L}function _(L,re){if(typeof re!="function"&&re!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof re);L.prototype=Object.create(re&&re.prototype,{constructor:{value:L,enumerable:!1,writable:!0,configurable:!0}}),re&&(Object.setPrototypeOf?Object.setPrototypeOf(L,re):L.__proto__=re)}var te=function(re){return Object.keys(re).reduce(function(de,ee){return(ee.substr(0,5)==="data-"||ee.substr(0,5)==="aria-"||ee==="role")&&(de[ee]=re[ee]),de},{})},q=function(L){_(re,L);function re(){var de,ee,xe,Ne;W(this,re);for(var Le=arguments.length,Ge=Array(Le),Qe=0;Qe=7&&this.setupTypeNumber(h),this.dataCache==null&&(this.dataCache=x.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,p)},v.setupPositionProbePattern=function(h,p){for(var c=-1;c<=7;c++){if(h+c<=-1||this.moduleCount<=h+c)continue;for(var m=-1;m<=7;m++){if(p+m<=-1||this.moduleCount<=p+m)continue;0<=c&&c<=6&&(m==0||m==6)||0<=m&&m<=6&&(c==0||c==6)||2<=c&&c<=4&&2<=m&&m<=4?this.modules[h+c][p+m]=!0:this.modules[h+c][p+m]=!1}}},v.getBestMaskPattern=function(){for(var h=0,p=0,c=0;c<8;c++){this.makeImpl(!0,c);var m=D.getLostPoint(this);(c==0||h>m)&&(h=m,p=c)}return p},v.createMovieClip=function(h,p,c){var m=h.createEmptyMovieClip(p,c),C=1;this.make();for(var g=0;g>c&1)==1;this.modules[Math.floor(c/3)][c%3+this.moduleCount-8-3]=m}for(var c=0;c<18;c++){var m=!h&&(p>>c&1)==1;this.modules[c%3+this.moduleCount-8-3][Math.floor(c/3)]=m}},v.setupTypeInfo=function(h,p){for(var c=this.errorCorrectLevel<<3|p,m=D.getBCHTypeInfo(c),C=0;C<15;C++){var g=!h&&(m>>C&1)==1;C<6?this.modules[C][8]=g:C<8?this.modules[C+1][8]=g:this.modules[this.moduleCount-15+C][8]=g}for(var C=0;C<15;C++){var g=!h&&(m>>C&1)==1;C<8?this.modules[8][this.moduleCount-C-1]=g:C<9?this.modules[8][15-C-1+1]=g:this.modules[8][15-C-1]=g}this.modules[this.moduleCount-8][8]=!h},v.mapData=function(h,p){for(var c=-1,m=this.moduleCount-1,C=7,g=0,T=this.moduleCount-1;T>0;T-=2)for(T==6&&T--;;){for(var B=0;B<2;B++)if(this.modules[m][T-B]==null){var F=!1;g>>C&1)==1);var J=D.getMask(p,m,T-B);J&&(F=!F),this.modules[m][T-B]=F,C--,C==-1&&(g++,C=7)}if(m+=c,m<0||this.moduleCount<=m){m-=c,c=-c;break}}},x.PAD0=236,x.PAD1=17,x.createData=function(h,p,c){for(var m=l.getRSBlocks(h,p),C=new M,g=0;gB*8)throw new Error("code length overflow. ("+C.getLengthInBits()+">"+B*8+")");for(C.getLengthInBits()+4<=B*8&&C.put(0,4);C.getLengthInBits()%8!=0;)C.putBit(!1);for(;!(C.getLengthInBits()>=B*8);){if(C.put(x.PAD0,8),C.getLengthInBits()>=B*8)break;C.put(x.PAD1,8)}return x.createBytes(C,m)},x.createBytes=function(h,p){for(var c=0,m=0,C=0,g=new Array(p.length),T=new Array(p.length),B=0;B=0?W.get(U):0}}for(var _=0,H=0;H>>2]>>>24-te%4*8&255;Y[U+te>>>2]|=q<<24-(U+te)%4*8}else for(var w=0;w<_;w+=4)Y[U+w>>>2]=W[w>>>2];return this.sigBytes+=_,this},clamp:function(){var K=this.words,Y=this.sigBytes;K[Y>>>2]&=4294967295<<32-Y%4*8,K.length=M.ceil(Y/4)},clone:function(){var K=c.clone.call(this);return K.words=this.words.slice(0),K},random:function(K){for(var Y=[],W=0;W>>2]>>>24-_%4*8&255;U.push((te>>>4).toString(16)),U.push((te&15).toString(16))}return U.join("")},parse:function(K){for(var Y=K.length,W=[],U=0;U>>3]|=parseInt(K.substr(U,2),16)<<24-U%8*4;return new m.init(W,Y/2)}},T=C.Latin1={stringify:function(K){for(var Y=K.words,W=K.sigBytes,U=[],_=0;_>>2]>>>24-_%4*8&255;U.push(String.fromCharCode(te))}return U.join("")},parse:function(K){for(var Y=K.length,W=[],U=0;U>>2]|=(K.charCodeAt(U)&255)<<24-U%4*8;return new m.init(W,Y)}},B=C.Utf8={stringify:function(K){try{return decodeURIComponent(escape(T.stringify(K)))}catch(Y){throw new Error("Malformed UTF-8 data")}},parse:function(K){return T.parse(unescape(encodeURIComponent(K)))}},F=p.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new m.init,this._nDataBytes=0},_append:function(K){typeof K=="string"&&(K=B.parse(K)),this._data.concat(K),this._nDataBytes+=K.sigBytes},_process:function(K){var Y,W=this._data,U=W.words,_=W.sigBytes,te=this.blockSize,q=te*4,w=_/q;K?w=M.ceil(w):w=M.max((w|0)-this._minBufferSize,0);var X=w*te,ne=M.min(X*4,_);if(X){for(var he=0;he=0;)v^=A.G15<=0;)v^=A.G18<>>=1;return v},getPatternPosition:function(x){return A.PATTERN_POSITION_TABLE[x-1]},getMask:function(x,v,h){switch(x){case D.PATTERN000:return(v+h)%2==0;case D.PATTERN001:return v%2==0;case D.PATTERN010:return h%3==0;case D.PATTERN011:return(v+h)%3==0;case D.PATTERN100:return(Math.floor(v/2)+Math.floor(h/3))%2==0;case D.PATTERN101:return v*h%2+v*h%3==0;case D.PATTERN110:return(v*h%2+v*h%3)%2==0;case D.PATTERN111:return(v*h%3+(v+h)%2)%2==0;default:throw new Error("bad maskPattern:"+x)}},getErrorCorrectPolynomial:function(x){for(var v=new l([1],0),h=0;h5&&(h+=3+m-5)}for(var p=0;pYe)){ke.next=7;break}return M.b.info("\u6587\u4EF6\u8D85\u8FC7".concat(Ye/1024/1024/1024,"GB\uFF0C\u4E0D\u7B26\u5408\u4E0A\u4F20\u8981\u6C42")),ke.abrupt("return",!1);case 7:return Q.push({name:nt.name,file:nt}),L(Object(D.a)(Q)),se.onChange(Q),ke.abrupt("return",!1);case 11:case"end":return ke.stop()}},Te)}));function Qe(Te){return Ge.apply(this,arguments)}return Qe}()},Le=function(){var Ge=Object(h.a)(C.a.mark(function Qe(Te,nt){var Ye,Pe,ke,Be,ot,ve,ge,$e,pe,Z;return C.a.wrap(function($){for(;;)switch($.prev=$.next){case 0:return nt.file_name=Te.name,ge=Te.name,$.next=4,Object(B.a)("/api/buckets/get_upload_token_for_big_files.json",{method:"get"});case 4:if($e=$.sent,$e.data=JSON.parse(_($e.data)),!(($e==null?void 0:$e.status)!==0)){$.next=12;break}return Q[Q.findIndex(function(Re){return Re.name===ge})].status="error",Q[Q.findIndex(function(Re){return Re.name===ge})].file.status="error",se.onChange(Q),M.b.warn("\u4E0A\u4F20\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5C1D\u8BD5"),$.abrupt("return");case 12:return ee=new W.a({endpoint:$e==null||((Ye=$e.data)===null||Ye===void 0)?void 0:Ye.end_point,region:$e==null||((Pe=$e.data)===null||Pe===void 0)?void 0:Pe.region,accessKeyId:$e==null||((ke=$e.data)===null||ke===void 0)?void 0:ke.access_key_id,accessKeySecret:$e==null||((Be=$e.data)===null||Be===void 0)?void 0:Be.access_key_secret,bucket:$e==null||((ot=$e.data)===null||ot===void 0)?void 0:ot.bucket,stsToken:$e==null||((ve=$e.data)===null||ve===void 0)?void 0:ve.security_token}),console.log(Te,"file"),xe(ee),pe=Te.name.split("."),pe.pop(),Z=nt.realFileName?pe:Object(H.a)(),$.abrupt("return",new Promise(function(Re,Ae){try{var Xe;ee.multipartUpload("".concat(se.identifier,"/").concat(Z).concat(ge.indexOf(".")>-1?"."+ge.split(".").pop():""),new Blob([Te.file],{type:Te.file.type}),{timeout:3600*1e3,partSize:1002400,progress:function(lt,bt,Tt){try{console.log("\u8FDB\u5EA6",lt,bt,Tt);var xt=Q.findIndex(function(Et){return Et.name===ge});Q[xt].file.percent=lt*100,Q[xt].tempCheckpoint=bt,L(Object(D.a)(Q))}catch(Et){}},checkpoint:Q[Q.findIndex(function(rt){return rt.name===ge})].tempCheckpoint,callback:{customValue:{id:ge+""},url:$e==null||((Xe=$e.data)===null||Xe===void 0)?void 0:Xe.callback_url,host:$e==null?void 0:$e.data.bucket_host,body:"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&my_var=${x:my_var}&"+Object(B.e)(nt)}}).then(function(rt){var lt,bt=Q.findIndex(function(at){return at.name===ge}),Tt="done";if(((lt=rt.data)===null||lt===void 0?void 0:lt.status)===0){var xt;Te.response=(xt=rt.data)===null||xt===void 0?void 0:xt.data;var Et=Q.findIndex(function(at){return at.name===ge});Q[Et].status="done",Q[Et].file.status="done"}else{var Nt;M.b.warn((Nt=rt.data)===null||Nt===void 0?void 0:Nt.message),Tt="error"}Q[bt].status=Tt,Q[bt].file.status=Tt,se.onChange(Q),Re(rt==null?void 0:rt.data)}).catch(function(rt){Q[Q.findIndex(function(lt){return lt.name===ge})].status="error",Q[Q.findIndex(function(lt){return lt.name===ge})].file.status="error",M.b.warn("\u4E0A\u4F20\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5C1D\u8BD5"),L(Object(D.a)(Q)),se.onChange(Q),Ae(rt),console.log("err:",rt)})}catch(rt){}}));case 19:case"end":return $.stop()}},Qe)}));return function(Te,nt){return Ge.apply(this,arguments)}}();return Object(g.useEffect)(function(){Q.every(function(Ge){return Ge==="done"||Ge==="error"})&&se.onComplete(Q)},[Q]),Object(g.useEffect)(function(){if(_e){var Ge;(Ge=ee)===null||Ge===void 0||Ge.cancel()}},[_e]),Object(g.useEffect)(function(){se.uploading&&Q.map(function(){var Ge=Object(h.a)(C.a.mark(function Qe(Te){var nt,Ye;return C.a.wrap(function(ke){for(;;)switch(ke.prev=ke.next){case 0:if(!((!Te.status||Te.status==="error")&&!_e)){ke.next=6;break}return Te.status="uploading",Te.file.status="uploading",ke.next=5,Le(Te,{login:le==null||((nt=le.userInfo)===null||nt===void 0)?void 0:nt.login,container_type:se.container_type,container_id:se.container_id,description:se.description,realFileName:se.realFileName});case 5:Ye=ke.sent;case 6:case"end":return ke.stop()}},Qe)}));return function(Qe){return Ge.apply(this,arguments)}}())},[se.uploading]),T.a.createElement(U,Object(y.a)({},Ne,{height:se.height,className:se.className}),T.a.createElement("p",{className:"ant-upload-hint"},se.text||"\u62D6\u62FD\u6587\u4EF6\u6216\u8005\u70B9\u51FB\u4E0A\u4F20"))};V.b=Object(K.a)(function(ne){var he=ne.loading,le=ne.globalSetting,_e=ne.user;return{globalSetting:le,loading:he.models.competitions,user:_e}})(X)},KmYQ:function(d,V,O){(function(y,l,M){d.exports=V=l(O("Ib8C"),O("OLod"))})(this,function(y){return y.pad.ZeroPadding={pad:function(l,M){var D=M*4;l.clamp(),l.sigBytes+=D-(l.sigBytes%D||D)},unpad:function(l){for(var M=l.words,D=l.sigBytes-1,D=l.sigBytes-1;D>=0;D--)if(M[D>>>2]>>>24-D%4*8&255){l.sigBytes=D+1;break}}},y.pad.ZeroPadding})},MlIO:function(d,V,O){(function(y,l){d.exports=V=l(O("Ib8C"))})(this,function(y){return function(l){var M=y,D=M.lib,A=D.Base,x=D.WordArray,v=M.x64={},h=v.Word=A.extend({init:function(c,m){this.high=c,this.low=m}}),p=v.WordArray=A.extend({init:function(c,m){c=this.words=c||[],m!=l?this.sigBytes=m:this.sigBytes=c.length*8},toX32:function(){for(var c=this.words,m=c.length,C=[],g=0;g>>2]&255;ne.sigBytes-=he}},Y=D.BlockCipher=g.extend({cfg:g.cfg.extend({mode:J,padding:K}),reset:function(){var ne;g.reset.call(this);var he=this.cfg,le=he.iv,_e=he.mode;this._xformMode==this._ENC_XFORM_MODE?ne=_e.createEncryptor:(ne=_e.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==ne?this._mode.init(this,le&&le.words):(this._mode=ne.call(_e,this,le&&le.words),this._mode.__creator=ne)},_doProcessBlock:function(ne,he){this._mode.processBlock(ne,he)},_doFinalize:function(){var ne,he=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(he.pad(this._data,this.blockSize),ne=this._process(!0)):(ne=this._process(!0),he.unpad(ne)),ne},blockSize:128/32}),W=D.CipherParams=A.extend({init:function(ne){this.mixIn(ne)},toString:function(ne){return(ne||this.formatter).stringify(this)}}),U=M.format={},_=U.OpenSSL={stringify:function(ne){var he,le=ne.ciphertext,_e=ne.salt;return _e?he=x.create([1398893684,1701076831]).concat(_e).concat(le):he=le,he.toString(c)},parse:function(ne){var he,le=c.parse(ne),_e=le.words;return _e[0]==1398893684&&_e[1]==1701076831&&(he=x.create(_e.slice(2,4)),_e.splice(0,4),le.sigBytes-=16),W.create({ciphertext:le,salt:he})}},te=D.SerializableCipher=A.extend({cfg:A.extend({format:_}),encrypt:function(ne,he,le,_e){_e=this.cfg.extend(_e);var se=ne.createEncryptor(le,_e),be=se.finalize(he),j=se.cfg;return W.create({ciphertext:be,key:le,iv:j.iv,algorithm:ne,mode:j.mode,padding:j.padding,blockSize:ne.blockSize,formatter:_e.format})},decrypt:function(ne,he,le,_e){_e=this.cfg.extend(_e),he=this._parse(he,_e.format);var se=ne.createDecryptor(le,_e).finalize(he.ciphertext);return se},_parse:function(ne,he){return typeof ne=="string"?he.parse(ne,this):ne}}),q=M.kdf={},w=q.OpenSSL={execute:function(ne,he,le,_e){_e||(_e=x.random(64/8));var se=C.create({keySize:he+le}).compute(ne,_e),be=x.create(se.words.slice(he),le*4);return se.sigBytes=he*4,W.create({key:se,iv:be,salt:_e})}},X=D.PasswordBasedCipher=te.extend({cfg:te.cfg.extend({kdf:w}),encrypt:function(ne,he,le,_e){_e=this.cfg.extend(_e);var se=_e.kdf.execute(le,ne.keySize,ne.ivSize);_e.iv=se.iv;var be=te.encrypt.call(this,ne,he,se.key,_e);return be.mixIn(se),be},decrypt:function(ne,he,le,_e){_e=this.cfg.extend(_e),he=this._parse(he,_e.format);var se=_e.kdf.execute(le,ne.keySize,ne.ivSize,he.salt);_e.iv=se.iv;var be=te.decrypt.call(this,ne,he,se.key,_e);return be}})}()})},Og1z:function(d,V){(function(O){d.exports=function(){var y={887:function(){}},l={};function M(D){if(l[D])return l[D].exports;var A=l[D]={exports:{}},x=!0;try{y[D](A,A.exports,M),x=!1}finally{x&&delete l[D]}return A.exports}return M.ab=O+"/",M(887)}()}).call(this,"/")},PVpz:function(d,V,O){(function(y,l,M){d.exports=V=l(O("Ib8C"),O("ETIr"),O("cv67"),O("K3mO"),O("OLod"))})(this,function(y){return function(){var l=y,M=l.lib,D=M.StreamCipher,A=l.algo,x=[],v=[],h=[],p=A.RabbitLegacy=D.extend({_doReset:function(){var m=this._key.words,C=this.cfg.iv,g=this._X=[m[0],m[3]<<16|m[2]>>>16,m[1],m[0]<<16|m[3]>>>16,m[2],m[1]<<16|m[0]>>>16,m[3],m[2]<<16|m[1]>>>16],T=this._C=[m[2]<<16|m[2]>>>16,m[0]&4294901760|m[1]&65535,m[3]<<16|m[3]>>>16,m[1]&4294901760|m[2]&65535,m[0]<<16|m[0]>>>16,m[2]&4294901760|m[3]&65535,m[1]<<16|m[1]>>>16,m[3]&4294901760|m[0]&65535];this._b=0;for(var B=0;B<4;B++)c.call(this);for(var B=0;B<8;B++)T[B]^=g[B+4&7];if(C){var F=C.words,J=F[0],H=F[1],K=(J<<8|J>>>24)&16711935|(J<<24|J>>>8)&4278255360,Y=(H<<8|H>>>24)&16711935|(H<<24|H>>>8)&4278255360,W=K>>>16|Y&4294901760,U=Y<<16|K&65535;T[0]^=K,T[1]^=W,T[2]^=Y,T[3]^=U,T[4]^=K,T[5]^=W,T[6]^=Y,T[7]^=U;for(var B=0;B<4;B++)c.call(this)}},_doProcessBlock:function(m,C){var g=this._X;c.call(this),x[0]=g[0]^g[5]>>>16^g[3]<<16,x[1]=g[2]^g[7]>>>16^g[5]<<16,x[2]=g[4]^g[1]>>>16^g[7]<<16,x[3]=g[6]^g[3]>>>16^g[1]<<16;for(var T=0;T<4;T++)x[T]=(x[T]<<8|x[T]>>>24)&16711935|(x[T]<<24|x[T]>>>8)&4278255360,m[C+T]^=x[T]},blockSize:128/32,ivSize:64/32});function c(){for(var m=this._X,C=this._C,g=0;g<8;g++)v[g]=C[g];C[0]=C[0]+1295307597+this._b|0,C[1]=C[1]+3545052371+(C[0]>>>0>>0?1:0)|0,C[2]=C[2]+886263092+(C[1]>>>0>>0?1:0)|0,C[3]=C[3]+1295307597+(C[2]>>>0>>0?1:0)|0,C[4]=C[4]+3545052371+(C[3]>>>0>>0?1:0)|0,C[5]=C[5]+886263092+(C[4]>>>0>>0?1:0)|0,C[6]=C[6]+1295307597+(C[5]>>>0>>0?1:0)|0,C[7]=C[7]+3545052371+(C[6]>>>0>>0?1:0)|0,this._b=C[7]>>>0>>0?1:0;for(var g=0;g<8;g++){var T=m[g]+C[g],B=T&65535,F=T>>>16,J=((B*B>>>17)+B*F>>>15)+F*F,H=((T&4294901760)*T|0)+((T&65535)*T|0);h[g]=J^H}m[0]=h[0]+(h[7]<<16|h[7]>>>16)+(h[6]<<16|h[6]>>>16)|0,m[1]=h[1]+(h[0]<<8|h[0]>>>24)+h[7]|0,m[2]=h[2]+(h[1]<<16|h[1]>>>16)+(h[0]<<16|h[0]>>>16)|0,m[3]=h[3]+(h[2]<<8|h[2]>>>24)+h[1]|0,m[4]=h[4]+(h[3]<<16|h[3]>>>16)+(h[2]<<16|h[2]>>>16)|0,m[5]=h[5]+(h[4]<<8|h[4]>>>24)+h[3]|0,m[6]=h[6]+(h[5]<<16|h[5]>>>16)+(h[4]<<16|h[4]>>>16)|0,m[7]=h[7]+(h[6]<<8|h[6]>>>24)+h[5]|0}l.RabbitLegacy=D._createHelper(p)}(),y.RabbitLegacy})},"Re/O":function(d,V,O){"use strict";(function(y,l,M){O.d(V,"a",function(){return Nr}),O.d(V,"b",function(){return _n}),O.d(V,"c",function(){return qo}),O.d(V,"d",function(){return vl}),O.d(V,"e",function(){return qc}),O.d(V,"f",function(){return zp}),O.d(V,"g",function(){return Gc}),O.d(V,"h",function(){return hn}),O.d(V,"i",function(){return Da}),O.d(V,"j",function(){return ps}),O.d(V,"k",function(){return fs}),O.d(V,"l",function(){return Vc}),O.d(V,"m",function(){return On}),O.d(V,"n",function(){return ei}),O.d(V,"o",function(){return Dl}),O.d(V,"p",function(){return Up}),O.d(V,"q",function(){return yu}),O.d(V,"r",function(){return bl}),O.d(V,"s",function(){return ml}),O.d(V,"t",function(){return Qo}),O.d(V,"u",function(){return hu}),O.d(V,"v",function(){return Ln}),O.d(V,"w",function(){return bu}),O.d(V,"x",function(){return ba}),O.d(V,"y",function(){return It}),O.d(V,"z",function(){return fl}),O.d(V,"A",function(){return Kc}),O.d(V,"B",function(){return no}),O.d(V,"C",function(){return gl}),O.d(V,"D",function(){return zo}),O.d(V,"E",function(){return jn}),O.d(V,"F",function(){return Ao}),O.d(V,"G",function(){return Ur}),O.d(V,"H",function(){return Qn}),O.d(V,"I",function(){return Zn}),O.d(V,"J",function(){return Za}),O.d(V,"K",function(){return kn}),O.d(V,"L",function(){return Rr}),O.d(V,"M",function(){return eo}),O.d(V,"N",function(){return Cl}),O.d(V,"O",function(){return xa}),O.d(V,"P",function(){return Tr});/** * @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. * ============================================================================= */var D=function(n,r){return(D=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=t[o])})(n,r)};function A(n,r){function e(){this.constructor=n}D(n,r),n.prototype=r===null?Object.create(r):(e.prototype=r.prototype,new e)}function x(n,r,e,t){return new(e||(e=Promise))(function(o,a){function i(f){try{u(t.next(f))}catch(E){a(E)}}function s(f){try{u(t.throw(f))}catch(E){a(E)}}function u(f){f.done?o(f.value):new e(function(E){E(f.value)}).then(i,s)}u((t=t.apply(n,r||[])).next())})}function v(n,r){var e,t,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(u){return function(f){return function(E){if(e)throw new TypeError("Generator is already executing.");for(;i;)try{if(e=1,t&&(o=2&E[0]?t.return:E[0]?t.throw||((o=t.return)&&o.call(t),0):t.next)&&!(o=o.call(t,E[1])).done)return o;switch(t=0,o&&(E=[2&E[0],o.value]),E[0]){case 0:case 1:o=E;break;case 4:return i.label++,{value:E[1],done:!1};case 5:i.label++,t=E[1],E=[0];continue;case 7:E=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(E[0]===6||E[0]===2)){i=0;continue}if(E[0]===3&&(!o||E[1]>o[0]&&E[1]0;)t=Math.random()*r|0,e=n[--r],n[r]=n[t],n[t]=e}function _(n,r,e){return Math.max(n,Math.min(r,e))}function te(n){return n%2==0?n:n+1}function q(n){for(var r=0,e=0;e=e?o():setTimeout(i,s)}};i()})}function re(n,r){for(var e=1,t=-1,o=0;o=0)e*=n[o];else if(n[o]===-1){if(t!==-1)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+t+" and dim "+o);t=o}else if(n[o]<0)throw Error("Shapes can not be < 0. Found "+n[o]+" at dim "+o);if(t===-1){if(r>0&&r!==e)throw Error("Size("+r+") must match the product of shape "+n);return n}if(e===0)throw Error("Cannot infer the missing size in ["+n+"] when there are 0 elements");if(r%e!=0)throw Error("The implicit shape can't be a fractional number. Got "+r+" / "+e);var a=n.slice();return a[t]=r/e,a}function de(n,r){var e=r.length;return w((n=n==null?r.map(function(t,o){return o}):[].concat(n)).every(function(t){return t>=-e&&ts)&&n[s]===1&&(e.push(n[s]),t.push(s)),a[i]<=s&&i++}n[s]!==1&&(e.push(n[s]),t.push(s))}return{newShape:e,keptDims:t}}function xe(n,r){var e=null;if(n==null||n==="float32")e=new Float32Array(r);else if(n==="int32")e=new Int32Array(r);else{if(n!=="bool")throw new Error("Unknown data type "+n);e=new Uint8Array(r)}return e}function Ne(n,r){var e=null;if(n==null||n==="float32")e=new Float32Array(r);else if(n==="int32")e=new Int32Array(r);else if(n==="bool")e=new Uint8Array(r);else{if(n!=="string")throw new Error("Unknown data type "+n);e=new Array(r)}return e}function Le(n,r){for(var e=0;e=0;--t)e[t]=e[t+1]*n[t+1];return e}function pe(n,r,e){if(r==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=he(n)),e&&Le(n,r),function(a,i){return a instanceof Float32Array&&i==="float32"||a instanceof Int32Array&&i==="int32"||a instanceof Uint8Array&&i==="bool"}(n,r))return n;if(r==null||r==="float32"||r==="complex64")return new Float32Array(n);if(r==="int32")return new Int32Array(n);if(r==="bool"){for(var t=new Uint8Array(n.length),o=0;o=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+n+"]."})})}function Xe(n,r){return r===void 0&&(r="utf-8"),r=r||"utf-8",c().platform.encode(n,r)}function rt(n,r){return r===void 0&&(r="utf-8"),r=r||"utf-8",c().platform.decode(n,r)}function lt(n,r,e){if(r===0)return 0;if(r===1)return n[0];for(var t=n[n.length-1],o=0;o0?oe:"")+" "}console.log("%c"+u+" %c"+s+" %c"+f+"D "+I+" %c"+E+" %c"+P+" %c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},n}(),Nt=20,at=3,Bt=7;function mr(n,r,e,t){var o=$e(r),a=function(f,E,I,P){var G=le(E),oe=P[P.length-1],ue=new Array(oe).fill(0),ie=E.length,ce=I==="complex64"?Lr(f):f;if(ie>1)for(var ye=0;yeNt){var we=at*ie,Ee=Array.from(E.slice(0,we)),Se=Array.from(E.slice((ce-at)*ie,ce*ie));return P==="complex64"&&(Ee=Lr(Ee),Se=Lr(Se)),["["+Ee.map(function(st,pt){return rr(st,oe[pt],P)}).join(", ")+", ..., "+Se.map(function(st,pt){return rr(st,oe[ce-at+pt],P)}).join(", ")+"]"]}return["["+(P==="complex64"?Lr(E):Array.from(E)).map(function(st,pt){return rr(st,oe[pt],P)}).join(", ")+"]"]}var Me=I.slice(1),He=G.slice(1),Fe=G[0]*ie,je=[];if(ce>Nt){for(var Ue=0;Ue=this.shape[t]){var s="Requested out of range element at "+r+". Buffer shape="+this.shape;throw new Error(s)}t++}for(var u=r[r.length-1],f=0;f0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+s+" data ids) after running '"+r+"'")},n.prototype.runKernelFunc=function(r,e,t,o,a,i,s){var u,f=this;i===void 0&&(i=[]),s===void 0&&(s=[]);var E=[],I=this.isTapeOn();o==null&&(o=this.state.activeScope!=null?this.state.activeScope.name:"");var P,G=function(ye){I&&(E=ye.map(function(we){return f.keep(f.clone(we))}))},oe=this.state.numBytes,ue=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var ie,ce=T(o,this.backendName);return P=ce!=null?function(){var ye=f.backend.numDataIds();ie=ce.kernelFunc({inputs:e,attrs:a,backend:f.backend});var we=Array.isArray(ie)?ie:[ie];f.shouldCheckForMemLeaks()&&f.checkKernelForMemLeak(o,ye,we);var Ee=we.map(function(Me){var He=Me.dataId,Fe=Me.shape,je=Me.dtype;return f.makeTensorFromDataId(He,Fe,je)}),Se=Ee.filter(function(Me,He){return s[He]});return G((i||[]).slice().concat(Se)),Ee}:function(){var ye=f.backend.numDataIds();ie=f.tidy(function(){return r(f.backend,G)});var we=Array.isArray(ie)?ie:[ie];return f.shouldCheckForMemLeaks()&&f.checkKernelForMemLeak(o,ye,we),we},this.scopedRun(function(){return f.state.kernelDepth++},function(){return f.state.kernelDepth--},function(){u=f.ENV.getBool("DEBUG")?f.profiler.profileKernel(o,e,function(){return P()}):P()}),I&&this.addTapeNode(o,e,u,t,E),this.state.profiling&&this.state.activeProfile.kernels.push({name:o,bytesAdded:this.state.numBytes-oe,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-ue,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(ye){return e[ye].shape}),outputShapes:u.map(function(ye){return ye.shape})}),Array.isArray(ie)?u:u[0]},n.prototype.makeTensor=function(r,e,t,o){if(r==null)throw new Error("Values passed to engine.makeTensor() are null");t=t||"float32",o=o||this.backend;var a=r;t==="string"&&Pe(r[0])&&(a=r.map(function(E){return Xe(E)}));var i=o.write(a,e,t),s=new Nr(e,t,i,this.nextTensorId());if(this.incRef(s,o),t==="string"){var u=this.state.tensorInfo.get(i),f=Ye(a);this.state.numBytes+=f-u.bytes,u.bytes=f}return s},n.prototype.makeTensorFromDataId=function(r,e,t,o){var a=new Nr(e,t=t||"float32",r,this.nextTensorId());return this.incRef(a,o),a},n.prototype.makeVariable=function(r,e,t,o){e===void 0&&(e=!0),t=t||this.nextVariableId().toString(),o!=null&&o!==r.dtype&&(r=r.asType(o));var a=new _n(r,e,t,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null)throw new Error("Variable with name "+a.name+" was already registered");return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a},n.prototype.incRef=function(r,e){var t=this.state.tensorInfo.has(r.dataId)?this.state.tensorInfo.get(r.dataId).refCount:0;if(this.state.numTensors++,r.dtype==="string"&&this.state.numStringTensors++,t===0){this.state.numDataBuffers++;var o=0;r.dtype!=="complex64"&&r.dtype!=="string"&&(o=r.size*nt(r.dtype)),this.state.tensorInfo.set(r.dataId,{backend:e||this.backend,dtype:r.dtype,shape:r.shape,bytes:o,refCount:0}),this.state.numBytes+=o}this.state.tensorInfo.get(r.dataId).refCount++,r instanceof _n||this.track(r)},n.prototype.disposeTensor=function(r){if(this.state.tensorInfo.has(r.dataId)){this.state.numTensors--,r.dtype==="string"&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(r.dataId);e.refCount<=1?(r.dtype!=="complex64"&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(r.dataId),this.state.tensorInfo.delete(r.dataId)):this.state.tensorInfo.get(r.dataId).refCount--}},n.prototype.disposeVariables=function(){for(var r in this.state.registeredVariables){var e=this.state.registeredVariables[r];this.disposeVariable(e)}},n.prototype.disposeVariable=function(r){this.disposeTensor(r),this.state.registeredVariables[r.name]!=null&&delete this.state.registeredVariables[r.name]},n.prototype.memory=function(){var r=this.backend.memory();return r.numTensors=this.state.numTensors,r.numDataBuffers=this.state.numDataBuffers,r.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(r.unreliable=!0,r.reasons==null&&(r.reasons=[]),r.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),r},n.prototype.profile=function(r){return x(this,void 0,void 0,function(){var e,t;return v(this,function(o){return this.state.profiling=!0,e=this.state.numBytes,t=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=r(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(a){return a.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-t,[2,this.state.activeProfile]})})},n.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&this.state.kernelDepth===0},n.prototype.addTapeNode=function(r,e,t,o,a){var i=this,s={id:this.state.nextTapeNodeId++,kernelName:r,inputs:e,outputs:t,saved:a},u=B(r);u!=null&&(o=u.gradFunc),o!=null&&(s.gradient=function(f){return f=f.map(function(E,I){if(E==null){var P=t[I],G=$(P.size,P.dtype);return i.makeTensor(G,P.shape,P.dtype)}return E}),o(f.length>1?f:f[0],a)}),this.state.activeTape.push(s)},n.prototype.keep=function(r){return r.kept=!0,r},n.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},n.prototype.endTape=function(){this.state.gradientDepth--},n.prototype.startScope=function(r){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};r&&(e.name=r),this.state.scopeStack.push(e),this.state.activeScope=e},n.prototype.endScope=function(r){for(var e=this,t=cn(r),o=new Set(t.map(function(u){return u.id})),a=0;a0,function(){return"gradients() received an empty list of xs."}),t!=null&&t.dtype!=="float32")throw new Error("dy must have 'float32' dtype, but has '"+t.dtype+"'");var i=this.scopedRun(function(){return a.startTape()},function(){return a.endTape()},function(){return a.tidy("forward",r)});w(i instanceof Nr,function(){return"The result y returned by f() must be a tensor."});var s=function(u,f,E){for(var I={},P={},G=0;G=0;G--)for(oe=(Me=u[G]).inputs,ye=0;ye0)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",function(){var u,f,E={};E[i.id]=t==null?(u=i.shape,f=k(le(u),"float32"),Ve.makeTensor(f,u,"float32")):t,function(P,G,oe){for(var ue=function(ce){var ye=G[ce],we=[];if(ye.outputs.forEach(function(He){var Fe=P[He.id];Fe!=null?we.push(Fe):we.push(null)}),ye.gradient==null)throw new Error("Cannot compute gradient: gradient function not found for "+ye.kernelName+".");var Ee=ye.gradient(we),Se=function(He){if(!(He in Ee))throw new Error("Cannot backprop through input "+He+". Available gradients found: "+Object.keys(Ee)+".");var Fe=oe(function(){return Ee[He]()});if(Fe.dtype!=="float32")throw new Error("Error in gradient for op "+ye.kernelName+". The gradient of input "+He+" must have 'float32' dtype, but has '"+Fe.dtype+"'");var je=ye.inputs[He];if(!_e(Fe.shape,je.shape))throw new Error("Error in gradient for op "+ye.kernelName+". The gradient of input '"+He+"' has shape '"+Fe.shape+"', which does not match the shape of the input '"+je.shape+"'");if(P[je.id]==null)P[je.id]=Fe;else{var Ue=P[je.id];P[je.id]=Ue.add(Fe),Ue.dispose()}};for(var Me in ye.inputs)Se(Me)},ie=G.length-1;ie>=0;ie--)ue(ie)}(E,s,function(P){return a.tidy(P)});var I=e.map(function(P){return E[P.id]});return a.state.gradientDepth===0&&(a.state.activeTape.forEach(function(P){for(var G=0,oe=P.saved;Ge||r>e)throw t="["+n+"x"+r+"]",new Error("Requested texture size "+t+" greater than WebGL maximum on this browser / GPU "+("["+e+"x"+e+"]")+".")}function Sn(n,r){return An(n,r,function(){return n.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function ln(n,r,e,t,o,a,i,s){var u=n.getAttribLocation(e,t);return u!==-1&&(St(n,r,function(){return n.bindBuffer(n.ARRAY_BUFFER,o)}),St(n,r,function(){return n.vertexAttribPointer(u,a,n.FLOAT,!1,i,s)}),St(n,r,function(){return n.enableVertexAttribArray(u)}),!0)}function Ka(n,r,e,t){Ja(n,t),St(n,r,function(){return n.activeTexture(n.TEXTURE0+t)}),St(n,r,function(){return n.bindTexture(n.TEXTURE_2D,e)})}function Ai(n,r,e,t){return An(n,r,function(){return n.getUniformLocation(e,t)},'uniform "'+t+'" not present in program.')}function Ya(n,r,e){return n.getUniformLocation(r,e)}function $a(n,r,e,t,o,a){St(n,r,function(){return Ka(n,r,t,a)}),St(n,r,function(){return n.uniform1i(o,a)})}function ia(n,r,e,t){St(n,r,function(){return n.bindFramebuffer(n.FRAMEBUFFER,t)}),St(n,r,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0)})}function sa(n,r,e){St(n,r,function(){return n.bindFramebuffer(n.FRAMEBUFFER,e)}),St(n,r,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0)})}function $r(n){var r=n.checkFramebufferStatus(n.FRAMEBUFFER);if(r!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Oi(n,r))}function Oi(n,r){switch(r){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+r}}function An(n,r,e,t){var o=St(n,r,function(){return e()});if(o==null)throw new Error(t);return o}function Ja(n,r){var e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,t=r+n.TEXTURE0;if(te)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+e+"]")+".")}function po(n,r){return r===void 0&&(r=2),le(n.slice(0,n.length-r))}function mo(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function vo(n){var r=[1,1,1];return n.length===0||n.length===1&&n[0]===1||(r=[po(n)].concat(mo(n))),r}function Ri(n,r){var e;r===void 0&&(r=!1);var t=c().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r&&(t*=2,(n=n.map(function(f,E){return E>=n.length-2?te(n[E]):n[E]})).length===1&&(n=[2,n[0]])),n.length!==2){var o=ee(n);n=o.newShape}var a=le(n);if(n.length<=1&&a<=t)return[1,a];if(n.length===2&&n[0]<=t&&n[1]<=t)return n;if(n.length===3&&n[0]*n[1]<=t&&n[2]<=t)return[n[0]*n[1],n[2]];if(n.length===3&&n[0]<=t&&n[1]*n[2]<=t)return[n[0],n[1]*n[2]];if(n.length===4&&n[0]*n[1]*n[2]<=t&&n[3]<=t)return[n[0]*n[1]*n[2],n[3]];if(n.length===4&&n[0]<=t&&n[1]*n[2]*n[3]<=t)return[n[0],n[1]*n[2]*n[3]];if(r){var i=po(n),s=2,u=2;return n.length&&(s=(e=mo(n))[0],u=e[1]),j(a=i*(s/2)*(u/2)).map(function(f){return 2*f})}return j(a)}function ua(n){return n%2==0}function go(n,r){if(_e(n=n.slice(-2),r=r.slice(-2)))return!0;if(!n.length||!r.length)return!0;if(n[0]===0||n[1]===0||r[0]===0||r[1]===0)return!0;if(n.length!==r.length){var e=n.slice(-1)[0],t=r.slice(-1)[0];if(e===t)return!0;if(ua(e)&&ua(t)&&(n[0]===1||r[0]===1))return!0}return n[1]===r[1]&&ua(n[0])&&ua(r[0])}function Ii(n){if(zr==null){var r=vn(n);zr=r.getParameter(r.MAX_TEXTURE_SIZE)}return zr}function ca(n){if(ho==null){var r=vn(n);ho=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ho)}function jo(n){if(n===0)return 0;var r=vn(n);return Jr(r,"EXT_disjoint_timer_query_webgl2")&&n===2?2:Jr(r,"EXT_disjoint_timer_query")?1:0}function Jr(n,r){return n.getExtension(r)!=null}function la(n){try{if(vn(n)!=null)return!0}catch(r){return!1}return!1}function Di(n){if(n===0)return!1;var r=vn(n);if(n===1){if(!Jr(r,"OES_texture_float"))return!1}else if(!Jr(r,"EXT_color_buffer_float"))return!1;return qa(r)}function Ni(n){if(n===0)return!1;var r=vn(n);if(n!==1){if(Jr(r,"EXT_color_buffer_float"))return qa(r);if(Jr(r,"EXT_color_buffer_half_float")){var e=r.getExtension("EXT_color_buffer_half_float");return function(t,o){var a=Po(t,o),i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,a.internalFormatHalfFloat,1,1,0,a.textureFormatFloat,a.textureTypeHalfFloat,null);var s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);var u=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(i),t.deleteFramebuffer(s),u}(r,e)}return!1}return!!Jr(r,"OES_texture_float")&&!!Jr(r,"WEBGL_color_buffer_float")&&qa(r)}function qa(n){var r=Po(n),e=n.createTexture();n.bindTexture(n.TEXTURE_2D,e),n.texImage2D(n.TEXTURE_2D,0,r.internalFormatFloat,1,1,0,r.textureFormatFloat,r.textureTypeFloat,null);var t=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,t),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0);var o=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(e),n.deleteFramebuffer(t),o}function ki(n){return n===2&&vn(n).fenceSync!=null}var Es=Object.freeze({callAndCheck:St,canBeRepresented:xs,getWebGLErrorMessage:Va,getExtensionOrThrow:Lo,createVertexShader:ws,createFragmentShader:gn,createProgram:an,linkProgram:yn,validateProgram:Jn,createStaticVertexBuffer:na,createStaticIndexBuffer:Xa,getNumChannels:function(){return c().getNumber("WEBGL_VERSION")===2?1:4},createTexture:oa,validateTextureSize:aa,createFramebuffer:Sn,bindVertexBufferToProgramAttribute:ln,bindTextureUnit:Ka,unbindTextureUnit:function(n,r,e){Ja(n,e),St(n,r,function(){return n.activeTexture(n.TEXTURE0+e)}),St(n,r,function(){return n.bindTexture(n.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:Ai,getProgramUniformLocation:Ya,bindTextureToProgramUniformSampler:$a,bindCanvasToFramebuffer:function(n,r){St(n,r,function(){return n.bindFramebuffer(n.FRAMEBUFFER,null)}),St(n,r,function(){return n.viewport(0,0,n.canvas.width,n.canvas.height)}),St(n,r,function(){return n.scissor(0,0,n.canvas.width,n.canvas.height)})},bindColorTextureToFramebuffer:ia,unbindColorTextureFromFramebuffer:sa,validateFramebuffer:$r,getFramebufferErrorMessage:Oi,getBatchDim:po,getRowsCols:mo,getShapeAs3D:vo,getTextureShapeFromLogicalShape:Ri,isReshapeFree:go,getWebGLMaxTextureSize:Ii,resetMaxTextureSize:function(){zr=null},resetMaxTexturesInShader:function(){ho=null},getMaxTexturesInShader:ca,getWebGLDisjointQueryTimerVersion:jo,hasExtension:Jr,isWebGLVersionEnabled:la,isCapableOfRenderingToFloatTexture:Di,isDownloadFloatTextureEnabled:Ni,isWebGLFenceEnabled:ki}),Lt=c();function Mi(){c().set("PROD",!0)}function qu(){c().set("DEBUG",!0)}function Qu(){c().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Pi(n){c().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Zu(){Ve.disposeVariables()}function Fo(){return Ve}function ec(){return Ve.memory()}function _s(n){return Ve.profile(n)}function Rr(n,r){return Ve.tidy(n,r)}function qr(n){cn(n).forEach(function(r){return r.dispose()})}function Cs(n){return Ve.keep(n)}function tc(n){return Ve.time(n)}function rc(n){return Ve.setBackend(n)}function ad(){return Ve.ready()}function nc(){return Ve.backendName}function Li(n){Ve.removeBackend(n)}function oc(n){return Ve.findBackend(n)}function Ts(n){return Ve.findBackendFactory(n)}function Ss(n,r,e){return e===void 0&&(e=1),Ve.registerBackend(n,r,e)}function ac(){return Ve.backend}function ic(n,r){c().setPlatform(n,r)}function da(){for(var n=[],r=0;r0,function(){return"Element arr["+s.join("][")+"] should be a primitive, but is an array of "+a.length+" elements"}),w(a.length===i[0],function(){return"Element arr["+s.join("][")+"] should have "+i[0]+" elements, but has "+a.length+" elements"});for(var u=i.slice(1),f=0;f=0&&(o=t),dn(t,o,r,e),n==null||!Te(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){var a=n==null?"null":n.constructor.name;throw new Error("Argument '"+r+"' passed to '"+e+"' must be a Tensor or TensorLike, but got '"+a+"'")}var i=bn(n,o);Te(n)||Array.isArray(n)||(n=[n]);var s=o!=="string"?pe(n,o,c().getBool("DEBUG")):he(n,[],!0);return Ve.makeTensor(s,i,o)}function yo(n,r,e,t){if(t===void 0&&(t="numeric"),!Array.isArray(n))throw new Error("Argument "+r+" passed to "+e+" must be a `Tensor[]` or `TensorLike[]`");return n.map(function(o,a){return Oe(o,r+"["+a+"]",e)},t)}function ji(n,r){for(var e=0;e=0&&r0}),Lt.registerFlag("WEBGL_VERSION",function(){return la(2)?2:la(1)?1:0}),Lt.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return Lt.get("WEBGL_VERSION")===2}),Lt.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),Lt.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),Lt.registerFlag("WEBGL_PACK",function(){return Lt.getBool("HAS_WEBGL")}),Lt.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_PACK_CLIP",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),Lt.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_PACK_REDUCE",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_LAZILY_UNPACK",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_CONV_IM2COL",function(){return Lt.getBool("WEBGL_PACK")}),Lt.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Ii(Lt.getNumber("WEBGL_VERSION"))}),Lt.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return ca(Lt.getNumber("WEBGL_VERSION"))}),Lt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var n=Lt.getNumber("WEBGL_VERSION");return n===0?0:jo(n)}),Lt.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return Lt.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(n=navigator.userAgent||navigator.vendor||window.opera,!(/(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(n)||/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(n.substr(0,4))));var n}),Lt.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return Di(Lt.getNumber("WEBGL_VERSION"))}),Lt.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!Lt.getBool("WEBGL_FORCE_F16_TEXTURES")&&Lt.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),Lt.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ni(Lt.getNumber("WEBGL_VERSION"))}),Lt.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return ki(Lt.getNumber("WEBGL_VERSION"))}),Lt.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return Lt.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),Xn=Pi;var xr=Ke({complex_:function(n,r){var e=Oe(n,"real","complex"),t=Oe(r,"imag","complex");return X(e.shape,t.shape,"real and imag shapes, "+e.shape+" and "+t.shape+", must match in call to tf.complex()."),Ve.runKernelFunc(function(o){return o.complex(e,t)},{$real:e,$imag:t})}}),un=Ke({real_:function(n){var r=Oe(n,"input","real");return Ve.runKernelFunc(function(e){return e.real(r)},{$input:r})}}),xn=Ke({imag_:function(n){var r=Oe(n,"input","imag");return Ve.runKernelFunc(function(e){return e.imag(r)},{$input:r})}});function Ur(n,r,e){return Nn(n,r,bn(n,e),e)}function Nn(n,r,e,t){if(t==null&&(t=ot(n)),t==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Te(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="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(r!=null){Ae(r);var o=le(r),a=le(e);w(o===a,function(){return"Based on the provided shape, ["+r+"], the tensor should have "+o+" values but has "+a});for(var i=0;i1)return Tr([0],t);var o=$(Math.abs(Math.ceil((r-n)/e)),t);r=1,function(){return"Pass at least one tensor to concat"});var e=yo(n,"tensors","concat");e[0].dtype==="complex64"&&e.forEach(function(s){if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor with dtype `+s.dtype+". ")}),r=de(r,e[0].shape)[0];var t=qn(e.map(function(s){return s.shape}),r);if(le(t)===0)return Ur([],t);if((e=e.filter(function(s){return s.size>0})).length===1)return e[0];var o=e.map(function(s){return s.shape});Fi(o,r);var a=e,i={axis:r};return Ve.runKernelFunc(function(s){return s.concat(e,r)},a,function(s){var u=o.map(function(f){return f[r]});return Bo(s,u,r).map(function(f){return function(){return f}})},"Concat",i)}}),Os=Ke({concat1d_:function(n){return hn(n,0)}}),Rs=Ke({concat2d_:function(n,r){return hn(n,r)}}),ha=Ke({concat3d_:function(n,r){return hn(n,r)}}),Is=Ke({concat4d_:function(n,r){return hn(n,r)}}),Bo=Ke({split_:function(n,r,e){e===void 0&&(e=0);var t,o=Oe(n,"x","split");return e=de(e,o.shape)[0],typeof r=="number"?(w(o.shape[e]%r==0,function(){return"Number of splits must evenly divide the axis."}),t=new Array(r).fill(o.shape[e]/r)):(w(o.shape[e]===r.reduce(function(a,i){return a+i}),function(){return"The sum of sizes must match the size of the axis dimension."}),t=r),Ve.runKernelFunc(function(a){return a.split(o,t,e)},{$x:o},function(a){return{$x:function(){return hn(a,e)}}})}});typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof y!="undefined"||typeof self!="undefined"&&self;function Qr(n,r){return n(r={exports:{}},r.exports),r.exports}var Pn=Qr(function(n){!function(r,e,t){function o(s){var u,f=this,E=(u=4022871197,function(I){I=I.toString();for(var P=0;P>>0,u=(G*=u)>>>0,u+=4294967296*(G-=u)}return 23283064365386963e-26*(u>>>0)});f.next=function(){var I=2091639*f.s0+23283064365386963e-26*f.c;return f.s0=f.s1,f.s1=f.s2,f.s2=I-(f.c=0|I)},f.c=1,f.s0=E(" "),f.s1=E(" "),f.s2=E(" "),f.s0-=E(s),f.s0<0&&(f.s0+=1),f.s1-=E(s),f.s1<0&&(f.s1+=1),f.s2-=E(s),f.s2<0&&(f.s2+=1),E=null}function a(s,u){return u.c=s.c,u.s0=s.s0,u.s1=s.s1,u.s2=s.s2,u}function i(s,u){var f=new o(s),E=u&&u.state,I=f.next;return I.int32=function(){return 4294967296*f.next()|0},I.double=function(){return I()+11102230246251565e-32*(2097152*I()|0)},I.quick=I,E&&(typeof E=="object"&&a(E,f),I.state=function(){return a(f,{})}),I}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.alea=i}(0,n,!1)}),Ds=Qr(function(n){!function(r,e,t){function o(s){var u=this,f="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var I=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^I^I>>>8},s===(0|s)?u.x=s:f+=s;for(var E=0;E>>0)/4294967296};return I.double=function(){do var P=((f.next()>>>11)+(f.next()>>>0)/4294967296)/(1<<21);while(P===0);return P},I.int32=f.next,I.quick=I,E&&(typeof E=="object"&&a(E,f),I.state=function(){return a(f,{})}),I}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.xor128=i}(0,n,!1)}),Ns=Qr(function(n){!function(r,e,t){function o(s){var u=this,f="";u.next=function(){var I=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^I^I<<1)|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,s===(0|s)?u.x=s:f+=s;for(var E=0;E>>4),u.next()}function a(s,u){return u.x=s.x,u.y=s.y,u.z=s.z,u.w=s.w,u.v=s.v,u.d=s.d,u}function i(s,u){var f=new o(s),E=u&&u.state,I=function(){return(f.next()>>>0)/4294967296};return I.double=function(){do var P=((f.next()>>>11)+(f.next()>>>0)/4294967296)/(1<<21);while(P===0);return P},I.int32=f.next,I.quick=I,E&&(typeof E=="object"&&a(E,f),I.state=function(){return a(f,{})}),I}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.xorwow=i}(0,n,!1)}),ks=Qr(function(n){!function(r,e,t){function o(s){var u=this;u.next=function(){var f,E,I=u.x,P=u.i;return f=I[P],E=(f^=f>>>7)^f<<24,E^=(f=I[P+1&7])^f>>>10,E^=(f=I[P+3&7])^f>>>3,E^=(f=I[P+4&7])^f<<7,f=I[P+7&7],E^=(f^=f<<13)^f<<9,I[P]=E,u.i=P+1&7,E},function(f,E){var I,P=[];if(E===(0|E))P[0]=E;else for(E=""+E,I=0;I0;--I)f.next()}(u,s)}function a(s,u){return u.x=s.x.slice(),u.i=s.i,u}function i(s,u){s==null&&(s=+new Date);var f=new o(s),E=u&&u.state,I=function(){return(f.next()>>>0)/4294967296};return I.double=function(){do var P=((f.next()>>>11)+(f.next()>>>0)/4294967296)/(1<<21);while(P===0);return P},I.int32=f.next,I.quick=I,E&&(E.x&&a(E,f),I.state=function(){return a(f,{})}),I}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.xorshift7=i}(0,n,!1)}),Ms=Qr(function(n){!function(r,e,t){function o(s){var u=this;u.next=function(){var f,E,I=u.w,P=u.X,G=u.i;return u.w=I=I+1640531527|0,E=P[G+34&127],f=P[G=G+1&127],E^=E<<13,f^=f<<17,E^=E>>>15,f^=f>>>12,E=P[G]=E^f,u.i=G,E+(I^I>>>16)|0},function(f,E){var I,P,G,oe,ue,ie=[],ce=128;for(E===(0|E)?(P=E,E=null):(E+="\0",P=0,ce=Math.max(ce,E.length)),G=0,oe=-32;oe>>15,P^=P<<4,P^=P>>>13,oe>=0&&(ue=ue+1640531527|0,G=(I=ie[127&oe]^=P+ue)==0?G+1:0);for(G>=128&&(ie[127&(E&&E.length||0)]=-1),G=127,oe=512;oe>0;--oe)P=ie[G+34&127],I=ie[G=G+1&127],P^=P<<13,I^=I<<17,P^=P>>>15,I^=I>>>12,ie[G]=P^I;f.w=ue,f.X=ie,f.i=G}(u,s)}function a(s,u){return u.i=s.i,u.w=s.w,u.X=s.X.slice(),u}function i(s,u){s==null&&(s=+new Date);var f=new o(s),E=u&&u.state,I=function(){return(f.next()>>>0)/4294967296};return I.double=function(){do var P=((f.next()>>>11)+(f.next()>>>0)/4294967296)/(1<<21);while(P===0);return P},I.int32=f.next,I.quick=I,E&&(E.X&&a(E,f),I.state=function(){return a(f,{})}),I}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.xor4096=i}(0,n,!1)}),Ui=Qr(function(n){!function(r,e,t){function o(s){var u=this,f="";u.next=function(){var I=u.b,P=u.c,G=u.d,oe=u.a;return I=I<<25^I>>>7^P,P=P-G|0,G=G<<24^G>>>8^oe,oe=oe-I|0,u.b=I=I<<20^I>>>12^P,u.c=P=P-G|0,u.d=G<<16^P>>>16^oe,u.a=oe-I|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,s===Math.floor(s)?(u.a=s/4294967296|0,u.b=0|s):f+=s;for(var E=0;E>>0)/4294967296};return I.double=function(){do var P=((f.next()>>>11)+(f.next()>>>0)/4294967296)/(1<<21);while(P===0);return P},I.int32=f.next,I.quick=I,E&&(typeof E=="object"&&a(E,f),I.state=function(){return a(f,{})}),I}e&&e.exports?e.exports=i:t&&t.amd?t(function(){return i}):this.tychei=i}(0,n,!1)}),wn=Qr(function(n){!function(r,e){var t,o=this,a=256,i=6,s="random",u=e.pow(a,i),f=e.pow(2,52),E=2*f,I=a-1;function P(ce,ye,we){var Ee=[],Se=ue(function Fe(je,Ue){var Ze,Je=[],dt=typeof je;if(Ue&&dt=="object")for(Ze in je)try{Je.push(Fe(je[Ze],Ue-1))}catch(ct){}return Je.length?Je:dt=="string"?je:je+"\0"}((ye=ye==1?{entropy:!0}:ye||{}).entropy?[ce,ie(r)]:ce==null?function(){try{var Fe;return t&&(Fe=t.randomBytes)?Fe=Fe(a):(Fe=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(Fe)),ie(Fe)}catch(Ze){var je=o.navigator,Ue=je&&je.plugins;return[+new Date,o,Ue,o.screen,ie(r)]}}():ce,3),Ee),Me=new G(Ee),He=function(){for(var Fe=Me.g(i),je=u,Ue=0;Fe=E;)Fe/=2,je/=2,Ue>>>=1;return(Fe+Ue)/je};return He.int32=function(){return 0|Me.g(4)},He.quick=function(){return Me.g(4)/4294967296},He.double=He,ue(ie(Me.S),r),(ye.pass||we||function(Fe,je,Ue,Ze){return Ze&&(Ze.S&&oe(Ze,Me),Fe.state=function(){return oe(Me,{})}),Ue?(e[s]=Fe,je):Fe})(He,Se,"global"in ye?ye.global:this==e,ye.state)}function G(ce){var ye,we=ce.length,Ee=this,Se=0,Me=Ee.i=Ee.j=0,He=Ee.S=[];for(we||(ce=[we++]);Se=1||s===0);var u=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*u,t=this.mean+this.stdDev*i*u,this.truncated&&!this.isValidTruncated(e)||(o=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)},n.prototype.convertValue=function(r){return this.dtype==null||this.dtype==="float32"?r:Math.round(r)},n.prototype.isValidTruncated=function(r){return r<=this.upper&&r>=this.lower},n}(),uc=function(){function n(r,e,t,o){this.alpha=r,this.beta=1/e,this.dtype=t;var a=o||Math.random();this.randu=Uo(a.toString()),this.randn=new pa(0,1,t,!1,this.randu()),this.d=r<1?r+2/3:r-1/3,this.c=1/Math.sqrt(9*this.d)}return n.prototype.nextValue=function(){for(var r,e,t,o,a,i;;){do o=this.randn.nextValue(),i=1+this.c*o;while(i<=0);if(i*=i*i,e=1-.331*(r=o*o)*r,t=.5*r+this.d*(1-i+Math.log(i)),(a=this.randu())=1+r.length,function(){return"input rank is "+t.rank+" but should be > than blockShape.length "+r.length}),w(e.length===r.length,function(){return"crops.length is "+e.length+" but should be equal to blockShape.length "+r.length}),w(t.shape[0]%o==0,function(){return"input tensor batch is "+t.shape[0]+" but is not divisible by the product of the elements of blockShape "+r.join(" * ")+" === "+o}),Ve.runKernelFunc(function(a){return a.batchToSpaceND(t,r,e)},{$x:t},function(a){return{$x:function(){return a.spaceToBatchND(r,e)}}})}}),Ps=Ke({broadcastTo_:function(n,r){var e=Oe(n,"broadcastTo","x"),t=e.shape;if(r.some(function(u){return!(u>0)||u%1!=0}))throw new Error("broadcastTo(): Invalid broadcast shape ["+r+"].");if(r.lengthe.rank){for(var o=e.shape.slice();o.length=0;i--)if(e.shape[i]===r[i])a[i]=1;else if(e.shape[i]!==1)throw new Error("broadcastTo(): ["+t+"] cannot be broadcast to ["+r+"].");var s=a.map(function(u,f){return u>1?f:-1}).filter(function(u){return u>=0});return s.length===0?e.clone():Ve.runKernelFunc(function(u){return u.tile(e,a)},{input:e},function(u){return{input:function(){return u.sum(s,!0)}}})}}),ga=Ke({cast_:function(n,r){var e=Oe(n,"x","cast");if(!Ge(r))throw new Error("Failed to cast to unknown dtype "+r);if(r==="string"&&e.dtype!=="string"||r!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");var t={dtype:r};return Ve.runKernelFunc(function(o){return o.cast(e,r)},{x:e},function(o){return{x:function(){return o.clone()}}},"Cast",t)}}),ya=Ke({clone_:function(n){var r=Oe(n,"x","clone",null);return Ve.runKernelFunc(function(){return Ve.makeTensorFromDataId(r.dataId,r.shape,r.dtype)},{$x:r},function(e){return{$x:function(){return e.toFloat()}}})}}),Ls=Ke({cumsum_:function(n,r,e,t){r===void 0&&(r=0),e===void 0&&(e=!1),t===void 0&&(t=!1);var o=Oe(n,"x","cumsum"),a=sn([r|=0],o.rank),i=o;a!=null&&(i=o.transpose(a));var s=fn(1,o.rank)[0],u=Ve.runKernelFunc(function(f){return f.cumsum(i,s,e,t)},{permutedX:i},function(f){return{permutedX:function(){return f.cumsum(r,e,!t)}}});return a!=null&&(u=u.transpose(a)),u}}),js=Ke({depthToSpace_:function(n,r,e){e===void 0&&(e="NHWC");var t=Oe(n,"x","depthToSpace"),o=e==="NHWC"?t.shape[1]:t.shape[2],a=e==="NHWC"?t.shape[2]:t.shape[3],i=e==="NHWC"?t.shape[3]:t.shape[1];return w(o*r>=0,function(){return`Negative dimension size caused by overflow when multiplying `+o+" and "+r+` for depthToSpace with input shape `+t.shape}),w(a*r>=0,function(){return`Negative dimension size caused by overflow when multiplying `+a+" and "+r+` for depthToSpace with input shape `+t.shape}),w(i%(r*r)==0,function(){return"Dimension size must be evenly divisible by "+r*r+" but is "+i+" for depthToSpace with input shape "+t.shape}),Ve.runKernelFunc(function(s){return s.depthToSpace(t,r,e)},{$x:t})}}),On=Ke({expandDims_:function(n,r){r===void 0&&(r=0);var e=Oe(n,"x","expandDims",null);w(r<=e.rank,function(){return"Axis must be <= rank of the tensor"});var t=e.shape.slice();return r<0&&(w(-(e.rank+1)<=r,function(){return"Axis must be in the interval ["+-(e.rank+1)+", "+e.rank+"]"}),r=e.rank+r+1),t.splice(r,0,1),ba(e,t)}}),Hi=Ke({eye_:function(n,r,e,t){t===void 0&&(t="float32"),r==null&&(r=n);for(var o=jt([n,r],t),a=n<=r?n:r,i=0;i2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);e=e||Math.random();var s=i===1?o.as2D(1,-1):o,u=Ve.runKernelFunc(function(f){return f.multinomial(s,t,r,e)},{logits2D:s});return i===1?u.as1D():u}}),ri=Ke({oneHot_:function(n,r,e,t){if(e===void 0&&(e=1),t===void 0&&(t=0),r<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+r);var o=Oe(n,"indices","oneHot","int32"),a=o.shape.concat([r]);return o=o.flatten(),Ve.runKernelFunc(function(i){return i.oneHot(o,r,e,t)},{$indices:o},function(i){return{$indices:function(){return Tr(o.shape,"float32")}}}).reshape(a)}}),Ln=Ke({pad_:function(n,r,e){e===void 0&&(e=0);var t=Oe(n,"x","pad");if(t.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o={paddings:r,constantValue:e};return Ve.runKernelFunc(function(a){return a.pad(t,r,e)},{x:t},function(a){var i=r.map(function(s){return s[0]});return{x:function(){return a.slice(i,t.shape)}}},"PadV2",o)}}),zi=Ke({pad1d_:function(n,r,e){return e===void 0&&(e=0),w(r.length===2,function(){return"Invalid number of paddings. Must be length of 2."}),Ln(n,[r],e)}}),Eo=Ke({pad2d_:function(n,r,e){return e===void 0&&(e=0),w(r.length===2&&r[0].length===2&&r[1].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Ln(n,r,e)}}),ni=Ke({pad3d_:function(n,r,e){return e===void 0&&(e=0),w(r.length===3&&r[0].length===2&&r[1].length===2&&r[2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Ln(n,r,e)}}),Fs=Ke({pad4d_:function(n,r,e){return e===void 0&&(e=0),w(r.length===4&&r[0].length===2&&r[1].length===2&&r[2].length===2&&r[3].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Ln(n,r,e)}}),Bs=Ke({rand_:function(n,r,e){var t=le(n),o=null;if(e==null||e==="float32")o=new Float32Array(t);else if(e==="int32")o=new Int32Array(t);else{if(e!=="bool")throw new Error("Unknown data type "+e);o=new Uint8Array(t)}for(var a=0;a=1+r.length,function(){return"input rank "+t.rank+" should be > than [blockShape] "+r.length}),w(e.length===r.length,function(){return"paddings.shape[0] "+e.length+" must be equal to [blockShape] "+r.length}),w(t.shape.reduce(function(o,a,i){return i>0&&i<=r.length?o&&(a+e[i-1][0]+e[i-1][1])%r[i-1]==0:o},!0),function(){return"input spatial dimensions "+t.shape.slice(1)+" with paddings "+e.toString()+" must be divisible by blockShapes "+r.toString()}),Ve.runKernelFunc(function(o){return o.spaceToBatchND(t,r,e)},{$x:t},function(o){return{$x:function(){return o.batchToSpaceND(r,e)}}})}}),Vi=Ke({squeeze_:function(n,r){var e=Oe(n,"x","squeeze");return ba(e,ee(e.shape,r).newShape)}}),jn=Ke({stack_:function(n,r){r===void 0&&(r=0);var e=yo(n,"tensors","stack");if(w(e.length>=1,function(){return"Pass at least one tensor to tf.stack"}),e.length===1)return e[0].expandDims(r);var t=e[0].rank,o=e[0].shape,a=e[0].dtype;w(r<=t,function(){return"Axis must be <= rank of the tensor"}),e.forEach(function(s){X(o,s.shape,"All tensors passed to stack must have matching shapes")}),e.forEach(function(s){w(a===s.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var i=e.map(function(s){return s.expandDims(r)});return hn(i,r)}}),eo=Ke({tile_:function(n,r){var e=Oe(n,"x","tile",null);w(e.rank===r.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of reps "+r+"."});var t=[e],o={reps:r};return Ve.runKernelFunc(function(a,i){var s=a.tile(e,r);return i([e]),s},{x:e},function(a,i){var s=i[0];return{x:function(){var u=Jt(s);if(s.rank===1)for(var f=0;f=-e.shape.length&&r=2*r+1||o%2==1?i.push(o):a.push(o);t.push.apply(t,a),t.push(0),t.push.apply(t,i)}return t}function wa(n,r,e,t){t===void 0&&(t=!0);var o=[];t?o.push(n[0]/e):o.push(n[0]*e);for(var a=1;an.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+r.shape[r.rank-1]+" vs. "+n.rank);if(n.size===0)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+n.shape+".");for(var e=r.shape,t=e[e.length-1],o=1,a=0;a1?r.shape[r.rank-1]:1,o=r.rank>1?r.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+e.shape+", indices.shape: "+r.shape+", shape: "+n+", sliceDim: "+t+", and batchDim: "+o+".";if(e.rank1?r.shape[t-1]:1,a=e.length,i=1,s=o;s0;)1&n&&r.push(e),n/=2,e++;return r}function Ea(n,r,e){for(var t=[],o=0;o0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=t[o];return a<0&&(a+=s),a=_(0,a,s-1)}function $i(n,r,e,t,o){var a=r[o],i=e[o]||1;(n&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=t[o];return a<0&&(a+=s),a=i>0?_(0,a,s):_(-1,a,s-1)}function Ji(n,r,e){for(var t=e.length,o=0;o1){t=o;break}for(o=t+1;o0||e[o]!==n[o])return!1;return!0}function qi(n,r){for(var e=n.length>0?n[n.length-1]:1,t=0;t0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."});var i=Ve.gradients(n,r,null,!0),s=i.value,u=i.grads;w(u.some(function(E){return E!=null}),function(){return"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()."}),w(s.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var f={};return r.forEach(function(E,I){u[I]!=null&&(f[E.name]=u[I])}),o!=null&&o.forEach(function(E){return f[E.name]=null}),{value:s,grads:f}}function _o(n){return Ve.customGrad(n)}function Co(n){if(n.filter(function(r){return r==null}).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.`)}var zo=Ke({softmax_:function(n,r){r===void 0&&(r=-1);var e=Oe(n,"logits","softmax","float32");if(r===-1&&(r=e.rank-1),r!==e.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and dim was "+r);return Ve.runKernelFunc(function(t,o){var a=t.softmax(e,r);return o([a]),a},{logits:e},function(t,o){var a=o[0],i=t.mul(a);return{logits:function(){return i.sub(i.sum([r],!0).mul(a))}}},"Softmax",{dim:r},[],[!0])}}),si=Ke({logSoftmax_:function(n,r){r===void 0&&(r=-1);var e=Oe(n,"logits","logSoftmax");if(r===-1&&(r=e.rank-1),r!==e.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and axis was "+r);return _o(function(t,o){var a=t.max(r,!0),i=t.sub(a),s=i.toFloat().sub(i.exp().sum(r,!0).log());return o([s]),{value:s,gradFunc:function(u,f){var E=f[0].exp();return u.sub(u.sum(r,!0).mul(E))}}})(e)}}),_a=function(){function n(r,e){this.backend=r,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return n.prototype.get=function(r){return this.data.has(r)||this.dataMover.moveData(this.backend,r),this.data.get(r)},n.prototype.set=function(r,e){this.dataIdsCount++,this.data.set(r,e)},n.prototype.has=function(r){return this.data.has(r)},n.prototype.delete=function(r){return this.dataIdsCount--,this.data.delete(r)},n.prototype.numDataIds=function(){return this.dataIdsCount},n}(),Ca=function(){function n(){}return n.prototype.time=function(r){return tt("time")},n.prototype.read=function(r){return tt("read")},n.prototype.readSync=function(r){return tt("readSync")},n.prototype.numDataIds=function(){return tt("numDataIds")},n.prototype.disposeData=function(r){return tt("disposeData")},n.prototype.write=function(r,e,t){return tt("write")},n.prototype.move=function(r,e,t,o){return tt("move")},n.prototype.memory=function(){return tt("memory")},n.prototype.floatPrecision=function(){return tt("floatPrecision")},n.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},n.prototype.batchMatMul=function(r,e,t,o){return tt("batchMatMul")},n.prototype.fusedBatchMatMul=function(r){return r.a,r.b,r.transposeA,r.transposeB,r.bias,r.activation,r.preluActivationWeights,tt("fusedBatchMatMul")},n.prototype.slice=function(r,e,t){return tt("slice")},n.prototype.stridedSlice=function(r,e,t,o){return tt("stridedSlice")},n.prototype.unstack=function(r,e){return tt("unstack")},n.prototype.reverse=function(r,e){return tt("reverse")},n.prototype.concat=function(r,e){return tt("concat")},n.prototype.neg=function(r){return tt("neg")},n.prototype.add=function(r,e){return tt("add")},n.prototype.addN=function(r){return tt("addN")},n.prototype.subtract=function(r,e){return tt("subtract")},n.prototype.multiply=function(r,e){return tt("multiply")},n.prototype.realDivide=function(r,e){return tt("realDivide")},n.prototype.floorDiv=function(r,e){return tt("floorDiv")},n.prototype.sum=function(r,e){return tt("sum")},n.prototype.prod=function(r,e){return tt("prod")},n.prototype.unsortedSegmentSum=function(r,e,t){return tt("unsortedSegmentSum")},n.prototype.argMin=function(r,e){return tt("argMin")},n.prototype.argMax=function(r,e){return tt("argMax")},n.prototype.equal=function(r,e){return tt("equal")},n.prototype.notEqual=function(r,e){return tt("notEqual")},n.prototype.less=function(r,e){return tt("less")},n.prototype.lessEqual=function(r,e){return tt("lessEqual")},n.prototype.greater=function(r,e){return tt("greater")},n.prototype.greaterEqual=function(r,e){return tt("greaterEqual")},n.prototype.logicalNot=function(r){return tt("logicalNot")},n.prototype.logicalAnd=function(r,e){return tt("logicalAnd")},n.prototype.logicalOr=function(r,e){return tt("logicalOr")},n.prototype.where=function(r){return tt("where")},n.prototype.select=function(r,e,t){return tt("select")},n.prototype.topk=function(r,e,t){return tt("topk")},n.prototype.min=function(r,e){return tt("min")},n.prototype.minimum=function(r,e){return tt("minimum")},n.prototype.mod=function(r,e){return tt("mod")},n.prototype.max=function(r,e){return tt("max")},n.prototype.maximum=function(r,e){return tt("maximum")},n.prototype.all=function(r,e){return tt("all")},n.prototype.any=function(r,e){return tt("any")},n.prototype.squaredDifference=function(r,e){return tt("squaredDifference")},n.prototype.ceil=function(r){return tt("ceil")},n.prototype.floor=function(r){return tt("floor")},n.prototype.round=function(r){return tt("round")},n.prototype.sign=function(r){return tt("sign")},n.prototype.isNaN=function(r){return tt("isNaN")},n.prototype.isInf=function(r){return tt("isInf")},n.prototype.isFinite=function(r){return tt("isFinite")},n.prototype.pow=function(r,e){return tt("pow")},n.prototype.exp=function(r){return tt("exp")},n.prototype.expm1=function(r){return tt("expm1")},n.prototype.softmax=function(r,e){return tt("softmax")},n.prototype.log=function(r){return tt("log")},n.prototype.log1p=function(r){return tt("log1p")},n.prototype.sqrt=function(r){return tt("sqrt")},n.prototype.rsqrt=function(r){return tt("rsqrt")},n.prototype.square=function(r){return tt("square")},n.prototype.reciprocal=function(r){return tt("reciprocal")},n.prototype.relu=function(r){return tt("relu")},n.prototype.relu6=function(r){return tt("relu6")},n.prototype.prelu=function(r,e){return tt("prelu")},n.prototype.elu=function(r){return tt("elu")},n.prototype.eluDer=function(r,e){return tt("eluDer")},n.prototype.selu=function(r){return tt("selu")},n.prototype.int=function(r){return tt("int")},n.prototype.clip=function(r,e,t){return tt("clip")},n.prototype.abs=function(r){return tt("abs")},n.prototype.complexAbs=function(r){return tt("complexAbs")},n.prototype.sigmoid=function(r){return tt("sigmoid")},n.prototype.softplus=function(r){return tt("softplus")},n.prototype.sin=function(r){return tt("sin")},n.prototype.cos=function(r){return tt("cos")},n.prototype.tan=function(r){return tt("tan")},n.prototype.asin=function(r){return tt("asin")},n.prototype.acos=function(r){return tt("acos")},n.prototype.atan=function(r){return tt("atan")},n.prototype.atan2=function(r,e){return tt("atan2")},n.prototype.sinh=function(r){return tt("sinh")},n.prototype.cosh=function(r){return tt("cosh")},n.prototype.tanh=function(r){return tt("tanh")},n.prototype.asinh=function(r){return tt("asinh")},n.prototype.acosh=function(r){return tt("acosh")},n.prototype.atanh=function(r){return tt("atanh")},n.prototype.erf=function(r){return tt("erf")},n.prototype.step=function(r,e){return tt("step")},n.prototype.fusedConv2d=function(r){return r.input,r.filter,r.convInfo,r.bias,r.activation,r.preluActivationWeights,tt("fusedConv2d")},n.prototype.conv2d=function(r,e,t){return tt("conv2d")},n.prototype.conv2dDerInput=function(r,e,t){return tt("conv2dDerInput")},n.prototype.conv2dDerFilter=function(r,e,t){return tt("conv2dDerFilter")},n.prototype.fusedDepthwiseConv2D=function(r){return r.input,r.filter,r.convInfo,r.bias,r.activation,r.preluActivationWeights,tt("fusedDepthwiseConv2D")},n.prototype.depthwiseConv2D=function(r,e,t){return tt("depthwiseConv2D")},n.prototype.depthwiseConv2DDerInput=function(r,e,t){return tt("depthwiseConv2DDerInput")},n.prototype.depthwiseConv2DDerFilter=function(r,e,t){return tt("depthwiseConv2DDerFilter")},n.prototype.conv3d=function(r,e,t){return tt("conv3d")},n.prototype.conv3dDerInput=function(r,e,t){return tt("conv3dDerInput")},n.prototype.conv3dDerFilter=function(r,e,t){return tt("conv3dDerFilter")},n.prototype.maxPool=function(r,e){return tt("maxPool")},n.prototype.maxPoolBackprop=function(r,e,t,o){return tt("maxPoolBackprop")},n.prototype.avgPool=function(r,e){return tt("avgPool")},n.prototype.avgPoolBackprop=function(r,e,t){return tt("avgPoolBackprop")},n.prototype.avgPool3d=function(r,e){return tt("avgPool3d")},n.prototype.avgPool3dBackprop=function(r,e,t){return tt("avgPool3dBackprop")},n.prototype.maxPool3d=function(r,e){return tt("maxPool3d")},n.prototype.maxPool3dBackprop=function(r,e,t,o){return tt("maxPool3dBackprop")},n.prototype.reshape=function(r,e){return tt("reshape")},n.prototype.cast=function(r,e){return tt("cast")},n.prototype.tile=function(r,e){return tt("tile")},n.prototype.pad=function(r,e,t){return tt("pad")},n.prototype.transpose=function(r,e){return tt("transpose")},n.prototype.gather=function(r,e,t){return tt("gather")},n.prototype.gatherND=function(r,e){return tt("gatherND")},n.prototype.scatterND=function(r,e,t){return tt("scatterND")},n.prototype.batchToSpaceND=function(r,e,t){return tt("batchToSpaceND")},n.prototype.spaceToBatchND=function(r,e,t){return tt("spaceToBatchND")},n.prototype.resizeBilinear=function(r,e,t,o){return tt("resizeBilinear")},n.prototype.resizeBilinearBackprop=function(r,e,t){return tt("resizeBilinearBackprop")},n.prototype.resizeNearestNeighbor=function(r,e,t,o){return tt("resizeNearestNeighbor")},n.prototype.resizeNearestNeighborBackprop=function(r,e,t){return tt("resizeNearestNeighborBackprop")},n.prototype.batchNormalization=function(r,e,t,o,a,i){return tt("batchNormalization")},n.prototype.localResponseNormalization4D=function(r,e,t,o,a){return tt("localResponseNormalization4D")},n.prototype.LRNGrad=function(r,e,t,o,a,i,s){return tt("LRNGrad")},n.prototype.multinomial=function(r,e,t,o){return tt("multinomial")},n.prototype.oneHot=function(r,e,t,o){return tt("oneHot")},n.prototype.cumsum=function(r,e,t,o){return tt("cumsum")},n.prototype.nonMaxSuppression=function(r,e,t,o,a){return tt("nonMaxSuppression")},n.prototype.fft=function(r){return tt("fft")},n.prototype.ifft=function(r){return tt("ifft")},n.prototype.complex=function(r,e){return tt("complex")},n.prototype.real=function(r){return tt("real")},n.prototype.imag=function(r){return tt("imag")},n.prototype.cropAndResize=function(r,e,t,o,a,i){return tt("cropAndResize")},n.prototype.depthToSpace=function(r,e,t){return tt("depthToSpace")},n.prototype.split=function(r,e,t){return tt("split")},n.prototype.sparseToDense=function(r,e,t,o){return tt("sparseToDense")},n.prototype.diag=function(r){return tt("diag")},n.prototype.fill=function(r,e,t){return tt("fill")},n.prototype.onesLike=function(r){return tt("onesLike")},n.prototype.zerosLike=function(r){return tt("zerosLike")},n.prototype.linspace=function(r,e,t){return tt("linspace")},n.prototype.dispose=function(){return tt("dispose")},n}();function tt(n){throw new Error("'"+n+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function En(n,r){for(var e=n.length,t=[],o=0;o1&&i===1&&t.unshift(a)}return t}function Ir(n,r){for(var e=[],t=0;t1)&&e.unshift(a)}return e}function Ht(n,r){for(var e=[],t=Math.max(n.length,r.length),o=0;o>>1)]);ue>0?I=G+1:(P=G,oe=!ue)}return oe?I:-I-1}(a,i,s||tu)}(n,r,e),o=t<0?-(t+1):t;n.splice(o,0,r)}function tu(n,r){return n>r?1:no}).sort(rs),f=a>0?-.5/a:0,E=[],I=[];E.length0;){var P=u.pop(),G=P.score,oe=P.boxIndex,ue=P.suppressBeginIndex;if(G=ue;--ce){var ye=ru(n,oe,E[ce]);if(ye>=t){ie=!0;break}if(P.score=P.score*nu(t,f,ye),P.score<=o)break}P.suppressBeginIndex=E.length,ie||(P.score===G?(E.push(oe),I.push(P.score)):P.score>o&&eu(u,P,rs))}var we=E.length;return s&&(E.fill(0,we),I.fill(0,we)),{selectedIndices:Qn(E,"int32"),selectedScores:Qn(I,"float32"),numValidOutputs:It(we,"int32")}}function ru(n,r,e){var t=n.subarray(4*r,4*r+4),o=n.subarray(4*e,4*e+4),a=Math.min(t[0],t[2]),i=Math.min(t[1],t[3]),s=Math.max(t[0],t[2]),u=Math.max(t[1],t[3]),f=Math.min(o[0],o[2]),E=Math.min(o[1],o[3]),I=Math.max(o[0],o[2]),P=Math.max(o[1],o[3]),G=(s-a)*(u-i),oe=(I-f)*(P-E);if(G<=0||oe<=0)return 0;var ue=Math.max(a,f),ie=Math.max(i,E),ce=Math.min(s,I),ye=Math.min(u,P),we=Math.max(ce-ue,0)*Math.max(ye-ie,0);return we/(G+oe-we)}function nu(n,r,e){var t=Math.exp(r*e*e);return e<=n?t:0}function rs(n,r){return n.score-r.score||n.score===r.score&&r.boxIndex-n.boxIndex}function ns(n,r,e){var t=new Array(n.rank).fill(0),o=n.shape.slice();return r.map(function(a){o[e]=a;var i=n.slice(t,o);return t[e]+=a,i})}function os(n,r){for(var e=new Array(n.rank),t=0;t":"<",u=e?"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 * `+t+`; int bestIndex = inOffset; float bestValue = getA(batch, bestIndex); for (int i = 0; i < `+t+`; i++) { int inIdx = `+u+`; float candidate = getA(batch, inIdx); if (candidate `+s+` bestValue) { bestValue = candidate; bestIndex = inIdx; } } setOutput(float(bestIndex)); } `};function au(n,r){return["x","y","z","w","u","v"].slice(0,r).map(function(e){return n+"."+e})}function en(n,r){return r===1?[n]:au(n,r)}function Kr(){var n,r,e,t,o,a,i,s,u,f;return c().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",r="in",e="out",t="in",o="texture",a="outputColor",i="out vec4 outputColor;",s=` 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) `,u="",f=` #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))); } `):(n="",r="attribute",e="varying",t="varying",o="texture2D",a="gl_FragColor",i="",s=` #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)); } `,u=` uniform float INFINITY; bool isinf(float val) { return abs(val) == INFINITY; } bvec4 isinf(vec4 val) { return equal(abs(val), vec4(INFINITY)); } `,f=` int round(float value) { return int(floor(value + 0.5)); } ivec4 round(vec4 value) { return ivec4(floor(value + vec4(0.5))); } `),{version:n,attribute:r,varyingVs:e,varyingFs:t,texture2D:o,output:a,defineOutput:i,defineSpecialNaN:s,defineSpecialInf:u,defineRound:f}}function R(n,r,e){e===void 0&&(e="index");var t=$e(r);return t.map(function(o,a){return"int "+n[a]+" = "+e+" / "+o+"; "+(a===t.length-1?"int "+n[a+1]+" = "+e+" - "+n[a]+" * "+o:"index -= "+n[a]+" * "+o)+";"}).join("")}function b(n){var r=$e(n).map(function(e){return e.toString()});return` int getFlatIndex(ivec3 coords) { return coords.x * `+r[0]+" + coords.y * "+r[1]+` + coords.z; } `}var S=` 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; } `;function N(n,r,e,t){var o=[];n.forEach(function(G){var oe=le(G.shapeInfo.logicalShape);G.shapeInfo.isUniform?o.push("uniform float "+G.name+(oe>1?"["+oe+"]":"")+";"):(o.push("uniform sampler2D "+G.name+";"),o.push("uniform int offset"+G.name+";"))});var a,i,s=o.join(` `),u=n.map(function(G){return function(oe,ue,ie){ie===void 0&&(ie=!1);var ce="";ce+=ie?ae(oe):z(oe);var ye=oe.shapeInfo.logicalShape,we=ue.logicalShape;return ye.length<=we.length&&(ce+=ie?function(Ee,Se){var Me,He=Ee.name,Fe=He.charAt(0).toUpperCase()+He.slice(1),je="get"+Fe+"AtOutCoords",Ue=Ee.shapeInfo.logicalShape.length,Ze=Se.logicalShape.length,Je=En(Ee.shapeInfo.logicalShape,Se.logicalShape),dt=ze(Ze),ct=Ze-Ue,st=["x","y","z","w","u","v"];Me=Ue===0?"":Ze<2&&Je.length>=1?"coords = 0;":Je.map(function(Mt){return"coords."+st[Mt+ct]+" = 0;"}).join(` `);var pt="";pt=Ze<2&&Ue>0?"coords":Ee.shapeInfo.logicalShape.map(function(Mt,Pt){return"coords."+st[Pt+ct]}).join(", ");var ht="return outputValue;",ut=le(Ee.shapeInfo.logicalShape)===1,gt=le(Se.logicalShape)===1;if(Ue!==1||ut||gt){if(ut&&!gt)ht=Ze===1?` return vec4(outputValue.x, outputValue.x, 0., 0.); `:` return vec4(outputValue.x); `;else if(Je.length){var yt=Ue-2,Ot=Ue-1;Je.indexOf(yt)>-1&&Je.indexOf(Ot)>-1?ht="return vec4(outputValue.x);":Je.indexOf(yt)>-1?ht="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":Je.indexOf(Ot)>-1&&(ht="return vec4(outputValue.xx, outputValue.zz);")}}else ht=` return vec4(outputValue.xy, outputValue.xy); `;return` vec4 `+je+`() { `+dt+` coords = getOutputCoords(); `+Me+` vec4 outputValue = get`+Fe+"("+pt+`); `+ht+` } `}(oe,ue):function(Ee,Se){var Me=Ee.name,He=Me.charAt(0).toUpperCase()+Me.slice(1),Fe="get"+He+"AtOutCoords",je=Se.texShape,Ue=Ee.shapeInfo.texShape,Ze=Ee.shapeInfo.logicalShape.length,Je=Se.logicalShape.length;if(!Ee.shapeInfo.isUniform&&Ze===Je&&Ee.shapeInfo.flatOffset==null&&_e(Ue,je))return` float `+Fe+`() { return sampleTexture(`+Me+`, resultUV); } `;var dt,ct=ze(Je),st=En(Ee.shapeInfo.logicalShape,Se.logicalShape),pt=Je-Ze,ht=["x","y","z","w","u","v"];dt=Ze===0?"":Je<2&&st.length>=1?"coords = 0;":st.map(function(gt){return"coords."+ht[gt+pt]+" = 0;"}).join(` `);var ut="";return ut=Je<2&&Ze>0?"coords":Ee.shapeInfo.logicalShape.map(function(gt,yt){return"coords."+ht[yt+pt]}).join(", "),` float `+Fe+`() { `+ct+` coords = getOutputCoords(); `+dt+` return get`+He+"("+ut+`); } `}(oe,ue)),ce}(G,r,t)}).join(` `),f=r.texShape,E=Kr(),I=function(G){return` float sampleTexture(sampler2D textureSampler, vec2 uv) { return `+G.texture2D+`(textureSampler, uv).r; } `}(E),P=function(G){return G.version+` precision highp float; precision highp int; precision highp sampler2D; `+G.varyingFs+` vec2 resultUV; `+G.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; `+G.defineSpecialNaN+` `+G.defineSpecialInf+` `+G.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); } `+me+` `+fe+` `+Ce+` `}(E);return r.isPacked?(a=function(G,oe){switch(G.length){case 0:return` int getOutputCoords() { return 0; } `;case 1:return function(Ee,Se){var Me=[Math.ceil(Se[0]/2),Math.ceil(Se[1]/2)];return Me[0]===1?` int getOutputCoords() { return 2 * int(resultUV.x * `+Me[1]+`.0); } `:Me[1]===1?` int getOutputCoords() { return 2 * int(resultUV.y * `+Me[0]+`.0); } `:` int getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+Me[0]+", "+Me[1]+`)); return 2 * (resTexRC.x * `+Me[1]+` + resTexRC.y); } `}(0,oe);case 2:return function(Ee,Se){var Me=[Math.ceil(Se[0]/2),Math.ceil(Se[1]/2)];if(_e(Ee,Se))return` ivec2 getOutputCoords() { return 2 * ivec2(resultUV.yx * vec2(`+Me[0]+", "+Me[1]+`)); } `;var He=Math.ceil(Ee[1]/2);return` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+Me[0]+", "+Me[1]+`)); int index = resTexRC.x * `+Me[1]+` + resTexRC.y; int r = 2 * (index / `+He+`); int c = imod(index, `+He+`) * 2; return ivec2(r, c); } `}(G,oe);case 3:return ue=G,ie=oe,ce=[Math.ceil(ie[0]/2),Math.ceil(ie[1]/2)],ye=Math.ceil(ue[2]/2),we=ye*Math.ceil(ue[1]/2),` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+ce[0]+", "+ce[1]+`)); int index = resTexRC.x * `+ce[1]+` + resTexRC.y; int b = index / `+we+`; index -= b * `+we+`; int r = 2 * (index / `+ye+`); int c = imod(index, `+ye+`) * 2; return ivec3(b, r, c); } `;default:return function(Ee,Se){for(var Me=[Math.ceil(Se[0]/2),Math.ceil(Se[1]/2)],He=Math.ceil(Ee[Ee.length-1]/2),Fe=He*Math.ceil(Ee[Ee.length-2]/2),je=Fe,Ue="",Ze="b, r, c",Je=2;Je2,function(){return"Packed arg"+(e.charAt(0).toUpperCase()+e.slice(1))+" supports only inputs with rank above 2."});var o=n[n.length-1],a=Math.ceil(o/r);this.outputShape=n.slice(0,-1),a>1&&this.outputShape.push(a),t||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,f=u.length,E=ze(f),I=en("coords",f);if(a===1){var P=ze(s=f+1);i=` `+P+" sourceLocR = "+P+"("+I.join()+`, 0); ++`+I[f-1]+`; `+P+" sourceLocG = "+P+"("+I.join()+`, 0); ++`+I[f-2]+`; `+P+" sourceLocA = "+P+"("+I.join()+`, 0); --`+I[f-1]+`; `+P+" sourceLocB = "+P+"("+I.join()+`, 0); --`+I[f-2]+";"}else s=f,i=` `+E+` sourceLocR = coords; ++`+I[f-1]+`; `+E+` sourceLocG = coords; ++`+I[f-2]+`; `+E+` sourceLocA = coords; --`+I[f-1]+`; `+E+` sourceLocB = coords; --`+I[f-2]+";";var G=["x","y","z","w","u","v"].slice(0,s),oe="."+G[s-1],ue=G.map(function(Fe){return"int "+Fe}),ie=en("sourceLocR",s-1).concat("inIdx.r"),ce=en("sourceLocG",s-1).concat("inIdx.g"),ye=en("sourceLocB",s-1).concat("inIdx.b"),we=en("sourceLocA",s-1).concat("inIdx.a"),Ee=e==="max"?"greaterThan":"lessThan",Se=t?"":` inIdx = round(vec4(getBestIndicesAChannel(`+ie.join()+`), getBestIndicesAChannel(`+ce.join()+`), getBestIndicesAChannel(`+ye.join()+`), getBestIndicesAChannel(`+we.join()+")));",Me=`vec4( getAChannel(`+ie.join()+`), hasNextCol ? getAChannel(`+ce.join()+`) : 0., hasNextRow ? getAChannel(`+ye.join()+`) : 0., hasNextRow && hasNextCol ? getAChannel(`+we.join()+") : 0.)",He=t?"":` float getBestIndicesAChannel(`+ue.join()+`) { return getChannel(getBestIndicesA(`+G.join()+`), vec2(`+G.slice(-2).join()+`)); }`;this.userCode=` float getAChannel(`+ue.join()+`) { return getChannel(getA(`+G.join()+`), vec2(`+G.slice(-2).join()+`)); } `+He+` void main() { `+E+` coords = getOutputCoords(); bool hasNextCol = `+I[f-1]+" < "+(u[f-1]-1)+`; bool hasNextRow = `+I[f-2]+" < "+(u[f-2]-1)+`; `+i+` ivec4 srcIdx = ivec4(sourceLocR`+oe+", sourceLocG"+oe+`, sourceLocB`+oe+", sourceLocA"+oe+") * "+r+`; ivec4 inIdx = srcIdx; vec4 bestIndex = vec4(inIdx); vec4 bestValue = `+Me+`; for (int i = 0; i < `+r+`; i++) { inIdx = srcIdx; `+Se+` vec4 candidate = `+Me+`; bvec4 nan = isnan(candidate); bvec4 replace = bvec4( vec4(`+Ee+`(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); } `},wt=function(n){this.variableNames=["dy"],this.outputShape=n.inShape;var r=n.filterHeight,e=n.filterWidth,t=n.strideHeight,o=n.strideWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.effectiveFilterHeight,u=n.effectiveFilterWidth,f=s-1-n.padInfo.top,E=u-1-n.padInfo.left,I=1/(r*e);this.userCode=` const ivec2 pads = ivec2(`+f+", "+E+`); const float avgMultiplier = float(`+I+`); 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 < `+s+`; wR += `+a+`) { float dyR = float(dyRCorner + wR) / `+t+`.0; if (dyR < 0.0 || dyR >= `+n.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < `+u+`; wC+= `+i+`) { float dyC = float(dyCCorner + wC) / `+o+`.0; if (dyC < 0.0 || dyC >= `+n.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(b, idyR, idyC, d); dotProd += dyValue * avgMultiplier; } } setOutput(dotProd); } `},Ct=function(n){this.variableNames=["dy"],this.outputShape=n.inShape;var r=n.filterDepth,e=n.filterHeight,t=n.filterWidth,o=n.strideDepth,a=n.strideHeight,i=n.strideWidth,s=n.dilationDepth,u=n.dilationHeight,f=n.dilationWidth,E=n.effectiveFilterDepth,I=n.effectiveFilterHeight,P=n.effectiveFilterWidth,G=E-1-n.padInfo.front,oe=I-1-n.padInfo.top,ue=P-1-n.padInfo.left,ie=1/(r*e*t);this.userCode=` const ivec3 pads = ivec3(`+G+", "+oe+", "+ue+`); const float avgMultiplier = float(`+ie+`); 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 < `+E+`; wD += `+s+`) { float dyD = float(dyDCorner + wD) / `+o+`.0; if (dyD < 0.0 || dyD >= `+n.outDepth+`.0 || fract(dyD) > 0.0) { continue; } int idyD = int(dyD); for (int wR = 0; wR < `+I+`; wR += `+u+`) { float dyR = float(dyRCorner + wR) / `+a+`.0; if (dyR < 0.0 || dyR >= `+n.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < `+P+`; wC += `+f+`) { float dyC = float(dyCCorner + wC) / `+i+`.0; if (dyC < 0.0 || dyC >= `+n.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(batch, idyD, idyR, idyC, ch); dotProd += dyValue * avgMultiplier; } } } setOutput(dotProd); } `},Dt=function(n,r,e,t,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Ht(n,r),Ht(n,e);var i="0.0";t!=null&&(Ht(n,t),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";o!=null&&(Ht(n,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=n,this.userCode=` void main() { float x = getXAtOutCoords(); float mean = getMeanAtOutCoords(); float variance = getVarianceAtOutCoords(); float offset = `+i+`; float scale = `+s+`; float inv = scale * inversesqrt(variance + float(`+a+`)); setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); } `},At=function(n,r,e,t,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Ht(n,r),Ht(n,e);var i="vec4(0.0)";t!=null&&(Ht(n,t),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";o!=null&&(Ht(n,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=n,this.userCode=` void main() { vec4 offset = `+i+`; vec4 scale = `+s+`; vec4 x = getXAtOutCoords(); vec4 mean = getMeanAtOutCoords(); vec4 variance = getVarianceAtOutCoords(); vec4 inv = scale * inversesqrt(variance + vec4(`+a+`)); setOutput((x - mean) * inv + offset); } `},mt="return areal * breal - aimag * bimag;",_t="return areal * bimag + aimag * breal;",Wt=function(n,r,e){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Ht(r,e),this.userCode=` float binaryOpComplex( float areal, float aimag, float breal, float bimag) { `+n+` } void main() { float areal = getARealAtOutCoords(); float aimag = getAImagAtOutCoords(); float breal = getBRealAtOutCoords(); float bimag = getBImagAtOutCoords(); setOutput(binaryOpComplex(areal, aimag, breal, bimag)); } `},sr="return a + b;",vr="return a - b;",or="return a * b;",Gt="return (a < 0.) ? b * a : a;",Ut=function(n,r,e){this.variableNames=["A","B"],this.outputShape=Ht(r,e),this.userCode=` float binaryOperation(float a, float b) { `+n+` } void main() { float a = getAAtOutCoords(); float b = getBAtOutCoords(); setOutput(binaryOperation(a, b)); } `},kr=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `,lr=function(n,r,e,t){t===void 0&&(t=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Ht(r,e);var o=this.outputShape.length,a="";if(t)if(o===0||le(this.outputShape)===1)a=` result.y = 0.; result.z = 0.; result.w = 0.; `;else if(a=` `+ze(o)+` coords = getOutputCoords(); `,o===1)a+=` result.y = (coords + 1) >= `+this.outputShape[0]+` ? 0. : result.y; result.z = 0.; result.w = 0.; `;else{var i=en("coords",o);a+=` bool nextRowOutOfBounds = (`+i[o-2]+" + 1) >= "+this.outputShape[o-2]+`; bool nextColOutOfBounds = (`+i[o-1]+" + 1) >= "+this.outputShape[o-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) { `+n+` } void main() { vec4 a = getAAtOutCoords(); vec4 b = getBAtOutCoords(); vec4 result = binaryOperation(a, b); `+a+` setOutput(result); } `},Xr=function(){function n(r){this.variableNames=["A"],this.outputShape=r,this.userCode=` uniform float minVal; uniform float maxVal; void main() { float value = getAAtOutCoords(); if (isnan(value)) { setOutput(value); return; } setOutput(clamp(value, minVal, maxVal)); } `}return n.prototype.getCustomSetupFunc=function(r,e){var t=this;return function(o,a){t.minLoc==null&&(t.minLoc=o.getUniformLocationNoThrow(a,"minVal"),t.maxLoc=o.getUniformLocationNoThrow(a,"maxVal")),o.gl.uniform1f(t.minLoc,r),o.gl.uniform1f(t.maxLoc,e)}},n}(),Yr=function(){function n(r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,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))); } `}return n.prototype.getCustomSetupFunc=function(r,e){var t=this;return function(o,a){t.minLoc==null&&(t.minLoc=o.getUniformLocationNoThrow(a,"minVal"),t.maxLoc=o.getUniformLocationNoThrow(a,"maxVal")),o.gl.uniform1f(t.minLoc,r),o.gl.uniform1f(t.maxLoc,e)}},n}(),Rt=function(n){this.variableNames=["real","imag"],this.outputShape=n,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)) ); } `},tn=function(n){this.outputShape=[],this.outputShape=qn(n,1),this.variableNames=n.map(function(s,u){return"T"+u});var r=new Array(n.length-1);r[0]=n[0][1];for(var e=1;e= "+s[u-1]+`) { return getChannel( getT`+u+"("+_r(i,f,G)+`), vec2(`+_r(E,f,G)+`)); }`}var oe=s.length,ue=s[s.length-1];P+=` return getChannel( getT`+oe+"("+_r(i,f,ue)+`), vec2(`+_r(E,f,ue)+"));",this.userCode=` float getValue(`+i.map(function(ie){return"int "+ie})+`) { `+P+` } void main() { `+o+` coords = getOutputCoords(); vec4 result = vec4(getValue(`+a+`), 0., 0., 0.); `+a[t-1]+" = "+a[t-1]+` + 1; if (`+a[t-1]+" < "+e[t-1]+`) { result.g = getValue(`+a+`); } `+a[t-2]+" = "+a[t-2]+` + 1; if (`+a[t-2]+" < "+e[t-2]+`) { result.a = getValue(`+a+`); } `+a[t-1]+" = "+a[t-1]+` - 1; if (`+a[t-2]+" < "+e[t-2]+` && `+a[t-1]+" < "+e[t-1]+`) { result.b = getValue(`+a+`); } setOutput(result); } `};function _r(n,r,e){var t=n.indexOf(r);return n.map(function(o,a){return a===t?o+" - "+e:o}).join()}var Un=function(n){this.variableNames=["x","dy"],this.outputShape=n.filterShape;var r=n.strideHeight,e=n.strideWidth,t=n.padInfo.top,o=n.padInfo.left,a=n.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 < `+n.batchSize+`; b++) { for (int yR = 0; yR < `+n.outHeight+`; yR++) { int xR = wR + yR * `+r+" - "+t+`; if (xR < 0 || xR >= `+n.inHeight+`) { continue; } for (int yC = 0; yC < `+n.outWidth+`; yC++) { int xC = wC + yC * `+e+" - "+o+`; if (xC < 0 || xC >= `+n.inWidth+`) { continue; } if (`+a+`) { 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); } `},Rn=function(n){this.variableNames=["dy","W"],this.outputShape=n.inShape;var r=n.filterHeight,e=n.filterWidth,t=n.strideHeight,o=n.strideWidth,a=n.dataFormat==="channelsLast",i=r-1-n.padInfo.top,s=e-1-n.padInfo.left,u=a?1:2,f=a?2:3,E=a?3:1;this.userCode=` const ivec2 pads = ivec2(`+i+", "+s+`); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d1 = coords[`+E+`]; ivec2 dyCorner = ivec2(coords[`+u+"], coords["+f+`]) - 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 < `+r+`; wR++) { float dyR = float(dyRCorner + wR) / `+t+`.0; if (dyR < 0.0 || dyR >= `+n.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = `+r+` - 1 - wR; for (int wC = 0; wC < `+e+`; wC++) { float dyC = float(dyCCorner + wC) / `+o+`.0; if (dyC < 0.0 || dyC >= `+n.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = `+e+` - 1 - wC; for (int d2 = 0; d2 < `+n.outChannels+`; d2++) { if (`+a+`) { 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); } `},Ko=function(n){this.variableNames=["x","dy"],this.outputShape=n.filterShape;var r=n.strideDepth,e=n.strideHeight,t=n.strideWidth,o=n.padInfo.front,a=n.padInfo.top,i=n.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 < `+n.batchSize+`; b++) { for (int yF = 0; yF < `+n.outDepth+`; yF++) { int xF = wF + yF * `+r+" - "+o+`; if (xF < 0 || xF >= `+n.inDepth+`) { continue; } for (int yR = 0; yR < `+n.outHeight+`; yR++) { int xR = wR + yR * `+e+" - "+a+`; if (xR < 0 || xR >= `+n.inHeight+`) { continue; } for (int yC = 0; yC < `+n.outWidth+`; yC++) { int xC = wC + yC * `+t+" - "+i+`; if (xC < 0 || xC >= `+n.inWidth+`) { continue; } float dyValue = getDy(b, yF, yR, yC, d2); float xValue = getX(b, xF, xR, xC, d1); dotProd += (xValue * dyValue); } } } } setOutput(dotProd); } `},Wn=function(n){this.variableNames=["dy","W"],this.outputShape=n.inShape;var r=n.filterDepth,e=n.filterHeight,t=n.filterWidth,o=n.strideDepth,a=n.strideHeight,i=n.strideWidth,s=r-1-n.padInfo.front,u=e-1-n.padInfo.top,f=t-1-n.padInfo.left;this.userCode=` const ivec3 pads = ivec3(`+s+", "+u+", "+f+`); 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 < `+r+`; wF++) { float dyF = float(dyFCorner + wF) / `+o+`.0; if (dyF < 0.0 || dyF >= `+n.outDepth+`.0 || fract(dyF) > 0.0) { continue; } int idyF = int(dyF); int wFPerm = `+r+` - 1 - wF; for (int wR = 0; wR < `+e+`; wR++) { float dyR = float(dyRCorner + wR) / `+a+`.0; if (dyR < 0.0 || dyR >= `+n.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = `+e+` - 1 - wR; for (int wC = 0; wC < `+t+`; wC++) { float dyC = float(dyCCorner + wC) / `+i+`.0; if (dyC < 0.0 || dyC >= `+n.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = `+t+` - 1 - wC; for (int d2 = 0; d2 < `+n.outChannels+`; d2++) { float xValue = getDy(batch, idyF, idyR, idyC, d2); float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); dotProd += xValue * wValue; } } } } setOutput(dotProd); } `},hi=function(n){this.variableNames=["x","dy"],this.outputShape=n.filterShape;var r=n.strideHeight,e=n.strideWidth,t=n.padInfo.top,o=n.padInfo.left,a=n.outChannels/n.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 * `+a+` + dm; float dotProd = 0.0; // TO DO: Vec4 over the batch size for (int b = 0; b < `+n.batchSize+`; b++) { for (int yR = 0; yR < `+n.outHeight+`; yR++) { int xR = wR + yR * `+r+" - "+t+`; if (xR < 0 || xR >= `+n.inHeight+`) { continue; } for (int yC = 0; yC < `+n.outWidth+`; yC++) { int xC = wC + yC * `+e+" - "+o+`; if (xC < 0 || xC >= `+n.inWidth+`) { continue; } float dyValue = getDy(b, yR, yC, d2); float xValue = getX(b, xR, xC, d1); dotProd += (xValue * dyValue); } } } setOutput(dotProd); } `},gr=function(n){this.variableNames=["dy","W"],this.outputShape=n.inShape;var r=n.filterHeight,e=n.filterWidth,t=n.strideHeight,o=n.strideWidth,a=r-1-n.padInfo.top,i=e-1-n.padInfo.left,s=n.outChannels/n.inChannels;this.userCode=` const ivec2 pads = ivec2(`+a+", "+i+`); 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 < `+r+`; wR++) { float dyR = float(dyRCorner + wR) / `+t+`.0; if (dyR < 0.0 || dyR >= `+n.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = `+r+` - 1 - wR; for (int wC = 0; wC < `+e+`; wC++) { float dyC = float(dyCCorner + wC) / `+o+`.0; if (dyC < 0.0 || dyC >= `+n.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = `+e+` - 1 - wC; // TO DO: Vec4 over the channelMul for (int dm = 0; dm < `+s+`; dm++) { int d2 = d1 * `+s+` + dm; float xValue = getDy(batch, idyR, idyC, d2); float wValue = getW(wRPerm, wCPerm, d1, dm); dotProd += xValue * wValue; } } } setOutput(dotProd); } `},kt=function(n,r,e,t){r===void 0&&(r=!1),e===void 0&&(e=null),t===void 0&&(t=!1),this.variableNames=["x","W"],this.outputShape=n.outShape;var o=n.padInfo.top,a=n.padInfo.left,i=n.strideHeight,s=n.strideWidth,u=n.dilationHeight,f=n.dilationWidth,E=n.filterHeight,I=n.filterWidth,P=4*Math.floor(n.inChannels/4),G=n.inChannels%4,oe=n.dataFormat==="channelsLast",ue=oe?1:2,ie=oe?2:3,ce=oe?3:1,ye="",we="";e&&(ye=t?`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); `+e+` }`:` float activation(float x) { `+e+` } `,we="result = activation(result);");var Ee=r?"result += getBiasAtOutCoords();":"";r&&this.variableNames.push("bias"),t&&this.variableNames.push("preluActivationWeights"),this.userCode=` `+ye+` const ivec2 strides = ivec2(`+i+", "+s+`); const ivec2 pads = ivec2(`+o+", "+a+`); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d2 = coords[`+ce+`]; ivec2 xRCCorner = ivec2(coords[`+ue+"], coords["+ie+`]) * 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 < `+E+`; wR++) { int xR = xRCorner + wR * `+u+`; if (xR < 0 || xR >= `+n.inHeight+`) { continue; } for (int wC = 0; wC < `+I+`; wC++) { int xC = xCCorner + wC * `+f+`; if (xC < 0 || xC >= `+n.inWidth+`) { continue; } for (int d1 = 0; d1 < `+P+`; 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 (`+oe+`) { 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 (`+(G===1)+`) { if (`+oe+`) { dotProd += getX(batch, xR, xC, `+P+`) * getW(wR, wC, `+P+`, d2); } else { dotProd += getX(batch, `+P+`, xR, xC) * getW(wR, wC, `+P+`, d2); } } else if (`+(G===2)+`) { vec2 wValues = vec2( getW(wR, wC, `+P+`, d2), getW(wR, wC, `+P+` + 1, d2) ); if (`+oe+`) { vec2 xValues = vec2( getX(batch, xR, xC, `+P+`), getX(batch, xR, xC, `+P+` + 1) ); dotProd += dot(xValues, wValues); } else { vec2 xValues = vec2( getX(batch, `+P+`, xR, xC), getX(batch, `+P+` + 1, xR, xC) ); dotProd += dot(xValues, wValues); } } else if (`+(G===3)+`) { vec3 wValues = vec3( getW(wR, wC, `+P+`, d2), getW(wR, wC, `+P+` + 1, d2), getW(wR, wC, `+P+` + 2, d2) ); if (`+oe+`) { vec3 xValues = vec3( getX(batch, xR, xC, `+P+`), getX(batch, xR, xC, `+P+` + 1), getX(batch, xR, xC, `+P+` + 2) ); dotProd += dot(xValues, wValues); } else { vec3 xValues = vec3( getX(batch, `+P+`, xR, xC), getX(batch, `+P+` + 1, xR, xC), getX(batch, `+P+` + 2, xR, xC) ); dotProd += dot(xValues, wValues); } } } } float result = dotProd; `+Ee+` `+we+` setOutput(result); } `},Vt=function(n){this.variableNames=["x","W"],this.outputShape=n.outShape;var r=n.padInfo.front,e=n.padInfo.top,t=n.padInfo.left,o=n.strideDepth,a=n.strideHeight,i=n.strideWidth,s=n.dilationDepth,u=n.dilationHeight,f=n.dilationWidth,E=n.filterDepth,I=n.filterHeight,P=n.filterWidth,G=4*Math.floor(n.inChannels/4),oe=n.inChannels%4;this.userCode=` const ivec3 strides = ivec3(`+o+", "+a+", "+i+`); const ivec3 pads = ivec3(`+r+", "+e+", "+t+`); 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 < `+E+`; wF++) { int xF = xFCorner + wF * `+s+`; if (xF < 0 || xF >= `+n.inDepth+`) { continue; } for (int wR = 0; wR < `+I+`; wR++) { int xR = xRCorner + wR * `+u+`; if (xR < 0 || xR >= `+n.inHeight+`) { continue; } for (int wC = 0; wC < `+P+`; wC++) { int xC = xCCorner + wC * `+f+`; if (xC < 0 || xC >= `+n.inWidth+`) { continue; } for (int d1 = 0; d1 < `+G+`; 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 (`+(oe===1)+`) { dotProd += getX(batch, xF, xR, xC, `+G+`) * getW(wF, wR, wC, `+G+`, d2); } else if (`+(oe===2)+`) { vec2 xValues = vec2( getX(batch, xF, xR, xC, `+G+`), getX(batch, xF, xR, xC, `+G+` + 1) ); vec2 wValues = vec2( getW(wF, wR, wC, `+G+`, d2), getW(wF, wR, wC, `+G+` + 1, d2) ); dotProd += dot(xValues, wValues); } else if (`+(oe===3)+`) { vec3 xValues = vec3( getX(batch, xF, xR, xC, `+G+`), getX(batch, xF, xR, xC, `+G+` + 1), getX(batch, xF, xR, xC, `+G+` + 2) ); vec3 wValues = vec3( getW(wF, wR, wC, `+G+`, d2), getW(wF, wR, wC, `+G+` + 1, d2), getW(wF, wR, wC, `+G+` + 2, d2) ); dotProd += dot(xValues, wValues); } } } } setOutput(dotProd); } `},yr=function(n,r,e,t){r===void 0&&(r=!1),e===void 0&&(e=null),t===void 0&&(t=!1),this.variableNames=["x","W"],this.outputShape=n.outShape;var o=n.inHeight,a=n.inWidth,i=n.padInfo.top,s=n.padInfo.left,u=n.strideHeight,f=n.strideWidth,E=n.dilationHeight,I=n.dilationWidth,P=n.filterHeight,G=n.filterWidth,oe=n.outChannels/n.inChannels,ue="",ie="";e&&(ue=t?`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); `+e+` }`:` float activation(float x) { `+e+` } `,ie="result = activation(result);");var ce=r?"result += getBiasAtOutCoords();":"";r&&this.variableNames.push("bias"),t&&this.variableNames.push("preluActivationWeights"),this.userCode=` `+ue+` const ivec2 strides = ivec2(`+u+", "+f+`); const ivec2 pads = ivec2(`+i+", "+s+`); void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; ivec2 xRCCorner = coords.yz * strides - pads; int d2 = coords.w; int d1 = d2 / `+oe+`; int q = d2 - d1 * `+oe+`; 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 < `+P+`; wR++) { int xR = xRCorner + wR * `+E+`; if (xR < 0 || xR >= `+o+`) { continue; } for (int wC = 0; wC < `+G+`; wC++) { int xC = xCCorner + wC * `+I+`; if (xC < 0 || xC >= `+a+`) { continue; } float xVal = getX(batch, xR, xC, d1); float wVal = getW(wR, wC, d1, q); dotProd += xVal * wVal; } } float result = dotProd; `+ce+` `+ie+` setOutput(result); } `},dr=function(n,r,e,t){r===void 0&&(r=!1),e===void 0&&(e=null),t===void 0&&(t=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n.outShape;for(var o=n.inHeight,a=n.inWidth,i=n.padInfo.top,s=n.padInfo.left,u=n.strideHeight,f=n.strideWidth,E=n.dilationHeight,I=n.dilationWidth,P=n.filterHeight,G=n.filterWidth,oe=G,ue="int xR; int xC; int xCOffset;",ie=0;ie= 0 && xR < `+o+" && xCOffset >= 0 && xCOffset < "+a+`) { xTexelR`+ie+"C"+ce+` = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if(xCOffset + 1 >= `+a+`) { xTexelR`+ie+"C"+ce+`.zw = vec2(0.); } } else { xTexelR`+ie+"C"+ce+` = vec4(0.); } xCOffset = xC + 1 - 2; if(xR >= 0 && xR < `+o+" && xCOffset >= 0 && xCOffset < "+a+`) { vec4 previous = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if(xCOffset + 1 >= `+a+`) { previous.zw = vec2(0.); } xR`+ie+"C"+ce+" = vec4(previous.zw, xTexelR"+ie+"C"+ce+`.xy); } else { xR`+ie+"C"+ce+" = vec4(0, 0, xTexelR"+ie+"C"+ce+`.xy); } `:` if(xR >= 0 && xR < `+o+" && xC >= 0 && xC < "+a+`) { xTexelR`+ie+"C"+ce+` = getX(batch, xR, xC, d1); } else { xTexelR`+ie+"C"+ce+` = vec4(0.); } xR`+ie+"C"+ce+" = xTexelR"+ie+"C"+ce+`; `,ce+1= 0 && xR < `+o+` && xCOffset >= 0 && xCOffset < `+a+`) { xTexelR`+ie+"C"+(ce+2)+` = getX(batch, xR, xCOffset, d1); } `,I>1&&(ue+=` xCOffset -= 2; if(xR >= 0 && xR < `+o+` && xCOffset >= 0 && xCOffset < `+a+`) { xTexelR`+ie+"C"+ce+` = getX(batch, xR, xCOffset, d1); } else { xTexelR`+ie+"C"+ce+` = vec4(0.); } `),ue+=` xR`+ie+"C"+(ce+1)+` = vec4( xTexelR`+ie+"C"+ce+".zw, xTexelR"+ie+"C"+(ce+2)+`.xy); `):ue+=` xCOffset = xC + `+we+`; if(xR >= 0 && xR < `+o+` && xCOffset >= 0 && xCOffset < `+a+`) { xTexelR`+ie+"C"+(ce+2)+` = getX(batch, xR, xCOffset, d1); } xR`+ie+"C"+(ce+1)+" = xTexelR"+ie+"C"+(ce+2)+`; `}}else ce= 0 && xR < `+o+`) { `,s%2==1?(ue+=` xCOffset = xC + 1 - `+f+`; if(xCOffset >= 0 && xCOffset < `+a+`) { xTexelR`+ie+"C"+ce+` = getX(batch, xR, xCOffset, d1); } else { xTexelR`+ie+"C"+ce+` = vec4(0.); } if(xC + 1 >= 0 && xC + 1 < `+a+`) { xTexelR`+ie+"C"+(ce+2)+` = getX(batch, xR, xC + 1, d1); } else { xTexelR`+ie+"C"+(ce+2)+` = vec4(0.); } xR`+ie+"C"+ce+` = vec4( xTexelR`+ie+"C"+ce+".zw, xTexelR"+ie+"C"+(ce+2)+`.zw); `,ce+1= 0 && xCOffset < `+a+`) { final = getX(batch, xR, xCOffset, d1); } xR`+ie+"C"+(ce+1)+" = vec4(xTexelR"+ie+"C"+(ce+2)+`.xy, final.xy); `)):(ue+=` if(xC >= 0 && xC < `+a+`) { xTexelR`+ie+"C"+ce+` = getX(batch, xR, xC, d1); } else { xTexelR`+ie+"C"+ce+` = vec4(0.); } xCOffset = xC + `+f+`; if(xCOffset >= 0 && xCOffset < `+a+`) { xTexelR`+ie+"C"+(ce+2)+` = getX(batch, xR, xCOffset, d1); } else { xTexelR`+ie+"C"+(ce+2)+` = vec4(0.); } xR`+ie+"C"+ce+` = vec4( xTexelR`+ie+"C"+ce+".xy, xTexelR"+ie+"C"+(ce+2)+`.xy); `,ce+11?[""+(i-1)/(E-1),"(y2-y1) * height_ratio","y1*"+oe+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+oe],ce=ie[0],ye=ie[1],we=ie[2],Ee=I>1?[""+(s-1)/(I-1),"(x2-x1) * width_ratio","x1*"+ue+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+ue],Se=Ee[0],Me=Ee[1],He=Ee[2];this.userCode=` const float height_ratio = float(`+ce+`); const float width_ratio = float(`+Se+`); 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 >= `+a+`) { return; } float height_scale = `+ye+`; float width_scale = `+Me+`; float in_y = `+we+`; if( in_y < 0.0 || in_y > `+oe+` ) { setOutput(float(`+o+`)); return; } float in_x = `+He+`; if( in_x < 0.0 || in_x > `+ue+` ) { setOutput(float(`+o+`)); return; } vec2 sourceFracIndexCR = vec2(in_x,in_y); if(`+P+` == 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); } } `},Zt=function(n,r,e){this.variableNames=["x"],this.outputShape=n;var t=n.length,o=n[n.length-1],a=e?"<":">";this.userCode=` int getIndex(int i) { `+(e?"return "+o+" -i - 1;":"return i;")+` } void main() { `+ze(t)+` coords = getOutputCoords(); int end = `+Qt(t,"coords")+`; float val = 0.0; for (int i = `+o+` - 1; i >= 0; i -= 1) { int idx = getIndex(i); if (idx `+a+` end) { continue; } if (idx == end && `+r+`) { continue; } `+Qt(t,"coords")+` = idx; val += getX(`+function(i,s){if(i===1)return""+s;if(i===2)return s+".x, "+s+".y";if(i===3)return s+".x, "+s+".y, "+s+".z";if(i===4)return s+".x, "+s+".y, "+s+".z, "+s+".w";throw Error("Cumulative sum for rank "+i+" is not yet supported")}(t,"coords")+`); } setOutput(val); } `};function Qt(n,r){if(n===1)return""+r;if(n===2)return r+".y";if(n===3)return r+".z";if(n===4)return r+".w";throw Error("Cumulative sum for rank "+n+" is not yet supported")}var pr=function(n){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Mo.DENSE;var r=Or(n),e=Kr();this.outputShape=n,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { `+R(["r","c","d"],n)+` return ivec3(r, c, d); } void main() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+r[0]+", "+r[1]+`)); int index = 4 * (resTexRC.x * `+r[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); } `+e.output+` = result; } `},Xt=function(n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Mo.DENSE;var r=Or(n),e=Kr();this.outputShape=n,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { `+R(["r","c","d"],n)+` return ivec3(r, c, d); } void main() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+r[0]+", "+r[1]+`)); int index = 4 * (resTexRC.x * `+r[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)); } `+e.output+` = result; } `},wr=function(){function n(r,e,t){this.variableNames=["x"],this.outputShape=[],this.outputShape=r,this.blockSize=e,this.dataFormat=t,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 / `+e+`; int offset_h = imod(h, `+e+`); int in_w = w / `+e+`; int offset_w = imod(w, `+e+`); int offset_d = (offset_h * `+e+` + offset_w) * `+this.getOutputDepthSize()+`; int in_d = d + offset_d; float result = `+this.getInputSamplingString()+`; setOutput(result); } `}return n.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},n.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},n.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},n.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},n.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},n}(),ro=function(n){this.variableNames=["X"],this.outputShape=[n,n],this.userCode=` void main() { ivec2 coords = getOutputCoords(); float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; setOutput(val); } `},Hn=function(n){this.variableNames=["A"],this.outTexUsage=Wr.DOWNLOAD;var r=Kr();this.outputShape=n,this.userCode=` `+S+` void main() { float x = getAAtOutCoords(); `+r.output+` = encode_float(x); } `},Yo=function(n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Wr.DOWNLOAD;var r=Kr();this.outputShape=n,this.userCode=` `+S+` void main() { ivec3 coords = getOutputCoords(); float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); `+r.output+` = encode_float(x); } `},Br=function(n,r,e){e===void 0&&(e=!1),this.variableNames=["A"];var t=Kr(),o=r[0],a=r[1];this.outputShape=n;var i="result";e&&(i="floor(result * 255. + 0.5)"),this.userCode=` `+b(n)+` void main() { ivec3 coords = getOutputCoords(); int flatIndex = getFlatIndex(coords); int offset = imod(flatIndex, 4); flatIndex = idiv(flatIndex, 4, 1.); int r = flatIndex / `+a+`; int c = imod(flatIndex, `+a+`); vec2 uv = (vec2(c, r) + halfCR) / vec2(`+a+".0, "+o+`.0); vec4 values = `+t.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]; } `+t.output+" = vec4("+i+`, 0., 0., 0.); } `},Ra=function(n,r,e){e===void 0&&(e=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var t=Kr(),o=r[0],a=r[1];this.outputShape=n;var i="",s="result";e&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var f=0;f<=1;f++){var E=2*u+f;i+=` localCoords = coords; if(localCoords[2] + `+f+" < "+n[2]+`) { localCoords[2] += `+f+`; if(localCoords[1] + `+u+" < "+n[1]+`) { localCoords[1] += `+u+`; flatIndex = getFlatIndex(localCoords); offset = imod(flatIndex, 4); flatIndex = idiv(flatIndex, 4, 1.); r = flatIndex / `+a+`; c = imod(flatIndex, `+a+`); uv = (vec2(c, r) + halfCR) / vec2(`+a+".0, "+o+`.0); values = `+t.texture2D+`(A, uv); if(offset == 0) { result[`+E+`] = values[0]; } else if(offset == 1) { result[`+E+`] = values[1]; } else if(offset == 2) { result[`+E+`] = values[2]; } else { result[`+E+`] = values[3]; } } } `}this.userCode=` `+b(n)+` void main() { ivec3 coords = getOutputCoords(); vec4 result = vec4(0.); int flatIndex, r, c, offset; ivec3 localCoords; vec2 uv; vec4 values; `+i+` `+t.output+" = "+s+`; } `},pi="return real * expR - imag * expI;",mi="return real * expI + imag * expR;",Ia=function(n,r,e){this.variableNames=["real","imag"];var t=r[1];this.outputShape=r;var o=e?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=e?t+".0":"1.0";this.userCode=` const float exponentMultiplier = `+o+`; float unaryOpComplex(float real, float expR, float imag, float expI) { `+n+` } float mulMatDFT(int batch, int index) { float indexRatio = float(index) / float(`+t+`); float exponentMultiplierTimesIndexRatio = exponentMultiplier * indexRatio; float result = 0.0; for (int i = 0; i < `+t+`; 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) / `+a+`; } return result; } void main() { ivec2 coords = getOutputCoords(); setOutput(mulMatDFT(coords[0], coords[1])); } `},vi=function(){function n(r,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=r,this.userCode=` uniform float value; void main() { // Input can be obtained from uniform value. setOutput(value); } `}return n.prototype.getCustomSetupFunc=function(r){var e=this;return function(t,o){e.valueLoc==null&&(e.valueLoc=t.getUniformLocationNoThrow(o,"value")),t.gl.uniform1f(e.valueLoc,r)}},n}(),br=function(n,r,e){this.variableNames=["A","indices"];var t=n.slice();t[e]=r,this.outputShape=t,this.rank=t.length;var o=ze(this.rank),a=function(i,s){var u=i.length;if(u>4)throw Error("Gather for rank "+u+" is not yet supported");if(u===1)return"int(getIndices(resRC))";for(var f=["resRC.x","resRC.y","resRC.z","resRC.w"],E=[],I=0;I1?"strides[j]":"strides";this.userCode=` `+t+" strides = "+t+"("+this.strides+`); void main() { `+o+` coords = getOutputCoords(); int flattenIndex = 0; for (int j = 0; j < `+this.sliceDim+`; j++) { int index = round(getIndices(coords[0], j)); flattenIndex += index * `+a+`; } setOutput(getX(flattenIndex, coords[1])); } `};function yi(n,r){var e=Kr();return ws(n,r,e.version+` precision highp float; `+e.attribute+` vec3 clipSpacePos; `+e.attribute+` vec2 uv; `+e.varyingVs+` vec2 resultUV; void main() { gl_Position = vec4(clipSpacePos, 1); resultUV = uv; }`)}function bi(n,r){return na(n,r,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function iu(n,r){return Xa(n,r,new Uint16Array([0,1,2,2,1,3]))}function In(n,r,e,t,o,a,i){aa(e,t);var s=oa(n,r),u=n.TEXTURE_2D;return St(n,r,function(){return n.bindTexture(u,s)}),St(n,r,function(){return n.texParameteri(u,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)}),St(n,r,function(){return n.texParameteri(u,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}),St(n,r,function(){return n.texParameteri(u,n.TEXTURE_MIN_FILTER,n.NEAREST)}),St(n,r,function(){return n.texParameteri(u,n.TEXTURE_MAG_FILTER,n.NEAREST)}),St(n,r,function(){return n.texImage2D(u,0,o,e,t,0,a,i,null)}),St(n,r,function(){return n.bindTexture(n.TEXTURE_2D,null)}),s}function $o(n,r,e,t,o){var a=Yn(e,t);return In(n,r,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,n.FLOAT)}function hc(n,r,e,t,o){var a=Yn(e,t);return In(n,r,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function pc(n,r,e,t,o){var a=Yn(e,t);return In(n,r,a[0],a[1],n.RGBA,n.RGBA,n.UNSIGNED_BYTE)}function mc(n,r,e,t,o){var a=$n(e,t);return In(n,r,a[0],a[1],o.internalFormatPackedFloat,n.RGBA,n.FLOAT)}function vc(n,r,e,t,o){var a=$n(e,t);return In(n,r,a[0],a[1],o.internalFormatPackedHalfFloat,n.RGBA,o.textureTypeHalfFloat)}function gc(n,r,e,t){return St(n,r,function(){return n.bindBuffer(n.ARRAY_BUFFER,t)}),ln(n,r,e,"clipSpacePos",t,3,20,0)&&ln(n,r,e,"uv",t,2,20,12)}function yc(n,r,e,t,o,a,i){var s,u,f;St(n,r,function(){return n.bindTexture(n.TEXTURE_2D,e)}),a instanceof Uint8Array?(s=new Uint8Array(t*o*4),u=n.UNSIGNED_BYTE,f=n.RGBA):(s=new Float32Array(t*o*4),u=n.FLOAT,f=i.internalFormatPackedFloat),s.set(a),St(n,r,function(){return n.texImage2D(n.TEXTURE_2D,0,f,t,o,0,n.RGBA,u,s)}),St(n,r,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function bc(n,r,e,t){St(n,r,function(){return n.bindTexture(n.TEXTURE_2D,e)}),t.data instanceof Uint8Array?St(n,r,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,t.width,t.height,0,n.RGBA,n.UNSIGNED_BYTE,t.data)}):St(n,r,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t)}),St(n,r,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function xc(n,r,e,t,o){var a=n.createBuffer();St(n,r,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,a)});var i=16*e*t;return St(n,r,function(){return n.bufferData(n.PIXEL_PACK_BUFFER,i,n.STREAM_READ)}),St(n,r,function(){return n.readPixels(0,0,t,e,n.RGBA,n.FLOAT,0)}),St(n,r,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,null)}),a}function wc(n,r,e){var t=n,o=new Float32Array(e);return t.bindBuffer(t.PIXEL_PACK_BUFFER,r),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,o),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),o}function Ec(n,r,e,t,o){var a=Yn(e,t),i=a[0],s=a[1],u=new Uint8Array(e*t*4);return St(n,r,function(){return n.readPixels(0,0,i,s,o.downloadTextureFormat,n.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function _c(n,r,e,t,o,a,i,s){var u=n,f=new Float32Array(function(E,I){var P=$n(E,I);return P[0]*P[1]*4}(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,r),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,f),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),f}function Cc(n,r,e,t){var o=new Float32Array(e*t*4);return St(n,r,function(){return n.readPixels(0,0,t,e,n.RGBA,n.FLOAT,o)}),o}var ld=Object.freeze({createVertexShader:yi,createVertexBuffer:bi,createIndexBuffer:iu,createFloat32MatrixTexture:$o,createFloat16MatrixTexture:hc,createUnsignedBytesMatrixTexture:pc,createPackedMatrixTexture:mc,createFloat16PackedMatrixTexture:vc,bindVertexProgramAttributeStreams:gc,uploadDenseMatrixToTexture:yc,uploadPixelDataToTexture:bc,createBufferFromOutputTexture:xc,downloadFloat32MatrixFromBuffer:wc,downloadByteEncodedFloatMatrixFromOutputTexture:Ec,downloadPackedMatrixFromBuffer:_c,downloadMatrixFromPackedOutputTexture:Cc}),Tc=function(){function n(r){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=c().getNumber("WEBGL_VERSION");r!=null?(this.gl=r,Ga(e,r)):this.gl=vn(e);var t="WEBGL_color_buffer_float";if(c().getNumber("WEBGL_VERSION")===1){if(this.textureFloatExtension=Lo(this.gl,this.debug,"OES_texture_float"),Jr(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=Lo(this.gl,this.debug,"OES_texture_half_float");else if(c().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(t),Jr(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=Lo(this.gl,this.debug,"EXT_color_buffer_half_float");else if(c().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(t="EXT_color_buffer_float",Jr(this.gl,t))this.colorBufferFloatExtension=this.gl.getExtension(t);else{if(!Jr(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=bi(this.gl,this.debug),this.indexBuffer=iu(this.gl,this.debug),this.framebuffer=Sn(this.gl,this.debug),this.textureConfig=Po(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(n.prototype,"debug",{get:function(){return c().getBool("DEBUG")},enumerable:!0,configurable:!0}),n.prototype.dispose=function(){var r=this;if(!this.disposed){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.");var e=this.gl;St(e,this.debug,function(){return e.finish()}),St(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),St(e,this.debug,function(){return e.deleteFramebuffer(r.framebuffer)}),St(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),St(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),St(e,this.debug,function(){return e.deleteBuffer(r.indexBuffer)}),this.disposed=!0}},n.prototype.createFloat32MatrixTexture=function(r,e){return this.throwIfDisposed(),$o(this.gl,this.debug,r,e,this.textureConfig)},n.prototype.createFloat16MatrixTexture=function(r,e){return this.throwIfDisposed(),hc(this.gl,this.debug,r,e,this.textureConfig)},n.prototype.createUnsignedBytesMatrixTexture=function(r,e){return this.throwIfDisposed(),pc(this.gl,this.debug,r,e,this.textureConfig)},n.prototype.uploadPixelDataToTexture=function(r,e){this.throwIfDisposed(),bc(this.gl,this.debug,r,e)},n.prototype.uploadDenseMatrixToTexture=function(r,e,t,o){this.throwIfDisposed(),yc(this.gl,this.debug,r,e,t,o,this.textureConfig)},n.prototype.createFloat16PackedMatrixTexture=function(r,e){return this.throwIfDisposed(),vc(this.gl,this.debug,r,e,this.textureConfig)},n.prototype.createPackedMatrixTexture=function(r,e){return this.throwIfDisposed(),mc(this.gl,this.debug,r,e,this.textureConfig)},n.prototype.deleteMatrixTexture=function(r){var e=this;this.throwIfDisposed(),this.outputTexture===r&&(sa(this.gl,this.debug,this.framebuffer),this.outputTexture=null),St(this.gl,this.debug,function(){return e.gl.deleteTexture(r)})},n.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(r,e,t){var o=this;return this.downloadMatrixDriver(r,function(){return Ec(o.gl,o.debug,e,t,o.textureConfig)})},n.prototype.downloadPackedMatrixFromBuffer=function(r,e,t,o,a,i){return _c(this.gl,r,0,0,0,a,i,this.textureConfig)},n.prototype.downloadFloat32MatrixFromBuffer=function(r,e){return wc(this.gl,r,e)},n.prototype.createBufferFromTexture=function(r,e,t){this.bindTextureToFrameBuffer(r);var o=xc(this.gl,this.debug,e,t,this.textureConfig);return this.unbindTextureToFrameBuffer(),o},n.prototype.createAndWaitForFence=function(){var r=this.createFence(this.gl);return this.pollFence(r)},n.prototype.createFence=function(r){var e,t,o=this;if(c().getBool("WEBGL_FENCE_API_ENABLED")){var a=r,i=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);r.flush(),t=function(){var s=a.clientWaitSync(i,0,0);return s===a.ALREADY_SIGNALED||s===a.CONDITION_SATISFIED},e=i}else c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),t=function(){return o.isQueryAvailable(e,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):t=function(){return!0};return{query:e,isFencePassed:t}},n.prototype.downloadMatrixFromPackedTexture=function(r,e,t){var o=this;return this.downloadMatrixDriver(r,function(){return Cc(o.gl,o.debug,e,t)})},n.prototype.createProgram=function(r){this.throwIfDisposed();var e=this.gl,t=gn(e,this.debug,r),o=yi(e,this.debug),a=an(e,this.debug);return St(e,this.debug,function(){return e.attachShader(a,o)}),St(e,this.debug,function(){return e.attachShader(a,t)}),yn(e,this.debug,a),this.debug&&Jn(e,this.debug,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=gc(e,this.debug,this.program,this.vertexBuffer)),a},n.prototype.deleteProgram=function(r){var e=this;this.throwIfDisposed(),r===this.program&&(this.program=null),r!=null&&St(this.gl,this.debug,function(){return e.gl.deleteProgram(r)})},n.prototype.setProgram=function(r){var e=this;this.throwIfDisposed(),this.program=r,this.program!=null&&this.debug&&Jn(this.gl,this.debug,this.program),St(this.gl,this.debug,function(){return e.gl.useProgram(r)})},n.prototype.getUniformLocation=function(r,e,t){return t===void 0&&(t=!0),this.throwIfDisposed(),t?Ai(this.gl,this.debug,r,e):Ya(this.gl,r,e)},n.prototype.getAttributeLocation=function(r,e){var t=this;return this.throwIfDisposed(),St(this.gl,this.debug,function(){return t.gl.getAttribLocation(r,e)})},n.prototype.getUniformLocationNoThrow=function(r,e){return this.throwIfDisposed(),this.gl.getUniformLocation(r,e)},n.prototype.setInputMatrixTexture=function(r,e,t){this.throwIfDisposed(),this.throwIfNoProgram(),$a(this.gl,this.debug,this.program,r,e,t)},n.prototype.setOutputMatrixTexture=function(r,e,t){this.setOutputMatrixTextureDriver(r,t,e)},n.prototype.setOutputPackedMatrixTexture=function(r,e,t){this.throwIfDisposed();var o=$n(e,t),a=o[0],i=o[1];this.setOutputMatrixTextureDriver(r,a,i)},n.prototype.setOutputMatrixWriteRegion=function(r,e,t,o){this.setOutputMatrixWriteRegionDriver(t,r,o,e)},n.prototype.setOutputPackedMatrixWriteRegion=function(r,e,t,o){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},n.prototype.debugValidate=function(){this.program!=null&&Jn(this.gl,this.debug,this.program),$r(this.gl)},n.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var r=this.gl;this.debug&&this.debugValidate(),St(r,this.debug,function(){return r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0)})},n.prototype.blockUntilAllProgramsCompleted=function(){var r=this;this.throwIfDisposed(),St(this.gl,this.debug,function(){return r.gl.finish()})},n.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Lo(this.gl,this.debug,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},n.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},n.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},n.prototype.beginQuery=function(){if(c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var r=this.gl,e=this.getQueryTimerExtensionWebGL2(),t=r.createQuery();return r.beginQuery(e.TIME_ELAPSED_EXT,t),t}var o=this.getQueryTimerExtensionWebGL1(),a=o.createQueryEXT();return o.beginQueryEXT(o.TIME_ELAPSED_EXT,a),a},n.prototype.endQuery=function(){if(c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")!==2){var r=this.getQueryTimerExtensionWebGL1();r.endQueryEXT(r.TIME_ELAPSED_EXT)}else{var e=this.gl,t=this.getQueryTimerExtensionWebGL2();e.endQuery(t.TIME_ELAPSED_EXT)}},n.prototype.waitForQueryAndGetTime=function(r){return x(this,void 0,void 0,function(){var e=this;return v(this,function(t){switch(t.label){case 0:return[4,L(function(){return e.disposed||e.isQueryAvailable(r,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return t.sent(),[2,this.getQueryTime(r,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},n.prototype.getQueryTime=function(r,e){if(e===0)return null;if(e===2){var t=this.gl;return t.getQueryParameter(r,t.QUERY_RESULT)/1e6}var o=this.getQueryTimerExtensionWebGL1();return o.getQueryObjectEXT(r,o.QUERY_RESULT_EXT)/1e6},n.prototype.isQueryAvailable=function(r,e){if(e===0)return!0;if(e===2){var t=this.gl,o=this.getQueryTimerExtensionWebGL2(),a=t.getQueryParameter(r,t.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(o=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(r,o.QUERY_RESULT_AVAILABLE_EXT),this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),a&&!this.disjoint},n.prototype.pollFence=function(r){var e=this;return new Promise(function(t){e.addItemToPoll(function(){return r.isFencePassed()},function(){return t()})})},n.prototype.pollItems=function(){for(var r=function(t){for(var o=0;o1||L(function(){return t.pollItems(),t.itemsToPoll.length===0})},n.prototype.bindTextureToFrameBuffer=function(r){this.throwIfDisposed(),ia(this.gl,this.debug,r,this.framebuffer),this.debug&&$r(this.gl)},n.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture!=null?(ia(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&$r(this.gl)):sa(this.gl,this.debug,this.framebuffer)},n.prototype.downloadMatrixDriver=function(r,e){this.bindTextureToFrameBuffer(r);var t=e();return this.unbindTextureToFrameBuffer(),t},n.prototype.setOutputMatrixTextureDriver=function(r,e,t){this.throwIfDisposed();var o=this.gl;ia(o,this.debug,r,this.framebuffer),this.debug&&$r(o),this.outputTexture=r,St(o,this.debug,function(){return o.viewport(0,0,e,t)}),St(o,this.debug,function(){return o.scissor(0,0,e,t)})},n.prototype.setOutputMatrixWriteRegionDriver=function(r,e,t,o){var a=this;this.throwIfDisposed(),St(this.gl,this.debug,function(){return a.gl.scissor(r,e,t,o)})},n.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},n.prototype.throwIfNoProgram=function(){if(this.program==null)throw new Error("No GPU program is currently set.")},n}();function Sc(n,r){if(n.length!==r.length)throw Error("Binary was compiled with "+n.length+" inputs, but was executed with "+r.length+" inputs");n.forEach(function(e,t){var o=e.logicalShape,a=r[t],i=a.shape;if(!_e(o,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+o+" and "+i+" must match");if(!e.isUniform||!a.isUniform){var s=e.texShape,u=a.isUniform?null:a.texData.texShape;if(!_e(s,u))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+s+" and "+u+" must match")}})}var dd=function(n,r,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;for(var t=e.filterWidth,o=e.inChannels,a=e.strideWidth,i=e.strideHeight,s=e.padInfo,u=e.outWidth,f=e.dilationWidth,E=e.dilationHeight,I=e.dataFormat,P=s.left,G=s.top,oe=o*t,ue=Kr(),ie=I==="channelsLast",ce=ie?0:1,ye=ie?1:2,we="",Ee=0;Ee<=1;Ee++)for(var Se=0;Se<=1;Se++)we+=` blockIndex = rc.y + `+Se+`; pos = rc.x + `+Ee+`; if(blockIndex < `+n[1]+" && pos < "+n[0]+`) { offsetY = int(blockIndex / (`+u+")) * "+i+" - "+G+`; d0 = offsetY + `+E+" * (pos / "+oe+`); if(d0 < `+r[ce]+` && d0 >= 0) { offsetX = int(mod(float(blockIndex), `+u+".) * "+a+". - "+P+`.); d1 = offsetX + `+f+" * (int(mod(float(pos), "+oe+".) / "+o+`.)); if(d1 < `+r[ye]+` && d1 >= 0) { ch = int(mod(float(pos), `+o+`.)); if (`+ie+`) { innerDims = vec2(d1, ch); result[`+(2*Ee+Se)+`] = getChannel( getA(d0, int(innerDims.x), int(innerDims.y)), innerDims); } else { innerDims = vec2(d0, d1); result[`+(2*Ee+Se)+`] = 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; `+we+` `+ue.output+` = result; } `},fd=function(n,r,e,t,o){this.variableNames=["x"],this.outputShape=[];var a,i=r,s=n[3]-1;this.outputShape=n;var u="float("+e+") + float("+t+") * sum";a=o===.5?"inversesqrt("+u+")":o===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 = -`+i+"; j <= "+i+`; j++) { int idx = d + j; if (idx >= 0 && idx <= `+s+`) { float z = getX(b, r, c, idx); sum += z * z; } } float val = x * `+a+`; setOutput(val); } `},hd=function(n,r,e,t,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=n,this.depth=n[3],this.depthRadius=r,this.bias=e,this.alpha=t,this.beta=o,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 - `+r+`))); int depthEnd = int(min(float(`+this.depth+`), float(d + `+r+` + 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(`+t+") * norm + float("+e+`); 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(`+t+`) * float(`+o+`) * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d) / norm; if (k == d) { dyi += pow(norm, -1.0 * `+o+`); } if (k == coords[3]) { dyi *= getDy(b, r, c, d); result += dyi; } } else { break; } } } setOutput(result); } `},pd=function(n,r,e,t,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var a,i=r,s=n[3]-1;this.outputShape=n;var u="float("+e+") + float("+t+") * sum";a=o===.5?"inversesqrt("+u+")":o===1?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 - `+i+`; 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 = - `+i+"; j <= "+i+`; j++) { ivec2 idx = depth + j; bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); bvec2 belowUpperBound = lessThanEqual(idx, ivec2(`+s+`)); 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); } `},md=function(n){this.variableNames=["dy","maxPos"],this.outputShape=n.inShape;var r=n.strideHeight,e=n.strideWidth,t=n.dilationHeight,o=n.effectiveFilterHeight,a=n.effectiveFilterWidth,i=o-1-n.padInfo.top,s=a-1-n.padInfo.left,u=o*a-1;this.userCode=` const ivec2 pads = ivec2(`+i+", "+s+`); 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 < `+o+`; wR += `+t+`) { float dyR = float(dyRCorner + wR) / `+r+`.0; if (dyR < 0.0 || dyR >= `+n.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < `+a+`; wC++) { float dyC = float(dyCCorner + wC) / `+e+`.0; if (dyC < 0.0 || dyC >= `+n.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(b, idyR, idyC, d); int maxPosValue = `+u+` - int(getMaxPos(b, idyR, idyC, d)); // Get the current value, check it against the value from the // position matrix. int curPosValue = wR * `+a+` + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } setOutput(dotProd); } `},vd=function(n){this.variableNames=["dy","maxPos"],this.outputShape=n.inShape;var r=n.strideDepth,e=n.strideHeight,t=n.strideWidth,o=n.dilationDepth,a=n.dilationHeight,i=n.dilationWidth,s=n.effectiveFilterDepth,u=n.effectiveFilterHeight,f=n.effectiveFilterWidth,E=s-1-n.padInfo.front,I=u-1-n.padInfo.top,P=f-1-n.padInfo.left,G=s*u*f-1;this.userCode=` const ivec3 pads = ivec3(`+E+", "+I+", "+P+`); 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 < `+s+`; wD += `+o+`) { float dyD = float(dyDCorner + wD) / `+r+`.0; if (dyD < 0.0 || dyD >= `+n.outDepth+`.0 || fract(dyD) > 0.0) { continue; } int idyD = int(dyD); for (int wR = 0; wR < `+u+`; wR += `+a+`) { float dyR = float(dyRCorner + wR) / `+e+`.0; if (dyR < 0.0 || dyR >= `+n.outHeight+`.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < `+f+`; wC += `+i+`) { float dyC = float(dyCCorner + wC) / `+t+`.0; if (dyC < 0.0 || dyC >= `+n.outWidth+`.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(batch, idyD, idyR, idyC, ch); int maxPosValue = `+G+` - int(getMaxPos(batch, idyD, idyR, idyC, ch)); // Get the current value, check it against the value from the // position matrix. int curPosValue = wD * `+u+" * "+f+` + wR * `+f+` + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } } setOutput(dotProd); } `},su=function(n,r,e,t,o,a,i){e===void 0&&(e=!1),t===void 0&&(t=!1),o===void 0&&(o=!1),a===void 0&&(a=null),i===void 0&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;var s=e?n[1]:n[2],u=Math.ceil(s/2),f=e?"i * 2, rc.y":"rc.y, i * 2",E=t?"rc.z, i * 2":"i * 2, rc.z",I=e?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],P=t?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],G="",oe="";a&&(G=i?`vec4 activation(vec4 a) { vec4 b = getPreluActivationWeightsAtOutCoords(); `+a+` }`:`vec4 activation(vec4 x) { `+a+` }`,oe="result = activation(result);");var ue=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode=` `+G+` const float sharedDimension = `+u+`.0; vec4 dot2x2ARowBCol(ivec3 rc) { vec4 result = vec4(0); for (int i = 0; i < `+u+`; i++) { vec4 a = getMatrixA(rc.x, `+f+`); vec4 b = getMatrixB(rc.x, `+E+`); // These swizzled products need to be separately added. // See: https://github.com/tensorflow/tfjs/issues/1735 result += (`+I[0]+" * "+P[0]+`); result += (`+I[1]+" * "+P[1]+`); } return result; } void main() { ivec3 rc = getOutputCoords(); vec4 result = dot2x2ARowBCol(rc); `+ue+` `+oe+` setOutput(result); } `},gd=function(){function n(r,e,t){this.variableNames=["probs"],this.outputShape=[r,t],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 < `+(e-1)+`; i++) { cdf += getProbs(batch, i); if (r < cdf) { setOutput(float(i)); return; } } // If no other event happened, last event happened. setOutput(float(`+(e-1)+`)); } `}return n.prototype.getCustomSetupFunc=function(r){var e=this;return function(t,o){e.seedLoc==null&&(e.seedLoc=t.getUniformLocation(o,"seed")),t.gl.uniform1f(e.seedLoc,r)}},n}(),yd=function(n,r,e,t){this.variableNames=["indices"],this.outputShape=[n,r],this.userCode=` void main() { ivec2 coords = getOutputCoords(); int index = round(getIndices(coords.x)); setOutput(mix(float(`+t+"), float("+e+`), float(index == coords.y))); } `},bd=function(n){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=n;var r=n.length;if(r===0)this.userCode=` void main() { setOutput(vec4(getA(), 0., 0., 0.)); } `;else{var e=en("rc",r),t=ze(r),o=function(s,u,f){if(s===1)return"rc > "+u[0];for(var E="",I=s-2;I= "+u[I],I= `+u+`; bool rEdge = rp1 >= `+f+`; `}(r,n[n.length-1],n[n.length-2],e),i=function(s,u){var f=s.length,E=function(I,P){for(var G=[],oe=0;oe<=1;oe++)for(var ue=0;ue<=1;ue++){for(var ie=(oe===0?"r":"rp1")+", "+(ue===0?"c":"cp1"),ce=2;ce= `+s[0]+` ? 0. : getA(rc + 1), 0, 0`:"getA("+E[0]+`), cEdge ? 0. : getA(`+E[1]+`), rEdge ? 0. : getA(`+E[2]+`), rEdge || cEdge ? 0. : getA(`+E[3]+")"}(n,e);this.userCode=` void main() { `+t+` rc = getOutputCoords(); if(`+o+`) { setOutput(vec4(0)); } else { `+a+` setOutput(vec4(`+i+`)); } } `}},xd=function(n,r,e){this.variableNames=["x"],this.outputShape=r.map(function(u,f){return u[0]+n[f]+u[1]});var t=n.length,o=ze(t),a=r.map(function(u){return u[0]}).join(","),i=r.map(function(u,f){return u[0]+n[f]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,t);this.userCode=t!==1?` `+o+" start = "+o+"("+a+`); `+o+" end = "+o+"("+i+`); void main() { `+o+` outC = getOutputCoords(); if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { setOutput(float(`+e+`)); } else { `+o+` coords = outC - start; setOutput(getX(`+s+`)); } } `:` int start = `+a+`; int end = `+i+`; void main() { int outC = getOutputCoords(); if (outC < start || outC >= end) { setOutput(float(`+e+`)); } else { setOutput(getX(outC - start)); } } `},wd=function(n,r,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r.map(function(ie,ce){return ie[0]+n[ce]+ie[1]});for(var t=n.length,o=ze(t),a=r.map(function(ie){return ie[0]}).join(","),i=r.map(function(ie,ce){return ie[0]+n[ce]}).join(","),s=en("rc",t),u=en("source",t),f=s[t-1]+" < "+this.outputShape[t-1],E=t===1?"source":"vec2("+u.slice(-2).join()+")",I=[o+" rc = outputLoc;",s[t-1]+` += 1; if(`+f+`) { `,t===1?"":`} rc = outputLoc; `+s[t-2]+` += 1; if(`+s[t-2]+" < "+this.outputShape[t-2]+") {",t===1?"":" "+s[t-1]+` += 1; if(`+f+") {"],P=t===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",G="",oe=0,ue=t===1?2:4;oe= `+n.inHeight+`) { continue; } for (int wC = 0; wC < `+f+`; wC += `+s+`) { int xC = xCCorner + wC; if (xC < 0 || xC >= `+n.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 >= currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = wR * `+f+` + wC; } } } setOutput(float(minMaxPosition)); } `;else{var oe=r+"("+r+"("+r+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";r==="avg"&&(oe="avgValue / count");var ue=4*Math.floor(t/4),ie=t%4,ce=` if (`+P+`) { avgValue += dot(values, ones); } else { minMaxValue = max(values, minMaxValue); } `;this.userCode=` const ivec2 strides = ivec2(`+o+", "+a+`); const ivec2 pads = ivec2(`+E+", "+I+`); const float initializationValue = `+G+`; 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 >= `+n.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(`+G+`); float avgValue = 0.0; count = 0.0; for (int wR = 0; wR < `+u+`; wR += `+i+`) { int xR = xRCorner + wR; if (xR < 0 || xR >= `+n.inHeight+`) { continue; } for (int wC = 0; wC < `+ue+`; wC += 4) { int xC = xCCorner + wC * `+s+`; vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + `+s+`, d), getValue(batch, xR, xC + 2 * `+s+`, d), getValue(batch, xR, xC + 3 * `+s+`, d) ); `+ce+` } int xC = xCCorner + `+ue+`; if (`+(ie===1)+`) { vec4 values = vec4( getValue(batch, xR, xC, d), initializationValue, initializationValue, initializationValue ); `+ce+` } else if (`+(ie===2)+`) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + `+s+`, d), initializationValue, initializationValue ); `+ce+` } else if (`+(ie===3)+`) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + `+s+`, d), getValue(batch, xR, xC + 2 * `+s+`, d), initializationValue ); `+ce+` } } setOutput(`+oe+`); } `}},cu=function(n,r,e){if(this.variableNames=["x"],r==="avg"&&e)throw new Error("Cannot compute positions for average pool.");var t=n.filterWidth,o=n.strideDepth,a=n.strideHeight,i=n.strideWidth,s=n.dilationDepth,u=n.dilationHeight,f=n.dilationWidth,E=n.effectiveFilterDepth,I=n.effectiveFilterHeight,P=n.effectiveFilterWidth,G=n.padInfo.front,oe=n.padInfo.top,ue=n.padInfo.left;this.outputShape=n.outShape;var ie=r==="avg",ce="0.0";if(ie||(ce="-1.0 / 1e-20"),e)this.userCode=` const ivec3 strides = ivec3(`+o+", "+a+", "+i+`); const ivec3 pads = ivec3(`+G+", "+oe+", "+ue+`); 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 < `+E+`; wD += `+s+`) { int xD = xDCorner + wD; if (xD < 0 || xD >= `+n.inDepth+`) { continue; } for (int wR = 0; wR < `+I+`; wR += `+u+`) { int xR = xRCorner + wR; if (xR < 0 || xR >= `+n.inHeight+`) { continue; } for (int wC = 0; wC < `+P+`; wC += `+f+`) { int xC = xCCorner + wC; if (xC < 0 || xC >= `+n.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 >= currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = wD * `+I+" * "+P+` + wR * `+P+` + wC;; } } } } setOutput(float(minMaxPosition)); } `;else{var ye=r+"("+r+"("+r+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";r==="avg"&&(ye="avgValue / count");var we=4*Math.floor(t/4),Ee=t%4,Se=` if (`+ie+`) { avgValue += dot(values, ones); } else { minMaxValue = max(values, minMaxValue); } `;this.userCode=` const ivec3 strides = ivec3(`+o+", "+a+", "+i+`); const ivec3 pads = ivec3(`+G+", "+oe+", "+ue+`); const float initializationValue = `+ce+`; 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 >= `+n.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(`+ce+`); float avgValue = 0.0; count = 0.0; for (int wD = 0; wD < `+E+`; wD += `+s+`) { int xD = xDCorner + wD; if (xD < 0 || xD >= `+n.inDepth+`) { continue; } for (int wR = 0; wR < `+I+`; wR += `+u+`) { int xR = xRCorner + wR; if (xR < 0 || xR >= `+n.inHeight+`) { continue; } for (int wC = 0; wC < `+we+`; wC += 4) { int xC = xCCorner + wC * `+f+`; vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + `+f+`, ch), getValue(batch, xD, xR, xC + 2 * `+f+`, ch), getValue(batch, xD, xR, xC + 3 * `+f+`, ch) ); `+Se+` } int xC = xCCorner + `+we+`; if (`+(Ee===1)+`) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), initializationValue, initializationValue, initializationValue ); `+Se+` } else if (`+(Ee===2)+`) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + `+f+`, ch), initializationValue, initializationValue ); `+Se+` } else if (`+(Ee===3)+`) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + `+f+`, ch), getValue(batch, xD, xR, xC + 2 * `+f+`, ch), initializationValue ); `+Se+` } } setOutput(`+ye+`); } } `}},Ed=function(n,r){this.variableNames=["x"];var e=n.windowSize,t=n.batchSize,o=n.inSize,a=Math.ceil(o/e);this.outputShape=[t,a];var i="0.0",s="";r==="prod"?i="1.0":r==="min"?(i="1.0 / 1e-20",s="min"):r==="max"&&(i="-1.0 / 1e-20",s="max");var u=r+"("+r+"("+r+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";r==="sum"?u="sumValue":r==="prod"?u="prodValue":r==="all"?u="allValue":r==="any"&&(u="anyValue");var f=4*Math.floor(e/4),E=e%4,I=` if (`+(r==="sum")+`) { sumValue += dot(values, ones); } else if (`+(r==="prod")+`) { vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]); prodValue *= tmp[0] * tmp[1]; } else { minMaxValue = `+s+`(values, minMaxValue); } `,P="vec4";r==="all"?(i="1.0",I=` bool reducedAllValue = all(values); float floatedReducedAllValue = float(reducedAllValue); allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); `,P="bvec4"):r==="any"&&(i="0.0",I=` bool reducedAnyValue = any(values); float floatedReducedAnyValue = float(reducedAnyValue); anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); `,P="bvec4");var G="";o%e>0&&(G=` if (inIdx < 0 || inIdx >= `+o+`) { return initializationValue; } `),this.userCode=` const float initializationValue = `+i+`; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float getValue(int batch, int inIdx) { `+G+` return getX(batch, inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = outIdx * `+e+`; vec4 minMaxValue = vec4(`+i+`); float prodValue = 1.0; float sumValue = 0.0; float allValue = 1.0; float anyValue = 0.0; for (int i = 0; i < `+f+`; i += 4) { int inIdx = inOffset + i; `+P+" values = "+P+`( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); `+I+` } int inIdx = inOffset + `+f+`; if (`+(E===1)+`) { `+P+" values = "+P+`( getValue(batch, inIdx), initializationValue, initializationValue, initializationValue ); `+I+` } else if (`+(E===2)+`) { `+P+" values = "+P+`( getValue(batch, inIdx), getValue(batch, inIdx + 1), initializationValue, initializationValue ); `+I+` } else if (`+(E===3)+`) { `+P+" values = "+P+`( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), initializationValue ); `+I+` } setOutput(`+u+`); } `},_d=function(n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;for(var e="",t=0;t<4;t++){var o="thisRC = rc;";t%2==1&&(o+="thisRC.z += 1;"),t>1&&(o+="thisRC.y += 1;"),e+=` `+o+` `+(t>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[`+t+`] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); `+(t>0?"}":"")+` `}this.userCode=` ivec3 inputCoordsFromReshapedOutCoords(int index) { `+R(["r","c","d"],r)+` return ivec3(r, c, d); } `+b(n)+` void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.); ivec3 thisRC; int rows = `+n[1]+`; int cols = `+n[2]+`; `+e+` setOutput(result); } `},Cd=function(n,r,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=r.shape;var t=r.shape,o=t[1],a=t[2],i=n.shape,s=i[1],u=i[2],f=[e&&s>1?o-1:o,e&&u>1?a-1:a],E=[e&&s>1?s-1:s,e&&u>1?u-1:u],I=f[0]/E[0],P=f[1]/E[1],G=1/I,oe=1/P,ue=2*Math.ceil(G)+2,ie=2*Math.ceil(oe)+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(`+I+`); const float widthScale = float(`+P+`); const float invHeightScale = float(`+G+`); const float invWidthScale = float(`+oe+`); const int winHeight = int(`+ue+`); const int winWidth = int(`+ie+`); // 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 >= `+s+`) { 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 >= `+u+`) { continue; } float dxR = float(dyR) * heightScale; int topDxRIndex = int(floor(dxR)); int bottomDxRIndex = int(min(ceil(dxR), `+(o-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), `+(a-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); } `},Td=function(n,r,e,t){this.variableNames=["A"],this.outputShape=[];var o=n[0],a=n[1],i=n[2],s=n[3];this.outputShape=[o,r,e,s];var u=[t&&r>1?a-1:a,t&&e>1?i-1:i],f=[t&&r>1?r-1:r,t&&e>1?e-1:e];this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( `+u[0]/f[0]+`, `+u[1]/f[1]+`); const vec2 inputShapeRC = vec2(`+a+".0, "+i+`.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); } `},Sd=function(n,r,e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=n[0],a=n[1],i=n[2],s=n[3];this.outputShape=[o,r,e,s];var u=[t&&r>1?a-1:a,t&&e>1?i-1:i],f=[t&&r>1?r-1:r,t&&e>1?e-1:e];this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( `+u[0]/f[0]+`, `+u[1]/f[1]+`, `+u[1]/f[1]+`); const vec3 inputShapeRC = vec3(`+a+".0, "+i+`.0, `+i+`.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 < `+(s-1)+`; bool hasNextRow = coords.z < `+(e-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); } `},Ad=function(n,r,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=r.shape;var t=r.shape,o=t[1],a=t[2],i=n.shape,s=i[1],u=i[2],f=[e&&s>1?o-1:o,e&&u>1?a-1:a],E=[e&&s>1?s-1:s,e&&u>1?u-1:u],I=f[0]/E[0],P=f[1]/E[1],G=1/I,oe=1/P,ue=2*Math.ceil(G)+2,ie=2*Math.ceil(oe)+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(`+I+`); const float widthScale = float(`+P+`); const float invHeightScale = float(`+G+`); const float invWidthScale = float(`+oe+`); const int winHeight = int(`+ue+`); const int winWidth = int(`+ie+`); // 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 >= `+s+`) { 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 >= `+u+`) { continue; } float sourceFracRow = float(`+f[0]+`) * (float(dyR) / float(`+E[0]+`)); float sourceFracCol = float(`+f[1]+`) * (float(dyC) / float(`+E[1]+`)); int sourceNearestRow = int(min( float(int(`+o+`) - 1), `+e+` ? float(round(sourceFracRow)) : float(floor(sourceFracRow)))); int sourceNearestCol = int(min( float(int(`+a+`) - 1), `+e+` ? float(round(sourceFracCol)) : float(floor(sourceFracCol)))); if (r == sourceNearestRow && c == sourceNearestCol) { accumulator += getDy(b, dyR, dyC, d); } } } // End loop over dy setOutput(accumulator); } `},Od=function(n,r,e,t){this.variableNames=["A"],this.outputShape=[];var o=n[0],a=n[1],i=n[2],s=n[3];this.outputShape=[o,r,e,s];var u=[t&&r>1?a-1:a,t&&e>1?i-1:i],f=[t&&r>1?r-1:r,t&&e>1?e-1:e],E=t?"0.5":"0.0";this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( `+u[0]/f[0]+`, `+u[1]/f[1]+`); const vec2 inputShapeRC = vec2(`+a+".0, "+i+`.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 + `+E+`))); float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); setOutput(newValue); } `},Rd=function(n,r){this.variableNames=["x"];var e=n.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");if(this.outputShape=n,e!==1){var t=n.map(function(a,i){return function(s){return r.indexOf(s)!==-1&&n[s]!==1?n[s]+" - coords["+s+"] - 1":"coords["+s+"]"}(i)}).join(","),o=ze(e);this.userCode=` void main() { `+o+` coords = getOutputCoords(); setOutput(getX(`+t+`)); } `}else this.userCode=` void main() { int coord = getOutputCoords(); setOutput(getX(`+n[0]+` - coord - 1)); } `},Id=function(n,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var e=n.length;if(e>4)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");this.outputShape=n;var t=en("rc",e),o=t[e-1]+" + 1 < "+this.outputShape[e-1],a=t[e-2]+" + 1 < "+this.outputShape[e-2],i=ze(e);function s(u){var f=n.map(function(E,I){return function(P,G){return r.indexOf(P)!==-1&&n[P]!==1?n[P]+" - "+G[P]+" - 1":""+G[P]}(I,u)});return"getChannel(getX("+f.join(",")+"), vec2("+f.slice(-2).join(",")+"))"}this.userCode=e===1?` void main(){ int rc = getOutputCoords(); vec4 result = vec4(0.); result.r = getChannel(getX(`+n[0]+` - rc - 1), `+n[0]+` - rc - 1); if(`+o+`){ result.g = getChannel(getX(`+n[0]+` - (rc + 1) - 1), `+n[0]+` - (rc + 1) - 1); } setOutput(result); } `:` void main() { `+i+` rc = getOutputCoords(); vec4 result = vec4(0.); result.r = `+function(u){return s(u)}(t.slice())+`; if(`+o+`){ result.g = `+function(u){return u[e-1]="("+u[e-1]+" + 1)",s(u)}(t.slice())+`; } if(`+a+`) { result.b = `+function(u){return u[e-2]="("+u[e-2]+" + 1)",s(u)}(t.slice())+`; if(`+o+`) { result.a = `+function(u){return u[e-1]="("+u[e-1]+" + 1)",u[e-2]="("+u[e-2]+" + 1)",s(u)}(t.slice())+`; } } setOutput(result); } `},Ac=function(n,r,e,t,o,a,i){i===void 0&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=ze(o.length),u=ze(a.length),f="";e===1?f="i":e===2&&(f="i, j");var E="getIndices("+f+")",I="";t===1?I="i":t===2&&(I="i, coords[1]");var P="getUpdates("+I+")",G=r>1?"strides[j]":"strides";this.userCode=` `+s+" strides = "+s+"("+o+`); void main() { `+u+` coords = getOutputCoords(); float sum = 0.0; bool found = false; for (int i = 0; i < `+n+`; i++) { int flattenedIndex = 0; for (int j = 0; j < `+r+`; j++) { int index = round(`+E+`); flattenedIndex += index * `+G+`; } if (flattenedIndex == coords[0]) { sum += `+P+`; found = true; } } setOutput(mix(getDefaultValue(), sum, float(found))); } `},Dd=function(n,r){this.variableNames=["x","segmentIds"];var e=n.windowSize,t=n.batchSize,o=n.inSize,a=n.numSegments,i=a*Math.ceil(o/e);this.outputShape=[t,i];var s=4*Math.floor(e/4),u=e%4,f=` sumValue += dot(values, segFilter); `,E="";o%e>0&&(E=` if (inIdx < 0 || inIdx >= `+o+`) { return initializationValue; } `);var I="";o%e>0&&(I=` if (inIdx < 0 || inIdx >= `+o+`) { return -1.0; } `),this.userCode=` const float initializationValue = 0.0; float getValue(int batch, int inIdx) { `+E+` return getX(batch, inIdx); } float getSegmentIdAtIndex(int inIdx) { `+I+` return getSegmentIds(inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = int(floor(float(outIdx) / float( `+a+")) * float("+e+`)); int currentSeg = int(mod(float(outIdx), float(`+a+`))); float sumValue = 0.0; for (int i = 0; i < `+s+`; 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 ); `+f+` } int inIdx = inOffset + `+s+`; if (`+(u===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 ); `+f+` } else if (`+(u===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 ); `+f+` } else if (`+(u===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 ); `+f+` } setOutput(sumValue); } `},Nd=function(n,r,e){var t,o;if(this.variableNames=["c","a","b"],this.outputShape=r,e>4)throw Error("Where for rank "+e+" is not yet supported");if(e===1)o="resRC",t="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u= 1.0) { setOutput(getA(`+o+`)); } else { setOutput(getB(`+o+`)); } } `},kd=function(){function n(r){this.variableNames=["source"],this.outputShape=r,this.rank=r.length;var e,t=ze(this.rank),o="uniform int start["+this.rank+"];",a=function(i){if(i===1)return"sourceLoc";if(i<=6)return lu.slice(0,i).map(function(s){return"sourceLoc."+s}).join(",");throw Error("Slicing for rank "+i+" is not yet supported")}(this.rank);e=` `+t+` sourceLoc; `+t+` coords = getOutputCoords(); `+r.map(function(i,s){return"sourceLoc."+lu[s]+" = start["+s+"] + coords."+lu[s]+";"}).join(` `)+` `,this.userCode=` `+o+` void main() { `+e+` setOutput(getSource(`+a+`)); } `}return n.prototype.getCustomSetupFunc=function(r){var e=this;if(r.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+r.length+")");return function(t,o){e.startLoc==null&&(e.startLoc=t.getUniformLocationNoThrow(o,"start"),e.startLoc==null)||t.gl.uniform1iv(e.startLoc,r)}},n}(),lu=["x","y","z","w","u","v"],Md=function(){function n(r){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.rank=r.length;var e=ze(this.rank),t=en("coords",this.rank),o=en("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":"vec2("+o.slice(-2).join()+")",i="getChannel(getSource("+o.join()+"), "+a+")",s=` result.x = `+i+`; if (++`+t[this.rank-1]+" < "+r[this.rank-1]+`) { ++`+o[this.rank-1]+`; result.y = `+i+`; --`+o[this.rank-1]+`; } `,u=this.rank===1?"":` --`+t[this.rank-1]+`; if (++`+t[this.rank-2]+" < "+r[this.rank-2]+`) { ++`+o[this.rank-2]+`; result.z = `+i+`; if (++`+t[this.rank-1]+" < "+r[this.rank-1]+`) { ++`+o[this.rank-1]+`; result.w = `+i+`; } } `,f=this.rank<=4?`sourceLoc = coords + `+e+"("+r.map(function(E,I){return"start["+I+"]"}).join()+");":r.map(function(E,I){return o[I]+" = "+t[I]+" + start["+I+"];"}).join(` `);this.userCode=` uniform int start[`+this.rank+`]; void main() { `+e+` coords = getOutputCoords(); `+e+` sourceLoc; `+f+` vec4 result = vec4(0.); `+s+` `+u+` setOutput(result); } `}return n.prototype.getCustomSetupFunc=function(r){var e=this;if(r.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+r.length+")");return function(t,o){e.startLoc==null&&(e.startLoc=t.getUniformLocationNoThrow(o,"start"),e.startLoc==null)||t.gl.uniform1iv(e.startLoc,r)}},n}(),Pd=function(n,r,e){this.variableNames=["x"],this.outputShape=e;var t=e.length,o=ze(e.length),a=ze(e.length),i="";if(t===1)i="coords * strides + begin";else{var s=0;i=e.map(function(u,f){return s++,e.length===1?"coords * strides["+f+"] + begin["+f+"]":"coords["+(s-1)+"] * strides["+f+"] + begin["+f+"]"}).join(",")}this.userCode=` `+o+" begin = "+o+"("+n+`); `+o+" strides = "+o+"("+r+`); void main() { `+a+` coords = getOutputCoords(); setOutput(getX(`+i+`)); } `},Ld=function(){function n(r){this.gpgpu=r,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return n.prototype.acquireTexture=function(r,e,t){var o,a=Oc(e,t),i=Rc(r,a,t);if(i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]),this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var s=this.freeTextures[i].shift();return this.usedTextures[i].push(s),s}return this.numUsedTextures++,this.log(),a===Hr.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(r[0],r[1]):a===Hr.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(r[0],r[1]):a===Hr.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(r[0],r[1]):a===Hr.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(r[0],r[1]):a===Hr.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(r[0],r[1])),this.usedTextures[i].push(o),o},n.prototype.releaseTexture=function(r,e,t,o){if(this.freeTextures!=null){var a=Rc(e,Oc(t,o),o);a in this.freeTextures||(this.freeTextures[a]=[]),this.freeTextures[a].push(r),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[a],s=i.indexOf(r);if(s<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(s,1),this.log()}},n.prototype.log=function(){if(this.logEnabled){var r=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+r+")")}},n.prototype.getNumUsedTextures=function(){return this.numUsedTextures},n.prototype.getNumFreeTextures=function(){return this.numFreeTextures},n.prototype.dispose=function(){var r=this;if(this.freeTextures!=null){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(t){r.gpgpu.deleteMatrixTexture(t)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(o){r.gpgpu.deleteMatrixTexture(o)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},n}();function Oc(n,r){if(n===Wr.UPLOAD)return Hr.PACKED_2X2_FLOAT32;if(n===Wr.RENDER||n==null)return function(e){return c().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Hr.PACKED_2X2_FLOAT32:Hr.UNPACKED_FLOAT32:e?Hr.PACKED_2X2_FLOAT16:Hr.UNPACKED_FLOAT16}(r);if(n===Wr.DOWNLOAD||n===Wr.PIXELS)return Hr.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+n)}function Rc(n,r,e){return n[0]+"_"+n[1]+"_"+r+"_"+e}var jd=function(n,r){this.variableNames=["A"];for(var e=new Array(n.length),t=0;t5)throw Error("Tile for rank "+s+" is not yet supported");if(s===1)return"imod(resRC, "+i[0]+")";for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],f=[],E=0;E6)throw Error("Transpose for rank "+s+" is not yet supported");for(var u=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],f=new Array(s),E=0;E6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=ze(this.rank),a=au("rc",this.rank),i=new Array(this.rank);for(t=0;t= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); `,Mc="return -x;",Pc="return ceil(x);",Lc="return floor(x);",jc="return exp(x);",Fc="return exp(x) - 1.0;",Hd=Dn+` return sin(x); `,zd=Dn+` return cos(x); `,Gd=Dn+` if (abs(x) > 1.) { return NAN; } return asin(x); `,Vd=Dn+` if (abs(x) > 1.) { return NAN; } return acos(x); `,Xd=Dn+` return atan(x); `,Kd=Dn+"return log(x + sqrt(x * x + 1.0));",Yd=Dn+` if (x < 1.0) return NAN; return log(x + sqrt(x * x - 1.0));`,$d=Dn+` if ((x < -1.0) || (x > 1.0)) return NAN; return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,is="return x;",Jd="return x;",Bc=` 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; `,Uc=` 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; `,Wc=` 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; `,xi=function(n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.userCode=` vec4 unaryOperation(vec4 x) { `+r+` } void main() { vec4 x = getAAtOutCoords(); vec4 y = unaryOperation(x); setOutput(y); } `},qd=function(n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=n;var r=n.length,e=en("rc",r),t=ze(r),o=function(s,u){if(s===1)return"rc";for(var f="",E=0;E0?[4,Promise.all(i)]:[3,2];case 1:return f=E.sent(),u.kernelMs=q(f),u.getExtraProfileInfo=function(){return f.map(function(I,P){return{name:s[P],ms:I}}).map(function(I){return I.name+": "+I.ms}).join(", ")},[3,3];case 2:u.kernelMs={error:"WebGL query timers are not supported in this environment."},E.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}})})},r.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},r.prototype.startTimer=function(){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Re(),endMs:null}},r.prototype.endTimer=function(e){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Re(),e)},r.prototype.getQueryTime=function(e){return x(this,void 0,void 0,function(){var t;return v(this,function(o){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]})})},r.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e)){if(this.pendingRead.has(e))return this.pendingDisposal.add(e),void this.pendingDeletes++;if(this.texData.has(e)){this.releaseGPUData(e);var t=this.texData.get(e).complexTensors;t!=null&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}}},r.prototype.releaseGPUData=function(e){var t=this.texData.get(e),o=t.texture,a=t.dtype,i=t.texShape,s=t.usage,u=t.isPacked,f=t.slice,E=f&&f.origDataId||e,I=this.dataRefCount.get(E);I>1?this.dataRefCount.set(E,I-1):(this.dataRefCount.delete(E),o!=null&&(this.numBytesInGPU-=this.computeBytes(i,a),this.textureManager.releaseTexture(o,i,s,u)));var P=this.texData.get(e);P.texture=null,P.texShape=null,P.isPacked=!1,P.slice=null},r.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},r.prototype.getDataInfo=function(e){return this.texData.get(e)},r.prototype.getCPUBackend=function(){return c().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=Ve.findBackend("cpu")),this.cpuBackend):null},r.prototype.shouldExecuteOnCPU=function(e,t){var o=this;return t===void 0&&(t=128),this.getCPUBackend()!=null&&e.every(function(a){return o.texData.get(a.dataId).texture==null&&a.sizec().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var i=Math.floor(e.length/2),s=this.concat(e.slice(0,i),t),u=this.concat(e.slice(i),t);return this.concat([s,u],t)}if(c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var f=new ur(e.map(function(G){return G.shape}),t);return this.compileAndRun(f,e)}var E=qn(e.map(function(G){return G.shape}),t),I=e.map(function(G){return G.as2D(-1,le(G.shape.slice(t)))}),P=new tn(I.map(function(G){return G.shape}));return this.compileAndRun(P,I).reshape(E)},r.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Mc,e.dtype);var t=new zt(e.shape,Mc);return this.compileAndRun(t,[e])},r.prototype.batchMatMul=function(e,t,o,a){var i=o?e.shape[2]:e.shape[1],s=a?t.shape[1]:t.shape[2],u=o?e.shape[1]:e.shape[2],f=e.shape[0];if((i===1||s===1)&&u>1e3){o&&(e=e.transpose([0,2,1])),a&&(t=t.transpose([0,2,1]));var E=s===1?e:e.as3D(f,u,1),I=s===1?2:1,P=s===1?t.as3D(f,1,u):t;return this.multiply(E,P).sum(I,!0)}var G=nr(e.dtype,t.dtype),oe=new su(e.shape,[f,i,s],o,a);return this.compileAndRun(oe,[e,t],G)},r.prototype.fusedBatchMatMul=function(e){var t=e.a,o=e.b,a=e.transposeA,i=e.transposeB,s=e.bias,u=e.activation,f=e.preluActivationWeights,E=a?t.shape[2]:t.shape[1],I=i?o.shape[1]:o.shape[2],P=t.shape[0],G=nr(t.dtype,o.dtype),oe=s!=null,ue=f!=null,ie=u?us(u,!0):null,ce=new su(t.shape,[P,E,I],a,i,oe,ie,ue),ye=[t,o];return s&&ye.push(s),f&&ye.push(f),this.compileAndRun(ce,ye,G)},r.prototype.multiply=function(e,t){if(e.dtype==="complex64"){var o=this.texData.get(e.dataId),a=this.texData.get(t.dataId),i=new Wt(mt,e.shape,t.shape),s=new Wt(_t,e.shape,t.shape),u=[this.makeComplexComponentTensorInfo(e,o.complexTensors.real),this.makeComplexComponentTensorInfo(e,o.complexTensors.imag),this.makeComplexComponentTensorInfo(t,a.complexTensors.real),this.makeComplexComponentTensorInfo(t,a.complexTensors.imag)],f=this.compileAndRun(i,u),E=this.compileAndRun(s,u),I=this.complex(f,E);return f.dispose(),E.dispose(),I}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,or,e.dtype);var P=new Ut(or,e.shape,t.shape);return this.compileAndRun(P,[e,t],e.dtype)},r.prototype.batchNormalization=function(e,t,o,a,i,s){var u=[e,t,o],f=null;s!=null&&(f=s.shape,u.push(s));var E=null;if(i!=null&&(E=i.shape,u.push(i)),c().getBool("WEBGL_PACK_NORMALIZATION")){var I=new At(e.shape,t.shape,o.shape,f,E,a);return this.compileAndRun(I,u)}var P=new Dt(e.shape,t.shape,o.shape,f,E,a);return this.compileAndRun(P,u)},r.prototype.localResponseNormalization4D=function(e,t,o,a,i){var s=c().getBool("WEBGL_PACK_NORMALIZATION")?new pd(e.shape,t,o,a,i):new fd(e.shape,t,o,a,i);return this.compileAndRun(s,[e])},r.prototype.LRNGrad=function(e,t,o,a,i,s,u){var f=new hd(t.shape,a,i,s,u);return this.compileAndRun(f,[t,o,e])},r.prototype.tile=function(e,t){if(e.dtype==="string"){var o=this.readSync(e.dataId).map(function(i){return rt(i)});return os(jt(e.shape,e.dtype,o),t)}var a=new jd(e.shape,t);return this.compileAndRun(a,[e])},r.prototype.pad=function(e,t,o){var a=c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new wd(e.shape,t,o):new xd(e.shape,t,o);return this.compileAndRun(a,[e])},r.prototype.transpose=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,t);var o=c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Bd(e.shape,t):new Fd(e.shape,t);return this.compileAndRun(o,[e])},r.prototype.gather=function(e,t,o){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.gather(e,t,o);var a=new br(e.shape,t.size,o);return this.compileAndRun(a,[e,t])},r.prototype.batchToSpaceND=function(e,t,o){w(e.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var a=t.reduce(function(I,P){return I*P}),i=Wo(e.shape,t,a),s=qt(i.length,t.length),u=wa(e.shape,t,a),f=Gs(o,t.length),E=Vs(u,o,t.length);return e.reshape(i).transpose(s).reshape(u).slice(f,E)},r.prototype.spaceToBatchND=function(e,t,o){w(e.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var a=t.reduce(function(P,G){return P*G}),i=[[0,0]];i.push.apply(i,o);for(var s=1+t.length;sG||oe===P?ue=!0:oe=ge(P,oe+1);return oe}(u,i),E=new Dd({windowSize:f,inSize:u,batchSize:s,numSegments:i},t),I=this.compileAndRun(E,[e,o],a);return I.shape[1]===i?I:(o=fa(0,i).tile([u/f]),this.segOpCompute(I,t,o,a,i))},r.prototype.argMinMaxReduce=function(e,t,o){var a=[t];if(on("arg"+o.charAt(0).toUpperCase()+o.slice(1),a,e.rank),!c().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var i=Gr(e.shape,a),s=i[0],u=le(i[1]),f=e.as2D(-1,u);return this.argReduce(f,o).reshape(s)}return this.argReducePacked(e,o)},r.prototype.argMin=function(e,t){return this.argMinMaxReduce(e,t,"min")},r.prototype.argMax=function(e,t){return this.argMinMaxReduce(e,t,"max")},r.prototype.cumsum=function(e,t,o,a){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var i=new Zt(e.shape,o,a);return this.compileAndRun(i,[e])},r.prototype.equal=function(e,t){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` return vec4(equal(a, b)); `,"bool");var o=new Ut("return float(a == b);",e.shape,t.shape);return this.compileAndRun(o,[e,t],"bool")},r.prototype.notEqual=function(e,t){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` return vec4(notEqual(a, b)); `,"bool");var o=new Ut("return float(a != b);",e.shape,t.shape);return this.compileAndRun(o,[e,t],"bool")},r.prototype.less=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.less(e,t);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` return vec4(lessThan(a, b)); `,"bool");var o=new Ut("return float(a < b);",e.shape,t.shape);return this.compileAndRun(o,[e,t],"bool")},r.prototype.lessEqual=function(e,t){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` return vec4(lessThanEqual(a, b)); `,"bool");var o=new Ut("return float(a <= b);",e.shape,t.shape);return this.compileAndRun(o,[e,t],"bool")},r.prototype.greater=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.greater(e,t);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` return vec4(greaterThan(a, b)); `,"bool");var o=new Ut("return float(a > b);",e.shape,t.shape);return this.compileAndRun(o,[e,t],"bool")},r.prototype.greaterEqual=function(e,t){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` return vec4(greaterThanEqual(a, b)); `,"bool");var o=new Ut("return float(a >= b);",e.shape,t.shape);return this.compileAndRun(o,[e,t],"bool")},r.prototype.logicalNot=function(e){var t=new zt(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e])},r.prototype.logicalAnd=function(e,t){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` return vec4( vec4(greaterThanEqual(a, vec4(1.0))) * vec4(greaterThanEqual(b, vec4(1.0)))); `,"bool");var o=new Ut("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape);return this.compileAndRun(o,[e,t],"bool")},r.prototype.logicalOr=function(e,t){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` return min( vec4(greaterThanEqual(a, vec4(1.0))) + vec4(greaterThanEqual(b, vec4(1.0))), vec4(1.0)); `,"bool");var o=new Ut("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape);return this.compileAndRun(o,[e,t],"bool")},r.prototype.select=function(e,t,o){var a=new Nd(e.rank,t.shape,t.rank);return this.compileAndRun(a,[e,t,o],nr(t.dtype,o.dtype))},r.prototype.where=function(e){da("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=e.dataSync();return fi(e.shape,t)},r.prototype.topk=function(e,t,o){return as(e.dataSync(),e.shape,e.dtype,t)},r.prototype.min=function(e,t){on("min",t,e.rank);var o=Gr(e.shape,t),a=o[0],i=le(o[1]),s=e.as2D(-1,i);return this.reduce(s,"min",s.dtype).reshape(a)},r.prototype.minimum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.minimum(e,t);var o=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lr(` vec4 result = vec4(min(a, b)); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); 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; return result; `,e.shape,t.shape):new Ut(` if (isnan(a)) return a; if (isnan(b)) return b; return min(a, b); `,e.shape,t.shape);return this.compileAndRun(o,[e,t])},r.prototype.mod=function(e,t){var o=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lr(` vec4 result = mod(a, b); vec4 isNaN = vec4(equal(b, vec4(0.0))); 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; return result; `,e.shape,t.shape):new Ut(`if (b == 0.0) return NAN; return mod(a, b);`,e.shape,t.shape);return this.compileAndRun(o,[e,t])},r.prototype.max=function(e,t){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.max(e,t);on("max",t,e.rank);var o=Gr(e.shape,t),a=o[0],i=le(o[1]),s=e.as2D(-1,i);return this.reduce(s,"max",s.dtype).reshape(a)},r.prototype.maximum=function(e,t){if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.maximum(e,t);var o=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lr(` vec4 result = vec4(max(a, b)); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); 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; return result; `,e.shape,t.shape):new Ut(` if (isnan(a)) return a; if (isnan(b)) return b; return max(a, b); `,e.shape,t.shape);return this.compileAndRun(o,[e,t])},r.prototype.all=function(e,t){on("all",t,e.rank);var o=Gr(e.shape,t),a=o[0],i=le(o[1]),s=e.as2D(-1,i);return this.reduce(s,"all",s.dtype).reshape(a)},r.prototype.any=function(e,t){on("any",t,e.rank);var o=Gr(e.shape,t),a=o[0],i=le(o[1]),s=e.as2D(-1,i);return this.reduce(s,"any",s.dtype).reshape(a)},r.prototype.realDivide=function(e,t){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` // 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; `,"float32",!0);var o=new Ut(` if (a == b) { return 1.0; }; return a / b;`,e.shape,t.shape);return this.compileAndRun(o,[e,t],"float32")},r.prototype.floorDiv=function(e,t){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,` 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); `,"int32");var o=new Ut(` 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; } `,e.shape,t.shape);return this.compileAndRun(o,[e,t],"int32")},r.prototype.add=function(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,sr);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.add(e,t);var o=nr(e.dtype,t.dtype);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,sr,o);var a=new Ut(sr,e.shape,t.shape);return this.compileAndRun(a,[e,t],o)},r.prototype.packedUnaryOp=function(e,t,o){var a=new xi(e.shape,t);return this.compileAndRun(a,[e],o)},r.prototype.packedBinaryOp=function(e,t,o,a,i){i===void 0&&(i=!1);var s=new lr(o,e.shape,t.shape,i);return this.compileAndRun(s,[e,t],a)},r.prototype.complexSeparableBinaryOp=function(e,t,o){var a=this,i=this.texData.get(e.dataId),s=this.texData.get(t.dataId),u=[[i.complexTensors.real,s.complexTensors.real],[i.complexTensors.imag,s.complexTensors.imag]].map(function(P){var G=P[0],oe=P[1],ue=a.makeComplexComponentTensorInfo(e,G),ie=a.makeComplexComponentTensorInfo(t,oe),ce=new Ut(o,e.shape,t.shape);return a.compileAndRun(ce,[ue,ie],nr(G.dtype,oe.dtype))}),f=u[0],E=u[1],I=this.complex(f,E);return f.dispose(),E.dispose(),I},r.prototype.makeComplexComponentTensorInfo=function(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}},r.prototype.addN=function(e){if(e.length===1)return e[0];if(e.length>c().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var t=Math.floor(e.length/2),o=this.addN(e.slice(0,t)),a=this.addN(e.slice(t));return this.addN([o,a])}var i=e.map(function(f){return f.dtype}).reduce(function(f,E){return nr(f,E)}),s=e.map(function(f){return f.shape}),u=c().getBool("WEBGL_PACK")?new dc(e[0].shape,s):new ou(e[0].shape,s);return this.compileAndRun(u,e,i)},r.prototype.subtract=function(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,vr);if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.subtract(e,t);var o=nr(e.dtype,t.dtype);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,vr,e.dtype);var a=new Ut(vr,e.shape,t.shape);return this.compileAndRun(a,[e,t],o)},r.prototype.pow=function(e,t){var o=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lr(` // 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)); 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; return result; `,e.shape,t.shape):new Ut(` 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); `,e.shape,t.shape),a=nr(e.dtype,t.dtype);return this.compileAndRun(o,[e,t],a)},r.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Pc,e.dtype);var t=new zt(e.shape,Pc);return this.compileAndRun(t,[e])},r.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Lc,e.dtype);var t=new zt(e.shape,Lc);return this.compileAndRun(t,[e])},r.prototype.sign=function(e){var t=new zt(e.shape,` if (isnan(x)) { return 0.0; } return sign(x); `);return this.compileAndRun(t,[e])},r.prototype.isNaN=function(e){var t=new zt(e.shape,"return float(isnan(x));");return this.compileAndRun(t,[e],"bool")},r.prototype.isInf=function(e){var t=new zt(e.shape,"return float(isinf(x));");return this.compileAndRun(t,[e],"bool")},r.prototype.isFinite=function(e){var t=new zt(e.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(t,[e],"bool")},r.prototype.round=function(e){var t=new zt(e.shape,` // 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; } } `);return this.compileAndRun(t,[e])},r.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,jc,e.dtype);var t=new zt(e.shape,jc);return this.compileAndRun(t,[e])},r.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Fc,e.dtype);var t=new zt(e.shape,Fc);return this.compileAndRun(t,[e])},r.prototype.softmax=function(e,t){var o=de([t],e.shape),a=this.max(e,o),i=Vr(a.shape,o),s=this.subtract(e,a.reshape(i)),u=this.exp(s),f=this.sum(u,o).reshape(i);return this.realDivide(u,f)},r.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,` 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; `,e.dtype);var t=new zt(e.shape,`if (x < 0.0) return NAN; return log(x);`);return this.compileAndRun(t,[e])},r.prototype.log1p=function(e){var t=new zt(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e])},r.prototype.sqrt=function(e){var t=new zt(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e])},r.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.rsqrt(e);var t=new zt(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e])},r.prototype.reciprocal=function(e){var t=new zt(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e])},r.prototype.relu=function(e){var t;return t=c().getBool("WEBGL_PACK")?new xi(e.shape,Bc):new zt(e.shape,Dc),this.compileAndRun(t,[e])},r.prototype.relu6=function(e){var t;return t=c().getBool("WEBGL_PACK")?new xi(e.shape,Uc):new zt(e.shape,Nc),this.compileAndRun(t,[e])},r.prototype.prelu=function(e,t){var o=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lr(kr,e.shape,t.shape):new Ut(Gt,e.shape,t.shape);return this.compileAndRun(o,[e,t])},r.prototype.elu=function(e){if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Wc,e.dtype);var t=new zt(e.shape,kc);return this.compileAndRun(t,[e])},r.prototype.eluDer=function(e,t){var o=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lr(` vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); `,e.shape,t.shape):new Ut("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(o,[e,t])},r.prototype.selu=function(e){var t=new zt(e.shape,Wd);return this.compileAndRun(t,[e])},r.prototype.int=function(e){var t=new zt(e.shape,"return float(int(x));");return this.compileAndRun(t,[e],"int32")},r.prototype.clip=function(e,t,o){var a,i=(a=c().getBool("WEBGL_PACK_CLIP")?new Yr(e.shape):new Xr(e.shape)).getCustomSetupFunc(t,o);return this.compileAndRun(a,[e],null,i)},r.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ic,e.dtype);var t=new zt(e.shape,Ic);return this.compileAndRun(t,[e])},r.prototype.complexAbs=function(e){var t=this.texData.get(e.dataId),o=new Rt(e.shape),a=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(o,a)},r.prototype.sigmoid=function(e){var t=new zt(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e])},r.prototype.softplus=function(e){var t=new zt(e.shape,` 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; `);return this.compileAndRun(t,[e])},r.prototype.sin=function(e){var t=new zt(e.shape,Hd);return this.compileAndRun(t,[e])},r.prototype.cos=function(e){var t=new zt(e.shape,zd);return this.compileAndRun(t,[e])},r.prototype.tan=function(e){var t=new zt(e.shape,"return tan(x);");return this.compileAndRun(t,[e])},r.prototype.asin=function(e){var t=new zt(e.shape,Gd);return this.compileAndRun(t,[e])},r.prototype.acos=function(e){var t=new zt(e.shape,Vd);return this.compileAndRun(t,[e])},r.prototype.atan=function(e){var t=new zt(e.shape,Xd);return this.compileAndRun(t,[e])},r.prototype.atan2=function(e,t){var o=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lr(` vec4 result = atan(a, b); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); 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; return result; `,e.shape,t.shape):new Ut(` if (isnan(a)) return a; if (isnan(b)) return b; return atan(a, b); `,e.shape,t.shape);return this.compileAndRun(o,[e,t])},r.prototype.sinh=function(e){var t=new zt(e.shape,` float e2x = exp(x); return (e2x - 1.0 / e2x) / 2.0; `);return this.compileAndRun(t,[e])},r.prototype.cosh=function(e){var t=new zt(e.shape,` float e2x = exp(-x); return (e2x + 1.0 / e2x) / 2.0; `);return this.compileAndRun(t,[e])},r.prototype.tanh=function(e){var t=new zt(e.shape,` float e2x = exp(-2.0 * abs(x)); return sign(x) * (1.0 - e2x) / (1.0 + e2x); `);return this.compileAndRun(t,[e])},r.prototype.asinh=function(e){var t=new zt(e.shape,Kd);return this.compileAndRun(t,[e])},r.prototype.acosh=function(e){var t=new zt(e.shape,Yd);return this.compileAndRun(t,[e])},r.prototype.atanh=function(e){var t=new zt(e.shape,$d);return this.compileAndRun(t,[e])},r.prototype.erf=function(e){var t=new zt(e.shape,` // Error function is calculated approximately with elementary function. // See "Handbook of Mathematical Functions with Formulas, // Graphs, and Mathematical Tables", Abramowitz and Stegun. float p = 0.3275911; float a1 = 0.254829592; float a2 = -0.284496736; float a3 = 1.421413741; float a4 = -1.453152027; float a5 = 1.061405429; 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)); `);return this.compileAndRun(t,[e])},r.prototype.step=function(e,t){var o=new zt(e.shape,function(a){return a===void 0&&(a=0),Dn+` return x > 0.0 ? 1.0 : float(`+a+`); `}(t));return this.compileAndRun(o,[e])},r.prototype.conv2dByMatMul=function(e,t,o,a,i,s){var u=e.shape,f=this.texData.get(e.dataId),E=o.inChannels,I=u[0]*u[1]*u[2],P=o.outChannels,G=o.dataFormat==="channelsLast",oe=(I===1||P===1)&&E>1e3,ue=u[2]%2!=0&&!!f.isPacked;if(oe||!c().getBool("WEBGL_LAZILY_UNPACK")||!c().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!ue){var ie=G?u[0]*u[1]*u[2]:u[0]*u[2]*u[3],ce=this.reshape(e,[1,ie,o.inChannels]),ye=this.reshape(t,[1,o.inChannels,o.outChannels]);return this.reshape(this.fusedBatchMatMul({a:ce,b:ye,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s}),o.outShape)}var we=G?u[0]*u[1]*(u[2]+1):u[0]*u[2]*(u[3]+1),Ee={dataId:e.dataId,shape:[1,we,o.inChannels],dtype:e.dtype},Se=f.shape;f.shape=f.shape.slice(),f.shape[f.shape.length-2]++,w(go(f.shape,Ee.shape),function(){return"packed reshape "+f.shape+" to "+Ee.shape+" isn't free"});var Me=this.reshape(t,[1,o.inChannels,o.outChannels]),He=this.fusedBatchMatMul({a:Ee,b:Me,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s}),Fe=this.texData.get(He.dataId);return w(Fe.isPacked,function(){return"batchMatMul result is expected to be packed"}),f.shape=Se,Fe.shape=o.outShape,Ve.makeTensorFromDataId(He.dataId,o.outShape,He.dtype)},r.prototype.conv2dWithIm2Row=function(e,t,o,a,i,s){var u=o.filterWidth,f=o.filterHeight,E=o.inChannels,I=o.outWidth,P=o.outHeight,G=o.dataFormat==="channelsLast",oe=u*f*E,ue=P*I,ie=[oe,ue],ce=e.squeeze([0]),ye=t.reshape([1,oe,-1]),we=new dd(ie,ce.shape,o),Ee=this.compileAndRun(we,[ce]).reshape([1,ie[0],ie[1]]),Se=a!=null,Me=s!=null,He=i?us(i,!0):null,Fe=new su(Ee.shape,[1,ue,o.outChannels],!0,!1,Se,He,Me),je=[Ee,ye];a&&je.push(a),Me&&je.push(s);var Ue=this.compileAndRun(Fe,je);return G?Ue.reshape([1,P,I,o.outChannels]):Ue.reshape([1,o.outChannels,P,I])},r.prototype.fusedConv2d=function(e){var t=e.input,o=e.filter,a=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights;if(a.filterHeight===1&&a.filterWidth===1&&a.dilationHeight===1&&a.dilationWidth===1&&a.strideHeight===1&&a.strideWidth===1&&(a.padInfo.type==="SAME"||a.padInfo.type==="VALID"))return this.conv2dByMatMul(t,o,a,i,s,u);if(c().getBool("WEBGL_CONV_IM2COL")&&t.shape[0]===1)return this.conv2dWithIm2Row(t,o,a,i,s,u);var f=i!=null,E=u!=null,I=s?us(s,!1):null,P=new kt(a,f,I,E),G=[t,o];return i&&G.push(i),u&&G.push(u),this.compileAndRun(P,G)},r.prototype.conv2d=function(e,t,o){if(o.filterHeight===1&&o.filterWidth===1&&o.dilationHeight===1&&o.dilationWidth===1&&o.strideHeight===1&&o.strideWidth===1&&(o.padInfo.type==="SAME"||o.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,o);if(c().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,o);var a=new kt(o);return this.compileAndRun(a,[e,t])},r.prototype.conv2dDerInput=function(e,t,o){var a=new Rn(o);return this.compileAndRun(a,[e,t])},r.prototype.conv2dDerFilter=function(e,t,o){var a=new Un(o);return this.compileAndRun(a,[e,t])},r.prototype.fusedDepthwiseConv2D=function(e){var t,o=e.input,a=e.filter,i=e.convInfo,s=e.bias,u=e.activation,f=e.preluActivationWeights,E=c().getBool("WEBGL_PACK_DEPTHWISECONV")&&i.strideWidth<=2&&i.outChannels/i.inChannels==1,I=u?us(u,E):null,P=[o,a],G=s!=null,oe=f!=null;return G&&P.push(s),oe&&P.push(f),E?(t=new dr(i,G,I,oe),this.compileAndRun(t,P)):(t=new yr(i,G,I,oe),this.compileAndRun(t,P))},r.prototype.depthwiseConv2D=function(e,t,o){var a;return c().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1?(a=new dr(o),this.compileAndRun(a,[e,t])):(a=new yr(o),this.compileAndRun(a,[e,t]))},r.prototype.depthwiseConv2DDerInput=function(e,t,o){var a=new gr(o);return this.compileAndRun(a,[e,t])},r.prototype.depthwiseConv2DDerFilter=function(e,t,o){var a=new hi(o);return this.compileAndRun(a,[e,t])},r.prototype.conv3d=function(e,t,o){var a=new Vt(o);return this.compileAndRun(a,[e,t])},r.prototype.conv3dDerInput=function(e,t,o){var a=new Wn(o);return this.compileAndRun(a,[e,t])},r.prototype.conv3dDerFilter=function(e,t,o){var a=new Ko(o);return this.compileAndRun(a,[e,t])},r.prototype.maxPool=function(e,t){var o=new uu(t,"max",!1);return this.compileAndRun(o,[e])},r.prototype.avgPool=function(e,t){var o=new uu(t,"avg",!1);return this.compileAndRun(o,[e],"float32")},r.prototype.maxPoolBackprop=function(e,t,o,a){var i=new uu(a,"max",!0),s=this.compileAndRun(i,[t]),u=new md(a),f=this.compileAndRun(u,[e,s],t.dtype);return s.dispose(),f},r.prototype.avgPoolBackprop=function(e,t,o){var a=new wt(o);return this.compileAndRun(a,[e],t.dtype)},r.prototype.cast=function(e,t){return ci(e,t,this)},r.prototype.unstack=function(e,t){for(var o=e.shape[t],a=new Array(e.rank-1),i=0,s=0;s1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+t});var a=e.shape[0],i=o==="NHWC"?e.shape[1]:e.shape[2],s=o==="NHWC"?e.shape[2]:e.shape[3],u=o==="NHWC"?e.shape[3]:e.shape[1],f=i*t,E=s*t,I=u/(t*t),P=new wr(o==="NHWC"?[a,f,E,I]:[a,I,f,E],t,o);return this.compileAndRun(P,[e])},r.prototype.split=function(e,t,o){return ns(e,t,o)},r.prototype.scatterND=function(e,t,o){var a=Ho(0,e,o),i=a.sliceRank,s=a.numUpdates,u=a.sliceSize,f=a.strides,E=a.outputSize,I=[E/u,u],P=e.reshape([s,i]),G=t.reshape([s,u]);if(E===0)return Aa(Ur([]),o);var oe=It(0),ue=new Ac(s,i,P.rank,G.rank,f,I);return this.compileAndRun(ue,[G,P,oe]).reshape(o)},r.prototype.sparseToDense=function(e,t,o,a){var i=Ho(0,e,o),s=i.sliceRank,u=i.numUpdates,f=i.strides,E=i.outputSize,I=new Ac(u,s,e.rank,t.rank,f,[E,1],!1);return this.compileAndRun(I,[t,e,a]).reshape(o)},r.prototype.fft=function(e){return this.fftImpl(e,!1)},r.prototype.ifft=function(e){return this.fftImpl(e,!0)},r.prototype.fftImpl=function(e,t){var o=this.texData.get(e.dataId),a=new Ia(pi,e.shape,t),i=new Ia(mi,e.shape,t),s=[this.makeComplexComponentTensorInfo(e,o.complexTensors.real),this.makeComplexComponentTensorInfo(e,o.complexTensors.imag)],u=this.compileAndRun(a,s),f=this.compileAndRun(i,s),E=this.complex(u,f).as2D(e.shape[0],e.shape[1]);return u.dispose(),f.dispose(),E},r.prototype.gatherND=function(e,t){var o=t.shape,a=o[o.length-1],i=Xi(e,t),s=i[0],u=i[1],f=i[2],E=i[3],I=t.reshape([u,a]),P=e.reshape([e.size/f,f]),G=new gi(a,E,[u,f]);return this.compileAndRun(G,[P,I]).reshape(s)},r.prototype.fill=function(e,t,o){if((o=o||ot(t))==="string"){var a=Ne(o,le(e));return a.fill(t),Ve.makeTensor(a,e,o,this)}var i=new vi(e,t),s=i.getCustomSetupFunc(t);return this.compileAndRun(i,[],o,s)},r.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},r.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)},r.prototype.linspace=function(e,t,o){return Zi(e,t,o)},r.prototype.makeTensorInfo=function(e,t){var o=this.write(null,e,t);return this.texData.get(o).usage=null,{dataId:o,shape:e,dtype:t}},r.prototype.makeOutput=function(e,t){var o=this.makeTensorInfo(e,t).dataId;return Ve.makeTensorFromDataId(o,e,t,this)},r.prototype.unpackTensor=function(e){var t=new qd(e.shape);return this.runWebGLProgram(t,[e],e.dtype)},r.prototype.packTensor=function(e){var t=new bd(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)},r.prototype.packedReshape=function(e,t){var o=[po(e.shape)].concat(mo(e.shape)),a={dtype:e.dtype,shape:o,dataId:e.dataId},i=[po(t)].concat(mo(t)),s=new _d(i,o),u=this.runWebGLProgram(s,[a],e.dtype,null,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}},r.prototype.decode=function(e){var t,o=this.texData.get(e),a=o.isPacked,i=o.shape,s=o.dtype,u=vo(i);return t=a?new Xt(u):new pr(u),{dtype:s,shape:i,dataId:this.runWebGLProgram(t,[{shape:u,dtype:s,dataId:e}],s,null,!0).dataId}},r.prototype.runWebGLProgram=function(e,t,o,a,i){var s=this;i===void 0&&(i=!1);var u=this.makeTensorInfo(e.outputShape,o),f=this.texData.get(u.dataId);if(e.packedOutput&&(f.isPacked=!0),e.outPackingScheme===Mo.DENSE){var E=Or(e.outputShape);f.texShape=E.map(function(we){return 2*we})}if(e.outTexUsage!=null&&(f.usage=e.outTexUsage),le(u.shape)===0)return f.values=xe(u.dtype,0),u;var I=[],P=t.map(function(we){if(we.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var Ee=s.texData.get(we.dataId);if(Ee.texture==null){if(!e.packedInputs&&le(we.shape)<=c().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:we.shape,texData:null,isUniform:!0,uniformValues:Ee.values};e.packedInputs&&(Ee.isPacked=!0,Ee.shape=we.shape)}else if(!!Ee.isPacked!=!!e.packedInputs)we=Ee.isPacked?s.unpackTensor(we):s.packTensor(we),I.push(we),Ee=s.texData.get(we.dataId);else if(Ee.isPacked&&!go(Ee.shape,we.shape)){var Se=we,Me=we.shape;we.shape=Ee.shape,we=s.packedReshape(we,Me),I.push(we),Ee=s.texData.get(we.dataId),Se.shape=Me}return s.uploadToGPU(we.dataId),{shape:we.shape,texData:Ee,isUniform:!1}});this.uploadToGPU(u.dataId);var G,oe={shape:u.shape,texData:f,isUniform:!1},ue=function(we,Ee,Se){var Me="";Ee.concat(Se).forEach(function(je){var Ue=je.texData!=null&&je.texData.slice!=null&&je.texData.slice.flatOffset>0,Ze=je.isUniform?"uniform":je.texData.texShape;Me+=je.shape+"_"+Ze+"_"+Ue});var He=we.userCode,Fe=we.constructor.name;return Fe+="_"+Me+"_"+He}(e,P,oe),ie=this.getAndSaveBinary(ue,function(){return function(we,Ee,Se,Me){var He=Ee.userCode,Fe=Se.map(function(ut,gt){var yt={logicalShape:ut.shape,texShape:ut.isUniform?null:ut.texData.texShape,isUniform:ut.isUniform,isPacked:!ut.isUniform&&ut.texData.isPacked,flatOffset:null};return ut.texData!=null&&ut.texData.slice!=null&&ut.texData.slice.flatOffset>0&&(yt.flatOffset=ut.texData.slice.flatOffset),{name:Ee.variableNames[gt],shapeInfo:yt}}),je=Fe.map(function(ut){return ut.shapeInfo}),Ue={logicalShape:Me.shape,texShape:Me.texData.texShape,isUniform:!1,isPacked:Me.texData.isPacked,flatOffset:null},Ze=N(Fe,Ue,He,Ee.packedInputs),Je=we.createProgram(Ze),dt=null,ct=we.getUniformLocation(Je,"NAN",!1);c().getNumber("WEBGL_VERSION")===1&&(dt=we.getUniformLocation(Je,"INFINITY",!1));for(var st={},pt=0;pt0)return 32}return 16})),this.floatPrecisionValue},r.prototype.epsilon=function(){return this.floatPrecision()===32?1e-7:1e-4},r.prototype.uploadToGPU=function(e){var t,o=this.texData.get(e),a=o.shape,i=o.dtype,s=o.values,u=o.texture,f=o.usage,E=o.isPacked;if(u==null){var I,P=this.activeTimers!=null;P&&(I=Re());var G=o.texShape;if(G==null&&(G=Ri(a,E),o.texShape=G),s!=null){var oe=vo(a),ue=void 0,ie=G[1],ce=G[0],ye=s instanceof Uint8Array;E?(ie=(t=$n(G[0],G[1]))[0],ce=t[1],ue=new Ra(oe,[ce,ie],ye)):ue=new Br(oe,[ce,ie],ye);var we=this.makeTensorInfo([ce,ie],i);this.texData.get(we.dataId).usage=ye?Wr.PIXELS:Wr.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(we.dataId),ie,ce,s);var Ee=this.runWebGLProgram(ue,[we],i,null,!0),Se=this.texData.get(Ee.dataId);o.texture=Se.texture,o.texShape=Se.texShape,o.isPacked=Se.isPacked,o.usage=Se.usage,this.disposeData(we.dataId),this.texData.delete(Ee.dataId),o.values=null,P&&(this.uploadWaitMs+=Re()-I)}else{var Me=this.acquireTexture(G,f,i,E);o.texture=Me}}},r.prototype.convertAndCacheOnCPU=function(e,t){var o=this.texData.get(e),a=o.dtype;return this.releaseGPUData(e),t!=null&&(o.values=function(i,s){if(s==="float32"||s==="complex64")return i;if(s==="int32"||s==="bool"){for(var u=s==="int32"?new Int32Array(i.length):new Uint8Array(i.length),f=0;f1024*this.numMBBeforeWarning*1024){var 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,a)},r.prototype.computeBytes=function(e,t){return e[0]*e[1]*nt(t)},r}(Ca);Ha()&&Ve.registerBackend("webgl",function(){return new Hc},2);var Zd=Ke({square_:function(n){var r=Oe(n,"x","square"),e=[r];return Ve.runKernelFunc(function(t,o){return o([r]),t.square(r)},{x:r},null,"Square",{},e,[])}}),wi="SquaredDifference",zc=Ke({squaredDifference_:function(n,r){var e,t=Oe(n,"a","squaredDifference"),o=Oe(r,"b","squaredDifference");e=cr(t,o),t=e[0],o=e[1],Ht(t.shape,o.shape);var a={a:t,b:o},i=[t,o];return Ve.runKernelFunc(function(s,u){var f=s.squaredDifference(t,o);return u([t,o]),f},a,function(s,u){var f=u[0],E=u[1],I=It(2);return{a:function(){return s.mul(f.sub(E).mul(I))},b:function(){return s.mul(E.sub(f).mul(I))}}},wi,{},i,[])}}),ef=Ke({abs_:function(n){var r=Oe(n,"x","abs");return r.dtype==="complex64"?Ve.runKernelFunc(function(e){return e.complexAbs(r)},{$x:r}):Ve.runKernelFunc(function(e,t){var o=e.abs(r);return t([r]),o},{x:r},function(e,t){var o=t[0];return{x:function(){return e.mul(o.toFloat().step(-1))}}},"Abs")}}),tf=Ke({acos_:function(n){var r=Oe(n,"x","acos");return Ve.runKernelFunc(function(e,t){var o=e.acos(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.divStrict(It(1).sub(o.toFloat().square()).sqrt()).neg()}}})}}),rf=Ke({acosh_:function(n){var r=Oe(n,"x","acosh");return Ve.runKernelFunc(function(e,t){var o=e.acosh(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.divStrict(o.toFloat().square().sub(1).sqrt())}}})}}),nf=Ke({asin_:function(n){var r=Oe(n,"x","asin");return Ve.runKernelFunc(function(e,t){var o=e.asin(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.divStrict(It(1).sub(o.toFloat().square()).sqrt())}}})}}),of=Ke({asinh_:function(n){var r=Oe(n,"x","asinh");return Ve.runKernelFunc(function(e,t){var o=e.asinh(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.divStrict(It(1).add(o.toFloat().square()).sqrt())}}})}}),af=Ke({atan_:function(n){var r=Oe(n,"x","atan");return Ve.runKernelFunc(function(e,t){var o=e.atan(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.div(o.toFloat().square().add(1))}}})}}),sf=Ke({atanh_:function(n){var r=Oe(n,"x","atanh");return Ve.runKernelFunc(function(e,t){var o=e.atanh(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.div(It(1).sub(o.toFloat().square()))}}})}}),uf=Ke({ceil_:function(n){var r=Oe(n,"x","ceil");return Ve.runKernelFunc(function(e){return e.ceil(r)},{$x:r},function(e){return{$x:function(){return Jt(e)}}})}}),Gc=Ke({clipByValue_:function(n,r,e){var t=Oe(n,"x","clipByValue");w(r<=e,function(){return"Error in clip: min ("+r+") must be less than or equal to max ("+e+")."});var o=[t],a={min:r,max:e};return Ve.runKernelFunc(function(i,s){var u=i.clip(t,r,e);return s([t]),u},{x:t},function(i,s){var u=s[0];return{x:function(){return i.where(u.greaterEqual(r).logicalAnd(u.lessEqual(e)),Jt(i))}}},"ClipByValue",a,o)}}),cf=Ke({cos_:function(n){var r=Oe(n,"x","cos"),e=[r];return Ve.runKernelFunc(function(t,o){var a=t.cos(r);return o([r]),a},{x:r},function(t,o){var a=o[0];return{x:function(){return a.toFloat().sin().neg().mul(t)}}},"Cos",{},e)}}),lf=Ke({cosh_:function(n){var r=Oe(n,"x","cosh");return Ve.runKernelFunc(function(e,t){var o=e.cosh(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return o.toFloat().sinh().mulStrict(e)}}})}}),df=Ke({erf_:function(n){var r=Oe(n,"x","erf");return w(r.dtype==="int32"||r.dtype==="float32",function(){return"Input dtype must be `int32` or `float32`."}),r.dtype==="int32"&&(r=r.toFloat()),Ve.runKernelFunc(function(e,t){var o=e.erf(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.mul(o.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),Vc=Ke({exp_:function(n){var r=Oe(n,"x","exp");return Ve.runKernelFunc(function(e,t){var o=e.exp(r);return t([o]),o},{x:r},function(e,t){return{x:function(){return e.mulStrict(t[0])}}},"Exp",{},[],[!0])}}),ff=Ke({expm1_:function(n){var r=Oe(n,"x","expm1");return Ve.runKernelFunc(function(e,t){var o=e.expm1(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.mul(o.exp())}}})}}),hf=Ke({floor_:function(n){var r=Oe(n,"x","floor");return Ve.runKernelFunc(function(e){return e.floor(r)},{$x:r},function(e){return{$x:function(){return Jt(e)}}})}}),pf=Ke({log_:function(n){var r=Oe(n,"x","log"),e=[r];return Ve.runKernelFunc(function(t,o){var a=t.log(r);return o([r]),a},{x:r},function(t,o){var a=o[0];return{x:function(){return t.div(a.toFloat())}}},"Log",{},e)}}),mf=Ke({log1p_:function(n){var r=Oe(n,"x","log1p");return Ve.runKernelFunc(function(e,t){var o=e.log1p(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.div(o.add(1))}}})}}),vf=Ke({logSigmoid_:function(n){var r=Oe(n,"x","logSigmoid");return Ve.runKernelFunc(function(e,t){var o=e.softplus(r.neg()).neg();return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.mul(o.neg().sigmoid())}}})}}),hu=Ke({neg_:function(n){var r=Oe(n,"x","neg"),e=[r];return Ve.runKernelFunc(function(t){return t.neg(r)},{x:r},function(t){return{x:function(){return t.neg()}}},"Neg",{},e)}}),gf=Ke({reciprocal_:function(n){var r=Oe(n,"x","reciprocal");return Ve.runKernelFunc(function(e,t){var o=e.reciprocal(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.div(o.square().neg())}}})}}),yf=Ke({round_:function(n){var r=Oe(n,"x","round");return Ve.runKernelFunc(function(e){return e.round(r)},{$x:r},function(e){return{$x:function(){return Jt(e)}}})}}),Xc=Ke({rsqrt_:function(n){var r=Oe(n,"x","rsqrt"),e=[r];return Ve.runKernelFunc(function(t,o){var a=t.rsqrt(r);return o([r]),a},{x:r},function(t,o){var a=o[0];return{x:function(){return t.div(a.pow(1.5).mul(2)).neg()}}},"Rsqrt",{},e)}}),Kc=Ke({sigmoid_:function(n){var r=Oe(n,"x","sigmoid");return Ve.runKernelFunc(function(e,t){var o=e.sigmoid(r);return t([o]),o},{x:r},function(e,t){var o=t[0];return{x:function(){return e.mul(o.mul(It(1).sub(o)))}}},"Sigmoid")}}),bf=Ke({sign_:function(n){var r=Oe(n,"x","sign");return Ve.runKernelFunc(function(e){return e.sign(r)},{$x:r},function(e){return{$x:function(){return Jt(e)}}})}}),xf=Ke({isNaN_:function(n){var r=Oe(n,"x","isNaN");return Ve.runKernelFunc(function(e){return e.isNaN(r)},{$x:r},function(e){return{$x:function(){return Jt(e)}}})}}),wf=Ke({isInf_:function(n){var r=Oe(n,"x","isInf");return Ve.runKernelFunc(function(e){return e.isInf(r)},{$x:r},function(e){return{$x:function(){return Jt(e)}}})}}),Ef=Ke({isFinite_:function(n){var r=Oe(n,"x","isFinite");return Ve.runKernelFunc(function(e){return e.isFinite(r)},{$x:r},function(e){return{$x:function(){return Jt(e)}}})}}),_f=Ke({sin_:function(n){var r=Oe(n,"x","sin"),e=[r];return Ve.runKernelFunc(function(t,o){var a=t.sin(r);return o([r]),a},{x:r},function(t,o){var a=o[0];return{x:function(){return a.toFloat().cos().mul(t)}}},"Sin",{},e)}}),Cf=Ke({sinh_:function(n){var r=Oe(n,"x","sinh");return Ve.runKernelFunc(function(e,t){var o=e.sinh(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return o.toFloat().cosh().mulStrict(e)}}})}}),Tf=Ke({softplus_:function(n){var r=Oe(n,"x","softplus");return Ve.runKernelFunc(function(e,t){var o=e.softplus(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.mul(o.sigmoid())}}})}}),Sf=Ke({sqrt_:function(n){var r=Oe(n,"x","sqrt");return Ve.runKernelFunc(function(e,t){var o=e.sqrt(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.div(o.toFloat().sqrt().mul(2))}}})}}),Af=Ke({step_:function(n,r){r===void 0&&(r=0);var e=Oe(n,"x","step");return Ve.runKernelFunc(function(t){return t.step(e,r)},{$x:e},function(t){return{$x:function(){return Jt(t)}}})}}),Of=Ke({tan_:function(n){var r=Oe(n,"x","tan");return Ve.runKernelFunc(function(e,t){var o=e.tan(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){return e.div(o.cos().square())}}})}}),Rf=Ke({tanh_:function(n){var r=Oe(n,"x","tanh");return Ve.runKernelFunc(function(e,t){var o=e.tanh(r);return t([o]),o},{x:r},function(e,t){var o=t[0];return{x:function(){return It(1).sub(o.square()).mulStrict(e)}}},"Tanh",{},null,[!0])}});function Yc(n,r,e,t,o,a){var i,s,u=Oe(n,"x","batchNorm"),f=Oe(r,"mean","batchNorm"),E=Oe(e,"variance","batchNorm");return o!=null&&(i=Oe(o,"scale","batchNorm")),t!=null&&(s=Oe(t,"offset","batchNorm")),w(u.rank===2,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),w(f.rank===2||f.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+f.rank+"."}),w(E.rank===2||E.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+E.rank+"."}),i!=null&&w(i.rank===2||i.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."}),s!=null&&w(s.rank===2||s.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),Ei(u,f,E,s,i,a)}function $c(n,r,e,t,o,a){var i,s,u=Oe(n,"x","batchNorm"),f=Oe(r,"mean","batchNorm"),E=Oe(e,"variance","batchNorm");return o!=null&&(i=Oe(o,"scale","batchNorm")),t!=null&&(s=Oe(t,"offset","batchNorm")),w(u.rank===3,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),w(f.rank===3||f.rank===1,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+f.rank+"."}),w(E.rank===3||E.rank===1,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+E.rank+"."}),i!=null&&w(i.rank===3||i.rank===1,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."}),s!=null&&w(s.rank===3||s.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),Ei(u,f,E,s,i,a)}function Jc(n,r,e,t,o,a){var i,s,u=Oe(n,"x","batchNorm"),f=Oe(r,"mean","batchNorm"),E=Oe(e,"variance","batchNorm");return o!=null&&(i=Oe(o,"scale","batchNorm")),t!=null&&(s=Oe(t,"offset","batchNorm")),w(u.rank===4,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),w(f.rank===4||f.rank===1,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+f.rank+"."}),w(E.rank===4||E.rank===1,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+E.rank+"."}),i!=null&&w(i.rank===4||i.rank===1,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."}),s!=null&&w(s.rank===4||s.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),Ei(u,f,E,s,i,a)}function Ei(n,r,e,t,o,a){a==null&&(a=.001);var i,s,u,f=Oe(n,"x","batchNorm"),E=Oe(r,"mean","batchNorm"),I=Oe(e,"variance","batchNorm");o!=null&&(i=Oe(o,"scale","batchNorm")),t!=null&&(s=Oe(t,"offset","batchNorm")),w(E.rank===I.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),w(s==null||E.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),w(i==null||E.rank===i.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=f.rank===0||f.rank===1?f.as4D(1,1,1,f.size):f.rank===2?f.as4D(1,1,f.shape[0],f.shape[1]):f.rank===3?f.as4D(1,f.shape[0],f.shape[1],f.shape[2]):f;var P=[f,E,I,i];return Ve.runKernelFunc(function(G,oe){var ue=G.batchNormalization(u,cs(E),cs(I),a,cs(i),cs(s));return oe([f,E,I,i]),ue},{x:f,mean:E,variance:I,scale:i,offset:s},function(G,oe){var ue=oe,ie=ue[0],ce=ue[1],ye=ue[2],we=ue[3],Ee=we==null?It(1):we,Se=Ir(ce.shape,u.shape),Me=[];if(ce.rank===1){for(var He=0;He0&&(s=s.sum(u)),s.reshape(t.shape)},b:function(){var s=i,u=Ir(o.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(o.shape)}}},"Add")}}),Bf=Ke({addN_:function(n){w(Array.isArray(n),function(){return"The argument passed to tf.addN() must be a list of tensors"}),w(n.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+n.length});var r=n.map(function(o,a){return Oe(o,"tensors"+a,"addN")}),e=r[0];r.forEach(function(o){if(o.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),r.forEach(function(o){if(!_e(o.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var t=r;return Ve.runKernelFunc(function(o){return o.addN(r)},t,function(o){var a={};return r.forEach(function(i,s){a[s]=function(){return o.clone()}}),a},"AddN")}}),Uf=Ke({addStrict_:function(n,r){var e=Oe(n,"a","addStrict"),t=Oe(r,"b","addStrict");return X(e.shape,t.shape,"Error in addStrict: "),e.add(t)}}),Wf=Ke({atan2_:function(n,r){var e,t=Oe(n,"a","atan2"),o=Oe(r,"b","atan2");e=cr(t,o),t=e[0],o=e[1];var a=Ht(t.shape,o.shape);return Ve.runKernelFunc(function(i,s){var u=i.atan2(t,o);return s([t,o]),u},{$a:t,$b:o},function(i,s){var u=s[0],f=s[1];return{$a:function(){var E=qo(u.square(),f.square()),I=i.mul(f.div(E)),P=Ir(u.shape,a);return P.length>0&&(I=I.sum(P)),I.reshape(u.shape)},$b:function(){var E=qo(u.square(),f.square()),I=hu(i.mul(u.div(E))),P=Ir(f.shape,a);return P.length>0&&(I=I.sum(P)),I.reshape(f.shape)}}})}}),fs=Ke({div_:function(n,r){var e,t=Oe(n,"a","div"),o=Oe(r,"b","div");if(e=cr(t,o),t=e[0],o=e[1],t.dtype==="int32"&&o.dtype==="int32")return el(t,o);var a=Ht(t.shape,o.shape);return Ve.runKernelFunc(function(i,s){var u=i.realDivide(t,o);return s([t,o]),u},{a:t,b:o},function(i,s){var u=s[0],f=s[1];return{a:function(){var E=i.div(f.toFloat()),I=Ir(u.shape,a);return I.length>0?E.sum(I).reshape(u.shape):E},b:function(){var E=i.mul(u.toFloat()),I=Ir(f.shape,a);I.length>0&&(E=E.sum(I).reshape(f.shape));var P=f.square();return E.div(P.toFloat()).neg()}}},"Div")}}),Hf=Ke({divNoNan_:function(n,r){var e,t=Oe(n,"a","div"),o=Oe(r,"b","div");t=(e=cr(t,o))[0],o=e[1];var a=fs(t,o),i=Jt(a),s=o.equal(i);return Jo(s,i,a)}}),zf=Ke({divStrict_:function(n,r){var e=Oe(n,"a","div"),t=Oe(r,"b","div");return X(e.shape,t.shape,"Error in divideStrict: "),e.div(t)}}),el=Ke({floorDiv_:function(n,r){var e,t=Oe(n,"a","floorDiv"),o=Oe(r,"b","floorDiv");e=cr(t,o),t=e[0],o=e[1];var a=Ht(t.shape,o.shape);return Ve.runKernelFunc(function(i,s){var u=i.floorDiv(t,o);return s([t,o]),u},{a:t,b:o},function(i,s){var u=s[0],f=s[1];return{a:function(){var E=i.div(f.toFloat()),I=Ir(u.shape,a);return I.length>0?E.sum(I).reshape(u.shape):E},b:function(){var E=i.mul(u.toFloat()),I=Ir(f.shape,a);I.length>0&&(E=E.sum(I).reshape(f.shape));var P=f.square();return E.div(P.toFloat()).neg()}}},"FloorDiv")}}),pu=Ke({maximum_:function(n,r){var e,t=Oe(n,"a","maximum"),o=Oe(r,"b","maximum");return e=cr(t,o),t=e[0],o=e[1],t.dtype==="bool"&&(t=t.toInt(),o=o.toInt()),Ht(t.shape,o.shape),Ve.runKernelFunc(function(a,i){var s=a.maximum(t,o);return i([t,o]),s},{a:t,b:o},function(a,i){var s=i[0],u=i[1];return{a:function(){return a.mul(s.greaterEqual(u).toFloat())},b:function(){return a.mul(s.less(u).toFloat())}}},"Maximum")}}),Gf=Ke({maximumStrict_:function(n,r){var e=Oe(n,"a","maximumStrict"),t=Oe(r,"b","maximumStrict");return X(e.shape,t.shape,"Error in maximumStrict: "),e.maximum(t)}}),tl=Ke({minimum_:function(n,r){var e,t=Oe(n,"a","minimum"),o=Oe(r,"b","minimum");return e=cr(t,o),t=e[0],o=e[1],t.dtype==="bool"&&(t=t.toInt(),o=o.toInt()),Ht(t.shape,o.shape),Ve.runKernelFunc(function(a,i){var s=a.minimum(t,o);return i([t,o]),s},{a:t,b:o},function(a,i){var s=i[0],u=i[1];return{a:function(){return a.mul(s.lessEqual(u).toFloat())},b:function(){return a.mul(s.greater(u).toFloat())}}},"Minimum")}}),Vf=Ke({minimumStrict_:function(n,r){var e=Oe(n,"a","minimumStrict"),t=Oe(r,"b","minimumStrict");return X(e.shape,t.shape,"Error in minimumStrict: "),e.minimum(t)}}),Xf=Ke({mod_:function(n,r){var e,t=Oe(n,"a","mod"),o=Oe(r,"b","mod");e=cr(t,o),t=e[0],o=e[1];var a=Ht(t.shape,o.shape);return Ve.runKernelFunc(function(i,s){var u=i.mod(t,o);return s([t,o]),u},{$a:t,$b:o},function(i,s){var u=s[0],f=s[1];return{$a:function(){var E=Ir(u.shape,a);return E.length>0?i.sum(E).reshape(u.shape):i},$b:function(){var E=i.mul(u.div(f).floor().neg()),I=Ir(f.shape,a);return I.length>0?E.sum(I).reshape(f.shape):E}}})}}),Kf=Ke({modStrict_:function(n,r){var e=Oe(n,"a","modStrict"),t=Oe(r,"b","modStrict");return X(e.shape,t.shape,"Error in modStrict: "),e.mod(t)}}),Qo=Ke({mul_:function(n,r){var e,t=Oe(n,"a","mul"),o=Oe(r,"b","mul");e=cr(t,o),t=e[0],o=e[1];var a=Ht(t.shape,o.shape);return Ve.runKernelFunc(function(i,s){var u=i.multiply(t,o);return s([t,o]),u},{a:t,b:o},function(i,s){var u=s[0],f=s[1];return{a:function(){var E=i.mul(f.toFloat()),I=Ir(u.shape,a);return I.length>0?E.sum(I).reshape(u.shape):E},b:function(){var E=i.mul(u.toFloat()),I=Ir(f.shape,a);return I.length>0?E.sum(I).reshape(f.shape):E}}},"Mul")}}),Yf=Ke({mulStrict_:function(n,r){var e=Oe(n,"a","mul"),t=Oe(r,"b","mul");return X(e.shape,t.shape,"Error in multiplyStrict: "),e.mul(t)}}),hs=Ke({pow_:function(n,r){var e,t=Oe(n,"base","pow"),o=Oe(r,"exp","pow");e=cr(t,o),t=e[0],o=e[1];var a=Ht(t.shape,o.shape),i=[t,o];return Ve.runKernelFunc(function(s,u){var f=s.pow(t,o);return u([t,o,f]),f},{a:t,b:o},function(s,u){var f=u[0],E=u[1],I=u[2];return{a:function(){var P=E.toFloat(),G=s.mul(P.mul(f.pow(P.sub(It(1))))),oe=Ir(f.shape,a);return oe.length>0&&(G=G.sum(oe)),G.reshape(f.shape)},b:function(){var P=f.greater(0),G=f.log().where(P,Jt(f)),oe=s.mul(I.mul(G)),ue=Ir(E.shape,a);return ue.length>0&&(oe=oe.sum(ue)),oe.reshape(E.shape)}}},"Pow",{},i,[!0])}}),$f=Ke({powStrict_:function(n,r){return X(n.shape,r.shape,"Error in powStrict: "),n.pow(r)}}),Jf=Ke({squaredDifferenceStrict_:function(n,r){var e=Oe(n,"a","squaredDifferenceStrict"),t=Oe(r,"b","squaredDifferenceStrict");return X(e.shape,t.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(t)}}),Ao=Ke({sub_:function(n,r){var e,t=Oe(n,"a","sub"),o=Oe(r,"b","sub");e=cr(t,o),t=e[0],o=e[1];var a=Ht(t.shape,o.shape);return Ve.runKernelFunc(function(i){return i.subtract(t,o)},{a:t,b:o},function(i){return{a:function(){var s=i,u=Ir(t.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(t.shape)},b:function(){var s=i,u=Ir(o.shape,a);return u.length>0&&(s=s.sum(u)),s.neg().reshape(o.shape)}}},"Sub")}}),qf=Ke({subStrict_:function(n,r){var e=Oe(n,"a","subStrict"),t=Oe(r,"b","subStrict");return X(e.shape,t.shape,"Error in subStrict: "),e.sub(t)}}),rl=Ke({equal_:function(n,r){var e,t=Oe(n,"a","equal"),o=Oe(r,"b","equal");return e=cr(t,o),t=e[0],o=e[1],Ht(t.shape,o.shape),Ve.runKernelFunc(function(a){return a.equal(t,o)},{$a:t,$b:o})}}),Qf=Ke({equalStrict_:function(n,r){var e=Oe(n,"a","equalStrict"),t=Oe(r,"b","equalStrict");return X(e.shape,t.shape,"Error in equalStrict: "),e.equal(t)}}),Zf=Ke({greater_:function(n,r){var e,t=Oe(n,"a","greater"),o=Oe(r,"b","greater");return e=cr(t,o),t=e[0],o=e[1],Ht(t.shape,o.shape),Ve.runKernelFunc(function(a){return a.greater(t,o)},{a:t,b:o},null,"Greater")}}),nl=Ke({greaterEqual_:function(n,r){var e,t=Oe(n,"a","greaterEqual"),o=Oe(r,"b","greaterEqual");return e=cr(t,o),t=e[0],o=e[1],Ht(t.shape,o.shape),Ve.runKernelFunc(function(a,i){var s=a.greaterEqual(t,o);return i([t,o]),s},{a:t,b:o},function(a,i){var s=i[0],u=i[1];return{a:function(){return Jt(s)},b:function(){return Jt(u)}}},"GreaterEqual")}}),eh=Ke({greaterEqualStrict_:function(n,r){var e=Oe(n,"a","greaterEqualStrict"),t=Oe(r,"b","greaterEqualStrict");return X(e.shape,t.shape,"Error in greaterEqualStrict: "),e.greaterEqual(t)}}),th=Ke({greaterStrict_:function(n,r){var e=Oe(n,"a","greaterStrict"),t=Oe(r,"b","greaterStrict");return X(e.shape,t.shape,"Error in greaterStrict: "),e.greater(t)}}),rh=Ke({less_:function(n,r){var e,t=Oe(n,"a","less"),o=Oe(r,"b","less");return e=cr(t,o),t=e[0],o=e[1],Ht(t.shape,o.shape),Ve.runKernelFunc(function(a){return a.less(t,o)},{a:t,b:o},null,"Less")}}),nh=Ke({lessEqual_:function(n,r){var e,t=Oe(n,"a","lessEqual"),o=Oe(r,"b","lessEqual");return e=cr(t,o),t=e[0],o=e[1],Ht(t.shape,o.shape),Ve.runKernelFunc(function(a,i){var s=a.lessEqual(t,o);return i([t,o]),s},{a:t,b:o},null,"LessEqual")}}),oh=Ke({lessEqualStrict_:function(n,r){var e=Oe(n,"a","lessEqualStrict"),t=Oe(r,"b","lessEqualStrict");return X(e.shape,t.shape,"Error in lessEqualStrict: "),e.lessEqual(t)}}),ah=Ke({lessStrict_:function(n,r){var e=Oe(n,"a","lessStrict"),t=Oe(r,"b","lessStrict");return X(e.shape,t.shape,"Error in lessStrict: "),e.less(t)}}),ih=Ke({notEqual_:function(n,r){var e,t=Oe(n,"a","notEqual"),o=Oe(r,"b","notEqual");return e=cr(t,o),t=e[0],o=e[1],Ht(t.shape,o.shape),Ve.runKernelFunc(function(a){return a.notEqual(t,o)},{a:t,b:o},null,"NotEqual")}}),sh=Ke({notEqualStrict_:function(n,r){var e=Oe(n,"a","notEqualStrict"),t=Oe(r,"b","notEqualStrict");return X(e.shape,t.shape,"Error in notEqualStrict: "),e.notEqual(t)}});function ol(n,r){for(var e=[],t=n;t0,function(){return"mask cannot be scalar"}),X(s.slice(a,a+i),o.shape,"mask's shape must match the first K dimensions of tensor's shape,"),u=1,f=a;f=2&&i.rank>=2&&a.rank===i.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."}),w(_e(I,P),function(){return"Error in matMul: outer dimensions ("+I+") and ("+P+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."}),w(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+e+" and transposeB="+t+" must match."});var ue=a.shape.slice(0,-2).concat([f,E]),ie=e?a.as3D(G,s,f):a.as3D(G,f,s),ce=t?i.as3D(oe,E,u):i.as3D(oe,u,E),ye={transposeA:e,transposeB:t};return Ve.runKernelFunc(function(we,Ee){var Se=we.batchMatMul(ie,ce,e,t);return Ee([ie,ce]),Se},{a:ie,b:ce},function(we,Ee){var Se=Ee,Me=Se[0],He=Se[1];return e||t?!e&&t?{a:function(){return we.matMul(He,!1,!1)},b:function(){return we.matMul(Me,!0,!1)}}:e&&!t?{a:function(){return He.matMul(we,!1,!0)},b:function(){return Me.matMul(we,!1,!1)}}:{a:function(){return He.matMul(we,!0,!0)},b:function(){return we.matMul(Me,!0,!0)}}:{a:function(){return we.matMul(He,!1,!0)},b:function(){return Me.matMul(we,!0,!1)}}},"BatchMatMul",ye).reshape(ue)}}),hh=Ke({dot_:function(n,r){var e=Oe(n,"t1","dot"),t=Oe(r,"t2","dot");w(!(e.rank!==1&&e.rank!==2||t.rank!==1&&t.rank!==2),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+e.rank+" and "+t.rank+"."});var o=e.rank===1?e.size:e.shape[1],a=t.rank===1?t.size:t.shape[0];return w(o===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."}),e.rank===1&&t.rank===1?e.as2D(1,-1).matMul(t.as2D(-1,1)).asScalar():e.rank===1&&t.rank===2?e.as2D(1,-1).matMul(t.as2D(t.shape[0],t.shape[1])).as1D():e.rank===2&&t.rank===1?e.matMul(t.as2D(-1,1)).as1D():e.matMul(t.as2D(t.shape[0],t.shape[1]))}}),ph=Ke({outerProduct_:function(n,r){var e=Oe(n,"v1","outerProduct"),t=Oe(r,"v2","outerProduct");return w(e.rank===1&&t.rank===1,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+e.rank+" and "+t.rank+"."}),e.as2D(-1,1).matMul(t.as2D(1,-1))}}),_i=Ke({reverse_:function(n,r){var e=Oe(n,"x","reverse");if(e.rank===0)return e.clone();var t=de(r,e.shape);return Ve.runKernelFunc(function(o){return o.reverse(e,t)},{$x:e},function(o){return{$x:function(){return o.reverse(t)}}}).reshapeAs(e)}}),mh=Ke({reverse1d_:function(n){var r=Oe(n,"x","reverse");return w(r.rank===1,function(){return"Error in reverse1D: x must be rank 1 but got rank "+r.rank+"."}),_i(r,0)}}),vh=Ke({reverse2d_:function(n,r){var e=Oe(n,"x","reverse");return w(e.rank===2,function(){return"Error in reverse2D: x must be rank 2 but got rank "+e.rank+"."}),_i(e,r)}}),gh=Ke({reverse3d_:function(n,r){var e=Oe(n,"x","reverse");return w(e.rank===3,function(){return"Error in reverse3D: x must be rank 3 but got rank "+e.rank+"."}),_i(e,r)}}),yh=Ke({reverse4d_:function(n,r){var e=Oe(n,"x","reverse");return w(e.rank===4,function(){return"Error in reverse4D: x must be rank 4 but got rank "+e.rank+"."}),_i(e,r)}});function hl(n,r,e,t,o,a){var i=Oe(n,"x","maxPool"),s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),t==null&&(t=[1,1]),w(s.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),w(Zr(e,t),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+t+"'"}),a!=null&&w(se(o),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var f=to(s.shape,r,e,t,o,a);if(f.filterWidth===1&&f.filterHeight===1&&_e(f.inShape,f.outShape))return i.clone();var E=[s],I=Ve.runKernelFunc(function(P,G){var oe=P.maxPool(s,f);return G([s,oe]),oe},{x:s},function(P,G){var oe=G[0],ue=G[1];return{x:function(){return function(ie,ce,ye,we,Ee,Se,Me,He){var Fe=Oe(ie,"dy","maxPoolBackprop"),je=Oe(ce,"input","maxPoolBackprop"),Ue=Oe(ye,"output","maxPoolBackprop");w(je.rank===Fe.rank,function(){return"Rank of input ("+je.rank+") does not match rank of dy ("+Fe.rank+")"}),Se==null&&(Se=[1,1]),w(Zr(Ee,Se),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+Ee+" and dilations '"+Se+"'"}),w(Fe.rank===4,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+Fe.rank+"."}),w(je.rank===4,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+je.rank+"."}),He!=null&&w(se(Me),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+He+" but got pad "+Me+"."});var Ze=to(je.shape,we,Ee,Se,Me,He);return Ve.runKernelFunc(function(Je){return Je.maxPoolBackprop(Fe,je,Ue,Ze)},{$dy:Fe,$input:je})}(P,oe,ue,r,e,t,o)}}},"MaxPool",f,E);return u?I.as3D(I.shape[1],I.shape[2],I.shape[3]):I}function pl(n,r,e,t,o,a){var i=Oe(n,"x","avgPool","float32");t==null&&(t=[1,1]),w(Zr(e,t),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+t+"'"});var s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),w(s.rank===4,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),a!=null&&w(se(o),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var f=to(s.shape,r,e,t,o,a);if(f.filterWidth===1&&f.filterHeight===1&&_e(f.inShape,f.outShape))return i.clone();var E=Ve.runKernelFunc(function(I){return I.avgPool(s,f)},{x:s},function(I){return{x:function(){return function(P,G,oe,ue,ie,ce){var ye=Oe(P,"dy","avgPoolBackprop"),we=Oe(G,"input","avgPoolBackprop");w(we.rank===ye.rank,function(){return"Rank of input ("+we.rank+") does not match rank of dy ("+ye.rank+")"}),ie==null&&(ie=[1,1]),w(Zr(ue,ie),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+ue+" and dilations '"+ie+"'"});var Ee=we,Se=ye,Me=!1;we.rank===3&&(Me=!0,Ee=we.as4D(1,we.shape[0],we.shape[1],we.shape[2]),Se=ye.as4D(1,ye.shape[0],ye.shape[1],ye.shape[2])),w(Se.rank===4,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+Se.rank+"."}),w(Ee.rank===4,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+Ee.rank+"."});var He=to(Ee.shape,oe,ue,ie,ce),Fe=Ve.runKernelFunc(function(je){return je.avgPoolBackprop(Se,Ee,He)},{dy4D:Se,input4D:Ee});return Me?Fe.as3D(Fe.shape[1],Fe.shape[2],Fe.shape[3]):Fe}(I,s,r,e,t,o)}}},"AvgPool",f);return E=E.cast(i.dtype),u?E.as3D(E.shape[1],E.shape[2],E.shape[3]):E}var ml=Ke({maxPool_:function(n,r,e,t,o){return hl(n,r,e,1,t,o)}}),vl=Ke({avgPool_:function(n,r,e,t,o){return pl(n,r,e,1,t,o)}}),bh=Ke({pool_:function(n,r,e,t,o,a){o==null&&(o=[1,1]),a==null&&(a=1),t===0&&(t="valid");var i=Oe(n,"x","maxPool"),s=i,u=!1;i.rank===3&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),w(Zr(a,o),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"});var f,E=to(s.shape,r,a,o,t),I=[E.dilationHeight,E.dilationWidth];f=t==="same"?function(Ee,Se){var Me=Ee.map(function(je,Ue){return je+(je-1)*(Se[Ue]-1)}).map(function(je){return je-1}),He=Me.map(function(je){return Math.floor(je/2)}),Fe=Me.map(function(je,Ue){return je-He[Ue]});return Me.map(function(je,Ue){return[He[Ue],Fe[Ue]]})}([E.filterHeight,E.filterWidth],I):[[0,0],[0,0]];var P=I[0]===1&&I[1]===1,G=function(Ee,Se,Me){var He=Me.map(function(ct){return ct[0]}),Fe=Me.map(function(ct){return ct[1]}),je=Ee.concat(He,Fe),Ue=Se.map(function(ct,st){return(ct-je[st]%ct)%ct}),Ze=Fe.map(function(ct,st){return ct+Ue[st]}),Je=Se.map(function(ct,st){return[He[st],Ze[st]]}),dt=Se.map(function(ct,st){return[0,Ue[st]]});return[Je,dt]}([E.inHeight,E.inWidth],I,f),oe=G[0],ue=G[1],ie=P?t:"valid",ce=P?s:Gi(s,I,oe),ye=(e==="avg"?function(){return pl(ce,r,a,1,ie)}:function(){return hl(ce,r,a,1,ie)})(),we=P?ye:va(ye,I,ue);return u?we.as3D(we.shape[1],we.shape[2],we.shape[3]):we}}),xh=Ke({maxPool3d_:function(n,r,e,t,o,a,i){a===void 0&&(a="NDHWC");var s=Oe(n,"x","maxPool3d"),u=s,f=!1;s.rank===4&&(f=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),i==null&&(i=[1,1,1]),w(u.rank===5,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),w(a==="NDHWC",function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),w(Zr(e,i),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+i+"'"}),o!=null&&w(se(t),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+t+"."});var E=Go(u.shape,r,e,i,t,o,a),I=Ve.runKernelFunc(function(P,G){var oe=P.maxPool3d(u,E);return G([u,oe]),oe},{x:u},function(P,G){var oe=G[0],ue=G[1];return{x:function(){return function(ie,ce,ye,we,Ee,Se,Me,He){var Fe=Oe(ie,"dy","maxPool3dBackprop"),je=Oe(ce,"input","maxPool3dBackprop"),Ue=Oe(ye,"output","maxPool3dBackprop"),Ze=Fe,Je=je,dt=Ue,ct=!1;je.rank===4&&(ct=!0,Ze=Fe.as5D(1,Fe.shape[0],Fe.shape[1],Fe.shape[2],Fe.shape[3]),Je=je.as5D(1,je.shape[0],je.shape[1],je.shape[2],je.shape[3]),dt=Ue.as5D(1,Ue.shape[0],Ue.shape[1],Ue.shape[2],Ue.shape[3])),w(Ze.rank===5,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+Ze.rank+"."}),w(Je.rank===5,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+Je.rank+"."}),w(dt.rank===5,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+dt.rank+"."}),Se==null&&(Se=[1,1,1]),w(Zr(Ee,Se),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+Ee+" and dilations '"+Se+"'"}),He!=null&&w(se(Me),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+He+" but got pad "+Me+"."});var st=Go(Je.shape,we,Ee,Se,Me,He),pt=Ve.runKernelFunc(function(ht){return ht.maxPool3dBackprop(Ze,Je,dt,st)},{dy5D:Ze,input5D:Je});return ct?pt.as4D(pt.shape[1],pt.shape[2],pt.shape[3],pt.shape[4]):pt}(P,oe,ue,r,e,i,t,o)}}});return f?I.as4D(I.shape[1],I.shape[2],I.shape[3],I.shape[4]):I}}),wh=Ke({avgPool3d_:function(n,r,e,t,o,a,i){a===void 0&&(a="NDHWC");var s=Oe(n,"x","avgPool3d","float32"),u=s,f=!1;s.rank===4&&(f=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),i==null&&(i=[1,1,1]),w(u.rank===5,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),w(a==="NDHWC",function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),w(Zr(e,i),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+i+"'"}),o!=null&&w(se(t),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+t+"."});var E=Go(u.shape,r,e,i,t,o,a),I=Ve.runKernelFunc(function(P){return P.avgPool3d(u,E)},{x:u},function(P){return{x:function(){return function(G,oe,ue,ie,ce,ye,we){var Ee=Oe(G,"dy","avgPool3dBackprop"),Se=Oe(oe,"input","avgPool3dBackprop"),Me=Ee,He=Se,Fe=!1;Se.rank===4&&(Fe=!0,Me=Ee.as5D(1,Ee.shape[0],Ee.shape[1],Ee.shape[2],Ee.shape[3]),He=Se.as5D(1,Se.shape[0],Se.shape[1],Se.shape[2],Se.shape[3])),w(Me.rank===5,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+Me.rank+"."}),w(He.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+He.rank+"."}),ce==null&&(ce=[1,1,1]),w(Zr(ie,ce),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+ie+" and dilations '"+ce+"'"}),we!=null&&w(se(ye),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+we+" but got pad "+ye+"."});var je=Go(He.shape,ue,ie,ce,ye,we),Ue=Ve.runKernelFunc(function(Ze){return Ze.avgPool3dBackprop(Me,He,je)},{dy5D:Me,input5D:He});return Fe?Ue.as4D(Ue.shape[1],Ue.shape[2],Ue.shape[3],Ue.shape[4]):Ue}(P,u,r,e,i,t,o)}}});return I=I.cast(u.dtype),f?I.as4D(I.shape[1],I.shape[2],I.shape[3],I.shape[4]):I}}),no=Ke({slice_:function(n,r,e){var t,o,a=Oe(n,"x","slice");if(a.rank===0)throw new Error("Slicing scalar is not possible");(t=typeof r=="number"?[r].concat(new Array(a.rank-1).fill(0)):r.length=0?u:(w(u===-1,function(){return"Negative size values should be exactly -1 but got "+u+" for the slice() size at index "+f+"."}),a.shape[f]-t[f])}),Ys(a,t,o);var i=a.shape,s={begin:t,size:o};return Ve.runKernelFunc(function(u){return u.slice(a,t,o)},{x:a},function(u){for(var f=[],E=0;E0&&(f=f.sum(E)),f.reshape(s.shape)}}},"Prelu")}}),bu=Ke({relu_:function(n){var r=Oe(n,"x","relu");return r.dtype==="bool"?r.toInt():Ve.runKernelFunc(function(e,t){var o=e.relu(r);return t([r]),o},{x:r},function(e,t){var o=t[0];return{x:function(){return e.mulStrict(o.step().toFloat())}}},"Relu")}}),_l=Ke({relu6_:function(n){var r=Oe(n,"x","relu6");return r.dtype==="bool"?r.toInt():Ve.runKernelFunc(function(e,t){var o=e.relu6(r);return t([r]),o},{x:r},function(e,t){var o=t[0],a=o.lessEqual(6).mul(o.step());return{x:function(){return e.mulStrict(a.toFloat())}}},"Relu6")}}),Ph=Ke({selu_:function(n){var r=Oe(n,"x","selu");return Ve.runKernelFunc(function(e,t){var o=e.selu(r);return t([r]),o},{$x:r},function(e,t){var o=t[0];return{$x:function(){var a=o.greater(It(0)),i=It(du),s=It(fu),u=e.mul(s),f=e.mul(i).mul(o.toFloat().exp());return Jo(a,u,f)}}})}}),Cl=Ke({transpose_:function(n,r){var e=Oe(n,"x","transpose");if(r==null&&(r=e.shape.map(function(o,a){return a}).reverse()),w(e.rank===r.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of perm "+r+"."}),r.forEach(function(o){w(o>=0&&oo)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+r);var a=Ve.runKernelFunc(function(i){return i.topk(t,r,e)},{$x:t});return{values:a[0],indices:a[1]}}}),Hh=Ke({scatterND_:function(n,r,e){var t=Oe(n,"indices","scatterND","int32"),o=Oe(r,"updates","scatterND");return Ks(o,t,e),Ve.runKernelFunc(function(a){return a.scatterND(t,o,e)},{indices:t,updates:o},null,"ScatterNd",{shape:e})}}),xu=Ke({fft_:function(n){w(n.dtype==="complex64",function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+n.dtype+"."});var r=n.shape[n.shape.length-1],e=n.size/r,t=n.as2D(e,r);return Ve.runKernelFunc(function(o){return o.fft(t)},{input:n}).reshape(n.shape)}}),ms=Ke({ifft_:function(n){w(n.dtype==="complex64",function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+n.dtype+"."});var r=n.shape[n.shape.length-1],e=n.size/r,t=n.as2D(e,r);return Ve.runKernelFunc(function(o){return o.ifft(t)},{input:n}).reshape(n.shape)}}),wu=Ke({rfft_:function(n,r){w(n.dtype==="float32",function(){return"The dtype for rfft() must be real value but got "+n.dtype});var e,t=n.shape[n.shape.length-1],o=n.size/t;if(r!=null&&rt){var s=n.shape.map(function(ce){return ce});s[n.shape.length-1]=r-t,e=n.concat(Tr(s),n.shape.length-1),t=r}else e=n;var u=e.zerosLike(),f=xr(e,u).as2D(o,t),E=xu(f),I=Math.floor(t/2)+1,P=un(E),G=xn(E),oe=P.split([I,t-I],P.shape.length-1),ue=G.split([I,t-I],G.shape.length-1),ie=e.shape.slice();return ie[e.shape.length-1]=I,xr(oe[0],ue[0]).reshape(ie)}}),Sl=Ke({irfft_:function(n){var r=n.shape[n.shape.length-1],e=n.size/r;if(r<=2){var t=n.as2D(e,r),o=ms(t);return un(o)}var a=[e,2*(r-1)],i=un(n).as2D(e,r),s=xn(n).as2D(e,r),u=i.slice([0,1],[e,r-2]).reverse(1),f=s.slice([0,1],[e,r-2]).reverse(1).mul(It(-1)),E=i.concat(u,1),I=s.concat(f,1);return t=xr(E,I).as2D(a[0],a[1]),o=ms(t),un(o)}}),zh=Object.freeze({fft:xu,ifft:ms,rfft:wu,irfft:Sl}),Gh=Ke({sparseToDense_:function(n,r,e,t){t===void 0&&(t=0);var o=Oe(n,"sparseIndices","sparseToDense","int32"),a=Oe(r,"sparseValues","sparseToDense"),i=Oe(t,"defaultValue","sparseToDense",a.dtype);return function(s,u,f,E){if(s.dtype!=="int32")throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+s.dtype+".");if(s.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+s.shape+".");var I=s.rank>0?s.shape[0]:1,P=s.rank>1?s.shape[1]:1;if(f.length!==P)throw new Error("outputShape has incorrect number of elements:, "+f.length+", should be: "+P+".");var G=u.size;if(u.rank!==0&&(u.rank!==1||G!==I))throw new Error("sparseValues has incorrect shape "+u.shape+", should be [] or ["+I+"]");if(u.dtype!==E.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,a,e,i),Ve.runKernelFunc(function(s){return s.sparseToDense(o,a,e,i)},{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}}),Vh=Ke({gatherND_:function(n,r){var e=Oe(r,"indices","gatherND","int32"),t=Oe(n,"x","gatherND");return Ve.runKernelFunc(function(o){return o.gatherND(t,e)},{x:t,indices:e},null,"GatherNd")}}),Xh=Ke({diag_:function(n){var r=Oe(n,"x","diag").flatten(),e=n.shape.concat(n.shape);return Ve.runKernelFunc(function(t){return t.diag(r)},{$x:r}).reshape(e)}}),Kh=Ke({dropout_:function(n,r,e,t){var o=Oe(n,"x","dropout");if(w(o.dtype==="float32",function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."}),w(r>=0&&r<1,function(){return"rate must be a float in the range [0, 1), but got "+r+"."}),r===0)return n instanceof Nr?o.clone():o;var a=function(u,f){if(f==null)return u.shape.slice();if(_e(u.shape,f))return f;if(u.shape.length===f.length){for(var E=[],I=0;I1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+t.rank}),w(t.rank-1===o.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+t.rank+" and targets rank "+o.rank}),X(t.shape.slice(0,t.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),a=t.shape[t.shape.length-1],w(e>0&&e<=a,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+a+"), but got "+e}),[4,t.data()];case 1:return i=ce.sent(),[4,o.data()];case 2:for(s=ce.sent(),u=[i.length/a,a],E=u[1],I=xe("bool",f=u[0]),P=0;P1?s.div(It(i)):s}if(e===rn.SUM_BY_NONZERO_WEIGHTS){if(o==null)return a.sum().div(It(t.size));var u=o.mul(Mn(t.shape)).notEqual(It(0)).sum().toFloat();return a.sum().div(u)}throw Error("Unknown reduction: "+e)}}),qh=Ke({cosineDistance_:function(n,r,e,t,o){o===void 0&&(o=rn.SUM_BY_NONZERO_WEIGHTS);var a=Oe(n,"labels","cosineDistance"),i=Oe(r,"predictions","cosineDistance"),s=null;t!=null&&(s=Oe(t,"weights","cosineDistance")),X(a.shape,i.shape,"Error in cosineDistance: ");var u=It(1).sub(a.mul(i).sum(e,!0));return oo(u,s,o)}}),Qh=Ke({hingeLoss_:function(n,r,e,t){t===void 0&&(t=rn.SUM_BY_NONZERO_WEIGHTS);var o=Oe(n,"labels","hingeLoss"),a=Oe(r,"predictions","hingeLoss"),i=null;e!=null&&(i=Oe(e,"weights","hingeLoss")),X(o.shape,a.shape,"Error in hingeLoss: ");var s=It(1);o=It(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return oo(u,i,t)}}),Zh=Ke({huberLoss_:function(n,r,e,t,o){t===void 0&&(t=1),o===void 0&&(o=rn.SUM_BY_NONZERO_WEIGHTS);var a=Oe(n,"labels","huberLoss"),i=Oe(r,"predictions","huberLoss"),s=null;e!=null&&(s=Oe(e,"weights","huberLoss")),X(a.shape,i.shape,"Error in huberLoss: ");var u=It(t),f=i.sub(a).abs(),E=tl(f,u),I=f.sub(E),P=It(.5).mul(E.square()).add(u.mul(I));return oo(P,s,o)}}),ep=Ke({logLoss_:function(n,r,e,t,o){t===void 0&&(t=1e-7),o===void 0&&(o=rn.SUM_BY_NONZERO_WEIGHTS);var a=Oe(n,"labels","logLoss"),i=Oe(r,"predictions","logLoss"),s=null;e!=null&&(s=Oe(e,"weights","logLoss")),X(a.shape,i.shape,"Error in logLoss: ");var u=It(1),f=It(t),E=a.mul(i.add(f).log()).neg().sub(u.sub(a).mul(u.sub(i).add(f).log()));return oo(E,s,o)}}),tp=Ke({meanSquaredError_:function(n,r,e,t){t===void 0&&(t=rn.SUM_BY_NONZERO_WEIGHTS);var o=Oe(n,"labels","meanSquaredError"),a=Oe(r,"predictions","meanSquaredError"),i=null;e!=null&&(i=Oe(e,"weights","meanSquaredError")),X(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return oo(s,i,t)}}),rp=Ke({sigmoidCrossEntropy_:function(n,r,e,t,o){t===void 0&&(t=0),o===void 0&&(o=rn.SUM_BY_NONZERO_WEIGHTS);var a=Oe(n,"multiClassLabels","sigmoidCrossEntropy"),i=Oe(r,"logits","sigmoidCrossEntropy"),s=null;if(e!=null&&(s=Oe(e,"weights","sigmoidCrossEntropy")),X(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),t>0){var u=It(t),f=It(1),E=It(.5);a=a.mul(f.sub(u)).add(E.mul(u))}var I=function(P,G){var oe=Oe(P,"labels","sigmoidCrossEntropyWithLogits"),ue=Oe(G,"logits","sigmoidCrossEntropyWithLogits");X(oe.shape,ue.shape,"Error in sigmoidCrossEntropyWithLogits: ");var ie=ue.relu(),ce=ue.mul(oe),ye=ue.abs().neg().exp().log1p();return ie.sub(ce).add(ye)}(a,i);return oo(I,s,o)}}),np=Ke({softmaxCrossEntropy_:function(n,r,e,t,o){t===void 0&&(t=0),o===void 0&&(o=rn.SUM_BY_NONZERO_WEIGHTS);var a=Oe(n,"onehotLabels","softmaxCrossEntropy"),i=Oe(r,"logits","softmaxCrossEntropy"),s=null;if(e!=null&&(s=Oe(e,"weights","softmaxCrossEntropy")),X(a.shape,i.shape,"Error in softmaxCrossEntropy: "),t>0){var u=It(t),f=It(1),E=It(a.shape[1]);a=a.mul(f.sub(u)).add(u.div(E))}var I=function(P,G,oe){if(oe===void 0&&(oe=-1),oe===-1&&(oe=G.rank-1),oe!==G.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+G.rank+" and dim was "+oe);return _o(function(ue,ie,ce){var ye=ie.logSumExp([oe],!0),we=ie.toFloat().sub(ye);return ce([ue,we]),{value:we.mul(ue).neg().sum([oe]),gradFunc:function(Ee,Se){var Me=Se[0],He=Se[1],Fe=Vr(Ee.shape,[oe]);return[Ee.reshape(Fe).mul(Me.toFloat().sub(He.exp())),Ee.reshape(Fe).mul(He.exp().sub(Me.toFloat()))]}}})(P,G)}(a,i);return oo(I,s,o)}}),op=Object.freeze({get Reduction(){return rn},absoluteDifference:Jh,computeWeightedLoss:oo,cosineDistance:qh,hingeLoss:Qh,huberLoss:Zh,logLoss:ep,meanSquaredError:tp,sigmoidCrossEntropy:rp,softmaxCrossEntropy:np});function Il(n,r){return r===void 0&&(r=!1),Ve.tidy(function(){if(n.shape.length!==2)throw new Error("qr2d() requires a 2D Tensor, but got a "+n.shape.length+"D Tensor.");for(var e=n.shape[0],t=n.shape[1],o=Hi(e),a=n.clone(),i=Zn([[1]],[1,1]),s=i.clone(),u=e>=t?t:e,f=function(I){var P,G=a,oe=s,ue=o;P=Ve.tidy(function(){var ie=a.slice([I,I],[e-I,1]),ce=ie.norm(),ye=a.slice([I,I],[1,1]),we=Zn([[-1]]).where(ye.greater(0),Zn([[1]])),Ee=ye.sub(we.mul(ce)),Se=ie.div(Ee);s=Se.shape[0]===1?i.clone():i.concat(Se.slice([1,0],[Se.shape[0]-1,Se.shape[1]]),0);var Me=we.matMul(Ee).div(ce).neg(),He=a.slice([I,0],[e-I,t]),Fe=Me.mul(s);if(I===0)a=He.sub(Fe.matMul(s.transpose().matMul(He)));else{var je=He.sub(Fe.matMul(s.transpose().matMul(He)));a=a.slice([0,0],[I,t]).concat(je,0)}var Ue=o.slice([0,I],[e,o.shape[1]-I]);if(I===0)o=Ue.sub(Ue.matMul(s).matMul(Fe.transpose()));else{var Ze=Ue.sub(Ue.matMul(s).matMul(Fe.transpose()));o=o.slice([0,0],[e,I]).concat(Ze,1)}return[s,a,o]}),s=P[0],a=P[1],o=P[2],qr([G,oe,ue])},E=0;Et&&(o=o.slice([0,0],[e,t]),a=a.slice([0,0],[t,t])),[o,a]})}var ap=Ke({bandPart_:function(n,r,e){if(r%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+r+".");if(e%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+e+".");var t=Oe(n,"a","bandPart");if(t.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+t.rank+".");var o=t.shape,a=t.shape.slice(-2),i=a[0],s=a[1];if(!(r<=i))throw new Error("bandPart(): numLower ("+r+") must not be greater than the number of rows ("+i+").");if(!(e<=s))throw new Error("bandPart(): numUpper ("+e+") must not be greater than the number of columns ("+s+").");r<0&&(r=i),e<0&&(e=s);var u=fa(0,i,1,"int32").reshape([-1,1]),f=fa(0,s,1,"int32"),E=Ao(u,f),I=ds(E.lessEqual(It(+r,"int32")),E.greaterEqual(It(-e,"int32"))),P=Tr([i,s],t.dtype);return jn(xa(t.reshape([-1,i,s])).map(function(G){return Jo(I,G,P)})).reshape(o)}}),ip=Ke({gramSchmidt_:function(n){var r;if(Array.isArray(n)){r=!1,w(n!=null&&n.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var e=n[0].shape[0],t=function(u){w(n[u].shape[0]===e,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+n[u].shape[0]+" vs. "+e+")"})},o=1;o0)for(var E=0;E= 2, but got rank "+n.rank);if(n.rank===2)return Il(n,r);var e=n.shape.slice(0,n.shape.length-2).reduce(function(i,s){return i*s}),t=xa(n.reshape([e,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),o=[],a=[];return t.forEach(function(i){var s=Il(i,r),u=s[0],f=s[1];o.push(u),a.push(f)}),[jn(o,0).reshape(n.shape),jn(a,0).reshape(n.shape)]}}),up=Object.freeze({bandPart:ap,gramSchmidt:ip,qr:sp});function vs(n,r,e,t,o,a){t==null&&(t=.5),o==null&&(o=Number.NEGATIVE_INFINITY),a==null&&(a=0);var i=n.shape[0];return e=Math.min(e,i),w(0<=t&&t<=1,function(){return"iouThreshold must be in [0, 1], but was '"+t+"'"}),w(n.rank===2,function(){return"boxes must be a 2D tensor, but was of rank '"+n.rank+"'"}),w(n.shape[1]===4,function(){return"boxes must have 4 columns, but 2nd dimension was "+n.shape[1]}),w(r.rank===1,function(){return"scores must be a 1D tensor"}),w(r.shape[0]===i,function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+r.shape[0]}),w(0<=a&&a<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"}),{maxOutputSize:e,iouThreshold:t,scoreThreshold:o,softNmsSigma:a}}var cp=Ke({resizeBilinear_:function(n,r,e){e===void 0&&(e=!1);var t=Oe(n,"images","resizeBilinear");w(t.rank===3||t.rank===4,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+t.rank+"."}),w(r.length===2,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+r+"."});var o=t,a=!1;t.rank===3&&(a=!0,o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var i=r[0],s=r[1],u=Ve.runKernelFunc(function(f,E){return E([o]),f.resizeBilinear(o,i,s,e)},{x:o},function(f,E){return{x:function(){return Ve.runKernelFunc(function(I){return I.resizeBilinearBackprop(f,E[0],e)},{})}}},"ResizeBilinear",{alignCorners:e,newHeight:i,newWidth:s});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),lp=Ke({resizeNearestNeighbor_:function(n,r,e){e===void 0&&(e=!1);var t=Oe(n,"images","resizeNearestNeighbor");w(t.rank===3||t.rank===4,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+t.rank+"."}),w(r.length===2,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+r+"."}),w(t.dtype==="float32"||t.dtype==="int32",function(){return"`images` must have `int32` or `float32` as dtype"});var o=t,a=!1;t.rank===3&&(a=!0,o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var i=r[0],s=r[1],u=Ve.runKernelFunc(function(f,E){return E([o]),f.resizeNearestNeighbor(o,i,s,e)},{batchImages:o},function(f,E){return{batchImages:function(){return Ve.runKernelFunc(function(I){return I.resizeNearestNeighborBackprop(f,E[0],e)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),dp=Ke({nonMaxSuppression_:function(n,r,e,t,o){t===void 0&&(t=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY);var a=Oe(n,"boxes","nonMaxSuppression"),i=Oe(r,"scores","nonMaxSuppression"),s=vs(a,i,e,t,o);e=s.maxOutputSize,t=s.iouThreshold,o=s.scoreThreshold;var u={maxOutputSize:e,iouThreshold:t,scoreThreshold:o};return Ve.runKernelFunc(function(f){return f.nonMaxSuppression(a,i,e,t,o)},{boxes:a,scores:i},null,"NonMaxSuppressionV3",u)}}),fp=function(n,r,e,t,o){return t===void 0&&(t=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),x(this,void 0,void 0,function(){var a,i,s,u,f,E,I;return v(this,function(P){switch(P.label){case 0:return a=Oe(n,"boxes","nonMaxSuppressionAsync"),i=Oe(r,"scores","nonMaxSuppressionAsync"),s=vs(a,i,e,t,o),e=s.maxOutputSize,t=s.iouThreshold,o=s.scoreThreshold,[4,Promise.all([a.data(),i.data()])];case 1:return u=P.sent(),f=u[0],E=u[1],I=li(f,E,e,t,o),a!==n&&a.dispose(),i!==r&&i.dispose(),[2,I]}})})},hp=Ke({nonMaxSuppressionWithScore_:function(n,r,e,t,o,a){t===void 0&&(t=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),a===void 0&&(a=0);var i=Oe(n,"boxes","nonMaxSuppression"),s=Oe(r,"scores","nonMaxSuppression"),u=vs(i,s,e,t,o,a),f={maxOutputSize:e=u.maxOutputSize,iouThreshold:t=u.iouThreshold,scoreThreshold:o=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},E=Ve.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},f);return{selectedIndices:E[0],selectedScores:E[1]}}}),pp=function(n,r,e,t,o,a){return t===void 0&&(t=.5),o===void 0&&(o=Number.NEGATIVE_INFINITY),a===void 0&&(a=0),x(this,void 0,void 0,function(){var i,s,u,f,E,I,P;return v(this,function(G){switch(G.label){case 0:return i=Oe(n,"boxes","nonMaxSuppressionAsync"),s=Oe(r,"scores","nonMaxSuppressionAsync"),u=vs(i,s,e,t,o,a),e=u.maxOutputSize,t=u.iouThreshold,o=u.scoreThreshold,a=u.softNmsSigma,[4,Promise.all([i.data(),s.data()])];case 1:return f=G.sent(),E=f[0],I=f[1],P=di(E,I,e,t,o,a),i!==n&&i.dispose(),s!==r&&s.dispose(),[2,P]}})})},mp=Ke({cropAndResize_:function(n,r,e,t,o,a){var i=Oe(n,"image","cropAndResize"),s=Oe(r,"boxes","cropAndResize","float32"),u=Oe(e,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var f=s.shape[0];return w(i.rank===4,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."}),w(s.rank===2&&s.shape[1]===4,function(){return"Error in cropAndResize: boxes must be have size ["+f+",4] but had shape "+s.shape+"."}),w(u.rank===1&&u.shape[0]===f,function(){return"Error in cropAndResize: boxInd must be have size ["+f+"] but had shape "+s.shape+"."}),w(t.length===2,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+t.length+"."}),w(t[0]>=1&&t[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+t}),w(o==="bilinear"||o==="nearest",function(){return"method must be bilinear or nearest, but was "+o}),Ve.runKernelFunc(function(E,I){return E.cropAndResize(i,s,u,t,o,a)},{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:a,cropSize:t})}}),Dl=Object.freeze({resizeBilinear:cp,resizeNearestNeighbor:lp,nonMaxSuppression:dp,nonMaxSuppressionAsync:fp,nonMaxSuppressionWithScore:hp,nonMaxSuppressionWithScoreAsync:pp,cropAndResize:mp}),Cu=function(n,r){return!(n>0)||r==="linear"},Tu=function(n,r,e){if(e==null||e==="linear")return n;if(e==="relu")return n.mul(r.step());throw new Error("Gradient for activation "+e+" has not been implemented yet.")},Su=function(n,r){var e=r,t=Ir(n.shape,r.shape);return t.length>0&&(e=e.sum(t)),e.reshape(n.shape)},Au=function(n,r,e){if(r==="linear")return n;if(r==="relu")return bu(n);if(r==="elu")return wl(n);if(r==="relu6")return _l(n);if(r==="prelu")return El(n,e);throw new Error("Unknown fused activation "+r+".")},vp=Ke({fusedMatMul_:function(n){var r,e=n.a,t=n.b,o=n.transposeA,a=o!==void 0&&o,i=n.transposeB,s=i!==void 0&&i,u=n.bias,f=n.activation,E=f===void 0?"linear":f,I=n.preluActivationWeights;if(Cu(Ve.state.gradientDepth,E)===!1){var P=yu(e,t,a,s);return u!=null&&(P=qo(P,u)),Au(P,E,I)}var G=Oe(e,"a","fused matMul"),oe=Oe(t,"b","fused matMul");r=cr(G,oe),G=r[0],oe=r[1];var ue=a?G.shape[G.rank-2]:G.shape[G.rank-1],ie=s?oe.shape[oe.rank-1]:oe.shape[oe.rank-2],ce=a?G.shape[G.rank-1]:G.shape[G.rank-2],ye=s?oe.shape[oe.rank-2]:oe.shape[oe.rank-1],we=G.shape.slice(0,-2),Ee=oe.shape.slice(0,-2),Se=le(we),Me=le(Ee);w(G.rank>=2&&oe.rank>=2&&G.rank===oe.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+G.rank+" and "+oe.rank+"."}),w(_e(we,Ee),function(){return"Error in fused matMul: outer dimensions ("+we+") and ("+Ee+") of Tensors with shapes "+G.shape+" and "+oe.shape+" must match."}),w(ue===ie,function(){return"Error in fused matMul: inner shapes ("+ue+") and ("+ie+") of Tensors with shapes "+G.shape+" and "+oe.shape+" and transposeA="+a+" and transposeB="+s+" must match."});var He,Fe,je=G.shape.slice(0,-2).concat([ce,ye]),Ue=a?G.as3D(Se,ue,ce):G.as3D(Se,ce,ue),Ze=s?oe.as3D(Me,ye,ie):oe.as3D(Me,ie,ye);u!=null&&Ht(je,(He=cr(He=Oe(u,"bias","fused matMul"),G)[0]).shape),I!=null&&(Fe=Oe(I,"prelu weights","fused matMul"));var Je={a:Ue,b:Ze};u!=null&&(Je.bias=He),I!=null&&(Je.preluActivationWeights=Fe);var dt=[Ue,Ze];return Ve.runKernelFunc(function(ct,st){var pt=ct.fusedBatchMatMul({a:Ue,b:Ze,transposeA:a,transposeB:s,bias:He,activation:E,preluActivationWeights:Fe});return st([Ue,Ze,pt]),pt},Je,function(ct,st){var pt=st[0],ht=st[1],ut=st[2],gt=Tu(ct,ut,E),yt={};return u!=null&&(yt={bias:function(){return Su(He,gt)}}),a||s?!a&&s?Object.assign({a:function(){return gt.matMul(ht,!1,!1)},b:function(){return gt.matMul(pt,!0,!1)}},yt):a&&!s?Object.assign({a:function(){return ht.matMul(gt,!1,!0)},b:function(){return pt.matMul(gt,!1,!1)}},yt):Object.assign({a:function(){return ht.matMul(gt,!0,!0)},b:function(){return gt.matMul(pt,!0,!0)}},yt):Object.assign({a:function(){return gt.matMul(ht,!1,!0)},b:function(){return pt.matMul(gt,!0,!1)}},yt)},"_FusedMatMul",{transposeA:a,transposeB:s,activation:E},dt,[!0]).reshape(je)}}),gp=Ke({fusedConv2d_:function(n){var r=n.x,e=n.filter,t=n.strides,o=n.pad,a=n.dataFormat,i=a===void 0?"NHWC":a,s=n.dilations,u=s===void 0?[1,1]:s,f=n.dimRoundingMode,E=n.bias,I=n.activation,P=I===void 0?"linear":I,G=n.preluActivationWeights;if(P=P||"linear",Cu(Ve.state.gradientDepth,P)===!1){var oe=Da(r,e,t,o,i,u,f);return E!=null&&(oe=qo(oe,E)),Au(oe,P,G)}var ue=Oe(r,"x","conv2d"),ie=Oe(e,"filter","conv2d"),ce=ue,ye=!1;ue.rank===3&&(ye=!0,ce=ue.as4D(1,ue.shape[0],ue.shape[1],ue.shape[2])),w(ce.rank===4,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+ce.rank+"."}),w(ie.rank===4,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+ie.rank+"."}),f!=null&&w(se(o),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+f+" but got pad "+o+"."}),w(ce.shape[3]===ie.shape[2],function(){return"Error in conv2d: depth of input ("+ce.shape[3]+") must match input depth for filter "+ie.shape[2]+"."}),w(Zr(t,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+t+" and dilations '"+u+"'"}),w(i==="NHWC",function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."});var we,Ee,Se=Fn(ce.shape,ie.shape,t,u,o,f);E!=null&&(we=cr(we=Oe(E,"bias","fused conv2d"),ue)[0],Ht(Se.outShape,we.shape)),G!=null&&(Ee=Oe(G,"prelu weights","fused conv2d"));var Me={x:ce,filter:ie};E!=null&&(Me.bias=we),G!=null&&(Me.preluActivationWeights=Ee);var He=[ie,ce],Fe=Ve.runKernelFunc(function(je,Ue){var Ze=je.fusedConv2d({input:ce,filter:ie,convInfo:Se,bias:we,activation:P,preluActivationWeights:Ee});return Ue([ie,ce,Ze]),Ze},Me,function(je,Ue){var Ze=Ue,Je=Ze[0],dt=Ze[1],ct=Ze[2],st=Tu(je,ct,P);w(So(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var pt={};return E!=null&&(pt={bias:function(){return Su(we,st)}}),Object.assign({x:function(){return cl(dt.shape,st,Je,t,o)},filter:function(){return gu(dt,st,Je.shape,t,o)}},pt)},"FusedConv2D",{convInfo:Se,activation:P},He,[!0]);return ye?Fe.as3D(Fe.shape[1],Fe.shape[2],Fe.shape[3]):Fe}}),yp=Ke({fusedDepthwiseConv2d_:function(n){var r=n.x,e=n.filter,t=n.strides,o=n.pad,a=n.dataFormat,i=a===void 0?"NHWC":a,s=n.dilations,u=s===void 0?[1,1]:s,f=n.dimRoundingMode,E=n.bias,I=n.activation,P=I===void 0?"linear":I,G=n.preluActivationWeights;if(Cu(Ve.state.gradientDepth,P)===!1){var oe=ps(r,e,t,o,i,u,f);return E!=null&&(oe=qo(oe,E)),Au(oe,P,G)}var ue=Oe(r,"x","depthwiseConv2d"),ie=Oe(e,"filter","depthwiseConv2d"),ce=ue,ye=!1;ue.rank===3&&(ye=!0,ce=ue.as4D(1,ue.shape[0],ue.shape[1],ue.shape[2])),w(ce.rank===4,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+ce.rank+"."}),w(ie.rank===4,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+ie.rank+"."}),w(ce.shape[3]===ie.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels ("+ce.shape[3]+") must match the inChannels dimension in filter "+ie.shape[2]+"."}),u==null&&(u=[1,1]),w(Zr(t,u),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+t+" and dilations '"+u+"'"}),f!=null&&w(se(o),function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+f+" but got pad "+o+"."});var we,Ee,Se=Fn(ce.shape,ie.shape,t,u,o,f,!0);E!=null&&(we=cr(we=Oe(E,"bias","fused conv2d"),ue)[0],Ht(Se.outShape,we.shape)),G!=null&&(Ee=Oe(G,"prelu weights","fused depthwiseConv2d"));var Me={x:ce,filter:ie};E!=null&&(Me.bias=we),G!=null&&(Me.preluActivationWeights=Ee);var He=[ie,ce],Fe=Ve.runKernelFunc(function(je,Ue){var Ze=je.fusedDepthwiseConv2D({input:ce,filter:ie,convInfo:Se,bias:we,activation:P,preluActivationWeights:Ee});return Ue([ie,ce,Ze]),Ze},Me,function(je,Ue){w(So(u),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"});var Ze=Ue[0],Je=Ue[1],dt=Ue[2],ct=Tu(je,dt,P),st={};return E!=null&&(st={bias:function(){return Su(we,ct)}}),Object.assign({x:function(){return ll(Je.shape,ct,Ze,Se)},filter:function(){return dl(Je,ct,Ze.shape,Se)}},st)},"FusedDepthwiseConv2D",{convInfo:Se,activation:P},He,[!0]);return ye?Fe.as3D(Fe.shape[1],Fe.shape[2],Fe.shape[3]):Fe}}),bp=Object.freeze({matMul:vp,conv2d:gp,depthwiseConv2d:yp}),xp=Object.freeze({image:Dl,linalg:up,losses:op,spectral:zh,fused:bp,signal:Yh,square:Zd,squaredDifference:zc,conv1d:ch,conv2d:Da,conv3d:lh,depthwiseConv2d:ps,separableConv2d:fl,conv2dTranspose:dh,conv3dTranspose:fh,op:Ke,batchNormalization2d:If,batchNormalization3d:Df,batchNormalization4d:Nf,batchNormalization:kf,batchNorm:qc,batchNorm2d:Mf,batchNorm3d:Pf,batchNorm4d:Lf,booleanMaskAsync:uh,complex:xr,real:un,imag:xn,concat:hn,concat1d:Os,concat2d:Rs,concat3d:ha,concat4d:Is,split:Bo,matMul:yu,dot:hh,outerProduct:ph,reverse:_i,reverse1d:mh,reverse2d:vh,reverse3d:gh,reverse4d:yh,maxPool:ml,avgPool:vl,pool:bh,maxPool3d:xh,avgPool3d:wh,slice:no,slice1d:Eh,slice2d:_h,slice3d:gl,slice4d:Ch,abs:ef,acos:tf,acosh:rf,asin:nf,asinh:of,atan:af,atanh:sf,ceil:uf,clipByValue:Gc,cos:cf,cosh:lf,erf:df,exp:Vc,expm1:ff,floor:hf,log:pf,log1p:mf,logSigmoid:vf,neg:hu,reciprocal:gf,round:yf,rsqrt:Xc,sigmoid:Kc,sign:bf,isNaN:xf,isInf:wf,isFinite:Ef,sin:_f,sinh:Cf,softplus:Tf,sqrt:Sf,step:Af,tan:Of,tanh:Rf,all:Th,any:Sh,argMax:Ah,argMin:Oh,logSumExp:Rh,max:bl,mean:Ih,min:Dh,moments:Nh,sum:xl,prod:kh,equal:rl,equalStrict:Qf,greater:Zf,greaterEqual:nl,greaterEqualStrict:eh,greaterStrict:th,less:rh,lessEqual:nh,lessEqualStrict:oh,lessStrict:ah,notEqual:ih,notEqualStrict:sh,add:qo,addN:Bf,addStrict:Uf,atan2:Wf,div:fs,divNoNan:Hf,divStrict:zf,floorDiv:el,maximum:pu,maximumStrict:Gf,minimum:tl,minimumStrict:Vf,mod:Xf,modStrict:Kf,mul:Qo,mulStrict:Yf,pow:hs,powStrict:$f,squaredDifferenceStrict:Jf,sub:Ao,subStrict:qf,elu:wl,leakyRelu:Mh,prelu:El,relu:bu,relu6:_l,selu:Ph,logicalAnd:ds,logicalNot:jf,logicalOr:Qc,logicalXor:Ff,where:Jo,whereAsync:Zc,buffer:jt,print:ma,batchToSpaceND:va,broadcastTo:Ps,cast:ga,clone:ya,cumsum:Ls,depthToSpace:js,expandDims:On,eye:Hi,multinomial:ti,oneHot:ri,pad:Ln,pad1d:zi,pad2d:Eo,pad3d:ni,pad4d:Fs,rand:Bs,randomNormal:Us,randomGamma:Ws,randomUniform:oi,reshape:ba,spaceToBatchND:Gi,squeeze:Vi,stack:jn,tile:eo,truncatedNormal:Hs,unstack:xa,setdiff1dAsync:zs,fill:ei,linspace:sc,ones:Mn,range:fa,scalar:It,tensor:Ur,tensor1d:Qn,tensor2d:Zn,tensor3d:Za,tensor4d:kn,tensor5d:xo,tensor6d:As,variable:wo,zeros:Tr,onesLike:Bi,zerosLike:Jt,transpose:Cl,softmax:zo,logSoftmax:si,localResponseNormalization:Lh,norm:Tl,gather:mu,unsortedSegmentSum:il,basicLSTMCell:jh,multiRNNCell:Fh,movingAverage:Bh,stridedSlice:Uh,topk:Wh,scatterND:Hh,fft:xu,ifft:ms,rfft:wu,irfft:Sl,sparseToDense:Gh,gatherND:Vh,diag:Xh,dropout:Kh,hannWindow:Eu,hammingWindow:Ol,frame:_u,stft:Rl,inTopKAsync:$h});function ft(n,r){Array.isArray(n)||(n=[n]),n.forEach(function(e){e!=null&&w(e.dtype!=="complex64",function(){return r+" does not support complex64 tensors."})})}function Ou(n,r,e,t){if(e==="linear")return n.linear(r);if(e==="relu")return n.relu(r);if(e==="elu")return n.elu(r);if(e==="relu6")return n.relu6(r);if(e==="prelu")return n.prelu(r,t);throw new Error("Activation "+e+" has not been implemented for the CPU backend.")}var wp=function(n){function r(){var e=n.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new _a(e,Ve),e}return A(r,n),r.prototype.write=function(e,t,o){this.firstUse&&(this.firstUse=!1,c().get("IS_NODE")&&da(` ============================ Hi there \u{1F44B}. 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. ============================`));var a={};return this.data.set(a,{values:e,dtype:o}),a},r.prototype.move=function(e,t,o,a){this.data.set(e,{values:t,dtype:a})},r.prototype.numDataIds=function(){return this.data.numDataIds()},r.prototype.read=function(e){return x(this,void 0,void 0,function(){return v(this,function(t){return[2,this.readSync(e)]})})},r.prototype.readSync=function(e){var t=this.data.get(e),o=t.dtype,a=t.complexTensors;return o==="complex64"?Oa(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.data.get(e).values},r.prototype.bufferSync=function(e){var t=this.readSync(e.dataId),o=t;if(e.dtype==="string")try{o=t.map(function(a){return rt(a)})}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return jt(e.shape,e.dtype,o)},r.prototype.makeOutput=function(e,t,o){var a=this.write(e,t,o);return Ve.makeTensorFromDataId(a,t,o,this)},r.prototype.disposeData=function(e){if(this.data.has(e)){var t=this.data.get(e).complexTensors;t!=null&&(t.real.dispose(),t.imag.dispose()),this.data.delete(e)}},r.prototype.time=function(e){return x(this,void 0,void 0,function(){var t;return v(this,function(o){return t=Re(),e(),[2,{kernelMs:Re()-t}]})})},r.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},r.prototype.complex=function(e,t){var o=this.makeOutput(null,e.shape,"complex64");return this.data.get(o.dataId).complexTensors={real:Ve.keep(e.clone()),imag:Ve.keep(t.clone())},o},r.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},r.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},r.prototype.slice=function(e,t,o){if(ft(e,"slice"),Ji(e.shape,t,o)){var a=qi(t,e.strides),i=le(o);return Ur(this.readSync(e.dataId).subarray(a,a+i),o,e.dtype)}for(var s=jt(o,e.dtype),u=this.bufferSync(e),f=0;foe&&(oe=ce,ue=ie)}E[P]=ue}return u},r.prototype.cumsum=function(e,t,o,a){if(ft(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);for(var i=nr(e.dtype,"int32"),s=Tr(e.shape,i),u=this.readSync(s.dataId),f=this.readSync(e.dataId),E=e.shape[e.rank-1],I=a?function(ie,ce){return ie+E-ce-1}:function(ie,ce){return ie+ce},P=0;Pa?1:0})},r.prototype.greaterEqual=function(e,t){return ft([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",function(o,a){return o>=a?1:0})},r.prototype.logicalNot=function(e){ft(e,"logicalNot");for(var t=this.readSync(e.dataId),o=new Uint8Array(t.length),a=0;a1||t.rank===1?1:le(t.shape.slice(1)),P=0;P=0&&a>=0?i:(i+a)%a})},r.prototype.max=function(e,t){ft(e,"max"),on("max",t,e.rank);for(var o=Gr(e.shape,t),a=o[0],i=o[1],s=Tr(a,e.dtype),u=le(i),f=this.readSync(s.dataId),E=this.readSync(e.dataId),I=0;IG&&(G=ue)}f[I]=G}return s},r.prototype.maximum=function(e,t){return ft([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,function(o,a){return Math.max(o,a)})},r.prototype.all=function(e,t){ft(e,"all"),on("all",t,e.rank);for(var o=Gr(e.shape,t),a=o[0],i=o[1],s=Tr(a,e.dtype),u=le(i),f=this.readSync(s.dataId),E=this.readSync(e.dataId),I=0;I0?o[a]=1:o[a]=0;return this.makeOutput(o,e.shape,"float32")},r.prototype.isNaN=function(e){ft(e,"x");for(var t=this.readSync(e.dataId),o=new Uint8Array(t.length),a=0;a.5?o[a]=Math.ceil(t[a]):o[a]=i%2==0?i:i+1}return this.makeOutput(o,e.shape,"float32")},r.prototype.exp=function(e){ft(e,"exp");for(var t=this.readSync(e.dataId),o=new Float32Array(t.length),a=0;a=0?i:Math.exp(i)-1}return this.makeOutput(t,e.shape,"float32")},r.prototype.eluDer=function(e,t){ft([e,t],"eluDer");for(var o=new Float32Array(t.size),a=this.readSync(t.dataId),i=this.readSync(e.dataId),s=0;s=1?i[s]:i[s]*(u+1)}return this.makeOutput(o,t.shape,"float32")},r.prototype.selu=function(e){ft(e,"selu");for(var t=du,o=fu,a=new Float32Array(e.size),i=this.readSync(e.dataId),s=0;s=0?o*u:t*(Math.exp(u)-1)}return this.makeOutput(a,e.shape,"float32")},r.prototype.clip=function(e,t,o){ft(e,"clip");for(var a=new Float32Array(e.size),i=this.readSync(e.dataId),s=0;so?o:u-t,u=a[i]0?1:t}return this.makeOutput(o,e.shape,"float32")},r.prototype.fusedConv2d=function(e){var t=e.input,o=e.filter,a=e.convInfo,i=e.bias,s=e.activation,u=e.preluActivationWeights,f=this.conv2d(t,o,a);return i&&(f=this.add(f,i)),s&&(f=Ou(this,f,s,u)),f},r.prototype.conv2d=function(e,t,o){ft([e,t],"conv2d");for(var a=o.filterHeight,i=o.filterWidth,s=o.dilationHeight,u=o.dilationWidth,f=o.padInfo.left,E=o.padInfo.top,I=o.dataFormat==="channelsLast",P=jt(o.outShape,e.dtype),G=e.strides[0],oe=I?e.strides[1]:e.strides[2],ue=I?e.strides[2]:1,ie=I?1:e.strides[1],ce=P.strides[0],ye=I?P.strides[1]:P.strides[2],we=I?P.strides[2]:1,Ee=I?1:P.strides[1],Se=this.readSync(e.dataId),Me=this.readSync(t.dataId),He=P.values,Fe=0;Fe=o.inHeight))for(var pt=ct*t.strides[0],ht=je+st*oe,ut=0;ut=o.inWidth))for(var Pt=ht+Mt*ue,Kt=pt+Ot*t.strides[1],Yt=0;Yt=o.inDepth))for(var Ue=Fe*t.strides[0],Ze=we+je*e.strides[1],Je=0;Je=o.inHeight))for(var ht=Ue+st*t.strides[1],ut=Ze+pt*e.strides[2],gt=0;gt=o.inWidth))for(var Kt=ht+Mt*t.strides[2],Yt=ut+Pt*o.inChannels,$t=Kt,ar=0;ar=o.inHeight))for(var Fe=Me*t.strides[0],je=ce+He*e.strides[1],Ue=0;Ue=o.inWidth))for(var st=Fe+dt*t.strides[1],pt=je+ct*o.inChannels,ht=Ze,ut=st,gt=0;gtht?ht=Pt:o==="avg"&&(ut+=Pt,gt++)}if(isNaN(ht))break}ie[Je+dt*we+He]=o==="avg"?ut/gt:ht}return ue.toTensor()},r.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},r.prototype.maxPoolPositions=function(e,t){for(var o=jt(t.outShape,"int32"),a=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,f=t.effectiveFilterHeight,E=t.effectiveFilterWidth,I=t.padInfo.top,P=t.padInfo.left,G=this.bufferSync(e),oe=0;oeFe&&(Fe=ct,je=Ze*E+dt)}o.set(je,oe,ie,Ee,ue)}}return o.toTensor()},r.prototype.maxPoolBackprop=function(e,t,o,a){ft([t,o],"maxPoolBackprop");for(var i=this.maxPoolPositions(t,a),s=a.strideHeight,u=a.strideWidth,f=a.dilationHeight,E=a.dilationWidth,I=a.effectiveFilterHeight,P=a.effectiveFilterWidth,G=P-1-a.padInfo.left,oe=I-1-a.padInfo.top,ue=jt(t.shape,"float32"),ie=this.bufferSync(i),ce=this.bufferSync(e),ye=0;ye=a.outHeight||Math.floor(Ue)!==Ue))for(var Ze=0;Ze=a.outWidth||Math.floor(Je)!==Je)){var dt=I*P-1-ie.get(ye,Ue,Je,we)===je*P+Ze?1:0;dt!==0&&(Fe+=ce.get(ye,Ue,Je,we)*dt)}}}ue.set(Fe,ye,Ee,Se,we)}return ue.toTensor()},r.prototype.avgPoolBackprop=function(e,t,o){ft([e,t],"avgPoolBackprop");for(var a=o.strideHeight,i=o.strideWidth,s=o.filterHeight,u=o.filterWidth,f=o.dilationHeight,E=o.dilationWidth,I=o.effectiveFilterHeight,P=o.effectiveFilterWidth,G=P-1-o.padInfo.left,oe=I-1-o.padInfo.top,ue=jt(t.shape,"float32"),ie=1/(s*u),ce=this.bufferSync(e),ye=0;ye=o.outHeight||Math.floor(Ue)!==Ue))for(var Ze=0;Ze=o.outWidth||Math.floor(Je)!==Je||(Fe+=ce.get(ye,Ue,Je,we))}}ue.set(Fe*ie,ye,Ee,Se,we)}return ue.toTensor()},r.prototype.pool3d=function(e,t,o){ft(e,"pool3d");for(var a=t.strideDepth,i=t.strideHeight,s=t.strideWidth,u=t.dilationDepth,f=t.dilationHeight,E=t.dilationWidth,I=t.effectiveFilterDepth,P=t.effectiveFilterHeight,G=t.effectiveFilterWidth,oe=t.padInfo.front,ue=t.padInfo.top,ie=t.padInfo.left,ce=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,ye=this.readSync(e.dataId),we=jt(t.outShape,e.dtype),Ee=we.values,Se=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],Me=t.outShape[2]*t.outShape[3]*t.outShape[4],He=t.outShape[3]*t.outShape[4],Fe=t.outShape[4],je=0;jeer?er=Pr:o==="avg"&&(ir+=Pr,Fr++),isNaN(er))break}if(isNaN(er))break}if(isNaN(er))break}Ee[ar+Je]=o==="avg"?ir/Fr:er}}}return we.toTensor()},r.prototype.avgPool3d=function(e,t){return ft(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()},r.prototype.avgPool3dBackprop=function(e,t,o){ft([e,t],"avgPool3dBackprop");for(var a=o.strideDepth,i=o.strideHeight,s=o.strideWidth,u=o.filterDepth,f=o.filterHeight,E=o.filterWidth,I=o.dilationDepth,P=o.dilationHeight,G=o.dilationWidth,oe=o.effectiveFilterDepth,ue=o.effectiveFilterHeight,ie=o.effectiveFilterWidth,ce=oe-1-o.padInfo.front,ye=ie-1-o.padInfo.left,we=ue-1-o.padInfo.top,Ee=jt(t.shape,"float32"),Se=1/(u*f*E),Me=this.bufferSync(e),He=0;He=o.outDepth||Math.floor(ht)!==ht))for(var ut=0;ut=o.outHeight||Math.floor(gt)!==gt))for(var yt=0;yt=o.outWidth||Math.floor(Ot)!==Ot||(st+=Me.get(He,ht,gt,Ot,Fe))}}}Ee.set(st*Se,He,je,Ue,Ze,Fe)}return Ee.toTensor()},r.prototype.maxPool3d=function(e,t){return ft(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()},r.prototype.maxPool3dPositions=function(e,t){for(var o=jt(t.outShape,"int32"),a=t.strideDepth,i=t.strideHeight,s=t.strideWidth,u=t.dilationDepth,f=t.dilationHeight,E=t.dilationWidth,I=t.effectiveFilterDepth,P=t.effectiveFilterHeight,G=t.effectiveFilterWidth,oe=t.padInfo.front,ue=t.padInfo.top,ie=t.padInfo.left,ce=this.bufferSync(e),ye=0;ye=pt&&(pt=Kt,ht=gt*P*G+Ot*P+Pt)}o.set(ht,ye,Ee,Fe,Je,we)}}}return o.toTensor()},r.prototype.maxPool3dBackprop=function(e,t,o,a){ft([t,o],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(t,a),s=a.strideDepth,u=a.strideHeight,f=a.strideWidth,E=a.dilationDepth,I=a.dilationHeight,P=a.dilationWidth,G=a.effectiveFilterDepth,oe=a.effectiveFilterHeight,ue=a.effectiveFilterWidth,ie=G-1-a.padInfo.front,ce=ue-1-a.padInfo.left,ye=oe-1-a.padInfo.top,we=jt(t.shape,"float32"),Ee=this.bufferSync(i),Se=this.bufferSync(e),Me=0;Me=a.outDepth||Math.floor(pt)!==pt))for(var ht=0;ht=a.outHeight||Math.floor(ut)!==ut))for(var gt=0;gt=a.outWidth||Math.floor(yt)!==yt)){var Ot=G*oe*ue-1-Ee.get(Me,pt,ut,yt,He)===st*oe*ue+ht*ue+gt?1:0;Ot!==0&&(ct+=Se.get(Me,pt,ut,yt,He)*Ot)}}}}we.set(ct,Me,Fe,je,Ue,He)}return we.toTensor()},r.prototype.cast=function(e,t){return ci(e,t,this)},r.prototype.reshape=function(e,t){return Aa(e,t)},r.prototype.avgPool=function(e,t){return ft(e,"avgPool"),this.pool(e,t,"avg").toFloat()},r.prototype.resizeBilinear=function(e,t,o,a){ft(e,"resizeBilinear");for(var i=e.shape,s=i[0],u=i[1],f=i[2],E=i[3],I=this.readSync(e.dataId),P=new Float32Array(le([s,t,o,E])),G=[a&&t>1?u-1:u,a&&o>1?f-1:f],oe=[a&&t>1?t-1:t,a&&o>1?o-1:o],ue=0,ie=G[0]/oe[0],ce=G[1]/oe[1],ye=0;ye1?s-1:s,o&&P>1?u-1:u],ue=[o&&I>1?I-1:I,o&&P>1?P-1:P],ie=oe[0]/ue[0],ce=oe[1]/ue[1],ye=this.readSync(e.dataId),we=0,Ee=0;Ee1?u-1:u,a&&o>1?f-1:f],oe=[a&&t>1?t-1:t,a&&o>1?o-1:o],ue=G[0]/oe[0],ie=G[1]/oe[1],ce=0,ye=0;ye1?s-1:s,o&&P>1?u-1:u],ie=[o&&I>1?I-1:I,o&&P>1?P-1:P],ce=ue[0]/ie[0],ye=ue[1]/ie[1],we=1/ce,Ee=1/ye,Se=2*Math.ceil(we)+2,Me=2*Math.ceil(Ee)+2,He=0;He=I)){var Ot=Fe+yt*e.strides[1],Mt=yt*ce;if(je===Math.min(s-1,o?Math.round(Mt):Math.floor(Mt)))for(var Pt=0;Pt=P)){var Yt=Ot+Kt*e.strides[2],$t=Kt*ye;dt===Math.min(u-1,o?Math.round($t):Math.floor($t))&&(ut+=oe[Yt+ht])}}}}G[ct+ht]=ut}return kn(G,t.shape,t.dtype)},r.prototype.batchNormalization=function(e,t,o,a,i,s){ft([e,t,o,i,s],"batchNorm");for(var u=this.readSync(e.dataId),f=this.readSync(t.dataId),E=this.readSync(o.dataId),I=i?this.readSync(i.dataId):new Float32Array([1]),P=s?this.readSync(s.dataId):new Float32Array([0]),G=new Float32Array(u.length),oe=P.length,ue=I.length,ie=E.length,ce=f.length,ye=0,we=0,Ee=0,Se=0,Me=0;Me=oe&&(ye=0),we>=ce&&(we=0),Ee>=ue&&(Ee=0),Se>=ie&&(Se=0);return kn(G,e.shape)},r.prototype.localResponseNormalization4D=function(e,t,o,a,i){ft(e,"localResponseNormalization4D");var s=e.shape[3],u=s-1,f=this.readSync(e.dataId),E=e.size,I=new Float32Array(E);function P(ie){for(var ce=ie%s,ye=ie-ce+Math.max(0,ce-t),we=ie-ce+Math.min(ce+t,u),Ee=0;ye<=we;ye++){var Se=f[ye];Ee+=Se*Se}return Ee}for(var G=0;G=0&&s[u]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+t});for(var a=e.shape[0],i=e.shape[1],s=e.shape[2],u=e.shape[3],f=i*t,E=s*t,I=u/(t*t),P=this.readSync(e.dataId),G=new Float32Array(a*f*E*I),oe=0,ue=0;ue=f))for(var dt=oe>1?(Ue-Fe)*(E-1)/(oe-1):0,ct=ue>1?(Ze-je)*(I-1)/(ue-1):0,st=0;st1?Fe*(E-1)+st*dt:.5*(Fe+Ue)*(E-1);if(pt<0||pt>E-1)for(var ht=0;ht1?je*(I-1)+ht*ct:.5*(je+Ze)*(I-1))<0||tr>I-1)for(ut=0;ut1?je*(I-1)+ht*ct:.5*(je+Ze)*(I-1))<0||tr>I-1)for(ut=0;ut=e.size/f)throw new Error("Invalid indices: "+ue+" does not index into "+e.shape);for(var we=0;we=a/i)throw new Error("Invalid indices: "+ce+" does not index into "+o);for(var Se=0;Se0,function(){return"scheme must not be an empty string."});var t=n.getInstance();w(t.managers[r]==null,function(){return"A model store manager is already registered for scheme '"+r+"'."}),t.managers[r]=e},n.getManager=function(r){var e=this.getInstance().managers[r];if(e==null)throw new Error("Cannot find model manager for scheme '"+r+"'");return e},n.getSchemes=function(){return Object.keys(this.getInstance().managers)},n}();function ys(n){if(n.indexOf(ka)===-1)throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Oo.getSchemes().join(","));return{scheme:n.split(ka)[0],path:n.split(ka)[1]}}function Fl(n,r,e){return e===void 0&&(e=!1),x(this,void 0,void 0,function(){var t,o,a,i,s,u,f,E,I;return v(this,function(P){switch(P.label){case 0:return w(n!==r,function(){return"Old path and new path are the same: '"+n+"'"}),w((t=pn.getLoadHandlers(n)).length>0,function(){return"Copying failed because no load handler is found for source URL "+n+"."}),w(t.length<2,function(){return"Copying failed because more than one ("+t.length+") load handlers for source URL "+n+"."}),o=t[0],w((a=pn.getSaveHandlers(r)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+r+"."}),w(a.length<2,function(){return"Copying failed because more than one ("+t.length+") save handlers for destination URL "+r+"."}),i=a[0],s=ys(n).scheme,u=ys(n).path,f=s===ys(n).scheme,[4,o.load()];case 1:return E=P.sent(),e&&f?[4,Oo.getManager(s).removeModel(u)]:[3,3];case 2:P.sent(),P.label=3;case 3:return[4,i.save(E)];case 4:return I=P.sent(),!e||f?[3,6]:[4,Oo.getManager(s).removeModel(u)];case 5:P.sent(),P.label=6;case 6:return[2,I.modelArtifactsInfo]}})})}var Zo="models_store",Ro="model_info_store";function Bl(){if(!c().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var n=window||self,r=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(r==null)throw new Error("The current browser does not appear to support IndexedDB.");return r}function Lu(n){var r=n.result;r.createObjectStore(Zo,{keyPath:"modelPath"}),r.createObjectStore(Ro,{keyPath:"modelPath"})}var Ma=function(){function n(r){if(this.indexedDB=Bl(),r==null||!r)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=r}return n.prototype.save=function(r){return x(this,void 0,void 0,function(){return v(this,function(e){if(r.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,r)]})})},n.prototype.load=function(){return x(this,void 0,void 0,function(){return v(this,function(r){return[2,this.databaseAction(this.modelPath)]})})},n.prototype.databaseAction=function(r,e){var t=this;return new Promise(function(o,a){var i=t.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Lu(i)},i.onsuccess=function(){var s=i.result;if(e==null){var u=s.transaction(Zo,"readonly"),f=u.objectStore(Zo).get(t.modelPath);f.onsuccess=function(){if(f.result==null)return s.close(),a(new Error("Cannot find model with path '"+t.modelPath+"' in IndexedDB."));o(f.result.modelArtifacts)},f.onerror=function(ue){return s.close(),a(f.error)},u.oncomplete=function(){return s.close()}}else{var E,I=Ci(e),P=s.transaction(Ro,"readwrite"),G=P.objectStore(Ro),oe=G.put({modelPath:t.modelPath,modelArtifactsInfo:I});oe.onsuccess=function(){var ue=(E=s.transaction(Zo,"readwrite")).objectStore(Zo).put({modelPath:t.modelPath,modelArtifacts:e,modelArtifactsInfo:I});ue.onsuccess=function(){return o({modelArtifactsInfo:I})},ue.onerror=function(ie){var ce=(G=P.objectStore(Ro)).delete(t.modelPath);ce.onsuccess=function(){return s.close(),a(ue.error)},ce.onerror=function(ye){return s.close(),a(ue.error)}}},oe.onerror=function(ue){return s.close(),a(oe.error)},P.oncomplete=function(){E==null?s.close():E.oncomplete=function(){return s.close()}}}},i.onerror=function(s){return a(i.error)}})},n.URL_SCHEME="indexeddb://",n}(),Ul=function(n){return c().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(Ma.URL_SCHEME)?(r=n.slice(Ma.URL_SCHEME.length),new Ma(r)):null;var r};pn.registerSaveRouter(Ul),pn.registerLoadRouter(Ul);var Op=function(){function n(){this.indexedDB=Bl()}return n.prototype.listModels=function(){return x(this,void 0,void 0,function(){var r=this;return v(this,function(e){return[2,new Promise(function(t,o){var a=r.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return Lu(a)},a.onsuccess=function(){var i=a.result,s=i.transaction(Ro,"readonly"),u=s.objectStore(Ro).getAll();u.onsuccess=function(){for(var f={},E=0,I=u.result;E0,function(){return"promises must be a none empty array"})}(n),function(a,i){w(a>=0&&a<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+a}),w(i>=0&&i<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+i}),w(i>=a,function(){return"startFraction must be no more than endFraction, but got startFraction "+a+" and endFraction "+i})}(e=e==null?0:e,t=t==null?1:t);var o=0;return Promise.all(n.map(function(a){return a.then(function(i){var s=e+ ++o/n.length*(t-e);return r(s),i}),a}))}function Xl(n,r){return x(this,void 0,void 0,function(){var e,t,o,a,i,s,u,f,E;return v(this,function(I){switch(I.label){case 0:return r==null&&(r={}),e=r.fetchFunc==null?c().platform.fetch:r.fetchFunc,t=n.map(function(P){return e(P,r.requestInit,{isBinary:!0})}),o=0,a=.5,r.onProgress!=null?[3,2]:[4,Promise.all(t)];case 1:return i=I.sent(),[3,4];case 2:return[4,Vl(t,r.onProgress,o,a)];case 3:i=I.sent(),I.label=4;case 4:return s=i.map(function(P){return P.arrayBuffer()}),u=.5,f=1,r.onProgress!=null?[3,6]:[4,Promise.all(s)];case 5:return E=I.sent(),[3,8];case 6:return[4,Vl(s,r.onProgress,u,f)];case 7:E=I.sent(),I.label=8;case 8:return[2,E]}})})}function Kl(n){var r=this;return function(e,t,o){return t===void 0&&(t=""),x(r,void 0,void 0,function(){var a,i,s,u,f,E,I,P,G,oe;return v(this,function(ue){switch(ue.label){case 0:if(a=e.map(function(){return!1}),i={},s=o!=null?o.map(function(){return!1}):[],u=[],e.forEach(function(ie,ce){var ye=0;ie.weights.forEach(function(we){var Ee="quantization"in we?we.quantization.dtype:we.dtype,Se=ku[Ee]*le(we.shape),Me=function(){a[ce]=!0,i[ce]==null&&(i[ce]=[]),i[ce].push({manifestEntry:we,groupOffset:ye,sizeBytes:Se})};o!=null?o.forEach(function(He,Fe){He===we.name&&(Me(),s[Fe]=!0)}):Me(),u.push(we.name),ye+=Se})}),!s.every(function(ie){return ie}))throw f=o.filter(function(ie,ce){return!s[ce]}),new Error("Could not find weights in manifest with names: "+f.join(", ")+`. Manifest JSON has weights with names: `+u.join(", ")+".");return E=a.reduce(function(ie,ce,ye){return ce&&ie.push(ye),ie},[]),I=[],E.forEach(function(ie){e[ie].paths.forEach(function(ce){var ye=t+(t.endsWith("/")?"":"/")+ce;I.push(ye)})}),[4,n(I)];case 1:return P=ue.sent(),G={},oe=0,E.forEach(function(ie){for(var ce=e[ie].paths.length,ye=0,we=0;we0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(r)&&w(r.length===2,function(){return"URL paths for http must have a length of 2, (actual length is "+r.length+")."}),this.path=r,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return n.prototype.save=function(r){return x(this,void 0,void 0,function(){var e,t,o,a;return v(this,function(i){switch(i.label){case 0:if(r.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,t=[{paths:["./model.weights.bin"],weights:r.weightSpecs}],o={modelTopology:r.modelTopology,format:r.format,generatedBy:r.generatedBy,convertedBy:r.convertedBy,userDefinedMetadata:r.userDefinedMetadata,weightsManifest:t},e.body.append("model.json",new Blob([JSON.stringify(o)],{type:"application/json"}),"model.json"),r.weightData!=null&&e.body.append("model.weights.bin",new Blob([r.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=i.sent()).ok)return[2,{modelArtifactsInfo:Ci(r),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},n.prototype.load=function(){return x(this,void 0,void 0,function(){var r,e,t,o,a,i,s,u,f,E,I,P;return v(this,function(G){switch(G.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(r=G.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+r.status+". Please verify this URL points to the model JSON of the model to load.");G.label=2;case 2:return G.trys.push([2,4,,5]),[4,r.json()];case 3:return e=G.sent(),[3,5];case 4:throw G.sent(),t="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?t+=" 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.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t);case 5:if(o=e.modelTopology,a=e.weightsManifest,i=e.generatedBy,s=e.convertedBy,u=e.format,f=e.userDefinedMetadata,o==null&&a==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return a==null?[3,7]:[4,this.loadWeights(a)];case 6:P=G.sent(),E=P[0],I=P[1],G.label=7;case 7:return[2,{modelTopology:o,weightSpecs:E,weightData:I,userDefinedMetadata:f,generatedBy:i,convertedBy:s,format:u}]}})})},n.prototype.loadWeights=function(r){return x(this,void 0,void 0,function(){var e,t,o,a,i,s,u,f,E,I,P;return v(this,function(G){switch(G.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,t=function(oe){var ue=oe.lastIndexOf("/"),ie=oe.lastIndexOf("?"),ce=oe.substring(0,ue),ye=ie>ue?oe.substring(ie):"";return[ce+"/",ye]}(e),o=t[0],a=t[1],i=this.weightPathPrefix||o,s=[],u=0,f=r;u0&&Number.isInteger(e),function(){return"If provided, numClasses must be a positive integer, but got "+e}),w(t.rank===1,function(){return"Expected the rank of labels to be 1, but got "+t.rank}),w(o.rank===1,function(){return"Expected the rank of predictions to be 1, but got "+o.rank}),w(t.shape[0]===o.shape[0],function(){return"Mismatch in the number of examples: "+t.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."}),w(e>0&&Number.isInteger(e),function(){return"numClasses is required to be a positive integer, but got "+e});var a=ri(t.asType("int32"),e),i=ri(o.asType("int32"),e);return a.transpose().matMul(i).asType("int32")}}),$p=Object.freeze({confusionMatrix:Wp}),Hp=Ke({fromPixels_:function(n,r){if(r===void 0&&(r=3),r>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=!1,t=!1,o=!1,a=!1,i=!1;if(n.data instanceof Uint8Array)e=!0;else if(typeof ImageData!="undefined"&&n instanceof ImageData)t=!0;else if(typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement)a=!0;else{if(n.getContext==null)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 "+n.constructor.name);i=!0}if(o&&(o&&n.readyState<2))throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the