/*! For license information please see whatIfService.min.js.LICENSE.txt */ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n=e();for(var r in n)("object"==typeof exports?exports:t)[r]=n[r]}}(self,(function(){return(()=>{var t={714:(t,e,n)=>{"use strict";n.r(e),n.d(e,{AdadeltaOptimizer:()=>vf,AdagradOptimizer:()=>yf,AdamOptimizer:()=>bf,AdamaxOptimizer:()=>xf,Add:()=>vr,AddN:()=>yr,BroadcastTo:()=>kr,Callback:()=>wb,CallbackList:()=>Km,CustomCallback:()=>Jm,DataStorage:()=>ii,Div:()=>br,ENV:()=>p,EarlyStopping:()=>Ib,Environment:()=>u,FromPixels:()=>Rr,FusedBatchNorm:()=>xr,GraphModel:()=>Ex,History:()=>Ym,Identity:()=>Er,InputSpec:()=>Fm,KernelBackend:()=>oi,LayerVariable:()=>Dm,LayersModel:()=>rv,MaxPoolWithArgmax:()=>Dr,MomentumOptimizer:()=>Cf,NonMaxSuppressionV5:()=>Sr,OneHot:()=>Ir,Optimizer:()=>gf,PadV2:()=>Tr,RMSPropOptimizer:()=>Nf,RNN:()=>Ky,Rank:()=>Ct,Reduction:()=>ep,SGDOptimizer:()=>wf,Sequential:()=>iv,Square:()=>Cr,SquaredDifference:()=>wr,SymbolicTensor:()=>Mm,Tensor:()=>wt,TensorBuffer:()=>vt,Tile:()=>Ar,Transpose:()=>Nr,Variable:()=>Et,abs:()=>zr,acos:()=>Lr,acosh:()=>Br,add:()=>Or,addN:()=>Eu,addStrict:()=>ga,all:()=>xc,any:()=>wc,argMax:()=>Cc,argMin:()=>Nc,asin:()=>Pr,asinh:()=>Wr,atan:()=>Vr,atan2:()=>va,atanh:()=>Ur,avgPool:()=>lc,avgPool3d:()=>hc,backend:()=>ln,backend_util:()=>Ni,basicLSTMCell:()=>Pc,batchNorm:()=>_u,batchNorm2d:()=>zu,batchNorm3d:()=>Pu,batchNorm4d:()=>Uu,batchNormalization:()=>Ou,batchNormalization2d:()=>Mu,batchNormalization3d:()=>Bu,batchNormalization4d:()=>Vu,batchToSpaceND:()=>er,booleanMaskAsync:()=>Ll,broadcastTo:()=>ju,browser:()=>lf,buffer:()=>Qn,callbacks:()=>Eb,cast:()=>nr,ceil:()=>jr,clipByValue:()=>Gr,clone:()=>Gu,complex:()=>En,concat:()=>Kn,concat1d:()=>Xn,concat2d:()=>Yn,concat3d:()=>Jn,concat4d:()=>$n,constraints:()=>md,conv1d:()=>Vl,conv2d:()=>Ul,conv2dTranspose:()=>Jl,conv3d:()=>jl,conv3dTranspose:()=>$l,cos:()=>qr,cosh:()=>Hr,cumsum:()=>rr,customGrad:()=>ti,data:()=>r,deprecationWarn:()=>He,depthToSpace:()=>ar,depthwiseConv2d:()=>Hl,deregisterOp:()=>Fb,diag:()=>Zc,disableDeprecationWarnings:()=>qe,dispose:()=>Ze,disposeVariables:()=>Ke,div:()=>_a,divNoNan:()=>$u,divStrict:()=>ya,dot:()=>Ql,dropout:()=>Qc,elu:()=>Dc,enableDebugMode:()=>Ge,enableProdMode:()=>je,engine:()=>Xe,env:()=>c,equal:()=>wl,equalStrict:()=>Cl,erf:()=>Kr,exp:()=>Xr,expandDims:()=>ir,expm1:()=>Yr,eye:()=>Qu,fft:()=>qc,fill:()=>Un,findBackend:()=>on,findBackendFactory:()=>sn,floor:()=>Jr,floorDiv:()=>ba,frame:()=>ap,fused:()=>Lp,gather:()=>Ml,gatherND:()=>$c,gather_util:()=>Ma,getBackend:()=>rn,getGradient:()=>m,getKernel:()=>d,getKernelsForBackend:()=>g,grad:()=>Ya,grads:()=>Ja,greater:()=>Nl,greaterEqual:()=>Sl,greaterEqualStrict:()=>kl,greaterStrict:()=>Il,hammingWindow:()=>rp,hannWindow:()=>np,ifft:()=>Hc,imag:()=>Tn,image:()=>Tp,inTopKAsync:()=>sp,initializers:()=>xm,input:()=>lv,io:()=>af,irfft:()=>Xc,isFinite:()=>ua,isInf:()=>sa,isNaN:()=>oa,keep:()=>Qe,layers:()=>vb,leakyRelu:()=>Oc,less:()=>El,lessEqual:()=>Al,lessEqualStrict:()=>Tl,lessStrict:()=>Rl,linalg:()=>Cp,linspace:()=>jn,loadGraphModel:()=>Ax,loadLayersModel:()=>uv,localResponseNormalization:()=>Lc,log:()=>$r,log1p:()=>Zr,logSigmoid:()=>Qr,logSoftmax:()=>ri,logSumExp:()=>Sc,logicalAnd:()=>qu,logicalNot:()=>Hu,logicalOr:()=>Ku,logicalXor:()=>Xu,losses:()=>vp,matMul:()=>Zl,math:()=>sf,max:()=>kc,maxPool:()=>uc,maxPool3d:()=>pc,maxPoolWithArgmax:()=>fc,maximum:()=>xa,maximumStrict:()=>wa,mean:()=>Ic,memory:()=>Ye,metrics:()=>yb,min:()=>Ec,minimum:()=>Ca,minimumStrict:()=>Na,mod:()=>Sa,modStrict:()=>ka,model:()=>ov,models:()=>bb,moments:()=>Ac,movingAverage:()=>Vc,mul:()=>Ia,mulStrict:()=>Ea,multiRNNCell:()=>Wc,multinomial:()=>tl,neg:()=>ta,nextFrame:()=>Ef,norm:()=>Bc,notEqual:()=>Dl,notEqualStrict:()=>Ol,oneHot:()=>el,ones:()=>Wn,onesLike:()=>qn,op:()=>In,outerProduct:()=>tc,pad:()=>nl,pad1d:()=>rl,pad2d:()=>al,pad3d:()=>il,pad4d:()=>ol,pool:()=>cc,pow:()=>Aa,powStrict:()=>Ta,prelu:()=>_c,print:()=>tr,prod:()=>Rc,profile:()=>Je,rand:()=>sl,randomGamma:()=>ml,randomNormal:()=>gl,randomUniform:()=>vl,range:()=>Gn,ready:()=>nn,real:()=>An,reciprocal:()=>ea,registerBackend:()=>un,registerCallbackConstructor:()=>cv,registerGradient:()=>y,registerKernel:()=>v,registerOp:()=>Ob,regularizers:()=>xb,relu:()=>Fc,relu6:()=>Mc,removeBackend:()=>an,reshape:()=>or,reverse:()=>ec,reverse1d:()=>nc,reverse2d:()=>rc,reverse3d:()=>ac,reverse4d:()=>ic,rfft:()=>Kc,round:()=>na,rsqrt:()=>ra,scalar:()=>On,scatterND:()=>Gc,scatter_util:()=>Wa,selu:()=>zc,separableConv2d:()=>Yl,sequential:()=>sv,serialization:()=>ff,setBackend:()=>en,setPlatform:()=>cn,setdiff1dAsync:()=>pr,sigmoid:()=>aa,sign:()=>ia,signal:()=>op,sin:()=>la,sinh:()=>ca,slice:()=>dc,slice1d:()=>mc,slice2d:()=>gc,slice3d:()=>vc,slice4d:()=>yc,slice_util:()=>Xa,softmax:()=>ni,softplus:()=>pa,spaceToBatchND:()=>sr,sparseToDense:()=>Jc,spectral:()=>Yc,split:()=>Zn,sqrt:()=>ha,square:()=>yl,squaredDifference:()=>bl,squaredDifferenceStrict:()=>Ra,squeeze:()=>ur,stack:()=>lr,step:()=>fa,stft:()=>ip,stridedSlice:()=>Uc,sub:()=>Da,subStrict:()=>Oa,sum:()=>Tc,sumOutType:()=>Rt,tan:()=>da,tanh:()=>ma,tensor:()=>Rn,tensor1d:()=>_n,tensor2d:()=>Fn,tensor3d:()=>Mn,tensor4d:()=>zn,tensor5d:()=>Ln,tensor6d:()=>Bn,tensor_util:()=>Mt,test_util:()=>pl,tidy:()=>$e,tile:()=>Zu,time:()=>tn,topk:()=>jc,train:()=>kf,transpose:()=>ai,truncatedNormal:()=>xl,unregisterGradient:()=>x,unregisterKernel:()=>b,unsortedSegmentSum:()=>zl,unstack:()=>cr,util:()=>pt,valueAndGrad:()=>$a,valueAndGrads:()=>Za,variable:()=>Pn,variableGrads:()=>Qa,version:()=>nC,version_converter:()=>Tx,version_core:()=>df,version_layers:()=>Tg,webgl:()=>mf,where:()=>Yu,whereAsync:()=>Ju,zeros:()=>Vn,zerosLike:()=>Hn});var r={};n.r(r),n.d(r,{CSVDataset:()=>Fw,Dataset:()=>ww,FileDataSource:()=>Xw,TextLineDataset:()=>Ew,URLDataSource:()=>Yw,array:()=>Nw,csv:()=>Jw,func:()=>$w,generator:()=>Zw,microphone:()=>tC,version_data:()=>eC,webcam:()=>Qw,zip:()=>Sw});var a=function(t,e){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function i(t,e){function n(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function o(t,e,n,r){return new(n||(n=Promise))((function(a,i){function o(t){try{u(r.next(t))}catch(t){i(t)}}function s(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){t.done?a(t.value):new n((function(e){e(t.value)})).then(o,s)}u((r=r.apply(t,e||[])).next())}))}function s(t,e){var n,r,a,i,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function N(t,e,n){return Math.max(t,Math.min(e,n))}function S(t){return t%2==0?t:t+1}function k(t){for(var e=0,n=0;n=n?a():setTimeout(o,s)}};o()}))}function L(t,e){for(var n=1,r=-1,a=0;a=0)n*=t[a];else if(-1===t[a]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+a);r=a}else if(t[a]<0)throw Error("Shapes can not be < 0. Found "+t[a]+" at dim "+a);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var i=t.slice();return i[r]=e/n,i}function B(t,e){var n=e.length;return I((t=null==t?e.map((function(t,e){return e})):[].concat(t)).every((function(t){return t>=-n&&ts)&&1===t[s]&&(n.push(t[s]),r.push(s)),i[o]<=s&&o++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function W(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function V(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function U(t,e){for(var n=0;n=0;--r)n[r]=n[r+1]*t[r+1];return n}function et(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=T(t)),n&&U(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),a=0;a=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."}))}))}function st(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",c().platform.encode(t,e)}function ut(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",c().platform.decode(t,e)}function lt(t,e,n){if(0===e)return 0;if(1===e)return t[0];for(var r=t[t.length-1],a=0;a0?f:"")+" "}console.log("%c"+s+"\t%c"+o+"\t%c"+u+"D "+c+"\t%c"+l+"\t%c"+p+"\t%c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}();function dt(t,e,n){return M(Array.isArray(t)?parseFloat(t[0].toFixed(7))+" + "+parseFloat(t[1].toFixed(7))+"j":X(t)?"'"+t+"'":"bool"===n?mt(t):parseFloat(t.toFixed(7)).toString(),e)}function mt(t){return 0===t?"false":"true"}function gt(t){for(var e=[],n=0;n=this.shape[n]){var o="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(o)}n++}for(var s=t[t.length-1],u=0;u1)for(var l=0;l20){var c=3*s,p=Array.from(e.slice(0,c)),h=Array.from(e.slice((u-3)*s,u*s));return"complex64"===r&&(p=gt(p),h=gt(h)),["["+p.map((function(t,e){return dt(t,i[e],r)})).join(", ")+", ..., "+h.map((function(t,e){return dt(t,i[u-3+e],r)})).join(", ")+"]"]}return["["+("complex64"===r?gt(e):Array.from(e)).map((function(t,e){return dt(t,i[e],r)})).join(", ")+"]"]}var f=n.slice(1),d=a.slice(1),m=a[0]*s,g=[];if(u>20){for(var v=0;v<3;v++){var y=(b=v*m)+m;g.push.apply(g,t(e.slice(b,y),f,r,d,i,!1))}for(g.push("..."),v=u-3;v0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+o+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,r,a,i,o){var s,u=this,l=[],c=this.isTapeOn();null==r&&(r=null!=this.state.activeScope?this.state.activeScope.name:"");var p,h=this.state.numBytes,f=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var m,g=d(r,this.backendName);if(null!=g)p=function(){var t=u.backend.numDataIds();m=g.kernelFunc({inputs:e,attrs:a,backend:u.backend});var n=Array.isArray(m)?m:[m];u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,t,n);var s=n.map((function(t){var e=t.dataId,n=t.shape,r=t.dtype;return u.makeTensorFromDataId(e,n,r)}));if(c){var p=u.getTensorsForGradient(r,e,s);if(null==p){null==o&&(o=[]);var h=s.filter((function(t,e){return o[e]}));p=(i||[]).slice().concat(h)}l=u.saveTensorsForBackwardMode(p)}return s};else{var v=function(t){c&&(l=t.map((function(t){return u.keep(u.clone(t))})))};p=function(){var e=u.backend.numDataIds();m=u.tidy((function(){return t(u.backend,v)}));var n=Array.isArray(m)?m:[m];return u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,e,n),n}}return this.scopedRun((function(){return u.state.kernelDepth++}),(function(){return u.state.kernelDepth--}),(function(){s=u.ENV.getBool("DEBUG")?u.profiler.profileKernel(r,e,(function(){return p()})):p()})),c&&this.addTapeNode(r,e,s,n,l,a),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-h,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-f,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map((function(t){return e[t].shape})),outputShapes:s.map((function(t){return t.shape}))}),Array.isArray(m)?s:s[0]},t.prototype.saveTensorsForBackwardMode=function(t){var e=this;return t.map((function(t){return e.keep(e.clone(t))}))},t.prototype.getTensorsForGradient=function(t,e,n){var r=m(t);if(null!=r){var a=r.inputsToSave||[],i=r.outputsToSave||[],o=void 0;r.saveAllInputs?(I(Array.isArray(e),(function(){return"saveAllInputs is true, expected inputs to be an array."})),o=Object.keys(e).map((function(t){return e[t]}))):o=a.map((function(t){return e[t]}));var s=n.filter((function(t,e){return i[e]}));return o.concat(s)}return null},t.prototype.makeTensor=function(t,e,n,r){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var a=t;"string"===n&&X(t[0])&&(a=t.map((function(t){return st(t)})));var i=r.write(a,e,n),o=new wt(e,n,i,this.nextTensorId());if(this.incRef(o,r),"string"===n){var s=this.state.tensorInfo.get(i),u=K(a);this.state.numBytes+=u-s.bytes,s.bytes=u}return o},t.prototype.makeTensorFromDataId=function(t,e,n,r){var a=new wt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(a,r),a},t.prototype.makeVariable=function(t,e,n,r){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==t.dtype&&(t=t.asType(r));var a=new Et(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error("Variable with name "+a.name+" was already registered");return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a},t.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*H(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof Et||this.track(t)},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return o(this,void 0,void 0,(function(){var e,n;return s(this,(function(r){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map((function(t){return t.totalBytesSnapshot}))),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]}))}))},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n,r,a,i){var o=this,s={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:a},u=m(t);null!=u&&(r=u.gradFunc),null!=r&&(s.gradient=function(t){return t=t.map((function(t,e){if(null==t){var r=n[e],a=at(r.size,r.dtype);return o.makeTensor(a,r.shape,r.dtype)}return t})),r(t.length>1?t:t[0],a,i)}),this.state.activeTape.push(s)},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},t.prototype.endScope=function(t){for(var e=this,n=_t(t),r=new Set(n.map((function(t){return t.id}))),a=0;a0,(function(){return"gradients() received an empty list of xs."})),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var i=this.scopedRun((function(){return a.startTape()}),(function(){return a.endTape()}),(function(){return a.tidy("forward",t)}));I(i instanceof wt,(function(){return"The result y returned by f() must be a tensor."}));var o=function(t,e,n){for(var r={},a={},i=0;i=0;i--)for(o=(d=t[i]).inputs,c=0;c0)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 t,r,s={};s[i.id]=null==n?(r=rt(R(t=i.shape),"float32"),Bt.makeTensor(r,t,"float32")):n,function(t,e,n){for(var r=function(r){var a=e[r],i=[];if(a.outputs.forEach((function(e){var n=t[e.id];null!=n?i.push(n):i.push(null)})),null==a.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+a.kernelName+".");var o=a.gradient(i),s=function(e){if(!(e in o))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(o)+".");var r=n((function(){return o[e]()}));if("float32"!==r.dtype)throw new Error("Error in gradient for op "+a.kernelName+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var i=a.inputs[e];if(!D(r.shape,i.shape))throw new Error("Error in gradient for op "+a.kernelName+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+i.shape+"'");if(null==t[i.id])t[i.id]=r;else{var s=t[i.id];t[i.id]=s.add(r),s.dispose()}};for(var u in a.inputs)s(u)},a=e.length-1;a>=0;a--)r(a)}(s,o,(function(t){return a.tidy(t)}));var u=e.map((function(t){return s[t.id]}));return 0===a.state.gradientDepth&&(a.state.activeTape.forEach((function(t){for(var e=0,n=t.saved;en||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function de(t,e){return Se(t,e,(function(){return t.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function me(t,e,n,r,a,i,o,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Zt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,a)})),Zt(t,e,(function(){return t.vertexAttribPointer(u,i,t.FLOAT,!1,o,s)})),Zt(t,e,(function(){return t.enableVertexAttribArray(u)})),!0)}function ge(t,e,n,r){ke(t,r),Zt(t,e,(function(){return t.activeTexture(t.TEXTURE0+r)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)}))}function ve(t,e,n,r){return Se(t,e,(function(){return t.getUniformLocation(n,r)}),'uniform "'+r+'" not present in program.')}function ye(t,e,n){return t.getUniformLocation(e,n)}function be(t,e,n,r,a,i){Zt(t,e,(function(){return ge(t,e,r,i)})),Zt(t,e,(function(){return t.uniform1i(a,i)}))}function xe(t,e,n,r){Zt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)})),Zt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}))}function we(t,e,n){Zt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)})),Zt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)}))}function Ce(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ne(t,e))}function Ne(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function Se(t,e,n,r){var a=Zt(t,e,(function(){return n()}));if(null==a)throw new Error(r);return a}function ke(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(rn)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function Ie(t,e){return void 0===e&&(e=2),R(t.slice(0,t.length-e))}function Ee(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function Ae(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[Ie(t)].concat(Ee(t))),e}function Te(t,e){var n;void 0===e&&(e=!1);var r=c().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map((function(e,n){return n>=t.length-2?S(t[n]):t[n]}))).length&&(t=[2,t[0]])),2!==t.length){var a=P(t);t=a.newShape}var i=R(t);if(t.length<=1&&i<=r)return[1,i];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var o=Ie(t),s=2,u=2;return t.length&&(s=(n=Ee(t))[0],u=n[1]),F(i=o*(s/2)*(u/2)).map((function(t){return 2*t}))}return F(i)}function Re(t){return t%2==0}function De(t,e){if(D(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(Re(n)&&Re(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Re(t[0])&&Re(e[0])}function Oe(t){if(null==ae){var e=Kt(t);ae=e.getParameter(e.MAX_TEXTURE_SIZE)}return ae}function _e(t){if(null==ie){var e=Kt(t);ie=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ie)}function Fe(t){if(0===t)return 0;var e=Kt(t);return Me(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Me(e,"EXT_disjoint_timer_query")?1:0}function Me(t,e){return null!=t.getExtension(e)}function ze(t){try{if(null!=Kt(t))return!0}catch(t){return!1}return!1}function Le(t){if(0===t)return!1;var e=Kt(t);if(1===t){if(!Me(e,"OES_texture_float"))return!1}else if(!Me(e,"EXT_color_buffer_float"))return!1;return Pe(e)}function Be(t){if(0===t)return!1;var e=Kt(t);if(1!==t){if(Me(e,"EXT_color_buffer_float"))return Pe(e);if(Me(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=$t(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var a=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,a),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(a),i}(e,n)}return!1}return!!Me(e,"OES_texture_float")&&!!Me(e,"WEBGL_color_buffer_float")&&Pe(e)}function Pe(t){var e=$t(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),a}function We(t){return 2===t&&null!=Kt(t).fenceSync}var Ve=Object.freeze({callAndCheck:Zt,canBeRepresented:Qt,getWebGLErrorMessage:te,getExtensionOrThrow:ee,createVertexShader:ne,createFragmentShader:re,createProgram:se,linkProgram:ue,validateProgram:le,createStaticVertexBuffer:ce,createStaticIndexBuffer:pe,getNumChannels:function(){return 2===c().getNumber("WEBGL_VERSION")?1:4},createTexture:he,validateTextureSize:fe,createFramebuffer:de,bindVertexBufferToProgramAttribute:me,bindTextureUnit:ge,unbindTextureUnit:function(t,e,n){ke(t,n),Zt(t,e,(function(){return t.activeTexture(t.TEXTURE0+n)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:ve,getProgramUniformLocation:ye,bindTextureToProgramUniformSampler:be,bindCanvasToFramebuffer:function(t,e){Zt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),Zt(t,e,(function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)})),Zt(t,e,(function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)}))},bindColorTextureToFramebuffer:xe,unbindColorTextureFromFramebuffer:we,validateFramebuffer:Ce,getFramebufferErrorMessage:Ne,getBatchDim:Ie,getRowsCols:Ee,getShapeAs3D:Ae,getTextureShapeFromLogicalShape:Te,isReshapeFree:De,getWebGLMaxTextureSize:Oe,resetMaxTextureSize:function(){ae=null},resetMaxTexturesInShader:function(){ie=null},getMaxTexturesInShader:_e,getWebGLDisjointQueryTimerVersion:Fe,hasExtension:Me,isWebGLVersionEnabled:ze,isCapableOfRenderingToFloatTexture:Le,isDownloadFloatTextureEnabled:Be,isWebGLFenceEnabled:We}),Ue=c();function je(){c().set("PROD",!0)}function Ge(){c().set("DEBUG",!0)}function qe(){c().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function He(t){c().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ke(){Bt.disposeVariables()}function Xe(){return Bt}function Ye(){return Bt.memory()}function Je(t){return Bt.profile(t)}function $e(t,e){return Bt.tidy(t,e)}function Ze(t){_t(t).forEach((function(t){return t.dispose()}))}function Qe(t){return Bt.keep(t)}function tn(t){return Bt.time(t)}function en(t){return Bt.setBackend(t)}function nn(){return Bt.ready()}function rn(){return Bt.backendName}function an(t){Bt.removeBackend(t)}function on(t){return Bt.findBackend(t)}function sn(t){return Bt.findBackendFactory(t)}function un(t,e,n){return void 0===n&&(n=1),Bt.registerBackend(t,e,n)}function ln(){return Bt.backend}function cn(t,e){c().setPlatform(t,e)}function pn(){for(var t=[],e=0;e0,(function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"})),I(e.length===n[0],(function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"}));for(var a=n.slice(1),i=0;i=0&&(a=r),fn(r,a,e,n),null==t||!q(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var i=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+i+"'")}var o=hn(t,a);q(t)||Array.isArray(t)||(t=[t]);var s="string"!==a?et(t,a,c().getBool("DEBUG")):T(t,[],!0);return Bt.makeTensor(s,o,a)}function mn(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map((function(t,r){return dn(t,e+"["+r+"]",n)}),r)}function gn(t,e){for(var n=0;n=0&&e0})),Ue.registerFlag("WEBGL_VERSION",(function(){return ze(2)?2:ze(1)?1:0})),Ue.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===Ue.get("WEBGL_VERSION")})),Ue.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),Ue.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),Ue.registerFlag("WEBGL_PACK",(function(){return Ue.getBool("HAS_WEBGL")})),Ue.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_CLIP",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),Ue.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_PACK_REDUCE",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_CONV_IM2COL",(function(){return Ue.getBool("WEBGL_PACK")})),Ue.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return Oe(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return _e(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var t=Ue.getNumber("WEBGL_VERSION");return 0===t?0:Fe(t)})),Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return Ue.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=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(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))));var t})),Ue.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return Le(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!Ue.getBool("WEBGL_FORCE_F16_TEXTURES")&&Ue.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),Ue.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return Be(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return We(Ue.getNumber("WEBGL_VERSION"))})),Ue.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return Ue.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),xt=He;var En=In({complex_:function(t,e){var n=dn(t,"real","complex"),r=dn(e,"imag","complex");return E(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Bt.runKernelFunc((function(t){return t.complex(n,r)}),{$real:n,$imag:r})}}),An=In({real_:function(t){var e=dn(t,"input","real");return Bt.runKernelFunc((function(t){return t.real(e)}),{$input:e})}}),Tn=In({imag_:function(t){var e=dn(t,"input","imag");return Bt.runKernelFunc((function(t){return t.imag(e)}),{$input:e})}});function Rn(t,e,n){return Dn(t,e,hn(t,n),n)}function Dn(t,e,n,r){if(null==r&&(r=$(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!q(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=e){ot(e);var a=R(e),i=R(n);I(a===i,(function(){return"Based on the provided shape, ["+e+"], the tensor should have "+a+" values but has "+i}));for(var o=0;o1)return Vn([0],r);var a=at(Math.abs(Math.ceil((e-t)/n)),r);e=1,(function(){return"Pass at least one tensor to concat"}));var n=mn(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach((function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")})),e=B(e,n[0].shape)[0];var r=kn(n.map((function(t){return t.shape})),e);if(0===R(r))return Rn([],r);if(1===(n=n.filter((function(t){return t.size>0}))).length)return n[0];var a=n.map((function(t){return t.shape}));Sn(a,e);var i=n,o={axis:e};return Bt.runKernelFunc((function(t){return t.concat(n,e)}),i,(function(t){var n=a.map((function(t){return t[e]}));return Zn(t,n,e).map((function(t){return function(){return t}}))}),"Concat",o)}}),Xn=In({concat1d_:function(t){return Kn(t,0)}}),Yn=In({concat2d_:function(t,e){return Kn(t,e)}}),Jn=In({concat3d_:function(t,e){return Kn(t,e)}}),$n=In({concat4d_:function(t,e){return Kn(t,e)}}),Zn=In({split_:function(t,e,n){void 0===n&&(n=0);var r,a=dn(t,"x","split");return n=B(n,a.shape)[0],"number"==typeof e?(I(a.shape[n]%e==0,(function(){return"Number of splits must evenly divide the axis."})),r=new Array(e).fill(a.shape[n]/e)):(I(a.shape[n]===e.reduce((function(t,e){return t+e})),(function(){return"The sum of sizes must match the size of the axis dimension."})),r=e),Bt.runKernelFunc((function(t){return t.split(a,r,n)}),{$x:a},(function(t){return{$x:function(){return Kn(t,n)}}}))}});function Qn(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",ot(t),new vt(t,e,n)}function tr(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var er=In({batchToSpaceND_:function(t,e,n){var r=dn(t,"x","batchToSpaceND"),a=e.reduce((function(t,e){return t*e}));return I(r.rank>=1+e.length,(function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length})),I(n.length===e.length,(function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length})),I(r.shape[0]%a==0,(function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+a})),Bt.runKernelFunc((function(t){return t.batchToSpaceND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}}))}}),nr=In({cast_:function(t,e){var n=dn(t,"x","cast");if(!j(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");var r={dtype:e};return Bt.runKernelFunc((function(t){return t.cast(n,e)}),{x:n},(function(t){return{x:function(){return t.clone()}}}),"Cast",r)}}),rr=In({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var a=dn(t,"x","cumsum"),i=wn([e|=0],a.rank),o=a;null!=i&&(o=a.transpose(i));var s=Nn(1,a.rank)[0],u=Bt.runKernelFunc((function(t){return t.cumsum(o,s,n,r)}),{permutedX:o},(function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}}));return null!=i&&(u=u.transpose(i)),u}}),ar=In({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=dn(t,"x","depthToSpace"),a="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];return I(a*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape})),I(i*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape})),I(o%(e*e)==0,(function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+o+" for depthToSpace with input shape "+r.shape})),Bt.runKernelFunc((function(t){return t.depthToSpace(r,e,n)}),{$x:r})}}),ir=In({expandDims_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","expandDims",null);I(e<=n.rank,(function(){return"Axis must be <= rank of the tensor"}));var r=n.shape.slice();return e<0&&(I(-(n.rank+1)<=e,(function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"})),e=n.rank+e+1),r.splice(e,0,1),or(n,r)}}),or=In({reshape_:function(t,e){var n=dn(t,"x","reshape",null);e=L(e,n.size),I(n.size===R(e),(function(){return"new shape and old shape must have the same number of elements."}));var r={shape:e};return Bt.runKernelFunc((function(t){return t.reshape(n,e)}),{x:n},(function(t){return{x:function(){return t.reshape(n.shape)}}}),"Reshape",r)}}),sr=In({spaceToBatchND_:function(t,e,n){var r=dn(t,"x","spaceToBatchND");return I(r.rank>=1+e.length,(function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length})),I(n.length===e.length,(function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length})),I(r.shape.reduce((function(t,r,a){return a>0&&a<=e.length?t&&(r+n[a-1][0]+n[a-1][1])%e[a-1]==0:t}),!0),(function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()})),Bt.runKernelFunc((function(t){return t.spaceToBatchND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}}))}}),ur=In({squeeze_:function(t,e){var n=dn(t,"x","squeeze");return or(n,P(n.shape,e).newShape)}}),lr=In({stack_:function(t,e){void 0===e&&(e=0);var n=mn(t,"tensors","stack");if(I(n.length>=1,(function(){return"Pass at least one tensor to tf.stack"})),1===n.length)return n[0].expandDims(e);var r=n[0].rank,a=n[0].shape,i=n[0].dtype;I(e<=r,(function(){return"Axis must be <= rank of the tensor"})),n.forEach((function(t){E(a,t.shape,"All tensors passed to stack must have matching shapes")})),n.forEach((function(t){I(i===t.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var o=n.map((function(t){return t.expandDims(e)}));return Kn(o,e)}}),cr=In({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=dn(t,"x","unstack");I(e>=-n.shape.length&&e=2*e+1||a%2==1?o.push(a):i.push(a);r.push.apply(r,i),r.push(0),r.push.apply(r,o)}return r}function dr(t,e,n,r){void 0===r&&(r=!0);var a=[];r?a.push(t[0]/n):a.push(t[0]*n);for(var i=1;i1&&1===o&&r.unshift(i)}return r}function Fr(t,e){for(var n=[],r=0;r1)&&n.unshift(i)}return n}function Mr(t,e){for(var n=[],r=Math.max(t.length,e.length),a=0;a0&&(a=a.sum(o)),a.reshape(n.shape)},$b:function(){var e=Or(n.square(),r.square()),a=ta(t.mul(n.div(e))),o=Fr(r.shape,i);return o.length>0&&(a=a.sum(o)),a.reshape(r.shape)}}}))}}),ya=In({divStrict_:function(t,e){var n=dn(t,"a","div"),r=dn(e,"b","div");return E(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),ba=In({floorDiv_:function(t,e){var n,r=dn(t,"a","floorDiv"),a=dn(e,"b","floorDiv");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t,e){var n=t.floorDiv(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.div(r.toFloat()),a=Fr(n.shape,i);return a.length>0?e.sum(a).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),a=Fr(r.shape,i);a.length>0&&(e=e.sum(a).reshape(r.shape));var o=r.square();return e.div(o.toFloat()).neg()}}}),"FloorDiv")}}),xa=In({maximum_:function(t,e){var n,r=dn(t,"a","maximum"),a=dn(e,"b","maximum");return n=Dt(r,a),r=n[0],a=n[1],"bool"===r.dtype&&(r=r.toInt(),a=a.toInt()),Mr(r.shape,a.shape),Bt.runKernelFunc((function(t,e){var n=t.maximum(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){return t.mul(n.greaterEqual(r).toFloat())},b:function(){return t.mul(n.less(r).toFloat())}}}),"Maximum")}}),wa=In({maximumStrict_:function(t,e){var n=dn(t,"a","maximumStrict"),r=dn(e,"b","maximumStrict");return E(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),Ca=In({minimum_:function(t,e){var n,r=dn(t,"a","minimum"),a=dn(e,"b","minimum");return n=Dt(r,a),r=n[0],a=n[1],"bool"===r.dtype&&(r=r.toInt(),a=a.toInt()),Mr(r.shape,a.shape),Bt.runKernelFunc((function(t,e){var n=t.minimum(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){return t.mul(n.lessEqual(r).toFloat())},b:function(){return t.mul(n.greater(r).toFloat())}}}),"Minimum")}}),Na=In({minimumStrict_:function(t,e){var n=dn(t,"a","minimumStrict"),r=dn(e,"b","minimumStrict");return E(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),Sa=In({mod_:function(t,e){var n,r=dn(t,"a","mod"),a=dn(e,"b","mod");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t,e){var n=t.mod(r,a);return e([r,a]),n}),{$a:r,$b:a},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Fr(n.shape,i);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),a=Fr(r.shape,i);return a.length>0?e.sum(a).reshape(r.shape):e}}}))}}),ka=In({modStrict_:function(t,e){var n=dn(t,"a","modStrict"),r=dn(e,"b","modStrict");return E(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Ia=In({mul_:function(t,e){var n,r=dn(t,"a","mul"),a=dn(e,"b","mul");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t,e){var n=t.multiply(r,a);return e([r,a]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.mul(r.toFloat()),a=Fr(n.shape,i);return a.length>0?e.sum(a).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),a=Fr(r.shape,i);return a.length>0?e.sum(a).reshape(r.shape):e}}}),"Mul")}}),Ea=In({mulStrict_:function(t,e){var n=dn(t,"a","mul"),r=dn(e,"b","mul");return E(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),Aa=In({pow_:function(t,e){var n,r=dn(t,"base","pow"),a=dn(e,"exp","pow");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape),o=[r,a];return Bt.runKernelFunc((function(t,e){var n=t.pow(r,a);return e([r,a,n]),n}),{a:r,b:a},(function(t,e){var n=e[0],r=e[1],a=e[2];return{a:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(On(1))))),o=Fr(n.shape,i);return o.length>0&&(a=a.sum(o)),a.reshape(n.shape)},b:function(){var e=n.greater(0),o=n.log().where(e,Hn(n)),s=t.mul(a.mul(o)),u=Fr(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}}),"Pow",{},o,[!0])}}),Ta=In({powStrict_:function(t,e){return E(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Ra=In({squaredDifferenceStrict_:function(t,e){var n=dn(t,"a","squaredDifferenceStrict"),r=dn(e,"b","squaredDifferenceStrict");return E(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Da=In({sub_:function(t,e){var n,r=dn(t,"a","sub"),a=dn(e,"b","sub");n=Dt(r,a),r=n[0],a=n[1];var i=Mr(r.shape,a.shape);return Bt.runKernelFunc((function(t){return t.subtract(r,a)}),{a:r,b:a},(function(t){return{a:function(){var e=t,n=Fr(r.shape,i);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Fr(a.shape,i);return n.length>0&&(e=e.sum(n)),e.neg().reshape(a.shape)}}}),"Sub")}}),Oa=In({subStrict_:function(t,e){var n=dn(t,"a","subStrict"),r=dn(e,"b","subStrict");return E(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),_a=In({div_:function(t,e){var n,r=dn(t,"a","div"),a=dn(e,"b","div");if(n=Dt(r,a),r=n[0],a=n[1],"int32"===r.dtype&&"int32"===a.dtype)return ba(r,a);var i={a:r,b:a};return Bt.runKernelFunc((function(t,e){var n=t.realDivide(r,a);return e([r,a]),n}),i,null,br,{})}});function Fa(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>t.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],a=1,i=0;i1?e.shape[e.rank-1]:1,a=e.rank>1?e.rank-1:1,i="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+a+".";if(n.rank1?e.shape[r-1]:1,i=n.length,o=1,s=a;s0;)1&t&&e.push(n),t/=2,n++;return e}function ja(t,e,n){for(var r=[],a=0;a0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[a];return i<0&&(i+=s),N(0,i,s-1)}function qa(t,e,n,r,a){var i=e[a],o=n[a]||1;(t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[a];return i<0&&(i+=s),o>0?N(0,i,s):N(-1,i,s-1)}function Ha(t,e,n){for(var r=n.length,a=0;a1){r=a;break}for(a=r+1;a0||n[a]!==t[a])return!1;return!0}function Ka(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r0,(function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+i+" variables is trainable."}));var o=Bt.gradients(t,e,null,!0),s=o.value,u=o.grads;I(u.some((function(t){return null!=t})),(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()."})),I(0===s.rank,(function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"}));var l={};return e.forEach((function(t,e){null!=u[e]&&(l[t.name]=u[e])})),null!=a&&a.forEach((function(t){return l[t.name]=null})),{value:s,grads:l}}function ti(t){return Bt.customGrad(t)}function ei(t){if(t.filter((function(t){return null==t})).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var ni=In({softmax_:function(t,e){void 0===e&&(e=-1);var n=dn(t,"logits","softmax","float32");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Bt.runKernelFunc((function(t,r){var a=t.softmax(n,e);return r([a]),a}),{logits:n},(function(t,n){var r=n[0],a=t.mul(r);return{logits:function(){return a.sub(a.sum([e],!0).mul(r))}}}),"Softmax",{dim:e},[],[!0])}}),ri=In({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=dn(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return ti((function(t,n){var r=t.max(e,!0),a=t.sub(r),i=a.toFloat().sub(a.exp().sum(e,!0).log());return n([i]),{value:i,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}}))(n)}}),ai=In({transpose_:function(t,e){var n=dn(t,"x","transpose");if(null==e&&(e=n.shape.map((function(t,e){return e})).reverse()),I(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."})),e.forEach((function(t){I(t>=0&&t>>1)]);s>0?r=i+1:(a=i,o=!s)}return o?r:-r-1}(t,e,n||Ti)}(t,e,n),a=r<0?-(r+1):r;t.splice(a,0,e)}function Ti(t,e){return t>e?1:ta})).sort(Mi),l=i>0?-.5/i:0,c=[],p=[];c.length0;){var h=u.pop(),f=h.score,d=h.boxIndex,m=h.suppressBeginIndex;if(f=m;--v){var y=_i(t,d,c[v]);if(y>=r){g=!0;break}if(h.score=h.score*Fi(r,l,y),h.score<=a)break}h.suppressBeginIndex=c.length,g||(h.score===f?(c.push(d),p.push(h.score)):h.score>a&&Ai(u,h,Mi))}var b=c.length;return s&&(c.fill(0,b),p.fill(0,b)),{selectedIndices:_n(c,"int32"),selectedScores:_n(p,"float32"),numValidOutputs:On(b,"int32")}}function _i(t,e,n){var r=t.subarray(4*e,4*e+4),a=t.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),p=Math.max(a[0],a[2]),h=Math.max(a[1],a[3]),f=(s-i)*(u-o),d=(p-l)*(h-c);if(f<=0||d<=0)return 0;var m=Math.max(i,l),g=Math.max(o,c),v=Math.min(s,p),y=Math.min(u,h),b=Math.max(v-m,0)*Math.max(y-g,0);return b/(f+d-b)}function Fi(t,e,n){var r=Math.exp(e*n*n);return n<=t?r:0}function Mi(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function zi(t,e,n){var r=new Array(t.rank).fill(0),a=t.shape.slice();return e.map((function(e){a[n]=e;var i=t.slice(r,a);return r[n]+=e,i}))}function Li(t,e){for(var n=new Array(t.rank),r=0;r":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function ji(t,e){return["x","y","z","w","u","v"].slice(0,e).map((function(e){return t+"."+e}))}function Gi(t,e){return 1===e?[t]:ji(t,e)}function qi(){var t,e,n,r,a,i,o,s,u,l;return 2===c().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",a="texture",i="outputColor",o="out vec4 outputColor;",s="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",u="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(t="",e="attribute",n="varying",r="varying",a="texture2D",i="gl_FragColor",o="",s="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:a,output:i,defineOutput:o,defineSpecialNaN:s,defineSpecialInf:u,defineRound:l}}function Hi(t,e,n){void 0===n&&(n="index");var r=tt(e);return r.map((function(e,a){return"int "+t[a]+" = "+n+" / "+e+"; "+(a===r.length-1?"int "+t[a+1]+" = "+n+" - "+t[a]+" * "+e:"index -= "+t[a]+" * "+e)+";"})).join("")}function Ki(t){var e=tt(t).map((function(t){return t.toString()}));return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var Xi="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function Yi(t,e,n,r){var a=[];t.forEach((function(t){var e=R(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?a.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(a.push("uniform sampler2D "+t.name+";"),a.push("uniform int offset"+t.name+";"))}));var i,o,s=a.join("\n"),u=t.map((function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?$i(t):Ji(t);var a=t.shapeInfo.logicalShape,i=e.logicalShape;return a.length<=i.length&&(r+=n?function(t,e){var n,r,a=t.name,i=a.charAt(0).toUpperCase()+a.slice(1),o="get"+i+"AtOutCoords",s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length,l=_r(t.shapeInfo.logicalShape,e.logicalShape),c=ao(u),p=u-s,h=["x","y","z","w","u","v"];n=0===s?"":u<2&&l.length>=1?"coords = 0;":l.map((function(t){return"coords."+h[t+p]+" = 0;"})).join("\n"),r=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+h[e+p]})).join(", ");var f="return outputValue;",d=1===R(t.shapeInfo.logicalShape),m=1===R(e.logicalShape);if(1!==s||d||m){if(d&&!m)f=1===u?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(l.length){var g=s-2,v=s-1;l.indexOf(g)>-1&&l.indexOf(v)>-1?f="return vec4(outputValue.x);":l.indexOf(g)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":l.indexOf(v)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+o+"() {\n "+c+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+i+"("+r+");\n "+f+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",i=e.texShape,o=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&D(o,i))return"\n float "+a+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var l=ao(u),c=_r(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,h=["x","y","z","w","u","v"];return"\n float "+a+"() {\n "+l+" coords = getOutputCoords();\n "+(0===s?"":u<2&&c.length>=1?"coords = 0;":c.map((function(t){return"coords."+h[t+p]+" = 0;"})).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+h[e+p]})).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)})).join("\n"),l=e.texShape,c=qi(),p=function(t){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(c),h=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n "+t.defineSpecialNaN+"\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+Zi+"\n "+Qi+"\n "+to+"\n "}(c);return e.isPacked?(i=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(D(t,e))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(t[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=t,r=e,a=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=(i=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+a[0]+", "+a[1]+"));\n int index = resTexRC.x * "+a[1]+" + resTexRC.y;\n\n int b = index / "+o+";\n index -= b * "+o+";\n\n int r = 2 * (index / "+i+");\n int c = imod(index, "+i+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),a=r*Math.ceil(t[t.length-2]/2),i=a,o="",s="b, r, c",u=2;u2,(function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."}));var a=t[t.length-1],i=Math.ceil(a/e);this.outputShape=t.slice(0,-1),i>1&&this.outputShape.push(i),r||this.variableNames.push("bestIndicesA");var o,s,u=this.outputShape,l=u.length,c=ao(l),p=Gi("coords",l);if(1===i){var h=ao(s=l+1);o="\n "+h+" sourceLocR = "+h+"("+p.join()+", 0);\n ++"+p[l-1]+";\n "+h+" sourceLocG = "+h+"("+p.join()+", 0);\n ++"+p[l-2]+";\n "+h+" sourceLocA = "+h+"("+p.join()+", 0);\n --"+p[l-1]+";\n "+h+" sourceLocB = "+h+"("+p.join()+", 0);\n --"+p[l-2]+";"}else s=l,o="\n "+c+" sourceLocR = coords;\n ++"+p[l-1]+";\n "+c+" sourceLocG = coords;\n ++"+p[l-2]+";\n "+c+" sourceLocA = coords;\n --"+p[l-1]+";\n "+c+" sourceLocB = coords;\n --"+p[l-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),d="."+f[s-1],m=f.map((function(t){return"int "+t})),g=Gi("sourceLocR",s-1).concat("inIdx.r"),v=Gi("sourceLocG",s-1).concat("inIdx.g"),y=Gi("sourceLocB",s-1).concat("inIdx.b"),b=Gi("sourceLocA",s-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+b.join()+")));",C="vec4(\n getAChannel("+g.join()+"),\n hasNextCol ? getAChannel("+v.join()+") : 0.,\n hasNextRow ? getAChannel("+y.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+b.join()+") : 0.)",N=r?"":"\n float getBestIndicesAChannel("+m.join()+") {\n return getChannel(getBestIndicesA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+m.join()+") {\n return getChannel(getA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }\n "+N+"\n void main() {\n "+c+" coords = getOutputCoords();\n bool hasNextCol = "+p[l-1]+" < "+(u[l-1]-1)+";\n bool hasNextRow = "+p[l-2]+" < "+(u[l-2]-1)+";\n "+o+"\n ivec4 srcIdx = ivec4(sourceLocR"+d+", sourceLocG"+d+",\n sourceLocB"+d+", sourceLocA"+d+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+C+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+w+"\n vec4 candidate = "+C+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+x+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "},uo=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,i=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+i+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+o+") {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},lo=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,a=t.strideDepth,i=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=c-1-t.padInfo.front,d=p-1-t.padInfo.top,m=h-1-t.padInfo.left,g=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n const float avgMultiplier = float("+g+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+a+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+i+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+h+";\n wC += "+l+") {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},co=function(t,e,n,r,a,i){this.outputShape=[],this.variableNames=["x","mean","variance"],Mr(t,e),Mr(t,n);var o="0.0";null!=r&&(Mr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="1.0";null!=a&&(Mr(t,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+o+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+i+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},po=function(t,e,n,r,a,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Mr(t,e),Mr(t,n);var o="vec4(0.0)";null!=r&&(Mr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=a&&(Mr(t,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+o+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+i+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},ho=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Mr(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},fo="return a + b;",mo="return a - b;",go="return a * b;",vo="return (a < 0.) ? b * a : a;",yo=function(t,e,n){this.variableNames=["A","B"],this.outputShape=Mr(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},bo="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",xo=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Mr(e,n);var a=this.outputShape.length,i="";if(r)if(0===a||1===R(this.outputShape))i="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(i="\n "+ao(a)+" coords = getOutputCoords();\n ",1===a)i+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var o=Gi("coords",a);i+="\n bool nextRowOutOfBounds =\n ("+o[a-2]+" + 1) >= "+this.outputShape[a-2]+";\n bool nextColOutOfBounds =\n ("+o[a-1]+" + 1) >= "+this.outputShape[a-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+i+"\n\n setOutput(result);\n }\n "},wo=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,a){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Co=function(){function t(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,a){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(a,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),No=function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "},So=function(t){this.outputShape=[],this.outputShape=kn(t,1),this.variableNames=t.map((function(t,e){return"T"+e}));var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n= "+s[u-1]+") {\n return getChannel(\n getT"+u+"("+Io(o,l,f)+"),\n vec2("+Io(c,l,f)+"));\n }"}var d=s.length,m=s[s.length-1];h+="\n return getChannel(\n getT"+d+"("+Io(o,l,m)+"),\n vec2("+Io(c,l,m)+"));",this.userCode="\n float getValue("+o.map((function(t){return"int "+t}))+") {\n "+h+"\n }\n\n void main() {\n "+a+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+i+"), 0., 0., 0.);\n\n "+i[r-1]+" = "+i[r-1]+" + 1;\n if ("+i[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+i+");\n }\n\n "+i[r-2]+" = "+i[r-2]+" + 1;\n if ("+i[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+i+");\n }\n\n "+i[r-1]+" = "+i[r-1]+" - 1;\n if ("+i[r-2]+" < "+n[r-2]+" &&\n "+i[r-1]+" < "+n[r-1]+") {\n result.b = getValue("+i+");\n }\n setOutput(result);\n }\n "};function Io(t,e,n){var r=t.indexOf(e);return t.map((function(t,e){return e===r?t+" - "+n:t})).join()}var Eo=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,a=t.padInfo.left,i="channelsLast"===t.dataFormat;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+i+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ao=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,i="channelsLast"===t.dataFormat,o=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=i?1:2,l=i?2:3,c=i?3:1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+c+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+l+"]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n\n if ("+i+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},To=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,a=t.padInfo.front,i=t.padInfo.top,o=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+a+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+i+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ro=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,a=t.strideDepth,i=t.strideHeight,o=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+a+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+i+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Do=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,a=t.padInfo.left,i=t.outChannels/t.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+i+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Oo=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,a=t.strideWidth,i=e-1-t.padInfo.top,o=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},_o=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.padInfo.top,i=t.padInfo.left,o=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterHeight,p=t.filterWidth,h=4*Math.floor(t.inChannels/4),f=t.inChannels%4,d="channelsLast"===t.dataFormat,m=d?1:2,g=d?2:3,v=d?3:1,y="",b="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",b="result = activation(result);");var x=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+o+", "+s+");\n const ivec2 pads = ivec2("+a+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+v+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+m+"], coords["+g+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+h+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+d+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===f)+") {\n\n if ("+d+") {\n dotProd +=\n getX(batch, xR, xC, "+h+") *\n getW(wR, wC, "+h+", d2);\n } else {\n dotProd +=\n getX(batch, "+h+", xR, xC) *\n getW(wR, wC, "+h+", d2);\n }\n\n } else if ("+(2===f)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2)\n );\n\n if ("+d+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===f)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2),\n getW(wR, wC, "+h+" + 2, d2)\n );\n\n if ("+d+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1),\n getX(batch, xR, xC, "+h+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC),\n getX(batch, "+h+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+x+"\n "+b+"\n setOutput(result);\n }\n "},Fo=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,a=t.strideDepth,i=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,p=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+a+", "+i+", "+o+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+c+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+f+") *\n getW(wF, wR, wC, "+f+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1),\n getX(batch, xF, xR, xC, "+f+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2),\n getW(wF, wR, wC, "+f+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Mo=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var a=t.inHeight,i=t.inWidth,o=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,p=t.dilationWidth,h=t.filterHeight,f=t.filterWidth,d=t.outChannels/t.inChannels,m="",g="";n&&(m=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",g="result = activation(result);");var v=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+m+"\n\n const ivec2 strides = ivec2("+u+", "+l+");\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+d+";\n int q = d2 - d1 * "+d+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+h+"; wR++) {\n int xR = xRCorner + wR * "+c+";\n\n if (xR < 0 || xR >= "+a+") {\n continue;\n }\n\n for (int wC = 0; wC < "+f+"; wC++) {\n int xC = xCCorner + wC * "+p+";\n\n if (xC < 0 || xC >= "+i+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n "+v+"\n "+g+"\n setOutput(result);\n }\n "},zo=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var a=t.inHeight,i=t.inWidth,o=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,p=t.dilationWidth,h=t.filterHeight,f=t.filterWidth,d=f,m="int xR; int xC; int xCOffset;",g=0;g= 0 && xR < "+a+" && xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+i+") {\n xTexelR"+g+"C"+v+".zw = vec2(0.);\n }\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+a+" && xCOffset >= 0 && xCOffset < "+i+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+i+") {\n previous.zw = vec2(0.);\n }\n\n xR"+g+"C"+v+" = vec4(previous.zw, xTexelR"+g+"C"+v+".xy);\n } else {\n xR"+g+"C"+v+" = vec4(0, 0, xTexelR"+g+"C"+v+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+a+" && xC >= 0 && xC < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = xTexelR"+g+"C"+v+";\n ",v+1= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",p>1&&(m+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n "),m+="\n xR"+g+"C"+(v+1)+" = vec4(\n xTexelR"+g+"C"+v+".zw, xTexelR"+g+"C"+(v+2)+".xy);\n "):m+="\n xCOffset = xC + "+b+";\n\n if(xR >= 0 && xR < "+a+" &&\n xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+g+"C"+(v+1)+" = xTexelR"+g+"C"+(v+2)+";\n "}}else v= 0 && xR < "+a+") {\n ",s%2==1?(m+="\n xCOffset = xC + 1 - "+l+";\n if(xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+i+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+g+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = vec4(\n xTexelR"+g+"C"+v+".zw, xTexelR"+g+"C"+(v+2)+".zw);\n ",v+1= 0 && xCOffset < "+i+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+g+"C"+(v+1)+" = vec4(xTexelR"+g+"C"+(v+2)+".xy, final.xy);\n ")):(m+="\n if(xC >= 0 && xC < "+i+") {\n xTexelR"+g+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + "+l+";\n if(xCOffset >= 0 && xCOffset < "+i+") {\n xTexelR"+g+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+v+" = vec4(\n xTexelR"+g+"C"+v+".xy, xTexelR"+g+"C"+(v+2)+".xy);\n ",v+11?[""+(o-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],v=g[0],y=g[1],b=g[2],x=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],w=x[0],C=x[1],N=x[2];this.userCode="\n const float height_ratio = float("+v+");\n const float width_ratio = float("+w+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+i+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+C+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+a+"));\n return;\n }\n float in_x = "+N+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+a+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+h+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "},Bo=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,a=t[t.length-1],i=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+ao(r)+" coords = getOutputCoords();\n int end = "+Po(r,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+i+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+Po(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "};function Po(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var Wo=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Vt.DENSE;var e=Yt(t),n=qi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Hi(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+n.output+" = result;\n }\n "},Vo=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Vt.DENSE;var e=Yt(t),n=qi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+Hi(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+n.output+" = result;\n }\n "},Uo=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),jo=function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},Go=function(t){this.variableNames=["A"],this.outTexUsage=Ut.DOWNLOAD;var e=qi();this.outputShape=t,this.userCode="\n "+Xi+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},qo=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ut.DOWNLOAD;var e=qi();this.outputShape=t,this.userCode="\n "+Xi+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n "},Ho=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=qi(),a=e[0],i=e[1];this.outputShape=t;var o="result";n&&(o="floor(result * 255. + 0.5)"),this.userCode="\n "+Ki(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+i+";\n int c = imod(flatIndex, "+i+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+i+".0, "+a+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+o+", 0., 0., 0.);\n }\n "},Ko=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=qi(),a=e[0],i=e[1];this.outputShape=t;var o="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;o+="\n localCoords = coords;\n if(localCoords[2] + "+l+" < "+t[2]+") {\n localCoords[2] += "+l+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+i+";\n c = imod(flatIndex, "+i+");\n uv = (vec2(c, r) + halfCR) / vec2("+i+".0, "+a+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+c+"] = values[0];\n } else if(offset == 1) {\n result["+c+"] = values[1];\n } else if(offset == 2) {\n result["+c+"] = values[2];\n } else {\n result["+c+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+Ki(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n "+o+"\n\n "+r.output+" = "+s+";\n }\n "},Xo=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var a=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,i=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+a+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+t+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+i+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},Yo=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),Jo=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var a=ao(this.rank),i=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=0;i1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+a+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+i+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function Zo(t,e){var n=qi();return ne(t,e,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function Qo(t,e){return ce(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ts(t,e){return pe(t,e,new Uint16Array([0,1,2,2,1,3]))}function es(t,e,n,r,a,i,o){fe(n,r);var s=he(t,e),u=t.TEXTURE_2D;return Zt(t,e,(function(){return t.bindTexture(u,s)})),Zt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)})),Zt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)})),Zt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)})),Zt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)})),Zt(t,e,(function(){return t.texImage2D(u,0,a,n,r,0,i,o,null)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)})),s}function ns(t,e,n,r,a){var i=Xt(n,r);return es(t,e,i[0],i[1],a.internalFormatFloat,a.textureFormatFloat,t.FLOAT)}function rs(t,e,n,r,a){var i=Xt(n,r);return es(t,e,i[0],i[1],a.internalFormatHalfFloat,a.textureFormatFloat,a.textureTypeHalfFloat)}function as(t,e,n,r,a){var i=Xt(n,r);return es(t,e,i[0],i[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function is(t,e,n,r,a){var i=Jt(n,r);return es(t,e,i[0],i[1],a.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function os(t,e,n,r,a){var i=Jt(n,r);return es(t,e,i[0],i[1],a.internalFormatPackedHalfFloat,t.RGBA,a.textureTypeHalfFloat)}function ss(t,e,n,r){return Zt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),me(t,e,n,"clipSpacePos",r,3,20,0)&&me(t,e,n,"uv",r,2,20,12)}function us(t,e,n,r,a,i,o){var s,u,l;Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),i instanceof Uint8Array?(s=new Uint8Array(r*a*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*a*4),u=t.FLOAT,l=o.internalFormatPackedFloat),s.set(i),Zt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,a,0,t.RGBA,u,s)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function ls(t,e,n,r){Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),r.data instanceof Uint8Array?Zt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)})):Zt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)})),Zt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function cs(t,e,n,r,a){var i=t.createBuffer();Zt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,i)}));var o=16*n*r;return Zt(t,e,(function(){return t.bufferData(t.PIXEL_PACK_BUFFER,o,t.STREAM_READ)})),Zt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)})),Zt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)})),i}function ps(t,e,n){var r=t,a=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),a}function hs(t,e,n,r,a){var i=Xt(n,r),o=i[0],s=i[1],u=new Uint8Array(n*r*4);return Zt(t,e,(function(){return t.readPixels(0,0,o,s,a.downloadTextureFormat,t.UNSIGNED_BYTE,u)})),new Float32Array(u.buffer)}function fs(t,e,n,r,a,i,o,s){var u=t,l=new Float32Array(function(t,e){var n=Jt(t,e);return n[0]*n[1]*4}(i,o));return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function ds(t,e,n,r){var a=new Float32Array(n*r*4);return Zt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,a)})),a}var ms=Object.freeze({createVertexShader:Zo,createVertexBuffer:Qo,createIndexBuffer:ts,createFloat32MatrixTexture:ns,createFloat16MatrixTexture:rs,createUnsignedBytesMatrixTexture:as,createPackedMatrixTexture:is,createFloat16PackedMatrixTexture:os,bindVertexProgramAttributeStreams:ss,uploadDenseMatrixToTexture:us,uploadPixelDataToTexture:ls,createBufferFromOutputTexture:cs,downloadFloat32MatrixFromBuffer:ps,downloadByteEncodedFloatMatrixFromOutputTexture:hs,downloadPackedMatrixFromBuffer:fs,downloadMatrixFromPackedOutputTexture:ds}),gs=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=c().getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Ht(e,t)):this.gl=Kt(e);var n="WEBGL_color_buffer_float";if(1===c().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=ee(this.gl,this.debug,"OES_texture_float"),Me(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=ee(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(n),Me(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=ee(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(n="EXT_color_buffer_float",Me(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Me(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=Qo(this.gl,this.debug),this.indexBuffer=ts(this.gl,this.debug),this.framebuffer=de(this.gl,this.debug),this.textureConfig=$t(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return c().getBool("DEBUG")},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;Zt(e,this.debug,(function(){return e.finish()})),Zt(e,this.debug,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),Zt(e,this.debug,(function(){return e.deleteFramebuffer(t.framebuffer)})),Zt(e,this.debug,(function(){return e.bindBuffer(e.ARRAY_BUFFER,null)})),Zt(e,this.debug,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)})),Zt(e,this.debug,(function(){return e.deleteBuffer(t.indexBuffer)})),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),ns(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),rs(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),as(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),ls(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),us(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),os(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),is(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(we(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Zt(this.gl,this.debug,(function(){return e.gl.deleteTexture(t)}))},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,(function(){return hs(r.gl,r.debug,e,n,r.textureConfig)}))},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,a,i){return fs(this.gl,t,0,0,0,a,i,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return ps(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=cs(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},t.prototype.createFence=function(t){var e,n,r=this;if(c().getBool("WEBGL_FENCE_API_ENABLED")){var a=t,i=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=a.clientWaitSync(i,0,0);return t===a.ALREADY_SIGNALED||t===a.CONDITION_SATISFIED},e=i}else c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,(function(){return ds(r.gl,r.debug,e,n)}))},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=re(e,this.debug,t),r=Zo(e,this.debug),a=se(e,this.debug);return Zt(e,this.debug,(function(){return e.attachShader(a,r)})),Zt(e,this.debug,(function(){return e.attachShader(a,n)})),ue(e,this.debug,a),this.debug&&le(e,this.debug,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=ss(e,this.debug,this.program,this.vertexBuffer)),a},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Zt(this.gl,this.debug,(function(){return e.gl.deleteProgram(t)}))},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&le(this.gl,this.debug,this.program),Zt(this.gl,this.debug,(function(){return e.gl.useProgram(t)}))},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?ve(this.gl,this.debug,t,e):ye(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Zt(this.gl,this.debug,(function(){return n.gl.getAttribLocation(t,e)}))},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),be(this.gl,this.debug,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=Jt(e,n),a=r[0],i=r[1];this.setOutputMatrixTextureDriver(t,a,i)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&le(this.gl,this.debug,this.program),Ce(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Zt(t,this.debug,(function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Zt(this.gl,this.debug,(function(){return t.gl.finish()}))},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=ee(this.gl,this.debug,2===c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},t.prototype.endQuery=function(){if(2!==c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},t.prototype.waitForQueryAndGetTime=function(t){return o(this,void 0,void 0,(function(){var e=this;return s(this,(function(n){switch(n.label){case 0:return[4,z((function(){return e.disposed||e.isQueryAvailable(t,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(t,c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}}))}))},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise((function(n){e.addItemToPoll((function(){return t.isFencePassed()}),(function(){return n()}))}))},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e1||z((function(){return n.pollItems(),0===n.itemsToPoll.length}))},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),xe(this.gl,this.debug,t,this.framebuffer),this.debug&&Ce(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(xe(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Ce(this.gl)):we(this.gl,this.debug,this.framebuffer)},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;xe(r,this.debug,t,this.framebuffer),this.debug&&Ce(r),this.outputTexture=t,Zt(r,this.debug,(function(){return r.viewport(0,0,e,n)})),Zt(r,this.debug,(function(){return r.scissor(0,0,e,n)}))},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var a=this;this.throwIfDisposed(),Zt(this.gl,this.debug,(function(){return a.gl.scissor(t,e,n,r)}))},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function vs(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach((function(t,n){var r=t.logicalShape,a=e[n],i=a.shape;if(!D(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!t.isUniform||!a.isUniform){var o=t.texShape,s=a.isUniform?null:a.texData.texShape;if(!D(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}}))}var ys=function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=n.filterWidth,a=n.inChannels,i=n.strideWidth,o=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,p=n.dataFormat,h=s.left,f=s.top,d=a*r,m=qi(),g="channelsLast"===p,v=g?0:1,y=g?1:2,b="",x=0;x<=1;x++)for(var w=0;w<=1;w++)b+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+x+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+o+" - "+f+";\n d0 = offsetY + "+c+" * (pos / "+d+");\n\n if(d0 < "+e[v]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+i+". - "+h+".);\n d1 = offsetX + "+l+" * (int(mod(float(pos), "+d+".) / "+a+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+a+".));\n\n if ("+g+") {\n innerDims = vec2(d1, ch);\n result["+(2*x+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*x+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+b+"\n\n "+m.output+" = result;\n }\n "},bs=function(t,e,n,r,a){this.variableNames=["x"],this.outputShape=[];var i,o=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";i=.5===a?"inversesqrt("+u+")":1===a?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+o+"; j <= "+o+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+i+";\n setOutput(val);\n }\n "},xs=function(t,e,n,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=a,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+a+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+a+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "},ws=function(t,e,n,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var i,o=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";i=.5===a?"inversesqrt("+u+")":1===a?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+o+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+o+"; j <= "+o+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+i+";\n setOutput(result);\n }\n "},Cs=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,a=t.effectiveFilterHeight,i=t.effectiveFilterWidth,o=a-1-t.padInfo.top,s=i-1-t.padInfo.left,u=a*i-1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+a+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+i+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+i+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},Ns=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,a=t.dilationDepth,i=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=s-1-t.padInfo.front,p=u-1-t.padInfo.top,h=l-1-t.padInfo.left,f=s*u*l-1;this.userCode="\n const ivec3 pads = ivec3("+c+", "+p+", "+h+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+a+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+i+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+l+";\n wC += "+o+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+f+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+l+" +\n wR * "+l+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ss=function(t,e,n,r,a,i,o){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===a&&(a=!1),void 0===i&&(i=null),void 0===o&&(o=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),l=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",p=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",d="";i&&(f=o?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+i+"\n }":"vec4 activation(vec4 x) {\n "+i+"\n }",d="result = activation(result);");var m=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+f+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+l+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+p[0]+" * "+h[0]+");\n result += ("+p[1]+" * "+h[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+m+"\n\n "+d+"\n\n setOutput(result);\n }\n "},ks=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(e-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),Is=function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n "},Es=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=Gi("rc",e),r=ao(e),a=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",a=t-2;a= "+e[a],a= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),o=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var a=0;a<=1;a++){for(var i=(0===r?"r":"rp1")+", "+(0===a?"c":"cp1"),o=2;o= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+a+") {\n setOutput(vec4(0));\n } else {\n "+i+"\n\n setOutput(vec4("+o+"));\n }\n }\n "}},As=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));var r=t.length,a=ao(r),i=e.map((function(t){return t[0]})).join(","),o=e.map((function(e,n){return e[0]+t[n]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+a+" start = "+a+"("+i+");\n "+a+" end = "+a+"("+o+");\n\n void main() {\n "+a+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+a+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+i+";\n int end = "+o+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Ts=function(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));for(var r=t.length,a=ao(r),i=e.map((function(t){return t[0]})).join(","),o=e.map((function(e,n){return e[0]+t[n]})).join(","),s=Gi("rc",r),u=Gi("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[a+" rc = outputLoc;",s[r-1]+" += 1;\n if("+l+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+l+") {"],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,m=1===r?2:4;d= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+";\n wC += "+l+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = "+(r?a?m:g:"wR * "+p+" + wC")+";\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var b=4*Math.floor(i/4),x=i%4,w="\n if ("+d+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+o+", "+s+");\n const ivec2 pads = ivec2("+h+", "+f+");\n const float initializationValue = "+v+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+v+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+c+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+b+"; wC += 4) {\n int xC = xCCorner + wC * "+l+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+l+", d),\n getValue(batch, xR, xC + 2 * "+l+", d),\n getValue(batch, xR, xC + 3 * "+l+", d)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+b+";\n if ("+(1===x)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===x)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+l+", d),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===x)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+l+", d),\n getValue(batch, xR, xC + 2 * "+l+", d),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n "}},Ds=function(t,e,n,r,a){if(void 0===r&&(r=!1),void 0===a&&(a=!1),this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var i=t.filterWidth,o=t.strideDepth,s=t.strideHeight,u=t.strideWidth,l=t.dilationDepth,c=t.dilationHeight,p=t.dilationWidth,h=t.effectiveFilterDepth,f=t.effectiveFilterHeight,d=t.effectiveFilterWidth,m=t.padInfo.front,g=t.padInfo.top,v=t.padInfo.left;this.outputShape=t.outShape;var y="avg"===e,b="0.0";if(y||(b="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+s+", "+u+");\n const ivec3 pads = ivec3("+m+", "+g+", "+v+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+h+";\n wD += "+l+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+f+";\n wR += "+c+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+";\n wC += "+p+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = "+(r?a?"(((batch * "+t.inDepth+" + xD) * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"((xD * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"wD * "+f+" * "+d+" +\n wR * "+d+" + wC")+";\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var x=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(x="avgValue / count");var w=4*Math.floor(i/4),C=i%4,N="\n if ("+y+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+s+", "+u+");\n const ivec3 pads = ivec3("+m+", "+g+", "+v+");\n const float initializationValue = "+b+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+b+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+h+";\n wD += "+l+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+f+";\n wR += "+c+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+w+"; wC += 4) {\n int xC = xCCorner + wC * "+p+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+p+", ch),\n getValue(batch, xD, xR, xC + 2 * "+p+", ch),\n getValue(batch, xD, xR, xC + 3 * "+p+", ch)\n );\n\n "+N+"\n }\n\n int xC = xCCorner + "+w+";\n if ("+(1===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+N+"\n } else if ("+(2===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+p+", ch),\n initializationValue,\n initializationValue\n );\n\n "+N+"\n } else if ("+(3===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+p+", ch),\n getValue(batch, xD, xR, xC + 2 * "+p+", ch),\n initializationValue\n );\n\n "+N+"\n }\n }\n setOutput("+x+");\n }\n }\n "}},Os=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,a=t.inSize,i=Math.ceil(a/n);this.outputShape=[r,i];var o="0.0",s="";"prod"===e?o="1.0":"min"===e?(o="1.0 / 1e-20",s="min"):"max"===e&&(o="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,p="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",h="vec4";"all"===e?(o="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",h="bvec4"):"any"===e&&(o="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",h="bvec4");var f="";a%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+o+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+f+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+o+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; i += 4) {\n int inIdx = inOffset + i;\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+p+"\n }\n setOutput("+u+");\n }\n "},_s=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var a="thisRC = rc;";r%2==1&&(a+="thisRC.z += 1;"),r>1&&(a+="thisRC.y += 1;"),n+="\n "+a+"\n "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+Hi(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+Ki(t)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+t[1]+";\n int cols = "+t[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n "},Fs=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],i=r[2],o=t.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(a-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(i-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},Ms=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],i=t[1],o=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},zs=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var a=t[0],i=t[1],o=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+",\n "+u[1]/l[1]+");\n const vec3 inputShapeRC = vec3("+i+".0, "+o+".0,\n "+o+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+";\n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},Ls=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],i=r[2],o=t.shape,s=o[1],u=o[2],l=[n&&s>1?a-1:a,n&&u>1?i-1:i],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+i+") - 1),\n "+n+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},Bs=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],i=t[1],o=t[2],s=t[3];this.outputShape=[a,e,n,s];var u=[r&&e>1?i-1:i,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},Ps=function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map((function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)})).join(","),a=ao(n);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n "},Ws=function(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=Gi("rc",n),a=r[n-1]+" + 1 < "+this.outputShape[n-1],i=r[n-2]+" + 1 < "+this.outputShape[n-2],o=ao(n);function s(n){var r=t.map((function(r,a){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(a,n)}));return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+a+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+o+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(t){return s(t)}(r.slice())+";\n if("+a+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+i+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+a+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n "},Vs=function(t,e,n,r,a,i,o){void 0===o&&(o=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;var s=ao(a.length),u=ao(i.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var h="getUpdates("+p+")",f=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+a+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+c+");\n flattenedIndex += index * "+f+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+h+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},Us=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,a=t.inSize,i=t.numSegments,o=i*Math.ceil(a/n);this.outputShape=[r,o];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ",c="";a%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var p="";a%n>0&&(p="\n if (inIdx < 0 || inIdx >= "+a+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+p+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+i+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+i+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+l+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(2===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(3===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+l+"\n }\n setOutput(sumValue);\n }\n "},js=function(t,e,n){var r,a;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)a="resRC",r="resRC";else{for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "},Gs=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=ao(this.rank),r="uniform int start["+this.rank+"];",a=function(t){if(1===t)return"sourceLoc";if(t<=6)return qs.slice(0,t).map((function(t){return"sourceLoc."+t})).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map((function(t,e){return"sourceLoc."+qs[e]+" = start["+e+"] + coords."+qs[e]+";"})).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+a+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),qs=["x","y","z","w","u","v"],Hs=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=ao(this.rank),n=Gi("coords",this.rank),r=Gi("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",i="getChannel(getSource("+r.join()+"), "+a+")",o="\n result.x = "+i+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+i+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+i+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+i+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map((function(t,e){return"start["+e+"]"})).join()+");":t.map((function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"})).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+"\n vec4 result = vec4(0.);\n "+o+"\n "+s+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Ks=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,a=ao(n.length),i=ao(n.length),o="";if(1===r)o="coords * strides + begin";else{var s=0;o=n.map((function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"})).join(",")}this.userCode="\n "+a+" begin = "+a+"("+t+");\n "+a+" strides = "+a+"("+e+");\n\n void main() {\n "+i+" coords = getOutputCoords();\n setOutput(getX("+o+"));\n }\n "},Xs=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,a=Ys(e,n),i=Js(t,a,n);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 o=this.freeTextures[i].shift();return this.usedTextures[i].push(o),o}return this.numUsedTextures++,this.log(),a===jt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):a===jt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):a===jt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):a===jt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):a===jt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[i].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var a=Js(e,Ys(n,r),r);a in this.freeTextures||(this.freeTextures[a]=[]),this.freeTextures[a].push(t),this.numFreeTextures++,this.numUsedTextures--;var i=this.usedTextures[a],o=i.indexOf(t);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(o,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach((function(e){t.gpgpu.deleteMatrixTexture(e)}));for(var e in this.usedTextures)this.usedTextures[e].forEach((function(e){t.gpgpu.deleteMatrixTexture(e)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function Ys(t,e){if(t===Ut.UPLOAD)return jt.PACKED_2X2_FLOAT32;if(t===Ut.RENDER||null==t)return function(t){return c().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?jt.PACKED_2X2_FLOAT32:jt.UNPACKED_FLOAT32:t?jt.PACKED_2X2_FLOAT16:jt.UNPACKED_FLOAT16}(e);if(t===Ut.DOWNLOAD||t===Ut.PIXELS)return jt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function Js(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var $s=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],a=0;a0?[4,Promise.all(a)]:[3,2];case 1:return u=s.sent(),o.kernelMs=k(u),o.getExtraProfileInfo=function(){return u.map((function(t,e){return{name:i[e],ms:t}})).map((function(t){return t.name+": "+t.ms})).join(", ")},[3,3];case 2:o.kernelMs={error:"WebGL query timers are not supported in this environment."},s.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,o]}}))}))},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:it(),endMs:null}},e.prototype.endTimer=function(t){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=it(),t)},e.prototype.getQueryTime=function(t){return o(this,void 0,void 0,(function(){var e;return s(this,(function(n){return c().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]}))}))},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t)){if(this.pendingRead.has(t))return this.pendingDisposal.add(t),void this.pendingDeletes++;if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}}},e.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,a=e.texShape,i=e.usage,o=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(a,r),this.textureManager.releaseTexture(n,a,i,o)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null},e.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},e.prototype.getDataInfo=function(t){return this.texData.get(t)},e.prototype.getCPUBackend=function(){return c().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Bt.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every((function(t){return null==n.texData.get(t.dataId).texture&&R(t.shape)c().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var a=Math.floor(t.length/2),i=this.concat(t.slice(0,a),e),o=this.concat(t.slice(a),e);return this.concat([i,o],e)}if(c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var s=new ko(t.map((function(t){return t.shape})),e);return this.compileAndRun(s,t)}var u=kn(t.map((function(t){return t.shape})),e),l=t.map((function(t){return t.as2D(-1,R(t.shape.slice(e)))})),p=new So(l.map((function(t){return t.shape})));return this.compileAndRun(p,l).reshape(u)},e.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,au,t.dtype);var e=new Zs(t.shape,au);return this.compileAndRun(e,[t])},e.prototype.batchMatMul=function(t,e,n,r){var a=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],o=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===a||1===i)&&o>1e3){n&&(t=ai(t,[0,2,1])),r&&(e=ai(e,[0,2,1]));var u=1===i?t:t.as3D(s,o,1),l=1===i?2:1,c=1===i?e.as3D(s,1,o):e;return this.multiply(u,c).sum(l,!0)}var p=Tt(t.dtype,e.dtype),h=new Ss(t.shape,[s,a,i],n,r);return this.compileAndRun(h,[t,e],p)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,a=t.transposeB,i=t.bias,o=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],l=a?n.shape[1]:n.shape[2],c=e.shape[0],p=Tt(e.dtype,n.dtype),h=null!=i,f=null!=s,d=o?gu(o,!0):null,m=new Ss(e.shape,[c,u,l],r,a,h,d,f),g=[e,n];return i&&g.push(i),s&&g.push(s),this.compileAndRun(m,g,p)},e.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),a=new ho("return areal * breal - aimag * bimag;",t.shape,e.shape),i=new ho("return areal * bimag + aimag * breal;",t.shape,e.shape),o=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],s=this.compileAndRun(a,o),u=this.compileAndRun(i,o),l=this.complex(s,u);return s.dispose(),u.dispose(),l}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,go,t.dtype);var p=new yo(go,t.shape,e.shape);return this.compileAndRun(p,[t,e],t.dtype)},e.prototype.batchNormalization=function(t,e,n,r,a,i){var o=[t,e,n],s=null;null!=i&&(s=i.shape,o.push(i));var u=null;if(null!=a&&(u=a.shape,o.push(a)),c().getBool("WEBGL_PACK_NORMALIZATION")){var l=new po(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(l,o)}var p=new co(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(p,o)},e.prototype.localResponseNormalization4D=function(t,e,n,r,a){var i=c().getBool("WEBGL_PACK_NORMALIZATION")?new ws(t.shape,e,n,r,a):new bs(t.shape,e,n,r,a);return this.compileAndRun(i,[t])},e.prototype.LRNGrad=function(t,e,n,r,a,i,o){var s=new xs(e.shape,r,a,i,o);return this.compileAndRun(s,[e,n,t])},e.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map((function(t){return ut(t)}));return Li(Qn(t.shape,t.dtype,n),e)}var r=new $s(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(t,e,n){var r=c().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ts(t.shape,e,n):new As(t.shape,e,n);return this.compileAndRun(r,[t])},e.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new Jo(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){I(t.rank<=4,(function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"}));var r=e.reduce((function(t,e){return t*e})),a=hr(t.shape,e,r),i=fr(a.length,e.length),o=dr(t.shape,e,r),s=mr(n,e.length),u=gr(o,n,e.length);return ai(t.reshape(a),i).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){I(t.rank<=4,(function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"}));var r=e.reduce((function(t,e){return t*e})),a=[[0,0]];a.push.apply(a,n);for(var i=1+e.length;ie||n===t?r=!0:n=Q(t,n+1);return n}(o,a),u=new Us({windowSize:s,inSize:o,batchSize:i,numSegments:a},e),l=this.compileAndRun(u,[t,n],r);return l.shape[1]===a?l:(n=Gn(0,a).tile([o/s]),this.segOpCompute(l,e,n,r,a))},e.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(xn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!c().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var a=yn(t.shape,r),i=a[0],o=R(a[1]),s=t.as2D(-1,o);return this.argReduce(s,n).reshape(i)}return this.argReducePacked(t,n)},e.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},e.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},e.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var a=new Bo(t.shape,n,r);return this.compileAndRun(a,[t])},e.prototype.equal=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new yo("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.notEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new yo("return float(a != b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new yo("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.lessEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new yo("return float(a <= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new yo("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greaterEqual=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new yo("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalNot=function(t){var e=new Zs(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new yo("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalOr=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var n=new yo("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.select=function(t,e,n){var r=new js(t.rank,e.shape,e.rank);return this.compileAndRun(r,[t,e,n],Tt(e.dtype,n.dtype))},e.prototype.where=function(t){pn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return Pi(t.shape,e)},e.prototype.topk=function(t,e,n){return Bi(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){xn("min",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a);return this.reduce(i,"min",i.dtype).reshape(r)},e.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.mod=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);xn("max",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a);return this.reduce(i,"max",i.dtype).reshape(r)},e.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.all=function(t,e){xn("all",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a);return this.reduce(i,"all",i.dtype).reshape(r)},e.prototype.any=function(t,e){xn("any",e,t.rank);var n=yn(t.shape,e),r=n[0],a=R(n[1]),i=t.as2D(-1,a);return this.reduce(i,"any",i.dtype).reshape(r)},e.prototype.floorDiv=function(t,e){if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var n=new yo("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",t.shape,e.shape);return this.compileAndRun(n,[t,e],"int32")},e.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,fo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=Tt(t.dtype,e.dtype);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,fo,n);var r=new yo(fo,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.packedUnaryOp=function(t,e,n){var r=new fu(t.shape,e);return this.compileAndRun(r,[t],n)},e.prototype.packedBinaryOp=function(t,e,n,r,a){void 0===a&&(a=!1);var i=new xo(n,t.shape,e.shape,a);return this.compileAndRun(i,[t,e],r)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,a=this.texData.get(t.dataId),i=this.texData.get(e.dataId),o=[[a.complexTensors.real,i.complexTensors.real],[a.complexTensors.imag,i.complexTensors.imag]].map((function(a){var i=a[0],o=a[1],s=r.makeComplexComponentTensorInfo(t,i),u=r.makeComplexComponentTensorInfo(e,o),l=new yo(n,t.shape,e.shape);return r.compileAndRun(l,[s,u],Tt(i.dtype,o.dtype))})),s=o[0],u=o[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorInfo=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>c().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r])}var a=t.map((function(t){return t.dtype})).reduce((function(t,e){return Tt(t,e)})),i=t.map((function(t){return t.shape})),o=c().getBool("WEBGL_PACK")?new Vi(t[0].shape,i):new Wi(t[0].shape,i);return this.compileAndRun(o,t,a)},e.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,mo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=Tt(t.dtype,e.dtype);if(c().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,mo,t.dtype);var r=new yo(mo,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.pow=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),r=Tt(t.dtype,e.dtype);return this.compileAndRun(n,[t,e],r)},e.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,iu,t.dtype);var e=new Zs(t.shape,iu);return this.compileAndRun(e,[t])},e.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ou,t.dtype);var e=new Zs(t.shape,ou);return this.compileAndRun(e,[t])},e.prototype.sign=function(t){var e=new Zs(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},e.prototype.isNaN=function(t){var e=new Zs(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isInf=function(t){var e=new Zs(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isFinite=function(t){var e=new Zs(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.round=function(t){var e=new Zs(t.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(e,[t])},e.prototype.exp=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,su,t.dtype);var e=new Zs(t.shape,su);return this.compileAndRun(e,[t])},e.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,uu,t.dtype);var e=new Zs(t.shape,uu);return this.compileAndRun(e,[t])},e.prototype.softmax=function(t,e){var n=B([e],t.shape),r=this.max(t,n),a=bn(r.shape,n),i=this.subtract(t,r.reshape(a)),o=this.exp(i),s=this.sum(o,n).reshape(a);return _a(o,s)},e.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",t.dtype);var e=new Zs(t.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(e,[t])},e.prototype.log1p=function(t){var e=new Zs(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new Zs(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},e.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new Zs(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new Zs(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(t){var e;return e=c().getBool("WEBGL_PACK")?new fu(t.shape,cu):new Zs(t.shape,eu),this.compileAndRun(e,[t])},e.prototype.relu6=function(t){var e;return e=c().getBool("WEBGL_PACK")?new fu(t.shape,pu):new Zs(t.shape,nu),this.compileAndRun(e,[t])},e.prototype.prelu=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo(bo,t.shape,e.shape):new yo(vo,t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.elu=function(t){if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,hu,t.dtype);var e=new Zs(t.shape,ru);return this.compileAndRun(e,[t])},e.prototype.eluDer=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new yo("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.selu=function(t){var e=new Zs(t.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new Zs(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},e.prototype.clip=function(t,e,n){var r,a=(r=c().getBool("WEBGL_PACK_CLIP")?new Co(t.shape):new wo(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,a)},e.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(c().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,tu,t.dtype);var e=new Zs(t.shape,tu);return this.compileAndRun(e,[t])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new No(t.shape),r=[this.makeComplexComponentTensorInfo(t,e.complexTensors.real),this.makeComplexComponentTensorInfo(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(t){var e=new Zs(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new Zs(t.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(e,[t])},e.prototype.sin=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new Zs(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n");return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan2=function(t,e){var n=c().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new xo("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new yo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.sinh=function(t){var e=new Zs(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.cosh=function(t){var e=new Zs(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.tanh=function(t){var e=new Zs(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},e.prototype.asinh=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new Zs(t.shape,"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new Zs(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(e,[t])},e.prototype.step=function(t,e){var n=new Zs(t.shape,function(t){return void 0===t&&(t=0),Qs+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(t,e,n,r,a,i){var o=t.shape,s=this.texData.get(t.dataId),u=n.inChannels,l=o[0]*o[1]*o[2],p=n.outChannels,h="channelsLast"===n.dataFormat,f=(1===l||1===p)&&u>1e3,d=o[2]%2!=0&&!!s.isPacked;if(f||!c().getBool("WEBGL_LAZILY_UNPACK")||!c().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!d){var m=h?o[0]*o[1]*o[2]:o[0]*o[2]*o[3],g=this.reshape(t,[1,m,n.inChannels]),v=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:g,b:v,transposeA:!1,transposeB:!1,bias:r,activation:a,preluActivationWeights:i}),n.outShape)}var y=h?o[0]*o[1]*(o[2]+1):o[0]*o[2]*(o[3]+1),b={dataId:t.dataId,shape:[1,y,n.inChannels],dtype:t.dtype},x=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,I(De(s.shape,b.shape),(function(){return"packed reshape "+s.shape+" to "+b.shape+" isn't free"}));var w=this.reshape(e,[1,n.inChannels,n.outChannels]),C=this.fusedBatchMatMul({a:b,b:w,transposeA:!1,transposeB:!1,bias:r,activation:a,preluActivationWeights:i}),N=this.texData.get(C.dataId);return I(N.isPacked,(function(){return"batchMatMul result is expected to be packed"})),s.shape=x,N.shape=n.outShape,Bt.makeTensorFromDataId(C.dataId,n.outShape,C.dtype)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,a,i){var o=n.filterWidth,s=n.filterHeight,u=n.inChannels,l=n.outWidth,c=n.outHeight,p="channelsLast"===n.dataFormat,h=o*s*u,f=c*l,d=[h,f],m=t.squeeze([0]),g=e.reshape([1,h,-1]),v=new ys(d,m.shape,n),y=this.compileAndRun(v,[m]).reshape([1,d[0],d[1]]),b=null!=r,x=null!=i,w=a?gu(a,!0):null,C=new Ss(y.shape,[1,f,n.outChannels],!0,!1,b,w,x),N=[y,g];r&&N.push(r),x&&N.push(i);var S=this.compileAndRun(C,N);return p?S.reshape([1,c,l,n.outChannels]):S.reshape([1,n.outChannels,c,l])},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,a=t.bias,i=t.activation,o=t.preluActivationWeights;if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,a,i,o);if(c().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,a,i,o);var s=null!=a,u=null!=o,l=i?gu(i,!1):null,p=new _o(r,s,l,u),h=[e,n];return a&&h.push(a),o&&h.push(o),this.compileAndRun(p,h)},e.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(c().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new _o(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerInput=function(t,e,n){var r=new Ao(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new Eo(n);return this.compileAndRun(r,[t,e])},e.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,a=t.convInfo,i=t.bias,o=t.activation,s=t.preluActivationWeights,u=c().getBool("WEBGL_PACK_DEPTHWISECONV")&&a.strideWidth<=2&&a.outChannels/a.inChannels==1,l=o?gu(o,u):null,p=[n,r],h=null!=i,f=null!=s;return h&&p.push(i),f&&p.push(s),u?(e=new zo(a,h,l,f),this.compileAndRun(e,p)):(e=new Mo(a,h,l,f),this.compileAndRun(e,p))},e.prototype.depthwiseConv2D=function(t,e,n){var r;return c().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new zo(n),this.compileAndRun(r,[t,e])):(r=new Mo(n),this.compileAndRun(r,[t,e]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Oo(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Do(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new Fo(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new Ro(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new To(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new Rs(e,"max",!1);return this.compileAndRun(n,[t])},e.prototype.avgPool=function(t,e){var n=new Rs(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPoolBackprop=function(t,e,n,r){var a=new Rs(r,"max",!0),i=this.compileAndRun(a,[e]),o=new Cs(r),s=this.compileAndRun(o,[t,i],e.dtype);return i.dispose(),s},e.prototype.avgPoolBackprop=function(t,e,n){var r=new uo(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.cast=function(t,e){return xi(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),a=0,i=0;i1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));var r=t.shape[0],a="NHWC"===n?t.shape[1]:t.shape[2],i="NHWC"===n?t.shape[2]:t.shape[3],o="NHWC"===n?t.shape[3]:t.shape[1],s=a*e,u=i*e,l=o/(e*e),c=new Uo("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},e.prototype.split=function(t,e,n){return zi(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=Pa(0,t,n),a=r.sliceRank,i=r.numUpdates,o=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/o,o],c=t.reshape([i,a]),p=e.reshape([i,o]);if(0===u)return wi(Rn([]),n);var h=On(0),f=new Vs(i,a,c.rank,p.rank,s,l);return this.compileAndRun(f,[p,c,h]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var a=Pa(0,t,n),i=a.sliceRank,o=a.numUpdates,s=a.strides,u=a.outputSize,l=new Vs(o,i,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n)},e.prototype.fft=function(t){return this.fftImpl(t,!1)},e.prototype.ifft=function(t){return this.fftImpl(t,!0)},e.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new Xo("return real * expR - imag * expI;",t.shape,e),a=new Xo("return real * expI + imag * expR;",t.shape,e),i=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],o=this.compileAndRun(r,i),s=this.compileAndRun(a,i),u=this.complex(o,s).as2D(t.shape[0],t.shape[1]);return o.dispose(),s.dispose(),u},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],a=Fa(t,e),i=a[0],o=a[1],s=a[2],u=a[3],l=e.reshape([o,r]),c=t.reshape([t.size/s,s]),p=new $o(r,u,[o,s]);return this.compileAndRun(p,[c,l]).reshape(i)},e.prototype.fill=function(t,e,n){if("string"===(n=n||$(e))){var r=V(n,R(t));return r.fill(e),Bt.makeTensor(r,t,n,this)}var a=new Yo(t,e),i=a.getCustomSetupFunc(e);return this.compileAndRun(a,[],n,i)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},e.prototype.linspace=function(t,e,n){return Ci(t,e,n)},e.prototype.makeTensorInfo=function(t,e){var n=this.write(null,t,e);return this.texData.get(n).usage=null,{dataId:n,shape:t,dtype:e}},e.prototype.makeOutput=function(t,e){var n=this.makeTensorInfo(t,e).dataId;return Bt.makeTensorFromDataId(n,t,e,this)},e.prototype.unpackTensor=function(t){var e=new du(t.shape);return this.runWebGLProgram(e,[t],t.dtype)},e.prototype.packTensor=function(t){var e=new Es(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},e.prototype.packedReshape=function(t,e){var n=[Ie(t.shape)].concat(Ee(t.shape)),r={dtype:t.dtype,shape:n,dataId:t.dataId},a=[Ie(e)].concat(Ee(e)),i=new _s(a,n),o=this.runWebGLProgram(i,[r],t.dtype,null,!0);return{dataId:o.dataId,shape:e,dtype:o.dtype}},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,a=n.shape,i=n.dtype,o=Ae(a);return e=r?new Vo(o):new Wo(o),{dtype:i,shape:a,dataId:this.runWebGLProgram(e,[{shape:o,dtype:i,dataId:t}],i,null,!0).dataId}},e.prototype.runWebGLProgram=function(t,e,n,r,a){var i=this;void 0===a&&(a=!1);var o=this.makeTensorInfo(t.outputShape,n),s=this.texData.get(o.dataId);if(t.packedOutput&&(s.isPacked=!0),t.outPackingScheme===Vt.DENSE){var u=Yt(t.outputShape);s.texShape=u.map((function(t){return 2*t}))}if(null!=t.outTexUsage&&(s.usage=t.outTexUsage),0===R(o.shape))return s.values=W(o.dtype,0),o;var l=[],p=e.map((function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=i.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&R(e.shape)<=c().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.packedInputs&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.packedInputs)e=n.isPacked?i.unpackTensor(e):i.packTensor(e),l.push(e),n=i.texData.get(e.dataId);else if(n.isPacked&&!De(n.shape,e.shape)){var r=e,a=e.shape;e.shape=n.shape,e=i.packedReshape(e,a),l.push(e),n=i.texData.get(e.dataId),r.shape=a}return i.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}}));this.uploadToGPU(o.dataId);var h,f={shape:o.shape,texData:s,isUniform:!1},d=function(t,e,n){var r="";e.concat(n).forEach((function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e}));var a=t.userCode;return t.constructor.name+"_"+r+"_"+a}(t,p,f),m=this.getAndSaveBinary(d,(function(){return function(t,e,n,r){var a=e.userCode,i=n.map((function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}})),o=i.map((function(t){return t.shapeInfo})),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=Yi(i,s,a,e.packedInputs),l=t.createProgram(u),p=null,h=t.getUniformLocation(l,"NAN",!1);1===c().getNumber("WEBGL_VERSION")&&(p=t.getUniformLocation(l,"INFINITY",!1));for(var f={},d=0;d0)return 32}return 16}))),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,a=n.dtype,i=n.values,o=n.texture,s=n.usage,u=n.isPacked;if(null==o){var l,c=null!=this.activeTimers;c&&(l=it());var p=n.texShape;if(null==p&&(p=Te(r,u),n.texShape=p),null!=i){var h=Ae(r),f=void 0,d=p[1],m=p[0],g=i instanceof Uint8Array;u?(d=(e=Jt(p[0],p[1]))[0],m=e[1],f=new Ko(h,[m,d],g)):f=new Ho(h,[m,d],g);var v=this.makeTensorInfo([m,d],a);this.texData.get(v.dataId).usage=g?Ut.PIXELS:Ut.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),d,m,i);var y=this.runWebGLProgram(f,[v],a,null,!0),b=this.texData.get(y.dataId);n.texture=b.texture,n.texShape=b.texShape,n.isPacked=b.isPacked,n.usage=b.usage,this.disposeData(v.dataId),this.texData.delete(y.dataId),n.values=null,c&&(this.uploadWaitMs+=it()-l)}else{var x=this.acquireTexture(p,s,a,u);n.texture=x}}},e.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r1024*this.numMBBeforeWarning*1024){var a=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+a+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},e.prototype.computeBytes=function(t,e){return t[0]*t[1]*H(e)},e}(oi);function yu(t,e){return t(e={exports:{}},e.exports),e.exports}Pt()&&Bt.registerBackend("webgl",(function(){return new vu}),2),"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self&&self;var bu=yu((function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}function a(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new r(t),i=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.alea=i}(0,t)})),xu=yu((function(t){!function(t,e,n){function r(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.xor128=i}(0,t)})),wu=yu((function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r>>4),e.next()}function a(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new r(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)})),Cu=yu((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,a=e.i;return t=r[a],n=(t^=t>>>7)^t<<24,n^=(t=r[a+1&7])^t>>>10,n^=(t=r[a+3&7])^t>>>3,n^=(t=r[a+4&7])^t<<7,t=r[a+7&7],n^=(t^=t<<13)^t<<9,r[a]=n,e.i=a+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n0;--n)t.next()}(e,t)}function a(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new r(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.x&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)})),Nu=yu((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,a=e.X,i=e.i;return e.w=r=r+1640531527|0,n=a[i+34&127],t=a[i=i+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=a[i]=n^t,e.i=i,n+(r^r>>>16)|0},function(t,e){var n,r,a,i,o,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),a=0,i=-32;i>>15,r^=r<<4,r^=r>>>13,i>=0&&(o=o+1640531527|0,a=0==(n=s[127&i]^=r+o)?a+1:0);for(a>=128&&(s[127&(e&&e.length||0)]=-1),a=127,i=512;i>0;--i)r=s[a+34&127],n=s[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[a]=r^n;t.w=o,t.X=s,t.i=a}(e,t)}function a(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new r(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.X&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)})),Su=yu((function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,a=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^a,e.a=a-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&a(i,n),o.state=function(){return a(n,{})}),o}e&&e.exports?e.exports=i:this.tychei=i}(0,t)})),ku=yu((function(t){!function(e,r){var a,i=this,o=256,s="random",u=r.pow(o,6),l=r.pow(2,52),c=2*l,p=255;function h(t,n,p){var h=[],v=m(function t(e,n){var r,a=[],i=typeof e;if(n&&"object"==i)for(r in e)try{a.push(t(e[r],n-1))}catch(t){}return a.length?a:"string"==i?e:e+"\0"}((n=1==n?{entropy:!0}:n||{}).entropy?[t,g(e)]:null==t?function(){try{var t;return a&&(t=a.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),g(t)}catch(t){var n=i.navigator,r=n&&n.plugins;return[+new Date,i,r,i.screen,g(e)]}}():t,3),h),y=new f(h),b=function(){for(var t=y.g(6),e=u,n=0;t=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|y.g(4)},b.quick=function(){return y.g(4)/4294967296},b.double=b,m(g(y.S),e),(n.pass||p||function(t,e,n,a){return a&&(a.S&&d(a,y),t.state=function(){return d(y,{})}),n?(r[s]=t,e):t})(b,v,"global"in n?n.global:this==r,n.state)}function f(t){var e,n=t.length,r=this,a=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);a=1,(function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length}));var e=t.map((function(t,e){return dn(t,"tensors"+e,"addN")})),n=e[0];e.forEach((function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),e.forEach((function(t){if(!D(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var r=e;return Bt.runKernelFunc((function(t,n){return t.addN(e)}),r,null,"AddN")}});function Au(){He("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}function Tu(t){return 0===t.rank||1===t.rank?t.as4D(1,1,1,t.size):2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}function Ru(t,e,n,r,a,i){null==i&&(i=.001);var o,s,u=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),c=dn(n,"variance","batchNorm");null!=a&&(o=dn(a,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),I(l.rank===c.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),I(null==s||l.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),I(null==o||l.rank===o.rank,(function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}));var p={x:u,scale:o,offset:s,mean:l,variance:c},h={varianceEpsilon:i};return Bt.runKernelFunc((function(t,e){var n=Tu(u),r=t.batchNormalization(n,Du(l),Du(c),i,Du(o),Du(s));return e([u,l,c,o]),r}),p,null,"FusedBatchNorm",h).reshape(u.shape)}function Du(t){return null==t?null:0===t.rank?t.as1D():1===t.rank?t:2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}var Ou=In({batchNormalization_:function(t,e,n,r,a,i){return void 0===r&&(r=.001),Au(),Ru(t,e,n,i,a,r)}}),_u=In({batchNorm_:Ru});function Fu(t,e,n,r,a,i){var o,s,u=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),c=dn(n,"variance","batchNorm");return null!=a&&(o=dn(a,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),I(2===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),I(2===l.rank||1===l.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."})),I(2===c.rank||1===c.rank,(function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."})),null!=o&&I(2===o.rank||1===o.rank,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."})),null!=s&&I(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),_u(u,l,c,s,o,i)}var Mu=In({batchNormalization2d_:function(t,e,n,r,a,i){return void 0===r&&(r=.001),Au(),Fu(t,e,n,i,a,r)}}),zu=In({batchNorm2d_:Fu});function Lu(t,e,n,r,a,i){var o,s,u=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),c=dn(n,"variance","batchNorm");return null!=a&&(o=dn(a,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),I(3===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),I(3===l.rank||1===l.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."})),I(3===c.rank||1===c.rank,(function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."})),null!=o&&I(3===o.rank||1===o.rank,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."})),null!=s&&I(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),_u(u,l,c,s,o,i)}var Bu=In({batchNormalization3d_:function(t,e,n,r,a,i){return void 0===r&&(r=.001),Au(),Lu(t,e,n,i,a,r)}}),Pu=In({batchNorm3d_:Lu});function Wu(t,e,n,r,a,i){var o,s,u=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),c=dn(n,"variance","batchNorm");return null!=a&&(o=dn(a,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),I(4===u.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."})),I(4===l.rank||1===l.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."})),I(4===c.rank||1===c.rank,(function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."})),null!=o&&I(4===o.rank||1===o.rank,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."})),null!=s&&I(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),_u(u,l,c,s,o,i)}var Vu=In({batchNormalization4d_:function(t,e,n,r,a,i){return void 0===r&&(r=.001),Au(),Wu(t,e,n,i,a,r)}}),Uu=In({batchNorm4d_:Wu}),ju=In({broadcastTo_:function(t,e){var n=dn(t,"broadcastTo","x"),r=n.shape;if(e.some((function(t){return!(t>0)||t%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+e+"].");if(e.lengthn.rank){for(var a=n.shape.slice();a.length=0;s--)if(i[s]===e[s])o[s]=1;else if(1!==n.shape[s])throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+e+"].");var u=o.map((function(t,e){return t>1?e:-1})).filter((function(t){return t>=0}));if(0===u.length)return n.clone();var l={x:n},c={shape:e,inputShape:i};return Bt.runKernelFunc((function(t){return t.tile(n,o)}),l,(function(t){return{x:function(){return t.sum(u,!0)}}}),kr,c)}}),Gu=In({clone_:function(t){var e=dn(t,"x","clone",null);return Bt.runKernelFunc((function(){return Bt.makeTensorFromDataId(e.dataId,e.shape,e.dtype)}),{x:e},null,Er)}}),qu=In({logicalAnd_:function(t,e){var n=dn(t,"a","logicalAnd","bool"),r=dn(e,"b","logicalAnd","bool");return Mr(n.shape,r.shape),Bt.runKernelFunc((function(t){return t.logicalAnd(n,r)}),{a:n,b:r},null,"LogicalAnd")}}),Hu=In({logicalNot_:function(t){var e=dn(t,"x","logicalNot","bool");return Bt.runKernelFunc((function(t){return t.logicalNot(e)}),{$x:e})}}),Ku=In({logicalOr_:function(t,e){var n=dn(t,"a","logicalOr","bool"),r=dn(e,"b","logicalOr","bool");return Mr(n.shape,r.shape),Bt.runKernelFunc((function(t){return t.logicalOr(n,r)}),{$a:n,$b:r})}}),Xu=In({logicalXor_:function(t,e){var n=dn(t,"a","logicalXor","bool"),r=dn(e,"b","logicalXor","bool");return Mr(n.shape,r.shape),Ku(t,e).logicalAnd(qu(t,e).logicalNot())}}),Yu=In({where_:function(t,e,n){var r=dn(e,"a","where"),a=dn(n,"b","where"),i=dn(t,"condition","where","bool");return E(r.shape,a.shape,"Error in where: "),1===i.rank?I(i.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):E(i.shape,a.shape,"Error in where: "),Bt.runKernelFunc((function(t,e){var n=t.select(i,r,a);return e([i]),n}),{$condition:i,$a:r,$b:a},(function(t,e){var n=e[0];return{$condition:function(){return Hn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}}))}}),Ju=function(t){return o(this,void 0,void 0,(function(){var e,n,r;return s(this,(function(a){switch(a.label){case 0:return[4,(e=dn(t,"condition","whereAsync","bool")).data()];case 1:return n=a.sent(),r=Pi(e.shape,n),t!==e&&e.dispose(),[2,r]}}))}))},$u=In({divNoNan_:function(t,e){var n,r=dn(t,"a","div"),a=dn(e,"b","div");r=(n=Dt(r,a))[0],a=n[1];var i=_a(r,a),o=Hn(i),s=a.equal(o);return Yu(s,o,i)}}),Zu=In({tile_:function(t,e){var n=dn(t,"x","tile",null);I(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}));var r=[n],a={x:n},i={reps:e};return Bt.runKernelFunc((function(t,r){var a=t.tile(n,e);return r([n]),a}),a,null,Ar,i,r)}}),Qu=In({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var a=Qn([t,e],r),i=t<=e?t:e,o=0;o2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var s=1===o?a.as2D(1,-1):a,u=Bt.runKernelFunc((function(t){return t.multinomial(s,r,e,n)}),{logits2D:s});return 1===o?u.as1D():u}}),el=In({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var a=dn(t,"indices","oneHot","int32"),i=a.shape.concat([e]),o={indices:a=a.flatten()},s={depth:e,onValue:n,offValue:r};return Bt.runKernelFunc((function(t,i){return i([a]),t.oneHot(a,e,n,r)}),o,null,Ir,s).reshape(i)}}),nl=In({pad_:function(t,e,n){void 0===n&&(n=0);var r=dn(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var a={paddings:e,constantValue:n},i={x:r};return Bt.runKernelFunc((function(t,a){return a([r]),t.pad(r,e,n)}),i,null,Tr,a)}}),rl=In({pad1d_:function(t,e,n){return void 0===n&&(n=0),I(2===e.length,(function(){return"Invalid number of paddings. Must be length of 2."})),nl(t,[e],n)}}),al=In({pad2d_:function(t,e,n){return void 0===n&&(n=0),I(2===e.length&&2===e[0].length&&2===e[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),nl(t,e,n)}}),il=In({pad3d_:function(t,e,n){return void 0===n&&(n=0),I(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),nl(t,e,n)}}),ol=In({pad4d_:function(t,e,n){return void 0===n&&(n=0),I(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),nl(t,e,n)}}),sl=In({rand_:function(t,e,n){var r=R(t),a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);a=new Uint8Array(r)}for(var i=0;in)}var pl=Object.freeze({TEST_EPSILON_FLOAT16:.1,expectArraysClose:function(t,e,n){return null==n&&(n=ul()),ll(t,e,(function(t,e){return cl(t,e,n)}))},testEpsilon:ul,expectPromiseToFail:function(t,e){t().then((function(){return e.fail()}),(function(){return e()}))},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return X(t)||X(t[0])||X(e)||X(e[0])?ll(t,n,(function(t,e){return t==e})):ll(t,e,(function(t,e){return cl(t,e,0)}))},expectNumbersClose:function(t,e,n){if(null==n&&(n=ul()),!cl(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;rn)throw new Error("Value out of range:"+t[r]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}}),hl=function(){function t(t,e,n,r,a){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var i=a||Math.random();this.random=Iu(i.toString())}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,r=!1;!r;){var a=void 0,i=void 0,o=void 0;do{o=(a=2*this.random()-1)*a+(i=2*this.random()-1)*i}while(o>=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*a*s,n=this.mean+this.stdDev*i*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),fl=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var a=r||Math.random();this.randu=Iu(a.toString()),this.randn=new hl(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,a,i;;){do{r=this.randn.nextValue(),i=1+this.c*r}while(i<=0);if(i*=i*i,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-i+Math.log(i)),(a=this.randu())0,(function(){return"mask cannot be scalar"})),E(u.slice(i,i+o),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,c=i;c=2&&o.rank>=2&&i.rank===o.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+i.rank+" and "+o.rank+"."})),I(D(p,h),(function(){return"Error in matMul: outer dimensions ("+p+") and ("+h+") of Tensors with shapes "+i.shape+" and "+o.shape+" must match."})),I(s===u,(function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+i.shape+" and "+o.shape+" and transposeA="+n+" and transposeB="+r+" must match."}));var m=i.shape.slice(0,-2).concat([l,c]),g=n?i.as3D(f,s,l):i.as3D(f,l,s),v=r?o.as3D(d,c,u):o.as3D(d,u,c),y={transposeA:n,transposeB:r};return Bt.runKernelFunc((function(t,e){var a=t.batchMatMul(g,v,n,r);return e([g,v]),a}),{a:g,b:v},(function(t,e){var a=e,i=a[0],o=a[1];return n||r?!n&&r?{a:function(){return t.matMul(o,!1,!1)},b:function(){return t.matMul(i,!0,!1)}}:n&&!r?{a:function(){return o.matMul(t,!1,!0)},b:function(){return i.matMul(t,!1,!1)}}:{a:function(){return o.matMul(t,!0,!0)},b:function(){return t.matMul(i,!0,!0)}}:{a:function(){return t.matMul(o,!1,!0)},b:function(){return i.matMul(t,!0,!1)}}}),"BatchMatMul",y).reshape(m)}}),Ql=In({dot_:function(t,e){var n=dn(t,"t1","dot"),r=dn(e,"t2","dot");I(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."}));var a=1===n.rank?n.size:n.shape[1],i=1===r.rank?r.size:r.shape[0];return I(a===i,(function(){return"Error in dot: inner dimensions of inputs must match, but got "+a+" and "+i+"."})),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),tc=In({outerProduct_:function(t,e){var n=dn(t,"v1","outerProduct"),r=dn(e,"v2","outerProduct");return I(1===n.rank&&1===r.rank,(function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."})),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),ec=In({reverse_:function(t,e){var n=dn(t,"x","reverse");if(0===n.rank)return n.clone();var r=B(e,n.shape);return Bt.runKernelFunc((function(t){return t.reverse(n,r)}),{$x:n},(function(t){return{$x:function(){return t.reverse(r)}}})).reshapeAs(n)}}),nc=In({reverse1d_:function(t){var e=dn(t,"x","reverse");return I(1===e.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."})),ec(e,0)}}),rc=In({reverse2d_:function(t,e){var n=dn(t,"x","reverse");return I(2===n.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."})),ec(n,e)}}),ac=In({reverse3d_:function(t,e){var n=dn(t,"x","reverse");return I(3===n.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."})),ec(n,e)}}),ic=In({reverse4d_:function(t,e){var n=dn(t,"x","reverse");return I(4===n.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."})),ec(n,e)}});function oc(t,e,n,r,a,i){var o=dn(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),null==r&&(r=[1,1]),I(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),I(yi(n,r),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"})),null!=i&&I(O(a),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var l=ui(s.shape,e,n,r,a,i);if(1===l.filterWidth&&1===l.filterHeight&&D(l.inShape,l.outShape))return o.clone();var c=[s],p=Bt.runKernelFunc((function(t,e){var n=t.maxPool(s,l);return e([s,n]),n}),{x:s},(function(t,i){var o=i[0],s=i[1];return{x:function(){return function(t,e,n,r,a,i,o,s){var u=dn(t,"dy","maxPoolBackprop"),l=dn(e,"input","maxPoolBackprop"),c=dn(n,"output","maxPoolBackprop");I(l.rank===u.rank,(function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"})),null==i&&(i=[1,1]),I(yi(a,i),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+i+"'"})),I(4===u.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."})),I(4===l.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."}));var p=ui(l.shape,r,a,i,o,void 0);return Bt.runKernelFunc((function(t){return t.maxPoolBackprop(u,l,c,p)}),{$dy:u,$input:l})}(t,o,s,e,n,r,a)}}}),"MaxPool",l,c);return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function sc(t,e,n,r,a,i){var o=dn(t,"x","avgPool","float32");null==r&&(r=[1,1]),I(yi(n,r),(function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}));var s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),I(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=i&&I(O(a),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var l=ui(s.shape,e,n,r,a,i);if(1===l.filterWidth&&1===l.filterHeight&&D(l.inShape,l.outShape))return o.clone();var c=Bt.runKernelFunc((function(t){return t.avgPool(s,l)}),{x:s},(function(t){return{x:function(){return function(t,e,n,r,a,i){var o=dn(t,"dy","avgPoolBackprop"),s=dn(e,"input","avgPoolBackprop");I(s.rank===o.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+o.rank+")"})),null==a&&(a=[1,1]),I(yi(r,a),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+a+"'"}));var u=s,l=o,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),I(4===l.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."})),I(4===u.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}));var p=ui(u.shape,n,r,a,i),h=Bt.runKernelFunc((function(t){return t.avgPoolBackprop(l,u,p)}),{dy4D:l,input4D:u});return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}(t,s,e,n,r,a)}}}),"AvgPool",l);return c=c.cast(o.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var uc=In({maxPool_:function(t,e,n,r,a){return oc(t,e,n,1,r,a)}}),lc=In({avgPool_:function(t,e,n,r,a){return sc(t,e,n,1,r,a)}}),cc=In({pool_:function(t,e,n,r,a,i){null==a&&(a=[1,1]),null==i&&(i=1),0===r&&(r="valid");var o=dn(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),I(yi(i,a),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'"}));var l,c=ui(s.shape,e,i,a,r),p=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map((function(t,n){return t+(t-1)*(e[n]-1)})).map((function(t){return t-1})),r=n.map((function(t){return Math.floor(t/2)})),a=n.map((function(t,e){return t-r[e]}));return n.map((function(t,e){return[r[e],a[e]]}))}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];var h=1===p[0]&&1===p[1],f=function(t,e,n){var r=n.map((function(t){return t[0]})),a=n.map((function(t){return t[1]})),i=t.concat(r,a),o=e.map((function(t,e){return(t-i[e]%t)%t})),s=a.map((function(t,e){return t+o[e]}));return[e.map((function(t,e){return[r[e],s[e]]})),e.map((function(t,e){return[0,o[e]]}))]}([c.inHeight,c.inWidth],p,l),d=f[0],m=f[1],g=h?r:"valid",v=h?s:sr(s,p,d),y=("avg"===n?function(){return sc(v,e,i,1,g)}:function(){return oc(v,e,i,1,g)})(),b=h?y:er(y,p,m);return u?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}}),pc=In({maxPool3d_:function(t,e,n,r,a,i,o){void 0===i&&(i="NDHWC");var s=dn(t,"x","maxPool3d"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),I(5===u.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."})),I("NDHWC"===i,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+i})),I(yi(n,o),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),null!=a&&I(O(r),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var c=li(u.shape,e,n,o,r,a,i),p=Bt.runKernelFunc((function(t,e){var n=t.maxPool3d(u,c);return e([u,n]),n}),{x:u},(function(t,i){var s=i[0],u=i[1];return{x:function(){return function(t,e,n,r,a,i,o,s){var u=dn(t,"dy","maxPool3dBackprop"),l=dn(e,"input","maxPool3dBackprop"),c=dn(n,"output","maxPool3dBackprop"),p=u,h=l,f=c,d=!1;4===l.rank&&(d=!0,p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),h=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),f=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),I(5===p.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+p.rank+"."})),I(5===h.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+h.rank+"."})),I(5===f.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+f.rank+"."})),null==i&&(i=[1,1,1]),I(yi(a,i),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+i+"'"})),null!=s&&I(O(o),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+o+"."}));var m=li(h.shape,r,a,i,o,s),g=Bt.runKernelFunc((function(t){return t.maxPool3dBackprop(p,h,f,m)}),{dy5D:p,input5D:h});return d?g.as4D(g.shape[1],g.shape[2],g.shape[3],g.shape[4]):g}(t,s,u,e,n,o,r,a)}}}));return l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),hc=In({avgPool3d_:function(t,e,n,r,a,i,o){void 0===i&&(i="NDHWC");var s=dn(t,"x","avgPool3d","float32"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),I(5===u.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."})),I("NDHWC"===i,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+i})),I(yi(n,o),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"})),null!=a&&I(O(r),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}));var c=li(u.shape,e,n,o,r,a,i),p=Bt.runKernelFunc((function(t){return t.avgPool3d(u,c)}),{x:u},(function(t){return{x:function(){return function(t,e,n,r,a,i,o){var s=dn(t,"dy","avgPool3dBackprop"),u=dn(e,"input","avgPool3dBackprop"),l=s,c=u,p=!1;4===u.rank&&(p=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),c=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),I(5===l.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+l.rank+"."})),I(5===c.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+c.rank+"."})),null==a&&(a=[1,1,1]),I(yi(r,a),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+a+"'"})),null!=o&&I(O(i),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."}));var h=li(c.shape,n,r,a,i,o),f=Bt.runKernelFunc((function(t){return t.avgPool3dBackprop(l,c,h)}),{dy5D:l,input5D:c});return p?f.as4D(f.shape[1],f.shape[2],f.shape[3],f.shape[4]):f}(t,u,e,n,o,r,a)}}}));return p=p.cast(u.dtype),l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),fc=In({maxPoolWithArgmax_:function(t,e,n,r,a){void 0===a&&(a=!1);var i=dn(t,"x","maxPoolWithArgmax"),o={filterSize:e,strides:n,pad:r,includeBatchInIndex:a},s=Bt.runKernel("MaxPoolWithArgmax",{x:i},o);return{result:s[0],indexes:s[1]}}}),dc=In({slice_:function(t,e,n){var r,a,i=dn(t,"x","slice");if(0===i.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(i.rank-1).fill(0)):e.length=0?t:(I(-1===t,(function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."})),i.shape[e]-r[e])})),Va(i,r,a);var o=i.shape,s={begin:r,size:a};return Bt.runKernelFunc((function(t){return t.slice(i,r,a)}),{x:i},(function(t){for(var e=[],n=0;n0&&(e=e.sum(i)),e.reshape(r.shape)}}}),"Prelu")}}),Fc=In({relu_:function(t){var e=dn(t,"x","relu");return"bool"===e.dtype?e.toInt():Bt.runKernelFunc((function(t,n){var r=t.relu(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0];return{x:function(){return t.mulStrict(n.step().toFloat())}}}),"Relu")}}),Mc=In({relu6_:function(t){var e=dn(t,"x","relu6");return"bool"===e.dtype?e.toInt():Bt.runKernelFunc((function(t,n){var r=t.relu6(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return t.mulStrict(r.toFloat())}}}),"Relu6")}}),zc=In({selu_:function(t){var e=dn(t,"x","selu");return Bt.runKernelFunc((function(t,n){var r=t.selu(e);return n([e]),r}),{$x:e},(function(t,e){var n=e[0];return{$x:function(){var e=n.greater(On(0)),r=On(1.7580993408473768),a=On(1.0507009873554805),i=t.mul(a),o=t.mul(r).mul(n.toFloat().exp());return Yu(e,i,o)}}}))}}),Lc=In({localResponseNormalization_:function(t,e,n,r,a){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===a&&(a=.5);var i=dn(t,"x","localResponseNormalization");I(4===i.rank||3===i.rank,(function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+i.rank+"."})),I(O(e),(function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."}));var o=i,s=!1;3===i.rank&&(s=!0,o=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]));var u=Bt.runKernelFunc((function(t,i){var s=t.localResponseNormalization4D(o,e,n,r,a);return i([o,s]),s}),{x4D:o},(function(t,i){var o=i[0],s=i[1];return{x4D:function(){return Bt.runKernelFunc((function(i){return i.LRNGrad(t,o,s,e,n,r,a)}),{})}}}));return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Bc=In({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var a=function t(e,n,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(On(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(t=dn(t,"x","norm"),e,n),i=a.shape;if(r){var o=B(n,t.shape);i=bn(a.shape,o)}return a.reshape(i)}}),Pc=In({basicLSTMCell_:function(t,e,n,r,a,i){var o=dn(t,"forgetBias","basicLSTMCell"),s=dn(e,"lstmKernel","basicLSTMCell"),u=dn(n,"lstmBias","basicLSTMCell"),l=dn(r,"data","basicLSTMCell"),c=dn(a,"c","basicLSTMCell"),p=dn(i,"h","basicLSTMCell"),h=l.concat(p,1).matMul(s).add(u),f=h.shape[0],d=h.shape[1]/4,m=[f,d],g=h.slice([0,0],m),v=h.slice([0,d],m),y=h.slice([0,2*d],m),b=h.slice([0,3*d],m),x=g.sigmoid().mulStrict(v.tanh()).addStrict(c.mulStrict(o.add(y).sigmoid())),w=x.tanh().mulStrict(b.sigmoid());return[x,w]}}),Wc=In({multiRNNCell_:function(t,e,n,r){for(var a=dn(e,"data","multiRNNCell"),i=mn(n,"c","multiRNNCell"),o=mn(r,"h","multiRNNCell"),s=a,u=[],l=0;la)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+e);var i=Bt.runKernelFunc((function(t){return t.topk(r,e,n)}),{$x:r});return{values:i[0],indices:i[1]}}}),Gc=In({scatterND_:function(t,e,n){var r=dn(t,"indices","scatterND","int32"),a=dn(e,"updates","scatterND");return Ba(a,r,n),Bt.runKernelFunc((function(t){return t.scatterND(r,a,n)}),{indices:r,updates:a},null,"ScatterNd",{shape:n})}}),qc=In({fft_:function(t){I("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Bt.runKernelFunc((function(t){return t.fft(r)}),{input:t}).reshape(t.shape)}}),Hc=In({ifft_:function(t){I("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Bt.runKernelFunc((function(t){return t.ifft(r)}),{input:t}).reshape(t.shape)}}),Kc=In({rfft_:function(t,e){I("float32"===t.dtype,(function(){return"The dtype for rfft() must be real value but got "+t.dtype}));var n,r=t.shape[t.shape.length-1],a=t.size/r;if(null!=e&&er){var s=t.shape.map((function(t){return t}));s[t.shape.length-1]=e-r,n=t.concat(Vn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),l=En(n,u).as2D(a,r),c=qc(l),p=Math.floor(r/2)+1,h=An(c),f=Tn(c),d=h.split([p,r-p],h.shape.length-1),m=f.split([p,r-p],f.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=p,En(d[0],m[0]).reshape(g)}}),Xc=In({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),a=Hc(r);return An(a)}var i=[n,2*(e-1)],o=An(t).as2D(n,e),s=Tn(t).as2D(n,e),u=o.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(On(-1)),c=o.concat(u,1),p=s.concat(l,1);return r=En(c,p).as2D(i[0],i[1]),a=Hc(r),An(a)}}),Yc=Object.freeze({fft:qc,ifft:Hc,rfft:Kc,irfft:Xc}),Jc=In({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var a=dn(t,"sparseIndices","sparseToDense","int32"),i=dn(e,"sparseValues","sparseToDense"),o=dn(r,"defaultValue","sparseToDense",i.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var a=t.rank>0?t.shape[0]:1,i=t.rank>1?t.shape[1]:1;if(n.length!==i)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+i+".");var o=e.size;if(0!==e.rank&&(1!==e.rank||o!==a))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+a+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,i,n,o),Bt.runKernelFunc((function(t){return t.sparseToDense(a,i,n,o)}),{$sparseIndices:a,$sparseValues:i,$defaultValue:o})}}),$c=In({gatherND_:function(t,e){var n=dn(e,"indices","gatherND","int32"),r=dn(t,"x","gatherND");return Bt.runKernelFunc((function(t){return t.gatherND(r,n)}),{x:r,indices:n},null,"GatherNd")}}),Zc=In({diag_:function(t){var e=dn(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Bt.runKernelFunc((function(t){return t.diag(e)}),{$x:e}).reshape(n)}}),Qc=In({dropout_:function(t,e,n,r){var a=dn(t,"x","dropout");if(I("float32"===a.dtype,(function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+a.dtype+" tensor instead."})),I(e>=0&&e<1,(function(){return"rate must be a float in the range [0, 1), but got "+e+"."})),0===e)return t instanceof wt?a.clone():a;var i=function(t,e){if(null==e)return t.shape.slice();if(D(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank})),I(r.rank-1===a.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+a.rank})),E(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),i=r.shape[r.shape.length-1],I(n>0&&n<=i,(function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+i+"), but got "+n})),[4,r.data()];case 1:return o=s.sent(),[4,a.data()];case 2:for(u=s.sent(),l=[o.length/i,i],p=l[1],h=W("bool",c=l[0]),f=0;f1?s.div(On(o)):s}if(n===ep.SUM_BY_NONZERO_WEIGHTS){if(null==a)return i.sum().div(On(r.size));var u=a.mul(Wn(r.shape)).notEqual(On(0)).sum().toFloat();return i.sum().div(u)}throw Error("Unknown reduction: "+n)}}),cp=In({cosineDistance_:function(t,e,n,r,a){void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"labels","cosineDistance"),o=dn(e,"predictions","cosineDistance"),s=null;null!=r&&(s=dn(r,"weights","cosineDistance")),E(i.shape,o.shape,"Error in cosineDistance: ");var u=On(1).sub(i.mul(o).sum(n,!0));return lp(u,s,a)}}),pp=In({hingeLoss_:function(t,e,n,r){void 0===r&&(r=ep.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"labels","hingeLoss"),i=dn(e,"predictions","hingeLoss"),o=null;null!=n&&(o=dn(n,"weights","hingeLoss")),E(a.shape,i.shape,"Error in hingeLoss: ");var s=On(1);a=On(2).mul(a).sub(s);var u=s.sub(a.mul(i)).relu();return lp(u,o,r)}}),hp=In({huberLoss_:function(t,e,n,r,a){void 0===r&&(r=1),void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"labels","huberLoss"),o=dn(e,"predictions","huberLoss"),s=null;null!=n&&(s=dn(n,"weights","huberLoss")),E(i.shape,o.shape,"Error in huberLoss: ");var u=On(r),l=o.sub(i).abs(),c=Ca(l,u),p=l.sub(c),h=On(.5).mul(c.square()).add(u.mul(p));return lp(h,s,a)}}),fp=In({logLoss_:function(t,e,n,r,a){void 0===r&&(r=1e-7),void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"labels","logLoss"),o=dn(e,"predictions","logLoss"),s=null;null!=n&&(s=dn(n,"weights","logLoss")),E(i.shape,o.shape,"Error in logLoss: ");var u=On(1),l=On(r),c=i.mul(o.add(l).log()).neg().sub(u.sub(i).mul(u.sub(o).add(l).log()));return lp(c,s,a)}}),dp=In({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=ep.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"labels","meanSquaredError"),i=dn(e,"predictions","meanSquaredError"),o=null;null!=n&&(o=dn(n,"weights","meanSquaredError")),E(a.shape,i.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(i);return lp(s,o,r)}}),mp=In({sigmoidCrossEntropy_:function(t,e,n,r,a){void 0===r&&(r=0),void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"multiClassLabels","sigmoidCrossEntropy"),o=dn(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=dn(n,"weights","sigmoidCrossEntropy")),E(i.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=On(r),l=On(1),c=On(.5);i=i.mul(l.sub(u)).add(c.mul(u))}var p=function(t,e){var n=dn(t,"labels","sigmoidCrossEntropyWithLogits"),r=dn(e,"logits","sigmoidCrossEntropyWithLogits");E(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var a=r.relu(),i=r.mul(n),o=r.abs().neg().exp().log1p();return a.sub(i).add(o)}(i,o);return lp(p,s,a)}}),gp=In({softmaxCrossEntropy_:function(t,e,n,r,a){void 0===r&&(r=0),void 0===a&&(a=ep.SUM_BY_NONZERO_WEIGHTS);var i=dn(t,"onehotLabels","softmaxCrossEntropy"),o=dn(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=dn(n,"weights","softmaxCrossEntropy")),E(i.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){var u=On(r),l=On(1),c=On(i.shape[1]);i=i.mul(l.sub(u)).add(u.div(c))}var p=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return ti((function(t,e,r){var a=e.logSumExp([n],!0),i=e.toFloat().sub(a);return r([t,i]),{value:i.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],a=e[1],i=bn(t.shape,[n]);return[t.reshape(i).mul(r.toFloat().sub(a.exp())),t.reshape(i).mul(a.exp().sub(r.toFloat()))]}}}))(t,e)}(i,o);return lp(p,s,a)}}),vp=Object.freeze({get Reduction(){return ep},absoluteDifference:up,computeWeightedLoss:lp,cosineDistance:cp,hingeLoss:pp,huberLoss:hp,logLoss:fp,meanSquaredError:dp,sigmoidCrossEntropy:mp,softmaxCrossEntropy:gp});function yp(t,e){return void 0===e&&(e=!1),Bt.tidy((function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],a=Qu(n),i=t.clone(),o=Fn([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(t){var e,u=i,l=s,c=a;e=Bt.tidy((function(){var e=i.slice([t,t],[n-t,1]),u=e.norm(),l=i.slice([t,t],[1,1]),c=Fn([[-1]]).where(l.greater(0),Fn([[1]])),p=l.sub(c.mul(u)),h=e.div(p);s=1===h.shape[0]?o.clone():o.concat(h.slice([1,0],[h.shape[0]-1,h.shape[1]]),0);var f=c.matMul(p).div(u).neg(),d=i.slice([t,0],[n-t,r]),m=f.mul(s),g=s.transpose();if(0===t)i=d.sub(m.matMul(g.matMul(d)));else{var v=d.sub(m.matMul(g.matMul(d)));i=i.slice([0,0],[t,r]).concat(v,0)}var y=m.transpose(),b=a.slice([0,t],[n,a.shape[1]-t]);if(0===t)a=b.sub(b.matMul(s).matMul(y));else{var x=b.sub(b.matMul(s).matMul(y));a=a.slice([0,0],[n,t]).concat(x,1)}return[s,i,a]})),s=e[0],i=e[1],a=e[2],Ze([u,l,c])},c=0;cr&&(a=a.slice([0,0],[n,r]),i=i.slice([0,0],[r,r])),[a,i]}))}var bp=In({bandPart_:function(t,e,n){if(e%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+e+".");if(n%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+n+".");var r=dn(t,"a","bandPart");if(r.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+r.rank+".");var a=r.shape,i=r.shape.slice(-2),o=i[0],s=i[1];if(!(e<=o))throw new Error("bandPart(): numLower ("+e+") must not be greater than the number of rows ("+o+").");if(!(n<=s))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+s+").");e<0&&(e=o),n<0&&(n=s);var u=Gn(0,o,1,"int32").reshape([-1,1]),l=Gn(0,s,1,"int32"),c=Da(u,l),p=qu(c.lessEqual(On(+e,"int32")),c.greaterEqual(On(-n,"int32"))),h=Vn([o,s],r.dtype);return lr(cr(r.reshape([-1,o,s])).map((function(t){return Yu(p,t,h)}))).reshape(a)}}),xp=In({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,I(null!=t&&t.length>0,(function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"}));for(var n=t[0].shape[0],r=function(e){I(t[e].shape[0]===n,(function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"}))},a=1;a0)for(var n=0;n= 2, but got rank "+t.rank);if(2===t.rank)return yp(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce((function(t,e){return t*e})),r=cr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),a=[],i=[];return r.forEach((function(t){var n=yp(t,e),r=n[0],o=n[1];a.push(r),i.push(o)})),[lr(a,0).reshape(t.shape),lr(i,0).reshape(t.shape)]}}),Cp=Object.freeze({bandPart:bp,gramSchmidt:xp,qr:wp});function Np(t,e,n,r,a,i){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==i&&(i=0);var o=t.shape[0];return n=Math.min(n,o),I(0<=r&&r<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"})),I(2===t.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"})),I(4===t.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]})),I(1===e.rank,(function(){return"scores must be a 1D tensor"})),I(e.shape[0]===o,(function(){return"scores has incompatible shape with boxes. Expected "+o+", but was "+e.shape[0]})),I(0<=i&&i<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+i+"'"})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:i}}var Sp=In({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=dn(t,"images","resizeBilinear");I(3===r.rank||4===r.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."})),I(2===e.length,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."}));var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=e[0],s=e[1],u=Bt.runKernelFunc((function(t,e){return e([a]),t.resizeBilinear(a,o,s,n)}),{x:a},(function(t,e){return{x:function(){return Bt.runKernelFunc((function(r){return r.resizeBilinearBackprop(t,e[0],n)}),{})}}}),"ResizeBilinear",{alignCorners:n,newHeight:o,newWidth:s});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),kp=In({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=dn(t,"images","resizeNearestNeighbor");I(3===r.rank||4===r.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."})),I(2===e.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."})),I("float32"===r.dtype||"int32"===r.dtype,(function(){return"`images` must have `int32` or `float32` as dtype"}));var a=r,i=!1;3===r.rank&&(i=!0,a=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=e[0],s=e[1],u=Bt.runKernelFunc((function(t,e){return e([a]),t.resizeNearestNeighbor(a,o,s,n)}),{batchImages:a},(function(t,e){return{batchImages:function(){return Bt.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)}),{})}}}));return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Ip=In({nonMaxSuppression_:function(t,e,n,r,a){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY);var i=dn(t,"boxes","nonMaxSuppression"),o=dn(e,"scores","nonMaxSuppression"),s=Np(i,o,n,r,a);n=s.maxOutputSize,r=s.iouThreshold,a=s.scoreThreshold;var u={maxOutputSize:n,iouThreshold:r,scoreThreshold:a};return Bt.runKernelFunc((function(t){return t.nonMaxSuppression(i,o,n,r,a)}),{boxes:i,scores:o},null,"NonMaxSuppressionV3",u)}}),Ep=In({nonMaxSuppressionWithScore_:function(t,e,n,r,a,i){void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),void 0===i&&(i=0);var o=dn(t,"boxes","nonMaxSuppression"),s=dn(e,"scores","nonMaxSuppression"),u=Np(o,s,n,r,a,i),l={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:i=u.softNmsSigma},c=Bt.runKernel("NonMaxSuppressionV5",{boxes:o,scores:s},l);return{selectedIndices:c[0],selectedScores:c[1]}}}),Ap=In({cropAndResize_:function(t,e,n,r,a,i){var o=dn(t,"image","cropAndResize"),s=dn(e,"boxes","cropAndResize","float32"),u=dn(n,"boxInd","cropAndResize","int32");a=a||"bilinear",i=i||0;var l=s.shape[0];return I(4===o.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."})),I(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."})),I(1===u.rank&&u.shape[0]===l,(function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."})),I(2===r.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."})),I(r[0]>=1&&r[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+r})),I("bilinear"===a||"nearest"===a,(function(){return"method must be bilinear or nearest, but was "+a})),Bt.runKernelFunc((function(t,e){return t.cropAndResize(o,s,u,r,a,i)}),{images:o,boxes:s,boxInd:u},null,"CropAndResize",{method:a,extrapolationValue:i,cropSize:r})}}),Tp=Object.freeze({resizeBilinear:Sp,resizeNearestNeighbor:kp,nonMaxSuppression:Ip,nonMaxSuppressionAsync:function(t,e,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),o(this,void 0,void 0,(function(){var i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:return i=dn(t,"boxes","nonMaxSuppressionAsync"),o=dn(e,"scores","nonMaxSuppressionAsync"),u=Np(i,o,n,r,a),n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,[4,Promise.all([i.data(),o.data()])];case 1:return l=s.sent(),c=l[0],p=l[1],h=Ri(c,p,n,r,a),i!==t&&i.dispose(),o!==e&&o.dispose(),[2,h]}}))}))},nonMaxSuppressionWithScore:Ep,nonMaxSuppressionWithScoreAsync:function(t,e,n,r,a,i){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),void 0===i&&(i=0),o(this,void 0,void 0,(function(){var o,u,l,c,p,h,f;return s(this,(function(s){switch(s.label){case 0:return o=dn(t,"boxes","nonMaxSuppressionAsync"),u=dn(e,"scores","nonMaxSuppressionAsync"),l=Np(o,u,n,r,a,i),n=l.maxOutputSize,r=l.iouThreshold,a=l.scoreThreshold,i=l.softNmsSigma,[4,Promise.all([o.data(),u.data()])];case 1:return c=s.sent(),p=c[0],h=c[1],f=Di(p,h,n,r,a,i),o!==t&&o.dispose(),u!==e&&u.dispose(),[2,f]}}))}))},cropAndResize:Ap}),Rp=function(t,e){return!(t>0)||"linear"===e},Dp=function(t,e,n){if(null==n||"linear"===n)return t;if("relu"===n)return t.mul(e.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},Op=function(t,e){var n=e,r=Fr(t.shape,e.shape);return r.length>0&&(n=n.sum(r)),n.reshape(t.shape)},_p=function(t,e,n){if("linear"===e)return t;if("relu"===e)return Fc(t);if("elu"===e)return Dc(t);if("relu6"===e)return Mc(t);if("prelu"===e)return _c(t,n);throw new Error("Unknown fused activation "+e+".")},Fp=In({fusedMatMul_:function(t){var e,n=t.a,r=t.b,a=t.transposeA,i=void 0!==a&&a,o=t.transposeB,s=void 0!==o&&o,u=t.bias,l=t.activation,c=void 0===l?"linear":l,p=t.preluActivationWeights;if(!1===Rp(Bt.state.gradientDepth,c)){var h=Zl(n,r,i,s);return null!=u&&(h=Or(h,u)),_p(h,c,p)}var f=dn(n,"a","fused matMul"),d=dn(r,"b","fused matMul");e=Dt(f,d),f=e[0],d=e[1];var m=i?f.shape[f.rank-2]:f.shape[f.rank-1],g=s?d.shape[d.rank-1]:d.shape[d.rank-2],v=i?f.shape[f.rank-1]:f.shape[f.rank-2],y=s?d.shape[d.rank-2]:d.shape[d.rank-1],b=f.shape.slice(0,-2),x=d.shape.slice(0,-2),w=R(b),C=R(x);I(f.rank>=2&&d.rank>=2&&f.rank===d.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+f.rank+" and "+d.rank+"."})),I(D(b,x),(function(){return"Error in fused matMul: outer dimensions ("+b+") and ("+x+") of Tensors with shapes "+f.shape+" and "+d.shape+" must match."})),I(m===g,(function(){return"Error in fused matMul: inner shapes ("+m+") and ("+g+") of Tensors with shapes "+f.shape+" and "+d.shape+" and transposeA="+i+" and transposeB="+s+" must match."}));var N,S,k=f.shape.slice(0,-2).concat([v,y]),E=i?f.as3D(w,m,v):f.as3D(w,v,m),A=s?d.as3D(C,y,g):d.as3D(C,g,y);null!=u&&Mr(k,(N=Dt(N=dn(u,"bias","fused matMul"),f)[0]).shape),null!=p&&(S=dn(p,"prelu weights","fused matMul"));var T={a:E,b:A};null!=u&&(T.bias=N),null!=p&&(T.preluActivationWeights=S);var O=[E,A];return Bt.runKernelFunc((function(t,e){var n=t.fusedBatchMatMul({a:E,b:A,transposeA:i,transposeB:s,bias:N,activation:c,preluActivationWeights:S});return e([E,A,n]),n}),T,(function(t,e){var n=e[0],r=e[1],a=e[2],o=Dp(t,a,c),l={};return null!=u&&(l={bias:function(){return Op(N,o)}}),i||s?!i&&s?Object.assign({a:function(){return o.matMul(r,!1,!1)},b:function(){return o.matMul(n,!0,!1)}},l):i&&!s?Object.assign({a:function(){return r.matMul(o,!1,!0)},b:function(){return n.matMul(o,!1,!1)}},l):Object.assign({a:function(){return r.matMul(o,!0,!0)},b:function(){return o.matMul(n,!0,!0)}},l):Object.assign({a:function(){return o.matMul(r,!1,!0)},b:function(){return n.matMul(o,!0,!1)}},l)}),"_FusedMatMul",{transposeA:i,transposeB:s,activation:c},O,[!0]).reshape(k)}}),Mp=In({fusedConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,a=t.pad,i=t.dataFormat,o=void 0===i?"NHWC":i,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,p=t.activation,h=void 0===p?"linear":p,f=t.preluActivationWeights;if(h=h||"linear",!1===Rp(Bt.state.gradientDepth,h)){var d=Ul(e,n,r,a,o,u,l);return null!=c&&(d=Or(d,c)),_p(d,h,f)}var m=dn(e,"x","conv2d"),g=dn(n,"filter","conv2d"),v=m,y=!1;3===m.rank&&(y=!0,v=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),I(4===v.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+v.rank+"."})),I(4===g.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+g.rank+"."})),null!=l&&I(O(a),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+l+" but got pad "+a+"."})),I(v.shape[3]===g.shape[2],(function(){return"Error in conv2d: depth of input ("+v.shape[3]+") must match input depth for filter "+g.shape[2]+"."})),I(yi(r,u),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),I("NHWC"===o,(function(){return"Error in conv2d: got dataFormat of "+o+" but only NHWC is currently supported."}));var b,x,w=ci(v.shape,g.shape,r,u,a,l);null!=c&&(b=Dt(b=dn(c,"bias","fused conv2d"),m)[0],Mr(w.outShape,b.shape)),null!=f&&(x=dn(f,"prelu weights","fused conv2d"));var C={x:v,filter:g};null!=c&&(C.bias=b),null!=f&&(C.preluActivationWeights=x);var N=[g,v],S=Bt.runKernelFunc((function(t,e){var n=t.fusedConv2d({input:v,filter:g,convInfo:w,bias:b,activation:h,preluActivationWeights:x});return e([g,v,n]),n}),C,(function(t,e){var n=e,i=n[0],o=n[1],s=n[2],l=Dp(t,s,h);I(vi(u),(function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"}));var p={};return null!=c&&(p={bias:function(){return Op(b,l)}}),Object.assign({x:function(){return ql(o.shape,l,i,r,a)},filter:function(){return Gl(o,l,i.shape,r,a)}},p)}),"FusedConv2D",{convInfo:w,activation:h},N,[!0]);return y?S.as3D(S.shape[1],S.shape[2],S.shape[3]):S}}),zp=In({fusedDepthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,a=t.pad,i=t.dataFormat,o=void 0===i?"NHWC":i,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,p=t.activation,h=void 0===p?"linear":p,f=t.preluActivationWeights;if(!1===Rp(Bt.state.gradientDepth,h)){var d=Hl(e,n,r,a,o,u,l);return null!=c&&(d=Or(d,c)),_p(d,h,f)}var m=dn(e,"x","depthwiseConv2d"),g=dn(n,"filter","depthwiseConv2d"),v=m,y=!1;3===m.rank&&(y=!0,v=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),I(4===v.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+v.rank+"."})),I(4===g.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+g.rank+"."})),I(v.shape[3]===g.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+v.shape[3]+") must match the inChannels dimension in filter "+g.shape[2]+"."})),null==u&&(u=[1,1]),I(yi(r,u),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),null!=l&&I(O(a),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+l+" but got pad "+a+"."}));var b,x,w=ci(v.shape,g.shape,r,u,a,l,!0);null!=c&&(b=Dt(b=dn(c,"bias","fused conv2d"),m)[0],Mr(w.outShape,b.shape)),null!=f&&(x=dn(f,"prelu weights","fused depthwiseConv2d"));var C={x:v,filter:g};null!=c&&(C.bias=b),null!=f&&(C.preluActivationWeights=x);var N=[g,v],S=Bt.runKernelFunc((function(t,e){var n=t.fusedDepthwiseConv2D({input:v,filter:g,convInfo:w,bias:b,activation:h,preluActivationWeights:x});return e([g,v,n]),n}),C,(function(t,e){I(vi(u),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"}));var n=e[0],r=e[1],a=e[2],i=Dp(t,a,h),o={};return null!=c&&(o={bias:function(){return Op(b,i)}}),Object.assign({x:function(){return Kl(r.shape,i,n,w)},filter:function(){return Xl(r,i,n.shape,w)}},o)}),"FusedDepthwiseConv2D",{convInfo:w,activation:h},N,[!0]);return y?S.as3D(S.shape[1],S.shape[2],S.shape[3]):S}}),Lp=Object.freeze({matMul:Fp,conv2d:Mp,depthwiseConv2d:zp}),Bp=Object.freeze({image:Tp,linalg:Cp,losses:vp,spectral:Yc,fused:Lp,signal:op,add:Or,addN:Eu,batchNorm:_u,batchNormalization:Ou,batchNorm2d:zu,batchNormalization2d:Mu,batchNorm3d:Pu,batchNormalization3d:Bu,batchNorm4d:Uu,batchNormalization4d:Vu,broadcastTo:ju,clone:Gu,div:_a,divNoNan:$u,eye:Qu,multinomial:tl,oneHot:el,pad:nl,pad1d:rl,pad2d:al,pad3d:il,pad4d:ol,rand:sl,randomGamma:ml,randomNormal:gl,randomUniform:vl,square:yl,squaredDifference:bl,tile:Zu,truncatedNormal:xl,conv1d:Vl,conv2d:Ul,conv3d:jl,depthwiseConv2d:Hl,separableConv2d:Yl,conv2dTranspose:Jl,conv3dTranspose:$l,op:In,booleanMaskAsync:Ll,complex:En,real:An,imag:Tn,concat:Kn,concat1d:Xn,concat2d:Yn,concat3d:Jn,concat4d:$n,split:Zn,matMul:Zl,dot:Ql,outerProduct:tc,reverse:ec,reverse1d:nc,reverse2d:rc,reverse3d:ac,reverse4d:ic,maxPool:uc,avgPool:lc,pool:cc,maxPool3d:pc,avgPool3d:hc,maxPoolWithArgmax:fc,slice:dc,slice1d:mc,slice2d:gc,slice3d:vc,slice4d:yc,abs:zr,acos:Lr,acosh:Br,asin:Pr,asinh:Wr,atan:Vr,atanh:Ur,ceil:jr,clipByValue:Gr,cos:qr,cosh:Hr,erf:Kr,exp:Xr,expm1:Yr,floor:Jr,log:$r,log1p:Zr,logSigmoid:Qr,neg:ta,reciprocal:ea,round:na,rsqrt:ra,sigmoid:aa,sign:ia,isNaN:oa,isInf:sa,isFinite:ua,sin:la,sinh:ca,softplus:pa,sqrt:ha,step:fa,tan:da,tanh:ma,all:xc,any:wc,argMax:Cc,argMin:Nc,logSumExp:Sc,max:kc,mean:Ic,min:Ec,moments:Ac,sum:Tc,prod:Rc,equal:wl,equalStrict:Cl,greater:Nl,greaterEqual:Sl,greaterEqualStrict:kl,greaterStrict:Il,less:El,lessEqual:Al,lessEqualStrict:Tl,lessStrict:Rl,notEqual:Dl,notEqualStrict:Ol,addStrict:ga,atan2:va,divStrict:ya,floorDiv:ba,maximum:xa,maximumStrict:wa,minimum:Ca,minimumStrict:Na,mod:Sa,modStrict:ka,mul:Ia,mulStrict:Ea,pow:Aa,powStrict:Ta,squaredDifferenceStrict:Ra,sub:Da,subStrict:Oa,elu:Dc,leakyRelu:Oc,prelu:_c,relu:Fc,relu6:Mc,selu:zc,logicalAnd:qu,logicalNot:Hu,logicalOr:Ku,logicalXor:Xu,where:Yu,whereAsync:Ju,buffer:Qn,print:tr,batchToSpaceND:er,cast:nr,cumsum:rr,depthToSpace:ar,expandDims:ir,reshape:or,spaceToBatchND:sr,squeeze:ur,stack:lr,unstack:cr,setdiff1dAsync:pr,fill:Un,linspace:jn,ones:Wn,range:Gn,scalar:On,tensor:Rn,tensor1d:_n,tensor2d:Fn,tensor3d:Mn,tensor4d:zn,tensor5d:Ln,tensor6d:Bn,variable:Pn,zeros:Vn,onesLike:qn,zerosLike:Hn,transpose:ai,softmax:ni,logSoftmax:ri,localResponseNormalization:Lc,norm:Bc,gather:Ml,unsortedSegmentSum:zl,basicLSTMCell:Pc,multiRNNCell:Wc,movingAverage:Vc,stridedSlice:Uc,topk:jc,scatterND:Gc,fft:qc,ifft:Hc,rfft:Kc,irfft:Xc,sparseToDense:Jc,gatherND:$c,diag:Zc,dropout:Qc,hannWindow:np,hammingWindow:rp,frame:ap,stft:ip,inTopKAsync:sp});function Pp(t,e){Array.isArray(t)||(t=[t]),t.forEach((function(t){null!=t&&I("complex64"!==t.dtype,(function(){return e+" does not support complex64 tensors."}))}))}function Wp(t,e,n,r,a,i){for(var o=a.strideHeight,s=a.strideWidth,u=a.dilationHeight,l=a.dilationWidth,c=a.effectiveFilterHeight,p=a.effectiveFilterWidth,h=a.padInfo.top,f=a.padInfo.left,d="max"===i?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Qn(a.outShape,n),g=m.values,v=a.outShape[1]*a.outShape[2]*a.outShape[3],y=a.outShape[2]*a.outShape[3],b=a.outShape[3],x=0;x_?_=P:"avg"===i&&(F+=P,M++)}if(isNaN(_))break}g[A+T*b+N]="avg"===i?F/M:_}return m}function Vp(t,e,n,r,a,i){void 0===a&&(a=!1),void 0===i&&(i=!1);for(var o=Qn(r.outShape,"int32"),s=r.strideHeight,u=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterHeight,h=r.effectiveFilterWidth,f=r.padInfo.top,d=r.padInfo.left,m=Qn(e,n,t),g=0;gI&&(I=O,E=a?i?((g*r.inHeight+A)*r.inWidth+R)*r.inChannels+v:(A*r.inWidth+R)*r.inChannels+v:T*h+D)}o.set(E,g,y,C,v)}}return o}function Up(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("relu6"===n)return t.relu6(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var jp=function(t){function e(){var e=t.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new ii(e,Bt),e}return i(e,t),e.prototype.write=function(t,e,n){this.firstUse&&(this.firstUse=!1,c().get("IS_NODE")&&pn("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================"));var r={};return this.data.set(r,{values:t,dtype:n}),r},e.prototype.move=function(t,e,n,r){this.data.set(t,{values:e,dtype:r})},e.prototype.numDataIds=function(){return this.data.numDataIds()},e.prototype.read=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(e){return[2,this.readSync(t)]}))}))},e.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?Si(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(t).values},e.prototype.bufferSync=function(t){var e=this.readSync(t.dataId),n=e;if("string"===t.dtype)try{n=e.map((function(t){return ut(t)}))}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return Qn(t.shape,t.dtype,n)},e.prototype.makeOutput=function(t,e,n){var r=this.write(t,e,n);return Bt.makeTensorFromDataId(r,e,n,this)},e.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t)}},e.prototype.time=function(t){return o(this,void 0,void 0,(function(){var e;return s(this,(function(n){return e=it(),t(),[2,{kernelMs:it()-e}]}))}))},e.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."]}},e.prototype.complex=function(t,e){var n=this.makeOutput(null,t.shape,"complex64");return this.data.get(n.dataId).complexTensors={real:Bt.keep(t.clone()),imag:Bt.keep(e.clone())},n},e.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone()},e.prototype.slice=function(t,e,n){if(Pp(t,"slice"),Ha(t.shape,e,n)){var r=Ka(e,t.strides),a=R(n);return Rn(this.readSync(t.dataId).subarray(r,r+a),n,t.dtype)}for(var i=Qn(n,t.dtype),o=this.bufferSync(t),s=0;sh&&(h=m,f=d)}u[c]=f}return o},e.prototype.cumsum=function(t,e,n,r){if(Pp(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var a=Tt(t.dtype,"int32"),i=Vn(t.shape,a),o=this.readSync(i.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;ce?1:0}))},e.prototype.greaterEqual=function(t,e){return Pp([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>=e?1:0}))},e.prototype.logicalNot=function(t){Pp(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r1||1===e.rank?1:R(e.shape.slice(1)),c=0;c=0&&e>=0?n:(n+e)%e}))},e.prototype.max=function(t,e){Pp(t,"max"),xn("max",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],i=Vn(r,t.dtype),o=R(a),s=this.readSync(i.dataId),u=this.readSync(t.dataId),l=0;lp&&(p=f)}s[l]=p}return i},e.prototype.maximum=function(t,e){return Pp([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.max(t,e)}))},e.prototype.all=function(t,e){Pp(t,"all"),xn("all",e,t.rank);for(var n=yn(t.shape,e),r=n[0],a=n[1],i=Vn(r,t.dtype),o=R(a),s=this.readSync(i.dataId),u=this.readSync(t.dataId),l=0;l0?n[r]=1:n[r]=0;return this.makeOutput(n,t.shape,"float32")},e.prototype.isNaN=function(t){Pp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r.5?n[r]=Math.ceil(e[r]):n[r]=a%2==0?a:a+1}return this.makeOutput(n,t.shape,"float32")},e.prototype.exp=function(t){Pp(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r=0?a:Math.exp(a)-1}return this.makeOutput(e,t.shape,"float32")},e.prototype.eluDer=function(t,e){Pp([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),a=this.readSync(t.dataId),i=0;i=1?a[i]:a[i]*(o+1)}return this.makeOutput(n,e.shape,"float32")},e.prototype.selu=function(t){Pp(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r=0?1.0507009873554805*a:1.7580993408473768*(Math.exp(a)-1)}return this.makeOutput(e,t.shape,"float32")},e.prototype.clip=function(t,e,n){Pp(t,"clip");for(var r=new Float32Array(t.size),a=this.readSync(t.dataId),i=0;in?n:o-e,s=r[a]0?1:e}return this.makeOutput(n,t.shape,"float32")},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,a=t.bias,i=t.activation,o=t.preluActivationWeights,s=this.conv2d(e,n,r);return a&&(s=this.add(s,a)),i&&(s=Up(this,s,i,o)),s},e.prototype.conv2d=function(t,e,n){Pp([t,e],"conv2d");for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l="channelsLast"===n.dataFormat,c=Qn(n.outShape,t.dtype),p=t.strides[0],h=l?t.strides[1]:t.strides[2],f=l?t.strides[2]:1,d=l?1:t.strides[1],m=c.strides[0],g=l?c.strides[1]:c.strides[2],v=l?c.strides[2]:1,y=l?1:c.strides[1],b=this.readSync(t.dataId),x=this.readSync(e.dataId),w=c.values,C=0;C=n.inHeight))for(var R=A*e.strides[0],D=N+T*h,O=0;O=n.inWidth))for(var L=D+z*f,B=R+M*e.strides[1],P=0;P=n.inDepth))for(var S=C*e.strides[0],k=v+N*t.strides[1],I=0;I=n.inHeight))for(var D=S+T*e.strides[1],O=k+R*t.strides[2],_=0;_=n.inWidth))for(var B=D+z*e.strides[2],P=O+L*n.inChannels,W=B,V=0;V=n.inHeight))for(var C=x*e.strides[0],N=m+w*t.strides[1],S=0;S=n.inWidth))for(var T=C+E*e.strides[1],R=N+A*n.inChannels,D=k,O=T,_=0;_=r.outHeight||Math.floor(S)!==S))for(var k=0;k=r.outWidth||Math.floor(I)!==I)){var E=c*p-1-i.get(g,S,I,v)===N*p+k?1:0;0!==E&&(C+=m.get(g,S,I,v)*E)}}}d.set(C,g,y,b,v)}return d.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){Pp([t,e],"avgPoolBackprop");for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,p=c-1-n.padInfo.left,h=l-1-n.padInfo.top,f=Qn(e.shape,"float32"),d=1/(i*o),m=this.bufferSync(t),g=0;g=n.outHeight||Math.floor(S)!==S))for(var k=0;k=n.outWidth||Math.floor(I)!==I||(C+=m.get(g,S,I,v))}}f.set(C*d,g,y,b,v)}return f.toTensor()},e.prototype.pool3d=function(t,e,n){Pp(t,"pool3d");for(var r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(t.dataId),v=Qn(e.outShape,t.dtype),y=v.values,b=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],x=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],N=0;NU?U=J:"avg"===n&&(j+=J,G++),isNaN(U))break}if(isNaN(U))break}if(isNaN(U))break}y[V+I]="avg"===n?j/G:U}}}return v.toTensor()},e.prototype.avgPool3d=function(t,e){return Pp(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){Pp([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,a=n.strideHeight,i=n.strideWidth,o=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=n.dilationDepth,c=n.dilationHeight,p=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,m=h-1-n.padInfo.front,g=d-1-n.padInfo.left,v=f-1-n.padInfo.top,y=Qn(e.shape,"float32"),b=1/(o*s*u),x=this.bufferSync(t),w=0;w=n.outDepth||Math.floor(D)!==D))for(var O=0;O=n.outHeight||Math.floor(_)!==_))for(var F=0;F=n.outWidth||Math.floor(M)!==M||(T+=x.get(w,D,_,M,C))}}}y.set(T*b,w,N,S,k,C)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return Pp(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=Qn(e.outShape,"int32"),r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m=this.bufferSync(t),g=0;g=R&&(R=B,D=_*c*p+M*c+L)}n.set(D,g,y,C,I,v)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){Pp([e,n],"maxPool3dBackprop");for(var a=this.maxPool3dPositions(e,r),i=r.strideDepth,o=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,l=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=p-1-r.padInfo.front,m=f-1-r.padInfo.left,g=h-1-r.padInfo.top,v=Qn(e.shape,"float32"),y=this.bufferSync(a),b=this.bufferSync(t),x=0;x=r.outDepth||Math.floor(R)!==R))for(var D=0;D=r.outHeight||Math.floor(O)!==O))for(var _=0;_=r.outWidth||Math.floor(F)!==F)){var M=p*h*f-1-y.get(x,R,O,F,w)===T*h*f+D*f+_?1:0;0!==M&&(A+=b.get(x,R,O,F,w)*M)}}}}v.set(A,x,C,N,S,w)}return v.toTensor()},e.prototype.cast=function(t,e){return xi(t,e,this)},e.prototype.reshape=function(t,e){return wi(t,e)},e.prototype.avgPool=function(t,e){return Pp(t,"avgPool"),Pp(t,"maxPool"),Wp(this.readSync(t.dataId),t.shape,t.dtype,t.strides,e,"avg").toTensor().toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){Pp(t,"resizeBilinear");for(var a=t.shape,i=a[0],o=a[1],s=a[2],u=a[3],l=this.readSync(t.dataId),c=new Float32Array(R([i,e,n,u])),p=[r&&e>1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=p[0]/h[0],m=p[1]/h[1],g=0;g1?i-1:i,n&&c>1?o-1:o],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=h[0]/f[0],m=h[1]/f[1],g=this.readSync(t.dataId),v=0,y=0;y1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=p[0]/h[0],d=p[1]/h[1],m=0,g=0;g1?i-1:i,n&&c>1?o-1:o],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],m=f[0]/d[0],g=f[1]/d[1],v=1/m,y=1/g,b=2*Math.ceil(v)+2,x=2*Math.ceil(y)+2,w=0;w=l)){var M=C+F*t.strides[1],z=F*m;if(N===Math.min(i-1,n?Math.round(z):Math.floor(z)))for(var L=0;L=c)){var P=M+B*t.strides[2],W=B*g;E===Math.min(o-1,n?Math.round(W):Math.floor(W))&&(O+=h[P+D])}}}}p[A+D]=O}return zn(p,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,a,i){Pp([t,e,n,a,i],"batchNorm");for(var o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=a?this.readSync(a.dataId):new Float32Array([1]),c=i?this.readSync(i.dataId):new Float32Array([0]),p=new Float32Array(o.length),h=c.length,f=l.length,d=u.length,m=s.length,g=0,v=0,y=0,b=0,x=0;x=h&&(g=0),v>=m&&(v=0),y>=f&&(y=0),b>=d&&(b=0);return zn(p,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,a){Pp(t,"localResponseNormalization4D");var i=t.shape[3],o=i-1,s=this.readSync(t.dataId),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%i,r=t-n+Math.max(0,n-e),a=t-n+Math.min(n+e,o),u=0;r<=a;r++){var l=s[r];u+=l*l}return u}for(var p=0;p=0&&i[o]1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));for(var r=t.shape[0],a=t.shape[1],i=t.shape[2],o=t.shape[3],s=a*e,u=i*e,l=o/(e*e),c=this.readSync(t.dataId),p=new Float32Array(r*s*u*l),h=0,f=0;f=s))for(var E=h>1?(S-C)*(u-1)/(h-1):0,A=f>1?(k-N)*(l-1)/(f-1):0,T=0;T1?C*(u-1)+T*E:.5*(C+S)*(u-1);if(R<0||R>u-1)for(var D=0;D1?N*(l-1)+D*A:.5*(N+k)*(l-1))<0||q>l-1)for(O=0;O1?N*(l-1)+D*A:.5*(N+k)*(l-1))<0||q>l-1)for(O=0;O=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var v=0;v=r/a)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),a=0;a6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var a=ao(this.rank),i=ji("rc",this.rank),o=new Array(this.rank);for(r=0;r0&&(e=e.sum(r)),e.reshape(n.shape)},b:function(){var e=t,n=Fr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)}}}},{kernelName:"AddN",saveAllInputs:!0,gradFunc:function(t,e){var n={};return e.forEach((function(e,r){n[r]=function(){return t.clone()}})),n}},{kernelName:kr,gradFunc:function(t,e,n){for(var r=n,a=r.inputShape,i=r.shape,o=Array.from(i),s=a.length-1;s>=0;s--)if(a[s]===i[s])o[s]=1;else if(1!==a[s])throw new Error("broadcastTo(): ["+a+"] cannot be broadcast to ["+i+"].");var u=[];for(s=0;s1&&u.push(s);return{x:function(){return t.sum(u,!0)}}}},{kernelName:br,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],r=e[1],a=Mr(n.shape,r.shape);return{a:function(){var e=_a(t,r.toFloat()),i=Fr(n.shape,a);return i.length>0?Tc(e,i).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);i.length>0&&(e=Tc(e,i).reshape(r.shape));var o=yl(r);return ta(_a(e,o.toFloat()))}}}},{kernelName:"FusedBatchNorm",inputsToSave:["x","mean","variance","scale"],gradFunc:function(t,e,n){var r=n.varianceEpsilon,a=e[0],i=e[1],o=e[2],s=e[3],u=Tu(a),l=null==s?On(1):s,c=Fr(i.shape,u.shape),p=[];if(1===i.rank){for(var h=0;h0,(function(){return"scheme must not be an empty string."}));var r=t.getInstance();I(null==r.managers[e],(function(){return"A model store manager is already registered for scheme '"+e+"'."})),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function Sh(t){if(-1===t.indexOf(Ch))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Nh.getSchemes().join(","));return{scheme:t.split(Ch)[0],path:t.split(Ch)[1]}}function kh(t,e,n){return void 0===n&&(n=!1),o(this,void 0,void 0,(function(){var r,a,i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:return I(t!==e,(function(){return"Old path and new path are the same: '"+t+"'"})),I((r=wh.getLoadHandlers(t)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+t+"."})),I(r.length<2,(function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."})),a=r[0],I((i=wh.getSaveHandlers(e)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+e+"."})),I(i.length<2,(function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."})),o=i[0],u=Sh(t).scheme,l=Sh(t).path,c=u===Sh(t).scheme,[4,a.load()];case 1:return p=s.sent(),n&&c?[4,Nh.getManager(u).removeModel(l)]:[3,3];case 2:s.sent(),s.label=3;case 3:return[4,o.save(p)];case 4:return h=s.sent(),!n||c?[3,6]:[4,Nh.getManager(u).removeModel(l)];case 5:s.sent(),s.label=6;case 6:return[2,h.modelArtifactsInfo]}}))}))}var Ih="models_store",Eh="model_info_store";function Ah(){if(!c().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window||self,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function Th(t){var e=t.result;e.createObjectStore(Ih,{keyPath:"modelPath"}),e.createObjectStore(Eh,{keyPath:"modelPath"})}var Rh=function(){function t(t){if(this.indexedDB=Ah(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return o(this,void 0,void 0,(function(){return s(this,(function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]}))}))},t.prototype.load=function(){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,this.databaseAction(this.modelPath)]}))}))},t.prototype.databaseAction=function(t,e){var n=this;return new Promise((function(t,r){var a=n.indexedDB.open("tensorflowjs",1);a.onupgradeneeded=function(){return Th(a)},a.onsuccess=function(){var i=a.result;if(null==e){var o=i.transaction(Ih,"readonly"),s=o.objectStore(Ih).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return i.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return i.close(),r(s.error)},o.oncomplete=function(){return i.close()}}else{var u,l=xh(e),c=i.transaction(Eh,"readwrite"),p=c.objectStore(Eh),h=p.put({modelPath:n.modelPath,modelArtifactsInfo:l});h.onsuccess=function(){var a=(u=i.transaction(Ih,"readwrite")).objectStore(Ih).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});a.onsuccess=function(){return t({modelArtifactsInfo:l})},a.onerror=function(t){var e=(p=c.objectStore(Eh)).delete(n.modelPath);e.onsuccess=function(){return i.close(),r(a.error)},e.onerror=function(t){return i.close(),r(a.error)}}},h.onerror=function(t){return i.close(),r(h.error)},c.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close()}}}},a.onerror=function(t){return r(a.error)}}))},t.URL_SCHEME="indexeddb://",t}(),Dh=function(t){return c().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Rh.URL_SCHEME)?(e=t.slice(Rh.URL_SCHEME.length),new Rh(e)):null;var e};wh.registerSaveRouter(Dh),wh.registerLoadRouter(Dh);var Oh=function(){function t(){this.indexedDB=Ah()}return t.prototype.listModels=function(){return o(this,void 0,void 0,(function(){var t=this;return s(this,(function(e){return[2,new Promise((function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Th(r)},r.onsuccess=function(){var t=r.result,a=t.transaction(Eh,"readonly"),i=a.objectStore(Eh).getAll();i.onsuccess=function(){for(var t={},n=0,r=i.result;n0,(function(){return"promises must be a none empty array"}))}(t),function(t,e){I(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t})),I(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e})),I(e>=t,(function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e}))}(n=null==n?0:n,r=null==r?1:r);var a=0;return Promise.all(t.map((function(i){return i.then((function(i){var o=n+ ++a/t.length*(r-n);return e(o),i})),i})))}function Yh(t,e){return o(this,void 0,void 0,(function(){var n,r,a,i,o,u,l,p,h;return s(this,(function(s){switch(s.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?c().platform.fetch:e.fetchFunc,r=t.map((function(t){return n(t,e.requestInit,{isBinary:!0})})),a=0,i=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return o=s.sent(),[3,4];case 2:return[4,Xh(r,e.onProgress,a,i)];case 3:o=s.sent(),s.label=4;case 4:return u=o.map((function(t){return t.arrayBuffer()})),l=.5,p=1,null!=e.onProgress?[3,6]:[4,Promise.all(u)];case 5:return h=s.sent(),[3,8];case 6:return[4,Xh(u,e.onProgress,l,p)];case 7:h=s.sent(),s.label=8;case 8:return[2,h]}}))}))}function Jh(t){var e=this;return function(n,r,a){return void 0===r&&(r=""),o(e,void 0,void 0,(function(){var e,i,o,u,l,c,p,h,f,d;return s(this,(function(s){switch(s.label){case 0:if(e=n.map((function(){return!1})),i={},o=null!=a?a.map((function(){return!1})):[],u=[],n.forEach((function(t,n){var r=0;t.weights.forEach((function(t){var s="quantization"in t?t.quantization.dtype:t.dtype,l=fh[s]*R(t.shape),c=function(){e[n]=!0,null==i[n]&&(i[n]=[]),i[n].push({manifestEntry:t,groupOffset:r,sizeBytes:l})};null!=a?a.forEach((function(e,n){e===t.name&&(c(),o[n]=!0)})):c(),u.push(t.name),r+=l}))})),!o.every((function(t){return t})))throw l=a.filter((function(t,e){return!o[e]})),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce((function(t,e,n){return e&&t.push(n),t}),[]),p=[],c.forEach((function(t){n[t].paths.forEach((function(t){var e=r+(r.endsWith("/")?"":"/")+t;p.push(e)}))})),[4,t(p)];case 1:return h=s.sent(),f={},d=0,c.forEach((function(t){for(var e=n[t].paths.length,r=0,a=0;a0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(t)&&I(2===t.length,(function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+")."})),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return o(this,void 0,void 0,(function(){var e,n,r,a;return s(this,(function(i){switch(i.label){case 0:if(t.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,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=i.sent()).ok)return[2,{modelArtifactsInfo:xh(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}}))}))},t.prototype.load=function(){return o(this,void 0,void 0,(function(){var t,e,n,r,a,i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=s.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");s.label=2;case 2:return s.trys.push([2,4,,5]),[4,t.json()];case 3:return e=s.sent(),[3,5];case 4:throw s.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" 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.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,a=e.weightsManifest,i=e.generatedBy,o=e.convertedBy,u=e.format,l=e.userDefinedMetadata,null==r&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:h=s.sent(),c=h[0],p=h[1],s.label=7;case 7:return[2,{modelTopology:r,weightSpecs:c,weightData:p,userDefinedMetadata:l,generatedBy:i,convertedBy:o,format:u}]}}))}))},t.prototype.loadWeights=function(t){return o(this,void 0,void 0,(function(){var e,n,r,a,i,o,u,l,c,p,h;return s(this,(function(s){switch(s.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],a=n[1],i=this.weightPathPrefix||r,o=[],u=0,l=t;u0&&Number.isInteger(n),(function(){return"If provided, numClasses must be a positive integer, but got "+n})),I(1===r.rank,(function(){return"Expected the rank of labels to be 1, but got "+r.rank})),I(1===a.rank,(function(){return"Expected the rank of predictions to be 1, but got "+a.rank})),I(r.shape[0]===a.shape[0],(function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+a.shape[0]+". Labels and predictions should have the same number of elements."})),I(n>0&&Number.isInteger(n),(function(){return"numClasses is required to be a positive integer, but got "+n}));var i=el(r.asType("int32"),n),o=el(a.asType("int32"),n);return i.transpose().matMul(o).asType("int32")}}),sf=Object.freeze({confusionMatrix:of}),uf=In({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,r=!1,a=!1,i=!1,o=!1;if(t.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&t instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)a=!0;else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)i=!0;else{if(null==t.getContext)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 "+t.constructor.name);o=!0}if(a&&a&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the