2022-08-22 19:17:39 +02:00
/ *
2020-12-02 22:46:41 +01:00
Face - API
homepage : < https : //github.com/vladmandic/face-api>
author : < https : //github.com/vladmandic>'
2021-09-08 19:51:28 +02:00
* /
2020-12-02 22:46:41 +01:00
2022-10-30 14:06:17 +01:00
"use strict" ; var faceapi = ( ( ) => { var py = Object . defineProperty ; var pD = Object . getOwnPropertyDescriptor ; var hD = Object . getOwnPropertyNames ; var fD = Object . prototype . hasOwnProperty ; var Ys = ( e => typeof require != "undefined" ? require : typeof Proxy != "undefined" ? new Proxy ( e , { get : ( t , n ) => ( typeof require != "undefined" ? require : t ) [ n ] } ) : e ) ( function ( e ) { if ( typeof require != "undefined" ) return require . apply ( this , arguments ) ; throw new Error ( 'Dynamic require of "' + e + '" is not supported' ) } ) ; var sh = ( e , t ) => { for ( var n in t ) py ( e , n , { get : t [ n ] , enumerable : ! 0 } ) } , mD = ( e , t , n , r ) => { if ( t && typeof t == "object" || typeof t == "function" ) for ( let s of hD ( t ) ) ! fD . call ( e , s ) && s !== n && py ( e , s , { get : ( ) => t [ s ] , enumerable : ! ( r = pD ( t , s ) ) || r . enumerable } ) ; return e } ; var gD = e => mD ( py ( { } , "__esModule" , { value : ! 0 } ) , e ) ; var Wde = { } ; sh ( Wde , { AgeGenderNet : ( ) => wp , BoundingBox : ( ) => _i , Box : ( ) => ot , ComposableTask : ( ) => xr , ComputeAllFaceDescriptorsTask : ( ) => Gs , ComputeFaceDescriptorsTaskBase : ( ) => Tp , ComputeSingleFaceDescriptorTask : ( ) => Hs , DetectAllFaceLandmarksTask : ( ) => Np , DetectAllFacesTask : ( ) => vl , DetectFaceLandmarksTaskBase : ( ) => Cp , DetectFacesTaskBase : ( ) => Ep , DetectSingleFaceLandmarksTask : ( ) => _p , DetectSingleFaceTask : ( ) => Ap , Dimensions : ( ) => yn , FACE _EXPRESSION _LABELS : ( ) => FI , FaceDetection : ( ) => gt , FaceDetectionNet : ( ) => BI , FaceExpressionNet : ( ) => xp , FaceExpressions : ( ) => Ws , FaceLandmark68Net : ( ) => Mi , FaceLandmark68TinyNet : ( ) => Ip , FaceLandmarkNet : ( ) => MI , FaceLandmarks : ( ) => ar , FaceLandmarks5 : ( ) => vI , FaceLandmarks68 : ( ) => Ai , FaceMatch : ( ) => al , FaceMatcher : ( ) => $p , FaceRecognitionNet : ( ) => Li , Gender : ( ) => bg , LabeledBox : ( ) => ol , LabeledFaceDescriptors : ( ) => bs , NetInput : ( ) => vs , NeuralNetwork : ( ) => an , ObjectDetection : ( ) => Ls , Point : ( ) => Fe , PredictedBox : ( ) => xI , Rect : ( ) => Ei , SsdMobilenetv1 : ( ) => $a , SsdMobilenetv1Options : ( ) => vr , TinyFaceDetector : ( ) => Ui , TinyFaceDetectorOptions : ( ) => Sp , TinyYolov2 : ( ) => Wi , TinyYolov2Options : ( ) => es , allFaces : ( ) => Lde , allFacesSsdMobilenetv1 : ( ) => $$ , allFacesTinyYolov2 : ( ) => Mde , awaitMediaLoaded : ( ) => NI , bufferToImage : ( ) => _I , computeFaceDescriptor : ( ) => kde , createCanvas : ( ) => Ri , createCanvasFromMedia : ( ) => gp , createFaceDetectionNet : ( ) => gde , createFaceRecognitionNet : ( ) => ade , createSsdMobilenetv1 : ( ) => g$ , createTinyFaceDetector : ( ) => zde , createTinyYolov2 : ( ) => vde , detectAllFaces : ( ) => Cg , detectFaceLandmarks : ( ) => E$ , detectFaceLandmarksTiny : ( ) => Ide , detectLandmarks : ( ) => Pde , detectSingleFace : ( ) => Ode , draw : ( ) => PI , env : ( ) => Qe , euclideanDistance : ( ) => UI , extendWithAge : ( ) => wg , extendWithFaceDescriptor : ( ) => xg , extendWithFaceDetection : ( ) => $i , extendWithFaceExpressions : ( ) => hg , extendWithFaceLandmarks : ( ) => ml , extendWithGender : ( ) => Ig , extractFaceTensors : ( ) => ul , extractFaces : ( ) => cl , fetchImage : ( ) => Hle , fetchJson : ( ) => $I , fetchNetWeights : ( ) => qle , fetchOrThrow : ( ) => Bs , fetchVideo : ( ) => jle , getContext2dOrThrow : ( ) => Gn , getMediaDimensions : ( ) => Fi , imageTensorToCanvas : ( ) => EI , imageToSquare : ( ) => AI , inverseSigmoid : ( ) => Lle , iou : ( ) => mI , isMediaElement : ( ) => ag , isMediaLoaded : ( ) => mp , isWithAge : ( ) => ode , isWithFaceDetection : ( ) => ys , isWithFaceExpressions : ( ) => RI , isWithFaceLandmarks : ( ) => Oi , isWithGender : ( ) => ide , loadAgeGenderModel : ( ) => Dde , loadFaceDetectionModel : ( ) => Fde , loadFaceExpressionModel : ( ) => $de , loadFaceLandmarkModel : ( ) => _de , loadFaceLandmarkTinyModel : ( ) => Ede , loadFaceRecognitionModel : ( ) => Ade , loadSsdMobilenetv1Model : ( ) => A$ , loadTinyFaceDetectorModel : ( ) => Cde , loadTinyYolov2Model : ( ) => Nde , loadWeightMap : ( ) => DI , locateFaces : ( ) => Rde , matchDimensions : ( ) => Kle , minBbox : ( ) => gI , nets : ( ) => et , nonMaxSuppression : ( ) => bI , normalize : ( ) => Jr , padToSquare : ( ) => yI , predictAgeAndGender : ( ) => Tde , recognizeFaceExpressions : ( ) => Sde , resizeResults : ( ) => D$ , resolveInput : ( ) => Di , shuffleArray : ( ) => Mle , sigmoid : ( ) => pp , ssdMobilenetv1 : ( ) => _$ , tf : ( ) => Oe , tinyFaceDetector : ( ) => xde , tinyYolov2 : ( ) => wde , toNetInput : ( ) => bt , utils : ( ) => fI , validateConfig : ( ) => WI , version : ( ) => Bde } ) ; var Oe = { } ; sh ( Oe , { Abs : ( ) => Fc , Acos : ( ) => Rc , Acosh : ( ) => Pc , AdadeltaOptimizer : ( ) => km , AdagradOptimizer : ( ) => Sm , AdamOptimizer : ( ) => Tm , AdamaxOptimizer : ( ) => Cm , Add : ( ) => ba , AddN : ( ) => bo , All : ( ) => Oc , Any : ( ) => Mc , ArgMax : ( ) => yo , ArgMin : ( ) => dd , Asin : ( ) => Lc , Asinh : ( ) => zc , Atan : ( ) => Bc , Atan2 : ( ) => Vc , Atanh : ( ) => Wc , AvgPool : ( ) => vo , AvgPool3D : ( ) => pd , AvgPool3DGrad : ( ) => hf , AvgPoolGrad : ( ) => pf , BackendWasm : ( ) => HA , BatchMatMul : ( ) => xo , BatchToSpaceND : ( ) => Uc , Bincount : ( ) => ff , Broad
` ),H=P=>V.writeSync(2,P+ `
` ));var Z=d.print||j,J=d.printErr||H;Object.assign(d,g),g=null,d.arguments&&(b=d.arguments),d.thisProgram&&(y=d.thisProgram),d.quit&&(v=d.quit);var ee=4,re=Atomics.load,te=Atomics.store,ie=Atomics.compareExchange,ne;d.wasmBinary&&(ne=d.wasmBinary);var le=d.noExitRuntime||!0;typeof WebAssembly!="object"&&Yi("no native wasm support detected");var ue,ye,ve=!1,Se;function Le(P,K){P||Yi(K)}var je=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function nt(P,K,oe){for(var pe=K+oe,ke=K;P[ke]&&!(ke>=pe);)++ke;if(ke-K>16&&P.buffer&&je)return je.decode(P.buffer instanceof SharedArrayBuffer?P.slice(K,ke):P.subarray(K,ke));for(var He="";K<ke;){var Ne=P[K++];if(!(Ne&128)){He+=String.fromCharCode(Ne);continue}var Re=P[K++]&63;if((Ne&224)==192){He+=String.fromCharCode((Ne&31)<<6|Re);continue}var Mt=P[K++]&63;if((Ne&240)==224?Ne=(Ne&15)<<12|Re<<6|Mt:Ne=(Ne&7)<<18|Re<<12|Mt<<6|P[K++]&63,Ne<65536)He+=String.fromCharCode(Ne);else{var cr=Ne-65536;He+=String.fromCharCode(55296|cr>>10,56320|cr&1023)}}return He}function rt(P,K){return P?nt(o(),P,K):""}function st(P,K,oe,pe){if(!(pe>0))return 0;for(var ke=oe,He=oe+pe-1,Ne=0;Ne<P.length;++Ne){var Re=P.charCodeAt(Ne);if(Re>=55296&&Re<=57343){var Mt=P.charCodeAt(++Ne);Re=65536+((Re&1023)<<10)|Mt&1023}if(Re<=127){if(oe>=He)break;K[oe++]=Re}else if(Re<=2047){if(oe+1>=He)break;K[oe++]=192|Re>>6,K[oe++]=128|Re&63}else if(Re<=65535){if(oe+2>=He)break;K[oe++]=224|Re>>12,K[oe++]=128|Re>>6&63,K[oe++]=128|Re&63}else{if(oe+3>=He)break;K[oe++]=240|Re>>18,K[oe++]=128|Re>>12&63,K[oe++]=128|Re>>6&63,K[oe++]=128|Re&63}}return K[oe]=0,oe-ke}function Ze(P,K,oe){return st(P,o(),K,oe)}var ze,dt,qn,At,wr,on,Ir,vn,jn;C&&(ze=d.buffer);function yt(P){ze=P,d.HEAP8=dt=new Int8Array(P),d.HEAP16=At=new Int16Array(P),d.HEAP32=on=new Int32Array(P),d.HEAPU8=qn=new Uint8Array(P),d.HEAPU16=wr=new Uint16Array(P),d.HEAPU32=Ir=new Uint32Array(P),d.HEAPF32=vn=new Float32Array(P),d.HEAPF64=jn=new Float64Array(P)}var Pn=d.INITIAL_MEMORY||16777216;if(C)ue=d.wasmMemory,ze=d.buffer;else if(d.wasmMemory)ue=d.wasmMemory;else if(ue=new WebAssembly.Memory({initial:Pn/65536,maximum:32768,shared:!0}),!(ue.buffer instanceof SharedArrayBuffer))throw J("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),S&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");ue&&(ze=ue.buffer),Pn=ze.byteLength,yt(ze);var hn,ts=[],qs=[],kr=[],xl=!1;function Sr(){return le}function Ki(){if(d.preRun)for(typeof d.preRun=="function"&&(d.preRun=[d.preRun]);d.preRun.length;)Ng(d.preRun.shift());Sl(ts)}function Xt(){xl=!0,!C&&Sl(qs)}function Dp(){if(!C){if(d.postRun)for(typeof d.postRun=="function"&&(d.postRun=[d.postRun]);d.postRun.length;)GI(d.postRun.shift());Sl(kr)}}function Ng(P){ts.unshift(P)}function _g(P){qs.unshift(P)}function GI(P){kr.unshift(P)}var js=0,Xi=null,xs=null;function HI(P){js++,d.monitorRunDependencies&&d.monitorRunDependencies(js)}function qI(P){if(js--,d.monitorRunDependencies&&d.monitorRunDependencies(js),js==0&&(Xi!==null&&(clearInterval(Xi),Xi=null),xs)){var K=xs;xs=null,K()}}function Yi(P){C?postMessage({cmd:"onAbort",arg:P}):d.onAbort&&d.onAbort(P),P="Aborted("+P+")",J(P),ve=!0,Se=1,P+=". Build with -sASSERTIONS for more info.";var K=new WebAssembly.RuntimeError(P);throw f(K),K}var Eg="data:application/octet-stream;base64,";function Fp(P){return P.startsWith(Eg)}function wl(P){return P.startsWith("file://")}var xn;xn="tfjs-backend-wasm-threaded-simd.wasm",Fp(xn)||(xn= $ (xn));function Rp(P){try{if(P==xn&&ne)return new Uint8Array(ne);if(R)return R(P);throw"both async and sync fetching of the wasm failed"}catch(K){Yi(K)}}function Ag(){if(!ne&&(x||k)){if(typeof fetch=="function"&&!wl(xn))return fetch(xn,{credentials:"same-origin"}).then(function(P){if(!P.ok)throw"failed to load wasm binary file at '"+xn+"'";return P.arrayBuffer()}).catch(function(){return Rp(xn)});if(A)
");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:" alert ",text:text,threadId:Module[" _pthread _self "]()})}var err=threadPrintErr;self.alert=threadAlert;Module[" instantiateWasm "]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module[" wasmModule "],info);receiveInstance(instance);Module[" wasmModule "]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.onmessage=e=>{try{if(e.data.cmd===" load "){Module[" wasmModule "]=e.data.wasmModule;Module[" wasmMemory "]=e.data.wasmMemory;Module[" buffer "]=Module[" wasmMemory "].buffer;Module[" ENVIRONMENT _IS _PTHREAD "]=true;if(typeof e.data.urlOrBlob==" string "){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance})}else if(e.data.cmd===" run "){Module[" _ _performance _now _clock _drift "]=performance.now()-e.data.time;Module[" _ _emscripten _thread _init "](e.data.pthread_ptr,0,0,1);Module[" establishStackSpace "]();Module[" PThread "].receiveObjectTransfer(e.data);Module[" PThread "].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module[" executeNotifiedProxyingQueue "](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module[" invokeEntryPoint "](e.data.start_routine,e.data.arg)}catch(ex){if(ex!=" unwind "){if(ex instanceof Module[" ExitStatus "]){if(Module[" keepRuntimeAlive "]()){}else{Module[" _ _emscripten _thread _exit "](ex.status)}}else{throw ex}}}}else if(e.data.cmd===" cancel "){if(Module[" _pthread _self "]()){Module[" _ _emscripten _thread _exit "](-1)}}else if(e.data.target===" setimmediate "){}else if(e.data.cmd===" processProxyingQueue "){if(initializedJS){Module[" executeNotifiedProxyingQueue "](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err(" worker . js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module[" _ _emscripten _thread _crashed "]){Module[" _ _emscripten _thread _crashed "]()}throw ex}};`}}),LD=Wt({" node _modules / @ tensorflow / tfjs - backend - wasm / wasm - out / tfjs - backend - wasm . js "(e,t){var n=(()=>{var r=typeof document!=" undefined "&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!=" undefined "&&(r=r||__filename),function(s){s=s||{};var a=typeof s!=" undefined "?s:{},o,i;a.ready=new Promise(function(X,ae){o=X,i=ae});var c;typeof process!=" undefined "&&process.listeners&&(c={uncaughtException:process.listeners(" uncaughtException "),unhandledRejection:process.listeners(" unhandledRejection ")});var u=Object.assign({},a),l=[],p=" . / this . program ",d=(X,ae)=>{throw ae},h=typeof window==" object ",f=typeof importScripts==" function ",m=typeof process==" object "&&typeof process.versions==" object "&&typeof process.versions.node==" string ",g=" ";function b(X){return a.locateFile?a.locateFile(X,g):g+X}var y,v,x,k;function S(X){if(X instanceof Xi)return;F(" exiting due to exception : "+X)}if(m){f?g=_h().dirname(g)+" / ":g=__dirname+" / ";var C,E;typeof U1==" function "&&(C=Nv(),E=_h()),y=(X,ae)=>(X=E.normalize(X),C.readFileSync(X,ae?void 0:" utf8 ")),x=X=>{var ae=y(X,!0);return ae.buffer||(ae=new Uint8Array(ae)),ae},v=(X,ae,Ie)=>{X=E.normalize(X),C.readFile(X,function(Ge,wt){Ge?Ie(Ge):ae(wt.buffer)})},process.argv.length>1&&(p=process.argv[1].replace(/\\/g," / ")),l=process.argv.slice(2),process.on(" uncaughtException ",function(X){if(!(X instanceof Xi))throw X}),process.on(" unhandledRejection ",function(X){throw X}),d=(X,ae)=>{if(qn())throw process.exitCode=X,ae;S(ae),process.exit(X)},a.inspect=function(){return" [ Emscripten Module object ] "}}else(h||f)&&(f?g=self.location.href:typeof document!=" undefined "&&document.currentScript&&(g=document.currentScript.src),r&&(g=r),g.indexOf(" blob : ")!==0?g=g.substr(0,g.replace(/[?#].*/," ").lastIndexOf(" / ")+1):g=" ",y=X=>{var ae=new XMLHttpRequest;return ae.open(" GET ",X,!1),ae.send(null),ae.responseText},f&&(x=X=>{var ae=new XMLHttpRequest;return ae.open(" GET ",X,!1),ae.responseType=" arraybuffer " , ae . send ( null ) , ne
` )),c.join( `
` )}function _F(e,t,n,r){let s=ht(t),a=r[r.length-1],o=new Array(a).fill(0),i=t.length,c=n==="complex64"?Rl(e):e;if(i>1)for(let u=0;u<s/a;u++){let l=u*a;for(let p=0;p<a;p++)o[p]=Math.max(o[p],Fl(c[l+p],0,n).length)}return o}function Fl(e,t,n){let r;return Array.isArray(e)?r= ` $ { parseFloat ( e [ 0 ] . toFixed ( fy ) ) } + $ { parseFloat ( e [ 1 ] . toFixed ( fy ) ) } j ` :ea(e)?r= ` '${e}' ` :n==="bool"?r=uS(e):r=parseFloat(e.toFixed(fy)).toString(),Gl(r,t)}function uS(e){return e===0?"false":"true"}function vh(e,t,n,r,s,a=!0){let o=n==="complex64"?2:1,i=t[0],c=t.length;if(c===0){if(n==="complex64"){let m=Rl(e);return[Fl(m[0],0,n)]}return n==="bool"?[uS(e[0])]:[e[0].toString()]}if(c===1){if(i>lk){let g=El*o,b=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-El)*o,i*o));return n==="complex64"&&(b=Rl(b),y=Rl(y)),["["+b.map((v,x)=>Fl(v,s[x],n)).join(", ")+", ..., "+y.map((v,x)=>Fl(v,s[i-El+x],n)).join(", ")+"]"]}return["["+(n==="complex64"?Rl(e):Array.from(e)).map((g,b)=>Fl(g,s[b],n)).join(", ")+"]"]}let u=t.slice(1),l=r.slice(1),p=r[0]*o,d=[];if(i>lk){for(let m=0;m<El;m++){let g=m*p,b=g+p;d.push(...vh(e.slice(g,b),u,n,l,s,!1))}d.push("...");for(let m=i-El;m<i;m++){let g=m*p,b=g+p;d.push(...vh(e.slice(g,b),u,n,l,s,m===i-1))}}else for(let m=0;m<i;m++){let g=m*p,b=g+p;d.push(...vh(e.slice(g,b),u,n,l,s,m===i-1))}let h=c===2?",":"";d[0]="["+d[0]+h;for(let m=1;m<d.length-1;m++)d[m]=" "+d[m]+h;let f= ` ,
` ;for(let m=2;m<c;m++)f+= `
` ;return d[d.length-1]=" "+d[d.length-1]+"]"+(a?"":f),d}function Rl(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Ht=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=ht(e),n!=null){let r=n.length;D(r===this.size,()=> ` Length of values '${r}' does not match the size inferred by the shape '${this.size}' . ` )}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||K1(t,this.size),this.strides=Dc(e)}set(e,...t){t.length===0&&(t=[0]),D(t.length===this.rank,()=> ` The number of provided coordinates ( $ { t . length } ) must match the rank ( $ { this . rank } ) ` );let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let r of e){if(r<0||r>=this.shape[t]){let s= ` Requested out of range element at $ { e } . Buffer shape = $ { this . shape } ` ;throw new Error(s)}t++}let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Lr().makeTensor(this.values,this.shape,this.dtype)}},Lr=null,oc=null,EF=null;function AF(e){Lr=e}function $ F(e){oc=e}function DF(e){EF=e}var Te=class{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=ht(e),this.strides=Dc(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return oc.buffer(this.shape,this.dtype,e)}bufferSync(){return oc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return uc(this.shape,e,this.dtype==="complex64")}arraySync(){return uc(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Lr().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>Oh(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Lr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Lr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Oh(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await Lr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Lr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return oc.print(this,e)}clone(){return this.throwIfDisposed(),oc.clone(this)}toString(e=!1){let t=this.dataSync();return NF(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),oc.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Lr().makeVariable(this,e,t,n)}};Object.defineProperty(Te,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function Q(){return Dv("Tensor",()=>Te)}Q();var ia=class extends Te{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error( ` dtype of the new value ( $ { e . dtype } ) and previous value ( $ { this . dtype } ) must match ` );if(!ga(e.shape,this.shape))throw new Error( ` shape of the new value ( $ { e . shape } ) and previous value ( $ { this . shape } ) must match ` );Lr().disposeTensor(this),this.dataId=e.dataId,Lr().incRef(this,null)}dispose(){Lr().disposeVariable(this),this.isDisposedInternal=!0}};Obje
Manifest JSON has weights with names : $ { i . join ( ", " ) } . ` )}let c=s.reduce((h,f,m)=>(f&&h.push(m),h),[]),u=[];c.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;u.push(m)})});let l=await e(u),p={},d=0;return c.forEach(h=>{let f=t[h].paths.length,m=0;for(let x=0;x<f;x++)m+=l[d+x].byteLength;let g=new ArrayBuffer(m),b=new Uint8Array(g),y=0;for(let x=0;x<f;x++){let k=new Uint8Array(l[d+x]);b.set(k,y),y+=k.byteLength}a[h].forEach(x=>{let k=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),S=mS(k,[x.manifestEntry]);for(let C in S)p[C]=S[C]}),d+=f}),p}}var ER="application/octet-stream",AR="application/json",Bv=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(D(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of ` fetch ` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=q().platform.fetch,D(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&D(e.length===2,()=> ` URL paths for http must have a length of 2 , ( actual length is $ { e . length } ) . ` ),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=gS(e,n);t.body.append("model.json",new Blob([JSON.stringify(r)],{type:AR}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:ER}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Dd(e),responses:[s]};throw new Error( ` BrowserHTTPRequest . save ( ) failed due to HTTP response status $ { s . status } . ` )}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error( ` Request to $ { this . path } failed with status code $ { e . status } . Please verify this URL points to the model JSON of the model to load . ` );let t;try{t=await e.json()}catch(s){let a= ` Failed to parse model JSON of response from $ { this . path } . ` ;throw this.path.endsWith(".pb")?a+=" 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.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,r=t.weightsManifest;if(n==null&&r==null)throw new Error( ` The JSON from HTTP path $ { this . path } contains neither model topology or manifest for weights . ` );return Lv(t,s=>this.loadWeights(s))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]= $ R(t),s=this.weightPathPrefix||n,a=yS(e),o=[],i=[];for(let u of e)for(let l of u.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(l)):o.push(s+l+r);this.weightUrlConverter&&o.push(...await Promise.all(i));let c=await CS(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Mv(c)]}};Bv.URL_SCHEME_REGEX=/^https?: \/ \/ /;function $ R(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}function zy(e){return e.match(Bv.URL_SCHEME_REGEX)!=null}var _S=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>zy(r)):n=zy(e),n)return Wv(e,t)}return null}; $ t.registerSaveRouter(_S); $ t.registerLoadRouter(_S);function Wv(e,t){return new Bv(e,t)}function DR(e,t){return Wv(e,t)}var by=class{constructor(e){this.modelArtifacts=e}
Actual : $ { s } .
Expected : $ { a } . ` );for(let o=0;o<a.length;++o){let i=s[o],c=a[o];if(!n(i,c))throw new Error( ` Arrays differ : actual [ $ { o } ] = $ { i } , expected [ $ { o } ] = $ { c } .
Actual : $ { s } .
Expected : $ { a } . ` )}typeof expect!="undefined"&&expect().nothing()}function IP(e,t){e().then(()=>t.fail(),()=>t()),typeof expect!="undefined"&&expect().nothing()}function kP(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return ea(e)||ea(e[0])||ea(t)||ea(t[0])?Wy(e,n,(r,s)=>r==s):Wy(e,t,(r,s)=>Kv(r,s,0))}function SP(e,t,n){if(n==null&&(n=jv()),!Kv(e,t,n))throw new Error( ` Numbers differ : actual === $ { e } , expected === $ { t } ` );typeof expect!="undefined"&&expect().nothing()}function Kv(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function TP(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error( ` Value out of range : $ { e [ r ] } low : $ { t } , high : $ { n } ` )}function CP(e,t){let n=new Float32Array(e),r=new Float32Array(t);if(n.length!==r.length)throw new Error( ` Expected ArrayBuffer to be of length $ { r . length } , but it was $ { n . length } ` );for(let s=0;s<r.length;s++)if(n[s]!==r[s])throw new Error( ` Expected ArrayBuffer value at $ { s } to be $ { r [ s ] } but got $ { n [ s ] } instead ` )}function XS(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?XS(n):e[t]=Ad(n)}return e}function NP(e){let t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise(n=>{t.addEventListener("loadeddata",r=>n(t)),t.load()})}async function _P(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}var EP="4.0.0";function AP(e,t){let n=_(e,"a","add"),r=_(t,"b","add");[n,r]=_t(n,r);let s={a:n,b:r};return M.runKernel(ba,s)}var Y=z({add_:AP});function $ P(e,t){let n=_(e,"a","floorDiv"),r=_(t,"b","floorDiv");[n,r]=_t(n,r);let s={a:n,b:r};return M.runKernel(Fo,s)}var jf=z({floorDiv_: $ P});function DP(e,t){let n=_(e,"a","div"),r=_(t,"b","div");if([n,r]=_t(n,r),n.dtype==="int32"&&r.dtype==="int32")return jf(n,r);let s={a:n,b:r},a={};return M.runKernel(Eo,s,a)}var fe=z({div_:DP});function FP(e,t){let n=_(e,"a","mul"),r=_(t,"b","mul");[n,r]=_t(n,r);let s={a:n,b:r};return M.runKernel(qo,s)}var B=z({mul_:FP});function RP(e){let t=_(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return M.runKernel(hd,n)}else{let n={x:t};return M.runKernel(Fc,n)}}var Lt=z({abs_:RP});function PP(e){let n={x:_(e,"x","acos")};return M.runKernel(Rc,n)}var Xv=z({acos_:PP});function OP(e){let n={x:_(e,"x","acosh")};return M.runKernel(Pc,n)}var Yv=z({acosh_:OP});function MP(e){D(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),D(e.length>=1,()=> ` Must pass at least one tensor to tf . addN ( ) , but got $ { e . length } ` );let t=e.map((s,a)=>_(s, ` tensors$ { a } ` ,"addN")),n=t[0];t.forEach(s=>{if(s.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(s=>{if(!ga(s.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=t;return M.runKernel(bo,r)}var YS=z({addN_:MP});function LP(e,t=null,n=!1){let s={x:_(e,"x","all","bool")},a={axis:t,keepDims:n};return M.runKernel(Oc,s,a)}var Kf=z({all_:LP});function zP(e,t=null,n=!1){let s={x:_(e,"x","any","bool")},a={axis:t,keepDims:n};return M.runKernel(Mc,s,a)}var Ql=z({any_:zP});function BP(e,t=0){let r={x:_(e,"x","argMax")},s={axis:t};return M.runKernel(yo,r,s)}var ao=z({argMax_:BP});function WP(e,t=0){let r={x:_(e,"x","argMin")},s={axis:t};return M.runKernel(dd,r,s)}var Zv=z({argMin_:WP});function VP(e){let n={x:_(e,"x","asin")};return M.runKernel(Lc,n)}var Jv=z({asin_:VP});function UP(e){let n={x:_(e,"x","asinh")};return M.runKernel(zc,n)}var Qv=z({asinh_:UP});function GP(e){let n={x:_(e,"x","atan")};return M.runKernel(Bc,n)}var ex=z({atan_:GP});function HP(e,t){let n=_(e,"a","atan2"),r=_(t,"b","atan2");[n,r]=_t(n,r);let s={a:n,b:r};return M.runKernel(Vc,s)}var tx=z({atan2_:HP});function qP(e){let n={x:_(e,"x","atanh")};return M.runKernel(Wc,n)}var nx=z({atanh_:qP});function jP(e,t,n,r,s="NHWC",a){let o=e[3],i=[...t,o],c=QS(s);return Pd(e,i,n,a,r,null,null,c)}function ZS(e,t,n,r,s,a,o=
with dtype $ { a . dtype } . ` )}),n.length===1)return is(n[0]);let r=n,s={axis:t};return M.runKernel(Gc,r,s)}var Je=z({concat_:nO});function rO(e){let n={x:_(e,"x","sigmoid","float32")};return M.runKernel(oi,n)}var dr=z({sigmoid_:rO});function sO(e,t,n){let r=_(e,"x","slice","string_or_numeric");if(r.rank===0)throw new Error("Slicing scalar is not possible");let s={x:r},a={begin:t,size:n};return M.runKernel(Su,s,a)}var We=z({slice_:sO});function aO(e){let n={x:_(e,"x","tanh","float32")};return M.runKernel(hi,n)}var oo=z({tanh_:aO});function oO(e,t,n,r,s,a){let o=_(e,"forgetBias","basicLSTMCell"),i=_(t,"lstmKernel","basicLSTMCell"),c=_(n,"lstmBias","basicLSTMCell"),u=_(r,"data","basicLSTMCell"),l=_(s,"c","basicLSTMCell"),p=_(a,"h","basicLSTMCell"),d=Je([u,p],1),h=De(d,i),f=Y(h,c),m=f.shape[0],g=f.shape[1]/4,b=[m,g],y=We(f,[0,0],b),v=We(f,[0,g],b),x=We(f,[0,g*2],b),k=We(f,[0,g*3],b),S=Y(B(dr(y),oo(v)),B(l,dr(Y(o,x)))),C=B(oo(S),dr(k));return[S,C]}var eT=z({basicLSTMCell_:oO});function iO(e,t,n){let r=_(e,"x","batchToSpaceND"),s=t.reduce((i,c)=>i*c);D(r.rank>=1+t.length,()=> ` input rank is $ { r . rank } but should be > than blockShape . length $ { t . length } ` ),D(n.length===t.length,()=> ` crops . length is $ { n . length } but should be equal to blockShape . length $ { t . length } ` ),D(r.shape[0]%s===0,()=> ` input tensor batch is $ { r . shape [ 0 ] } but is not divisible by the product of the elements of blockShape $ { t . join ( " * " ) } === $ { s } ` );let a={x:r},o={blockShape:t,crops:n};return M.runKernel(Uc,a,o)}var Od=z({batchToSpaceND_:iO});function cO(e){let t;return e.rank===0||e.rank===1?t=W(e,[1,1,1,e.size]):e.rank===2?t=W(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function uO(e,t,n,r,s,a){a==null&&(a=.001);let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),c=_(n,"variance","batchNorm"),u;s!=null&&(u=_(s,"scale","batchNorm"));let l;r!=null&&(l=_(r,"offset","batchNorm")),D(i.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),D(l==null||i.rank===l.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),D(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let d={x:cO(o),scale:u,offset:l,mean:i,variance:c},h={varianceEpsilon:a},f=M.runKernel(Ro,d,h);return W(f,o.shape)}var ka=z({batchNorm_:uO});function lO(e,t,n,r,s,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),c=_(n,"variance","batchNorm"),u;s!=null&&(u=_(s,"scale","batchNorm"));let l;return r!=null&&(l=_(r,"offset","batchNorm")),D(o.rank===2,()=> ` Error in batchNorm2D : x must be rank 2 but got rank $ { o . rank } . ` ),D(i.rank===2||i.rank===1,()=> ` Error in batchNorm2D : mean must be rank 2 or rank 1 but got rank $ { i . rank } . ` ),D(c.rank===2||c.rank===1,()=> ` Error in batchNorm2D : variance must be rank 2 or rank 1 but got rank $ { c . rank } . ` ),u!=null&&D(u.rank===2||u.rank===1,()=> ` Error in batchNorm2D : scale must be rank 2 or rank 1 but got rank $ { u . rank } . ` ),l!=null&&D(l.rank===2||l.rank===1,()=> ` Error in batchNorm2D : offset must be rank 2 or rank 1 but got rank $ { l . rank } . ` ),ka(o,i,c,l,u,a)}var ax=z({batchNorm2d_:lO});function dO(e,t,n,r,s,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),c=_(n,"variance","batchNorm"),u;s!=null&&(u=_(s,"scale","batchNorm"));let l;return r!=null&&(l=_(r,"offset","batchNorm")),D(o.rank===3,()=> ` Error in batchNorm3D : x must be rank 3 but got rank $ { o . rank } . ` ),D(i.rank===3||i.rank===1,()=> ` Error in batchNorm3D : mean must be rank 3 or rank 1 but got rank $ { i . rank } . ` ),D(c.rank===3||c.rank===1,()=> ` Error in batchNorm3D : variance must be rank 3 or rank 1 but got rank $ { c . rank } . ` ),u!=null&&D(u.rank===3||u.rank===1,()=> ` Error in batchNorm3D : scale must be rank 3 or rank 1 but got rank $ { u . rank } . ` ),l!=null&&D(l.rank===3||l.rank===1,()=> ` Error in batchNorm3D : offset must be rank 3 or rank 1 but got rank $ { l . rank } . ` ),ka(o,i,c,l,u,a)}var ox=z({batchNorm3d_:dO});function pO(e,t,n,r,s,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),c=_(n,"variance","batchNorm"),u;s!=null&&(u=_(s,"scale","batchNorm")
$ { s } and $ { t } for depthToSpace with input shape
$ { r . shape } ` ),D(a*t>=0,()=> ` Negative dimension size caused by overflow when multiplying
$ { a } and $ { t } for depthToSpace with input shape
$ { r . shape } ` ),D(o%(t*t)===0,()=> ` Dimension size must be evenly divisible by $ { t * t } but is $ { o } for depthToSpace with input shape $ { r . shape } ` );let i={x:r},c={blockSize:t,dataFormat:n};return M.runKernel(jc,i,c)}var bx=z({depthToSpace_:RO});function PO(e,t,n,r,s="NHWC",a=[1,1],o){let i=_(e,"x","depthwiseConv2d","float32"),c=_(t,"filter","depthwiseConv2d","float32"),u=i,l=!1;i.rank===3&&(l=!0,u=W(i,[1,i.shape[0],i.shape[1],i.shape[2]])),D(u.rank===4,()=> ` Error in depthwiseConv2d : input must be rank 4 , but got rank $ { u . rank } . ` ),D(c.rank===4,()=> ` Error in depthwiseConv2d : filter must be rank 4 , but got rank $ { c . rank } . ` );let p=s==="NHWC"?u.shape[3]:u.shape[1];D(p===c.shape[2],()=> ` Error in depthwiseConv2d : number of input channels ( $ { p } ) must match the inChannels dimension in filter $ { c . shape [ 2 ] } . ` ),En("depthwiseConv2d",r,o);let d={x:u,filter:c},h={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},f=M.runKernel(_o,d,h);return l?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Sa=z({depthwiseConv2d_:PO});function OO(e){let n={x:_(e,"x","diag")};return M.runKernel(kf,n)}var rT=z({diag_:OO});function MO(e,t,n,r,s=[1,1],a="NHWC"){let o=_(e,"x","dilation2d"),i=_(t,"filter","dilation2d");D(o.rank===3||o.rank===4,()=> ` Error in dilation2d : input must be rank 3 or 4 , but got rank $ { o . rank } . ` ),D(i.rank===3,()=> ` Error in dilation2d : filter must be rank 3 , but got rank $ { i . rank } . ` ),D(a==="NHWC",()=> ` Error in dilation2d : Only NHWC is currently supported , but got dataFormat of $ { a } ` );let c=o,u=!1;o.rank===3&&(c=W(o,[1,o.shape[0],o.shape[1],o.shape[2]]),u=!0);let l={x:c,filter:i},p={strides:n,pad:r,dilations:s},d=M.runKernel(md,l,p);return u?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var yx=z({dilation2d_:MO});function LO(e,t){let n=_(e,"a","equal","string_or_numeric"),r=_(t,"b","equal","string_or_numeric");[n,r]=_t(n,r),ct(n.shape,r.shape);let s={a:n,b:r};return M.runKernel(Xc,s)}var tr=z({equal_:LO});function zO(e,t,n){let r=_(t,"a","where"),s=_(n,"b","where"),a=_(e,"condition","where","bool"),o=ct(ct(a.shape,r.shape),s.shape),i=Ya(a,o),c=Ya(r,o),u=Ya(s,o),l={condition:i,t:c,e:u};return M.runKernel(Iu,l)}var mn=z({where_:zO});function BO(e){let n={x:_(e,"x","zerosLike")};return M.runKernel(Pu,n)}var qe=z({zerosLike_:BO});function WO(e,t){let n=_(e,"a","div"),r=_(t,"b","div");[n,r]=_t(n,r);let s=fe(n,r),a=qe(s),o=tr(r,a);return mn(o,a,s)}var vx=z({divNoNan_:WO});function VO(e,t){let n=_(e,"t1","dot"),r=_(t,"t2","dot");D((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),()=> ` Error in dot : inputs must all be rank 1 or 2 , but got ranks $ { n . rank } and $ { r . rank } . ` );let s=n.rank===1?n.size:n.shape[1],a=r.rank===1?r.size:r.shape[0];if(D(s===a,()=> ` Error in dot : inner dimensions of inputs must match , but got $ { s } and $ { a } . ` ),n.rank===1&&r.rank===1){let o=W(n,[1,-1]),i=W(r,[-1,1]),c=De(o,i);return W(c,[])}else if(n.rank===1&&r.rank===2){let o=W(n,[1,-1]),i=W(r,[r.shape[0],r.shape[1]]),c=De(o,i);return W(c,[c.size])}else if(n.rank===2&&r.rank===1){let o=W(r,[-1,1]),i=De(n,o);return W(i,[i.size])}else{let o=W(r,[r.shape[0],r.shape[1]]);return De(n,o)}}var xx=z({dot_:VO});function UO(e,...t){let n=t.map((s,a)=>_(s, ` tensors$ { a } ` ,"einsum")),r={equation:e};return M.runKernel(Sf,n,r)}var sT=z({einsum_:UO});function GO(e){let n={x:_(e,"x","elu","float32")};return M.runKernel(Ao,n)}var Lu=z({elu_:GO});function HO(e){let t=_(e,"x","erf");D(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be ` int32 ` or ` float32 ` ."),t.dtype==="int32"&&(t=ce(t,"float32"));let n={x:t};return M.runKernel(Kc,n)}var wx=z({erf_:HO});function Ix(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function aT(e,t,n){let r=e.length+t.length,s=[],a=0,o=0;for(let i=0;i<r;i++)n.indexOf(i)===-1?s.push(e[a++]):s.push(t[o++]);return s}function oT(e,t){let n=[],r=e.length;for(let a=0;a<r;a++)t.indexOf(a)===-1&&n.push(e[a]);let s=t.map(a=>e[a]);return[n,s]}function io(e,t){let n=t.map(r=>1);return aT(e,n,t)}function qO(e,t,n){D(Ix(t,n),()=> ` $ { e } supports only inner - most axes for now . Got axes $ { t } and rank - $ { n } input . ` )}function iT(e,t){if(Ix(e
rank $ { a . rank } . ` ),D(hc(t),()=> ` Error in localResponseNormalization : depthRadius must be an integer but got depthRadius $ { t } . ` );let o=a,i=!1;a.rank===3&&(i=!0,o=W(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let c={x:o},u={depthRadius:t,bias:n,alpha:r,beta:s},l=M.runKernel(bd,c,u);return i?W(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var Ex=z({localResponseNormalization_:bM});function yM(e){let n={x:_(e,"x","log","float32")};return M.runKernel(Lo,n)}var nr=z({log_:yM});function vM(e){let n={x:_(e,"x","log1p")};return M.runKernel(iu,n)}var zd=z({log1p_:vM});function xM(e){return D(oa(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let r=_(t,"x","tf.grad","string_or_numeric"),s=n!=null?_(n,"dy","tf.grad"):null;return M.tidy(()=>{let{value:a,grads:o}=M.gradients(()=>e(r),[r],s);return s!=null&&_n(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),tm(o),o[0]})}}function wM(e){return D(oa(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{D(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of ` Tensor ` s or ` TensorLike ` s");let r=Jl(t,"args","tf.grads","string_or_numeric"),s=n!=null?_(n,"dy","tf.grads"):null;return M.tidy(()=>{let{value:a,grads:o}=M.gradients(()=>e(...r),r,s);return s!=null&&_n(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),tm(o),o})}}function IM(e){return D(oa(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{D(t instanceof Te,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),D(n==null||n instanceof Te,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:r,value:s}=M.gradients(()=>e(t),[t],n);return tm(r),{grad:r[0],value:s}}}function kM(e){return D(oa(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{D(Array.isArray(t)&&t.every(s=>s instanceof Te),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),D(n==null||n instanceof Te,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let r=M.gradients(()=>e(...t),t,n);return n!=null&&_n(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),tm(r.grads),r}}function lT(e,t){D(oa(e),()=>"The f passed in variableGrads(f) must be a function"),D(t==null||Array.isArray(t)&&t.every(u=>u instanceof ia),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in M.registeredVariables)t.push(M.registeredVariables[u])}let r=n?t.filter(u=>!u.trainable):null,s=t.length;t=t.filter(u=>u.trainable),D(t.length>0,()=> ` variableGrads ( ) expects at least one of the input variables to be trainable , but none of the $ { s } variables is trainable . ` );let a=!0,{value:o,grads:i}=M.gradients(e,t,null,a);D(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),D(o.rank===0,()=> ` The f passed in variableGrads ( f ) must return a scalar , but it returned a rank - $ { o . rank } tensor ` );let c={};return t.forEach((u,l)=>{i[l]!=null&&(c[u.name]=i[l])}),r!=null&&r.forEach(u=>c[u.name]=null),{value:o,grads:c}}function ls(e){return M.customGrad(e)}function tm(e){if(e.filter(n=>n==null).length>0)throw new Error( ` Cannot compute gradient of y = f ( x ) with respect to x . Make sure that
the f you passed encloses all operations that lead from x to y . ` )}function SM(e){let n={x:_(e,"x","softplus")};return M.runKernel(Nu,n)}var mi=z({softplus_:SM});function TM(e){let t=_(e,"x","logSigmoid");return ls(r=>({value:xt(mi(xt(r))),gradFunc:o=>B(o,dr(xt(r)))}))(t)}var Ax=z({logSigmoid_:TM});function CM(e,t){let n=_(e,"a","sub"),r=_(t,"b","sub");[n,r]=_t(n,r);let s={a:n,b:r};return M.runKernel(di,s)}var de=z({sub_:CM});function NM(e,t=-1){let n=_(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error( ` Log Softmax along a non - last dimension is not yet supported . Logits was rank $ { n . rank } and axis was $ { t } ` );return ls((s,a)=>{let i=pr(s,t,!0),c=de(s,i),u=de(ce(c,"float32"),nr(ge(gn(c),t,!0)));return a([u]),{value:u,gradFunc:(p,d)=>{let[h]=d,f=!0,m=gn(h);return de(p,B(ge(p,t,f),m))}}})(n)}var nm=z({logSoftmax_:NM});function _M(e,t=null,n=!1){let r=_(e,"x","logSumExp"),s=Fr(t,r.shape),a=pr(r,s,!0),o=de(r,a),i=gn(o),c=ge(i,s),u=nr(c),l=Y(W(a,u.shape),u);if(n){let p=io(l.shape,s);return W(l,p)}return l}var rm=z({logSumExp_:_M});function EM(e,t){let n=_(e,"a","logicalAnd","bool"),r=_(t,"b","logicalAnd","bool");ct(n.shape,r.shape);let s={a:n,b:r};return M.runKernel(cu,s)}var Dr=z({logicalAnd_:EM});function AM(e){let n={x:_(e,"x","logicalNot","bool")};return M.runKernel(uu,n)}var Bd=z({logicalNot_:AM});function $ M(e,t){let n=_(e,"a","logicalOr","bool"),r=_(t,"b","logicalOr","bool");ct(n.shape,r.shape);let s={a:n,b:r};return M.runKernel(lu,s)}var sm=z({logicalOr_: $ M});function DM(e,t){let n=_(e,"a","logicalXor","bool"),r=_(t,"b","logicalXor","bool");return ct(n.shape,r.shape),Dr(sm(e,t),Bd(Dr(e,t)))}var $ x=z({logicalXor_:DM}),oh=2147483648;function FM(e,t,n="left"){let r=_(e,"sortedSequence","searchSorted"),s=_(t,"values","searchSorted"),a=r.shape[r.shape.length-1],o=s.shape[s.shape.length-1],i=W(r,[-1,a]),c=W(s,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==c.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(ht(c.shape)>=oh)throw new Error( ` values tensor size must less than $ { oh } ` );if(i.shape[1]>=oh)throw new Error( ` trailing dim _size must less than $ { oh } for int32 output type , was $ { i . shape [ 1 ] } ` );let u={sortedSequence:i,values:c},l={side:n};return M.runKernel(Wf,u,l)}var am=z({searchSorted_:FM});function dT(e,t){return am(e,t,"left")}function RM(e,t,n,r,s){let a=_(e,"x","maxPool"),o=1,i=a,c=!1;a.rank===3&&(c=!0,i=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),D(i.rank===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { i . rank } . ` ),D(ps(n,o),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { n } and dilations '${o}' ` ),En("maxPool",r,s);let u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s},p=M.runKernel(Wo,u,l);return c?W(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Rt=z({maxPool_:RM});function PM(e,t=[1,1,1],n,r,s,a="NDHWC"){let o=_(e,"x","maxPool3d"),i=o,c=!1;o.rank===4&&(c=!0,i=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),D(i.rank===5,()=> ` Error in maxPool3d : x must be rank 5 but got rank $ { i . rank } . ` ),D(a==="NDHWC",()=> ` Error in maxPool3d : Only NDHWC is currently supported , but got dataFormat of $ { a } ` ),En("maxPool3d",r,s);let u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},p=M.runKernel(yd,u,l);return c?W(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Dx=z({maxPool3d_:PM});function OM(e,t,n,r,s=!1){let o={x:_(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},c=M.runKernel(Ff,o,i);return{result:c[0],indexes:c[1]}}var pT=z({maxPoolWithArgmax_:OM});function MM(e,t){let n=_(e,"a","maximum"),r=_(t,"b","maximum");[n,r]=_t(n,r),n.dtype==="bool"&&(n=ce(n,"int32"),r=ce(r,"int32")),ct(n.shape,r.shape);let s={a:n,b:r};return M.runKernel(Bo,s)}var hs=z({maximum_:MM});function LM(e,t=null,n=!1){let s={x:_(e,"x","mean")},a={axis:t,keepDims:n};return M.runKernel(Vo,s,a)}var Ct=z({mean_:LM});function kt(e,t="float32"){if(t==="complex64"){let r=kt(e,"float32"),s=kt(e,"float32");return As(r,s)}let n=df(h
$ { s . shape } ` );if(a.rank!==1)throw new Error( ` Values should be Tensor1D but received shape $ { a . shape } ` );if(o.rank!==1)throw new Error( ` Dense shape should be Tensor1D but received shape $ { o . shape } ` );if(i.rank!==0)throw new Error( ` Default value should be a scalar but received shape $ { i . shape } ` );let c={indices:s,values:a,denseShape:o,defaultValue:i},u=M.runKernel(xd,c);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var _z=z({sparseFillEmptyRows_:Nz});function Ez(e,t,n){let r=_(e,"inputIndices","sparseReshape","int32"),s=_(t,"inputShape","sparseReshape","int32"),a=_(n,"newShape","sparseReshape","int32");if(r.rank!==2)throw new Error( ` Input indices should be Tensor2D but received shape
$ { r . shape } ` );if(s.rank!==1)throw new Error( ` Input shape should be Tensor1D but received shape $ { s . shape } ` );if(a.rank!==1)throw new Error( ` New shape should be Tensor1D but received shape $ { a . shape } ` );let o={inputIndices:r,inputShape:s,newShape:a},i=M.runKernel(Au,o);return{outputIndices:i[0],outputShape:i[1]}}var Az=z({sparseReshape_:Ez});function $ z(e,t,n){let r=_(e,"data","sparseSegmentMean"),s=_(t,"indices","sparseSegmentMean","int32"),a=_(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error( ` Indices should be Tensor1D but received shape
$ { s . shape } ` );if(a.rank!==1)throw new Error( ` Segment ids should be Tensor1D but received shape
$ { a . shape } ` );let o={data:r,indices:s,segmentIds:a};return M.runKernel(wd,o)}var Dz=z({sparseSegmentMean_: $ z});function Fz(e,t,n){let r=_(e,"data","sparseSegmentSum"),s=_(t,"indices","sparseSegmentSum","int32"),a=_(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error( ` Indices should be Tensor1D but received shape
$ { s . shape } ` );if(a.rank!==1)throw new Error( ` Segment ids should be Tensor1D but received shape
$ { a . shape } ` );let o={data:r,indices:s,segmentIds:a};return M.runKernel(Id,o)}var Rz=z({sparseSegmentSum_:Fz});function Pz(e,t,n,r,s,a,o,i){let c=_(e,"data","stringNGrams","string");if(c.dtype!=="string")throw new Error("Data must be of datatype string");if(c.shape.length!==1)throw new Error( ` Data must be a vector , saw : $ { c . shape } ` );let u=_(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let l={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},p={data:c,dataSplits:u},d=M.runKernel(Sd,p,l);return{nGrams:d[0],nGramsSplits:d[1]}}var Oz=z({stringNGrams_:Pz});function Mz(e,t,n=!0){let r=_(e,"input","stringSplit","string"),s=_(t,"delimiter","stringSplit","string");if(r.rank!==1)throw new Error( ` Input should be Tensor1D but received shape $ { r . shape } ` );if(s.rank!==0)throw new Error( ` Delimiter should be a scalar but received shape $ { s . shape } ` );let a={skipEmpty:n},o={input:r,delimiter:s},i=M.runKernel(Td,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var Lz=z({stringSplit_:Mz});function zz(e,t){let n=_(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let s={input:n};return M.runKernel(Cd,s,r)}var Bz=z({stringToHashBucketFast_:zz}),ZT={fft:Hd,ifft:wc,rfft:qd,irfft:fm},JT={hammingWindow:yL,hannWindow:GT,frame:HT,stft:IL},Br={flipLeftRight:CL,grayscaleToRGB:_L,resizeNearestNeighbor:YT,resizeBilinear:XT,rotateWithOffset:AL,cropAndResize:SL,nonMaxSuppression:DL,nonMaxSuppressionAsync:BL,nonMaxSuppressionWithScore:VL,nonMaxSuppressionWithScoreAsync:GL,nonMaxSuppressionPadded:qL,nonMaxSuppressionPaddedAsync:KL,threshold:QL,transform:tz},Zx={bandPart:rz,gramSchmidt:az,qr:iz},QT={absoluteDifference:lz,computeWeightedLoss:Fs,cosineDistance:pz,hingeLoss:fz,huberLoss:gz,logLoss:yz,meanSquaredError:xz,sigmoidCrossEntropy:kz,softmaxCrossEntropy:Cz},eC={sparseFillEmptyRows:_z,sparseReshape:Az,sparseSegmentMean:Dz,sparseSegmentSum:Rz},tC={stringNGrams:Oz,stringSplit:Lz,stringToHashBucketFast:Bz},Rs=class extends qS{minimize(e,t=!1,n){let{value:r,grads:s}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:s[o.name]}));this.applyGradients(a)}else this.applyGradients(s);return _e(s),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return lT(e,t)}dispose(){this.iterations_!=null&&_e(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:xe(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error( ` setWeights ( ) is not implemented for this optimizer class $ { this . getClassName ( ) } ` )}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty(Rs,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var km=class extends Rs{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=M.registeredVariables[n],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName: ` $ { n } / accum _grad ` ,variable:O(()=>qe(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName: ` $ { n } / accum _var ` ,variable:O(()=>qe(s).variable(a))});let o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;O(()=>{let u=Y(B(i,this.rho),B(it(o),1-this.rho)),l=B(fe(un(Y(c,this.epsilon)),un(Y(i,this.epsilon))),o),p=Y(B(c,this.rho),B(it(l),1-this.rho));i.assign(u),c.assign(p);let d=Y(B(l,-this.learningRate),s);s.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpda
indices . shape [ 0 ] = $ { e } ` }function SB(e,t){return ` indices ( $ { e } , 0 ) is invalid : $ { t } < 0 ` }function TB(e,t,n){return ` indices ( $ { e } , 0 ) is invalid : $ { t } >= $ { n } ` }function CB(e,t){return ` only one output dimension may be - 1 , not both $ { e } and $ { t } ` }function NB(e,t){return ` size $ { e } must be non - negative , not $ { t } ` }function _B(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function EB(e,t){let n=ht(e),r=ht(t);return ` Input to reshape is a SparseTensor with $ { n }
dense values , but the requested shape requires a multiple of $ { r } . inputShape = $ { e } outputShape = $ { t } ` }function AB(e,t){let n=ht(e),r=ht(t);return ` Input to reshape is a tensor with $ { n } dense values , but the requested shape has $ { r } . inputShape = $ { e } outputShape = $ { t } ` }function $ B(){return"segment ids must be >= 0"}function DB(){return"segment ids are not increasing"}function FB(e,t){return ` Segment id $ { e } out of range [ 0 , $ { t } ) , possibly because segmentIds input is not sorted . ` }function RB(e,t,n){return ` Bad : indices [ $ { e } ] == $ { t } out of range [ 0 , $ { n } ) ` }var sC={};Ae(sC,{collectGatherOpShapeInfo:()=>MB,computeOutShape:()=>OB,segOpComputeOptimalWindowSize:()=>PB});function PB(e,t){let n=!1,r;for(e<=Qx?(r=e,n=!0):r=Ah(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=Ah(e,r+1);return r}function OB(e,t,n){let r=[],s=e.length;for(let a=0;a<s;a++)a!==t?r.push(e[a]):r.push(n);return r}function MB(e,t,n,r){let s=t.shape.length,a=e.shape.length;if(r!==0&&(r<-s||r>s))throw new Error( ` Expect batchDims in the range of [ - $ { s } , $ { s } ] , but got $ { r } ` );if(r<0&&(r+=s),r>a)throw new Error( ` batchDims ( $ { r } ) must be less than rank ( x ) (
$ { a } ) . ` );if(n<r)throw new Error( ` batchDims ( $ { r } ) must be less than or equal to axis ( $ { n } ) . ` );for(let p=0;p<r;++p)if(e.shape[p]!==t.shape[p])throw new Error( ` x . shape [ $ { p } ] : $ { e . shape [ p ] } should be equal to indices . shape [ $ { p } ] : $ { t . shape [ p ] } . ` );let o=e.shape[n],i=[],c=1,u=1,l=1;for(let p=0;p<r;++p)i.push(e.shape[p]),c*=e.shape[p];for(let p=r;p<n;p++)i.push(e.shape[p]),u*=e.shape[p];for(let p=r;p<s;p++)i.push(t.shape[p]);for(let p=n+1;p<a;p++)i.push(e.shape[p]),l*=e.shape[p];return{batchSize:c,sliceSize:l,outerSize:u,dimSize:o,outputShape:i}}function LB(e){try{return e.map(t=>Oh(t))}catch(t){throw new Error( ` Failed to decode encoded string bytes into utf - 8 , error : $ { t } ` )}}function zB(e){return e.map(t=>Ad(t))}var fs={};Ae(fs,{nonMaxSuppressionV3Impl:()=>qT,nonMaxSuppressionV4Impl:()=>jT,nonMaxSuppressionV5Impl:()=>KT,whereImpl:()=>PT});var aC={kernelName:Fc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>B(e,bi(ce(n,"float32"),-1))}}},BB={kernelName:Rc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=it(ce(n,"float32")),s=un(de(xe(1),r));return xt(fe(e,s))}}}},WB={kernelName:Pc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=un(de(it(ce(n,"float32")),1));return fe(e,r)}}}},VB={kernelName:ba,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=ct(n.shape,r.shape);return{a:()=>{let i=e,c=Bt(n.shape,s);return c.length>0&&(i=ge(i,c)),W(i,n.shape)},b:()=>{let i=e,c=Bt(r.shape,s);return c.length>0&&(i=ge(i,c)),W(i,r.shape)}}}},UB={kernelName:bo,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((r,s)=>{n[s]=()=>e.clone()}),n}},GB={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>qe(n)}}},HB={kernelName:dd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>qe(n)}}},qB={kernelName:Lc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,un(de(xe(1),it(ce(n,"float32")))))}}},jB={kernelName:zc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=un(Y(xe(1),it(ce(n,"float32"))));return fe(e,r)}}}},KB={kernelName:Vc,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=ct(n.shape,r.shape);return{a:()=>{let i=Y(it(n),it(r)),c=B(e,fe(r,i)),u=Bt(n.shape,s);return u.length>0&&(c=ge(c,u)),W(c,n.shape)},b:()=>{let i=Y(it(n),it(r)),c=xt(B(e,fe(n,i))),u=Bt(r.shape,s);return u.length>0&&(c=ge(c,u)),W(c,r.shape)}}}},XB={kernelName:Bc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,Y(it(ce(n,"float32")),1))}}},YB={kernelName:Wc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,de(xe(1),it(ce(n,"float32"))))}}};function ZB(e,t,n,r,s,a){let o=_(e,"dy","avgPool3dGrad"),i=_(t,"input","avgPool3dGrad"),c=o,u=i,l=!1;i.rank===4&&(l=!0,c=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),u=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),D(c.rank===5,()=> ` Error in avgPool3dGrad : dy must be rank 5 but got rank $ { c . rank } . ` ),D(u.rank===5,()=> ` Error in avgPool3dGrad : input must be rank 5 but got rank $ { u . rank } . ` ),En("avgPool3dGrad",s,a);let p={dy:c,input:u},d={filterSize:n,strides:r,pad:s,dimRoundingMode:a},h=M.runKernel(hf,p,d);return l?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var JB=z({avgPool3dGrad_:ZB}),QB={kernelName:pd,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>JB(e,r,s,a,o,i)}}};function eW(e,t,n,r,s){let a=_(e,"dy","avgPoolGrad"),o=_(t,"input","avgPoolGrad");D(o.rank===a.rank,()=> ` Rank of input ( $ { o . rank } ) does not match rank of dy ( $ { a . rank } ) ` );let i=o,c=a,u=!1;o.rank===3&&(u=!0,i=W(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),D(c.rank===4,()=> ` Error in avgPoolGrad : dy must be rank 4 but got rank $ { c . rank } . ` ),D(i.rank===4,()=> ` Error in avgPoolGrad : input must be rank 4 but got rank $ { i . rank } . ` );let l={dy:c,input:i},p={filterSize:n,strides:r,pad:s},d=M.runKernel(pf,l,p);return u?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var tW=z({avgPoolGrad_:eW}),nW={kernelName:vo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o}=n;return{x:()=>tW(e,r,s,a,o)}}},rW={kernelName:xo,i
1. The $ { r } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2. The custom $ { r } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );return o}else{let a=e;if(a.className==null||a.config==null)throw new U( ` $ { r } : Improper config format : $ { JSON . stringify ( a ) } .
'className' and 'config' must set . ` );let o=a.className,i,c;if(o in n?[i,c]=n[o]:o in Tr?[i,c]=Tr.className:o in t&&([i,c]=t[o]),i==null)throw new U( ` Unknown $ { r } : $ { o } . This may be due to one of the following reasons :
1. The $ { r } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2. The custom $ { r } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );if(c!=null){let u={};for(let h of Object.keys(Tr))u[h]=Tr[h];for(let h of Object.keys(n))u[h]=n[h];let l=a.config;l.customObjects=u;let p=Object.assign({},Tr);for(let h of Object.keys(n))Tr[h]=n[h];Uy(a.config);let d=c(i,a.config,n,s);return Tr=Object.assign({},p),d}else{let u=Object.assign({},Tr);for(let p of Object.keys(n))Tr[p]=n[p];let l=new i(a.config);return Tr=Object.assign({},u),l}}}function G4(e,t){return e<t?-1:e>t?1:0}function ih(e,t){return-1*G4(e,t)}function sa(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function H4(e){if(e==null)throw new U( ` Invalid value in obj : $ { JSON . stringify ( e ) } ` );for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function yi(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new U( ` $ { n } is not a valid $ { t } . Valid values are $ { e } or null / undefined . ` )}function tw(e,t,n=0,r=1/0){return ss(n>=0),ss(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(s=>typeof s===t)}function Qt(e,t){Array.isArray(e)?(w.assert(e.length>0,()=> ` $ { t } is unexpectedly an empty array . ` ),e.forEach((n,r)=>Qt(n, ` element $ { r + 1 } of $ { t } ` ))):w.assert(Number.isInteger(e)&&e>0,()=> ` Expected $ { t } to be a positive integer , but got $ { uC ( e ) } . ` )}function uC(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>uC(t)).join(",")+"]":typeof e=="string"? ` "${e}" ` : ` $ { e } ` }function q4(e,t,n){let r=n!=null?n():w.now(),s;return(...o)=>{let i=n!=null?n():w.now();return i-r<t||(r=i,s=e(...o)),s}}function lC(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}var j4=0;function dC(){return j4++}var ch={};function Em(e=""){return e in ch||(ch[e]=0),ch[e]+=1,e+ch[e].toString()}var K4=["channelsFirst","channelsLast"],X4=["nearest","bilinear"],Y4=["valid","same","causal"],Z4=["max","avg"],J4=["sum","mul","concat","ave"],rc=new Map;function Pt(e){yi(K4,"DataFormat",e)}function Q4(e){yi(X4,"InterpolationFormat",e)}function br(e){yi(Y4,"PaddingMode",e)}function pC(e){yi(Z4,"PoolMode",e)}var Hl=[],Ek="/";function Za(e,t){Hl.push(e);try{let n=t();return Hl.pop(),n}catch(n){throw Hl.pop(),n}}function eV(){return Hl.length===0?"":Hl.join(Ek)+Ek}function hC(e){if(!mC(e))throw new Error("Not a valid tensor name: '"+e+"'");return eV()+e}function fC(e){if(!mC(e))throw new Error("Not a valid tensor name: '"+e+"'");rc.has(e)||rc.set(e,0);let t=rc.get(e);if(rc.set(e,rc.get(e)+1),t>0){let n= ` $ { e } _$ { t } ` ;return rc.set(n,1),n}else return e}var tV=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9 \. _ \/ ]* $ /);function mC(e){return!!e.match(tV)}function nV(e){return e===parseInt(e.toString(),10)}function aa(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let r=1;for(let s=t;s<n;++s)r*=e[s];return r}function kc(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){let r=e[n];r<t&&(t=r)}return t}function ua(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){let r=e[n];r>t&&(t=r)}return t}function qr(e,t){if(t<e)throw new U( ` end ( $ { t } ) < begin ( $ { e } ) is forbidden . ` );let n=[];for(let r=e;r<t;++r)n.push(r);return n}var vy;function Gt(){return vy==null&&(vy=DS().epsilon()),vy}function jr(){return"channelsLast"}function vi(e,t){return ce(e,t)}function Xd(e,t=-1){let n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),W(e,n)}function rV(e,t){return O(()=>{if(e.shape.length!==2)throw new U( ` repeat ( ) expects a rank - 2 tensor , but received a rank - $ { e . shape . length } tensor . ` );let n=Xd(e,1);return Gy(n,[1,t,1])})}function sV(e){let t=[aa(e.shape)];return W(e,t)}function aV(e){if(e.rank<=1)throw new U( ` batchFlatten requires a minimum rank of 2. Got rank : $ { e . rank } . ` );let t=[e.shape[0],aa(e.shape,1)];return W(e,t)}function Ja(e,t,n){return O(()=>{switch(e.rank){case 1:return Gd(e,t,n);case 2:return hm(e,[t,0],[n,e.shape[1]]);case 3:return gi(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return xc(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return We(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);cas
Received countWeights = $ { t . countWeights } ` );n=Ce(t.countWeights)}let r=pr(e),s=yc(e),a=An(this.numTokens,r).bufferSync().get(0),o=Ds(s,0).bufferSync().get(0);if(!(a&&o))throw new U( ` Input values must be between 0 < values <= numTokens with numTokens = $ { this . numTokens } ` );return QU(e,this.outputMode,this.numTokens,n)})}};S0.className="CategoryEncoding";se.registerClass(S0);function eG(e){return new Hu(e)}function tG(e){return new Nw(e)}function nG(e){return new Sw(e)}function rG(e){return new Tw(e)}function sG(e){return new Cw(e)}function aG(e){return new Ew(e)}function oG(e){return new _w(e)}function iG(e){return new Wm(e)}function cG(e){return new tp(e)}function uG(e){return new Dw(e)}function lG(e){return new np(e)}function dG(e){return new Fw(e)}function pG(e){return new Rw(e)}function hG(e){return new Pw(e)}function fG(e){return new Ow(e)}function mG(e){return new Mw(e)}function gG(e){return new Hw(e)}function bG(e){return new Uw(e)}function yG(e){return new qm(e)}function vG(e){return new Vw(e)}function xG(e){return new Gw(e)}function wG(e){return new qw(e)}function IG(e){return new jw(e)}function kG(e){return new Kw(e)}function SG(e){return new Yw(e)}function TG(e){return new Zw(e)}function CG(e){return new Qw(e)}function NG(e){return new n0(e)}function _G(e){return new e0(e)}function EG(e){return new t0(e)}function AG(e){return new Jw(e)}function $ G(e){return new r0(e)}function DG(e){return new i0(e)}function FG(e){return new c0(e)}function RG(e){return new u0(e)}function T0(e){return new d0(e)}function PG(e){return T0(e)}function OG(e){return T0(e)}function C0(e){return new h0(e)}function MG(e){return C0(e)}function LG(e){return C0(e)}function N0(e){return new m0(e)}function zG(e){return N0(e)}function BG(e){return N0(e)}function WG(e){return new g0(e)}function VG(e){return new y0(e)}function fN(e){return new b0(e)}function mN(e){return new v0(e)}function gN(e){return new l0(e)}function bN(e){return new p0(e)}function UG(e){return new f0(e)}function GG(e){return new zw(e)}function HG(e){return new Um(e)}function qG(e){return new Bw(e)}function jG(e){return new sp(e)}function KG(e){return new Lw(e)}function XG(e){return new Vm(e)}function YG(e){return new Ww(e)}function ZG(e){return new Hm(e)}function JG(e){return new ms(e)}function QG(e){return new Gm(e)}function eH(e){return new w0(e)}function tH(e){return new x0(e)}var nH=fN,rH=mN,sH=gN,aH=bN;function oH(e){return new s0(e)}function iH(e){return new a0(e)}function cH(e){return new o0(e)}function uH(e){return new Xw(e)}function lH(e){return new I0(e)}function dH(e){return new k0(e)}function pH(e){return new S0(e)}var yN={};Ae(yN,{MAPE:()=>kH,MSE:()=>CH,binaryAccuracy:()=>hH,binaryCrossentropy:()=>fH,categoricalAccuracy:()=>gH,categoricalCrossentropy:()=>bH,cosineProximity:()=>xH,mape:()=>SH,meanAbsoluteError:()=>wH,meanAbsolutePercentageError:()=>IH,meanSquaredError:()=>TH,mse:()=>NH,precision:()=>yH,recall:()=>vH,sparseCategoricalAccuracy:()=>mH});function hH(e,t){return bw(e,t)}function fH(e,t){return DC(e,t)}function mH(e,t){return FC(e,t)}function gH(e,t){return yw(e,t)}function bH(e,t){return vw(e,t)}function yH(e,t){return $ C(e,t)}function vH(e,t){return nU(e,t)}function xH(e,t){return gw(e,t)}function wH(e,t){return zm(e,t)}function IH(e,t){return qu(e,t)}function kH(e,t){return qu(e,t)}function SH(e,t){return qu(e,t)}function TH(e,t){return xi(e,t)}function CH(e,t){return xi(e,t)}function NH(e,t){return xi(e,t)}var vN={};Ae(vN,{modelFromJSON:()=>DU});var xN={};Ae(xN,{l1:()=>EH,l1l2:()=>_H,l2:()=>AH});function _H(e){return new Qd(e)}function EH(e){return zU(e)}function AH(e){return BU(e)}var wN=class extends Sc{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Es))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function dh(e,t){return e<t}function Xk(e,t){return e>t}var IN=class extends wN{constructor(e){if(super(),e==null&&(e={}),e.restoreBestWeights)throw new Pe("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.min
because the value dtype is $ { t . dtype } , but TensorArray dtype is $ { this . dtype } . ` );if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Ar(this.elementShape,t.shape, ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } . ` ),n.read)throw new Error( ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } , because it has already been read . ` );if(n.written)throw new Error( ` TensorArray $ { this . name } : Could not write to TensorArray index $ { e } , because it has already been written . ` );n.tensor=t,Jt(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error( ` TensorArray $ { this . name } : could not write multiple tensors , because the index size : $ { e . length } is not the same as tensors size : $ { t . length } . ` );e.forEach((n,r)=>this.write(n,t[r]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but gather requested dtype $ { t } ` );if(e)e=e.slice(0,this.size());else{e=[];for(let r=0;r<this.size();r++)e.push(r)}if(e.length===0)return Cn([],[0].concat(this.elementShape));let n=this.readMany(e);return Ar(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Ft(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but concat requested dtype $ { e } ` );if(this.size()===0)return Cn([],[0].concat(this.elementShape));let t=[];for(let r=0;r<this.size();r++)t.push(r);let n=this.readMany(t);return Ar(this.elementShape,n[0].shape, ` TensorArray shape mismatch : tensor array shape ( $ { this . elementShape } ) vs first tensor shape ( $ { n [ 0 ] . shape } ) ` ),Je(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but tensor has dtype $ { t . dtype } ` );if(e.length!==t.shape[0])throw new Error( ` Expected len ( indices ) == tensor . shape [ 0 ] , but saw : $ { e . length } vs . $ { t . shape [ 0 ] } ` );let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error( ` Max index must be < array size ( $ { n } vs . $ { this . maxSize } ) ` );this.writeMany(e,lt(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but tensor has dtype $ { t . dtype } ` );let n=0,r=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error( ` Expected sum of lengths to be equal to
2021-09-11 17:11:38 +02:00
tensor . shape [ 0 ] , but sum of lengths is
2022-10-30 14:06:17 +01:00
$ { n } , and tensor 's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray' s size is not equal to the size of lengths ( $ { this . maxSize } vs . $ { e . length } ) , and the TensorArray is not marked as dynamically resizeable ` );let s=n===0?0:t.size/n,a=[];O(()=>{t=W(t,[1,n,s]);for(let i=0;i<e.length;++i){let u=[0,i===0?0:r[i-1],0],l=[1,e[i],s];a[i]=W(We(t,u,l),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},Cc=class{constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(s=>{if(n!==s.dtype)throw new Error( ` Invalid data types ; op elements $ { n } , but list elements $ { s . dtype } ` );Ar(t,s.shape,"TensorList shape mismatch: "),Jt(s)}),this.idTensor=xe(0),this.maxNumElements=r,Jt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Cc([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );if(n!==-1&&this.tensors.length!==n)throw new Error( ` Operation expected a list with $ { n } elements but got a list with $ { this . tensors . length } elements . ` );Ar(e,this.elementShape,"TensorList shape mismatch: ");let r= $ l(this.elementShape,this.tensors,e);return O(()=>{let s=this.tensors.map(a=>W(a,r));return Ft(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n= $ l(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Ar(r.shape,e,"TensorList shape mismatch: "),W(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { e . dtype } , but list elements $ { this . elementDtype } ` );if(Ar(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Jt(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error( ` TensorListResize expects size to be non - negative . Got : $ { e } ` );if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error( ` TensorListResize input size $ { e } is greater maxNumElement $ { this . maxNumElements } . ` );let t=new Cc([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { n } , but list elements $ { this . elementDtype } ` );if(e<0||e>this.tensors.length)throw new Error( ` Trying to access element $ { e } in a list with $ { this . tensors . length } elements . ` );if(this.tensors[e]==null)throw new Error( ` element at index $ { e } is null . ` );Ar(this.tensors[e].shape,t,"TensorList shape mismatch: ");let r= $ l(this.elementShape,this.tensors,t);return W(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t . dtype } , but list elements $ { this . elementDtype } ` );if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error( ` Trying to set element $ { e } in a list with max $ { this . maxNumElements } elements . ` );Ar(this.elementShape,t.shape,"TensorList shape mismatch: "),Jt(t),this.tensors[e]!=null&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );Ar(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let r= $ l(this.elementShape,this.tensors,n);return e.length===0?Cn([],[0].concat(r)):O(()=>{let s=e.map(a=>W(this.tensors[a],r));return Ft(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error( ` TensorList dtype is $ { this . elementDtype } but concat requested dtype $ { e } ` );Ar(this.elementShape,t,"TensorList shape mismatch: ");let n= $ l(thi
2021-09-11 17:11:38 +02:00
tensor . shape [ 0 ] , but sum of lengths is
2022-10-30 14:06:17 +01:00
$ { r } , and tensor ' s shape is : $ { e . shape } ` );let a=e.shape.slice(1),o=uv(a,n),i=r===0?0:e.size/r,c=O(()=>{let l=[];e=W(e,[1,r,i]);for(let p=0;p<t.length;++p){let h=[0,p===0?0:s[p-1],0],f=[1,t[p],i];l[p]=W(We(e,h,f),o)}return e.dispose(),l}),u=new Cc([],n,e.dtype,t.length);for(let l=0;l<c.length;l++)u.setItem(l,c[l]);return u}var d6=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let r=I("thenBranch",e,t,n),s=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let r=I("body",e,t,n),s=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(l=>l.id),c=await o[0].data();o.forEach(l=>{!l.kept&&i.indexOf(l.id)===-1&&l.dispose()});let u=a;for(;c[0];){let l=u;u=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let p=u.map(h=>h.id);l.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()});let d=await n.functionMap[s].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);c=await d[0].data(),d.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()})}return u}case"LoopCond":{let r=I("pred",e,t,n);return[Ts(r)]}case"Switch":{let r=I("pred",e,t,n),s=I("data",e,t,n);return s.kept||(s=Ts(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{let r=e.inputNames.find(s=>Sn(s,t,n)!==void 0);if(r){let s=Sn(r,t,n);return[Ts(s)]}return}case"Enter":{let r=I("frameName",e,t,n),s=I("tensor",e,t,n);return n.enterFrame(r),[Ts(s)]}case"Exit":{let r=I("tensor",e,t,n);return n.exitFrame(),[Ts(r)]}case"NextIteration":{let r=I("tensor",e,t,n);return n.nextIteration(),[Ts(r)]}case"TensorArrayV3":{let r=I("size",e,t,n),s=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),c=I("identicalElementShapes",e,t,n),u=I("name",e,t,n),l=new o6(u,s,r,a,c,o,i);return n.addTensorArray(l),[l.idTensor,xe(1)]}case"TensorArrayWriteV3":{let r=I("tensorArrayId",e,t,n),s=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(s,a),[o.idTensor]}case"TensorArrayReadV3":{let r=I("tensorArrayId",e,t,n),s=I("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{let r=I("tensorArrayId",e,t,n),s=I("indices",e,t,n),a=I("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{let r=I("tensorArrayId",e,t,n),s=I("indices",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(s,a),[o.idTensor]}case"TensorArrayConcatV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=I("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{let r=I("tensorArrayId",e,t,n),s=I("tensor",e,t,n),a=I("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(a,s),[o.idTensor]}case"TensorArraySizeV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return[xe(s.size(),"int32")]}case"TensorArrayCloseV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{let r=I("tensorListId",e,t,n),s=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(s,a),[o.idTensor]}case"TensorListGetItem":{let r=I("tensorListId",e,t,n),s=I("index",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let r=I("indices",e,t,n),s=I("tensor",e,t,n),a=I("elementShape",e,t,n),o=I("numElements",e,t,n),i=u6(s,r,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let r=I("elementShape",e,t,n),s=I("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=I(a,e,t,n),i=e.op==="TensorListReserve"?-1:o,c=c6(r,s,o,i);return n.addTensorList(c),[c.idTensor]}case"TensorListGather":{let r=I("tensorListId",e,t,n),s=I("indices",e,t,n),a=I("elementShape",e,t,n),o=I("element
$ { e } ` );let r;return this.size===1/0||this.size==null?r=this.size:t?r=Math.ceil(this.size/e):r=Math.floor(this.size/e),Yn(async()=>(await n.iterator()).columnMajorBatch(e,t,pq),r)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,Yn(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,Yn(async()=>(await t.iterator()).filter(r=>O(()=>e(r))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return Yn(async()=>(await t.iterator()).map(n=>O(()=>e(n))),this.size)}mapAsync(e){let t=this;return Yn(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError(" ` Dataset . prefetch ( ) ` requires bufferSize to be specified.");let t=this;return Yn(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,Yn(async()=>{let r=D0(async()=>({value:await t.iterator(),done:!1}));return Y6(r.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,Yn(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError(" ` Dataset . shuffle ( ) ` requires bufferSize to be specified."):new RangeError( ` \ ` Dataset.shuffle() \` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \` tf.Tensor \` s), consider setting bufferSize to the dataset size ( ${ this . size } elements) ` ) ; let r = this , s = V6 . alea ( t || w . now ( ) . toString ( ) ) ; return Yn ( async ( ) => { let a = s . int32 ( ) ; return n && ( a += s . int32 ( ) ) , ( await r . iterator ( ) ) . shuffle ( e , a . toString ( ) ) } , this . size ) } take ( e ) { let t = this , n ; return this . size != null && this . size > e ? n = e : this . size != null && this . size <= e ? n = this . size : n = null , Yn ( async ( ) => ( await t . iterator ( ) ) . take ( e ) , n ) } async toArray ( ) { if ( this . size === 1 / 0 ) throw new Error ( "Can not convert infinite data stream to array." ) ; return ( await this . iterator ( ) ) . toArray ( ) } async toArrayForTest ( ) { if ( this . size === 1 / 0 ) throw new Error ( "Can not convert infinite data stream to array." ) ; return ( await this . iterator ( ) ) . toArrayForTest ( ) } } ; ju . MAX _BUFFER _SIZE = 1e4 ; function Yn ( e , t = null ) { return new class extends ju { constructor ( ) { super ( ... arguments ) , this . size = t } async iterator ( ) { return e ( ) } } } function lq ( e ) { return Yn ( async ( ) => ZN ( e ) , e . length ) } function dq ( e ) { if ( ! Nc ( e ) ) throw new Error ( "The argument to zip() must be an object or array." ) ; let t ; if ( Array . isArray ( e ) ) for ( let n = 0 ; n < e . length ; n ++ ) t = t == null ? e [ n ] . size : Math . min ( t , e [ n ] . size ) ; else if ( e instanceof Object ) for ( let n in e ) t = t == null ? e [ n ] . size : Math . min ( t , e [ n ] . size ) ; return Yn ( async ( ) => { let n = await XN ( e , r => { if ( r instanceof ju ) return { value : r . iterator ( ) , recurse : ! 1 } ; if ( Nc ( r ) ) return { value : null , recurse : ! 0 } ; throw new Error ( "Leaves of the structure passed to zip() must be Datasets, not primitives." ) } ) ; return Z6 ( n , na . SHORTEST ) } , t ) } function pq ( e ) { if ( e === null ) return null ; let t = e [ 0 ] ; return q6 ( t ) ? { value : hq ( e ) , recurse : ! 1 } : { value : null , recurse : ! 0 } } function hq ( e ) { if ( e . length === 0 ) throw new Error ( "Can't make a batch of zero elements." ) ; return e [ 0 ] instanceof Te ? Ft ( e ) : Cn ( e ) } var e _ = class extends ju { constructor ( e ) { super ( ) , this . input = e } async iterator ( ) { return ( await this . input . iterator ( ) ) . decodeUTF8 ( ) . split ( `
` ).map(r=>(r.endsWith(" \r ")&&(r=r.slice(0,-1)),r))}},ph='"',Dl=Symbol("out"),a1=Symbol("field"),hh=Symbol("quote"),Sy=Symbol("quoteafterquote"),o1=Symbol("quoteinquote"),t_=class extends ju{constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new e_(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(w.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((r,s)=>(r[s]=r[s]+1||1,r),{}),n=Object.keys(t).filter(r=>t[r]>1);if(w.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let r of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(r)===-1)throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],o=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!o)){let i=t[s],c=null;if(i==="")if(o&&o.default!==void 0)c=o.default;else{if(o&&(o.required||o.isLabel))throw new Error( ` Required column $ { a } is empty in this line : $ { e } ` );c=void 0}else{let u=Number(i);if(isNaN(u))o&&o.dtype==="bool"?c=this.getBoolean(i):c=i;else if(!o||!o.dtype)c=u;else switch(o.dtype){case"float32":c=u;break;case"int32":c=Math.floor(u);break;case"bool":c=this.getBoolean(i);break;default:c=u}}o&&o.isLabel?r[a]=c:n[a]=c}}return Object.keys(r).length===0?n:{xs:n,ys:r}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],r=0,s=e.length,a=Dl;for(let o=0;o<s;o++)switch(a){case Dl:switch(e.charAt(o)){case ph:r=o+1,a=hh;break;case this.delimiter:if(r=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=Dl;break;default:a=a1,r=o;break}break;case a1:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o)),a=Dl,r=o+1;break;default:}break;case hh:switch(e.charAt(o)){case ph:a=Sy;break;default:}break;case Sy:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o-1)),a=Dl,r=o+1;break;case ph:a=hh;break;default:a=o1;break}break;case o1:switch(e.charAt(o)){case ph:a=hh;break;default:}break;default:}if(a===Sy?n.push(e.substring(r,s-1)):n.push(e.substring(r)),t&&n.length!==this.fullColumnNames.length)throw new Error( ` Invalid row in csv file . Should have $ { this . fullColumnNames . length } elements in a row , but got $ { n } ` );return n}},n_=class extends tn{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error( ` Invalid fftSi
2021-09-11 17:11:38 +02:00
=== === === === === === === === === =
2022-05-18 14:36:05 +02:00
Hi , looks like you are running TensorFlow . js in Node . js . To speed things up dramatically , install our node backend , visit https : //github.com/tensorflow/tfjs-node for more details.
2022-10-30 14:06:17 +01:00
=== === === === === === === === === = ` ));let r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return N.mergeRealAndImagArrays(r,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let n=t.map(r=>w.decodeString(r));return Me(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Me(e.shape,e.dtype,t)}makeOutput(e,t,n){return Er().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){be([e],"where");let t=this.readSync(e.dataId);return Nq(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};R0.nextDataId=0;var l_={};Ae(l_,{addImpl:()=>h_,bincountImpl:()=>O0,bincountReduceImpl:()=>f_,castImpl:()=>p_,ceilImpl:()=>m_,concatImpl:()=>M0,equalImpl:()=>g_,expImpl:()=>y_,expm1Impl:()=>x_,floorImpl:()=>w_,gatherNdImpl:()=>I_,gatherV2Impl:()=>k_,greaterEqualImpl:()=>T_,greaterImpl:()=>S_,lessEqualImpl:()=>N_,lessImpl:()=>C_,linSpaceImpl:()=>__,logImpl:()=>E_,maxImpl:()=>A_,maximumImpl:()=> $ _,minimumImpl:()=>D_,multiplyImpl:()=>L0,negImpl:()=>F_,notEqualImpl:()=>R_,prodImpl:()=>P_,raggedGatherImpl:()=>O_,raggedRangeImpl:()=>M_,raggedTensorToTensorImpl:()=>L_,rangeImpl:()=>B0,rsqrtImpl:()=>z_,scatterImpl:()=>cc,sigmoidImpl:()=>w5,simpleAbsImpl:()=>d_,sliceImpl:()=>Qh,sparseFillEmptyRowsImpl:()=>W_,sparseReshapeImpl:()=>V_,sparseSegmentReductionImpl:()=>W0,sqrtImpl:()=>S5,squaredDifferenceImpl:()=>U_,stridedSliceImpl:()=>G_,stringNGramsImpl:()=>V0,stringSplitImpl:()=>U0,stringToHashBucketFastImpl:()=>G0,subImpl:()=>H_,tileImpl:()=>q_,topKImpl:()=>K_,transposeImpl:()=>z0,uniqueImpl:()=>X_});function d_(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var _q=e=>{let{x:t}=e.inputs,n=e.backend;be(t,"abs");let r=new Float32Array(w.sizeFromShape(t.shape)),s=n.data.get(t.dataId).values;return r=d_(s),n.makeOutput(r,t.shape,t.dtype)},Eq={kernelName:Fc,backendName:"cpu",kernelFunc:_q};function Vt(e){return(t,n,r,s,a)=>{let o=N.assertAndGetBroadcastShape(t,n),i=o.length,c=w.computeStrides(o),u=w.sizeFromShape(o),l=w.getTypedArrayFromDType(a,u),p=t.length,d=n.length,h=w.computeStrides(t),f=w.computeStrides(n),m=N.getBroadcastDims(t,o),g=N.getBroadcastDims(n,o);if(m.length+g.length===0)for(let b=0;b<l.length;++b)l[b]=e(r[b%r.length],s[b%s.length]);else for(let b=0;b<l.length;++b){let y=w.indexToLoc(b,i,c),v=y.slice(-p);m.forEach(C=>v[C]=0);let x=w.locToIndex(v,p,h),k=y.slice(-d);g.forEach(C=>k[C]=0);let S=w.locToIndex(k,d,f);l[b]=e(r[x],s[S])}return[l,o]}}function Jn(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,i=n.makeTensorInfo(r.shape,"complex64"),c=n.data.get(i.dataId);return c.complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",a),imag:n.makeTensorInfo(s.shape,"float32",o)},i}var
$ { a . shape } ` );if(r.shape.length!==2)throw new Error( ` Indices must be a matrix , saw :
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Values must be a vector , saw :
$ { s . shape } ` );if(o.shape.length!==0)throw new Error( ` Default value must be a scalar , saw :
$ { o . shape } ` );let i=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values[0],[p,d,h,f,m]=W_(i,r.shape,r.dtype,c,s.dtype,u,l);return[n.makeTensorInfo(d,r.dtype,p),n.makeTensorInfo([d[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var s7={kernelName:xd,backendName:"cpu",kernelFunc:r7};function a7(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error( ` Input indices should be a matrix but received shape
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Target shape should be a vector but received shape $ { a . shape } ` );let o=Array.from(n.data.get(s.dataId).values),i=n.data.get(r.dataId).values,c=Array.from(n.data.get(a.dataId).values),[u,l,p]=V_(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(l,r.dtype,u),n.makeTensorInfo([p.length],a.dtype,new Int32Array(p))]}var o7={kernelName:Au,backendName:"cpu",kernelFunc:a7};function i7(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
$ { a . shape } ` );if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[u,l]=W0(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(l,r.dtype,u)}var c7={kernelName:wd,backendName:"cpu",kernelFunc:i7};function u7(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
$ { a . shape } ` );if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[u,l]=W0(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(l,r.dtype,u)}var l7={kernelName:Id,backendName:"cpu",kernelFunc:u7};function d7(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:u,sliceSize:l,strides:p,outputSize:d}=N.calculateShapes(a,s,i),h=!1,f=n.bufferSync(s),m;switch(a.dtype){case"bool":{let g=n.bufferSync(a),b=Boolean(n.data.get(o.dataId).values[0]);m=cc(f,g,i,d,l,u,c,p,b,h);break}case"float32":{let g=n.bufferSync(a),b=n.data.get(o.dataId).values[0];m=cc(f,g,i,d,l,u,c,p,b,h);break}case"int32":{let g=n.bufferSync(a),b=n.data.get(o.dataId).values[0];m=cc(f,g,i,d,l,u,c,p,b,h);break}case"string":{let g=n.bufferSync(a),b=w.decodeString(n.data.get(o.dataId).values[0]);m=cc(f,g,i,d,l,u,c,p,b,h);break}default:throw new Error( ` Unsupported type $ { a . dtype } ` )}return n.makeTensorInfo(i,m.dtype,m.values)}var p7={kernelName:Vf,backendName:"cpu",kernelFunc:d7};function h7(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],c=N.prepareSplitSize(s,a,i),u=new Array(s.shape.length).fill(0),l=s.shape.slice();return c.map(p=>{let d=[...l];d[i]=p;let h=po({inputs:{x:s},backend:n,attrs:{begin:u,size:d}});return u[i]+=p,h})}var f7={kernelName:Eu,backendName:"cpu",kernelFunc:h7},m7={kernelName:kd,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,r=t;be(n,"square");let s=r.data.get(n.dataId).values,a=new Float32Array(s.length);for(let i=0;i<s.length;++i){let c=s[i];a[i]=c*c}return{dataId:r.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},g7=at(xa,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),b7={kernelName:xa,backendName:"cpu",kernelFunc:g7};function y7(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:u,ellipsisMask:l,newAxisMask:p,shrinkAxisMask:d}=r;be(s,"stridedSlice");let{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=qt.sliceInfo(s.shape,a,o,i,c,u,l,p,d),k;if(m)k=ft({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||b){w.assert(s.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { s . shape . length } ` );let S=qt.computeOutShape(y,v,x),C=po({inputs:{x:s},backend:n,attrs:{begin:y,size:S}});k=ft({inputs:{x:C},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(C)}else{let S=n.bufferSync(s),C=G_(h,S,x,y);k=n.makeTensorInfo(f,C.dtype,C.values)}return k}var v7={kernelName: $ u,backendName:"cpu",kernelFunc:y7};function x7(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:u}=r,{data:l,dataSplits:p}=t,d=n.data.get(l.dataId).values,h=n.data.get(p.dataId).values,[f,m]=V0(d,h,s,a,o,i,c,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(p.shape,"int32",m)]}var w7={kernelName:Sd,backendName:"cpu",kernelFunc:x7};function I7(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error( ` Input must be a vector , got shape : $ { a . shape } ` );if(o.shape.length!==0)throw new Error( ` Delimiter must be a scalar , got shape : $ { o . shape } ` );let i=n.data.get(a.dataId).values,c=n.data.get(o.dataId).values[0],[u,l,p]=U0(i,c,s),d=l.length;return[n.makeTensorInfo([d,2],"int32",u),n.makeTensorInfo([d],"string",l),n.makeTensorInfo([2],"int32",new Int32Array(p))]}var k7={kernelName:Td,backendName:"cpu",kernelFunc:I7};function S7(e){let{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");let o=n.data.get(a.dataId).values,i=G0(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var T7={kernelName:Cd,backendName:"cpu",kernelFunc:S7},C7=at(pi,e=>Math.tan(e)),N7=
` ),a=s.length.toString().length+2,o=s.map((p,d)=>w.rightPad((d+1).toString(),a)+p),i=0;for(let p=0;p<o.length;p++)i=Math.max(o[p].length,i);let c=o.slice(0,r-1),u=o.slice(r-1,r),l=o.slice(r);console.log(c.join( `
2021-09-11 17:11:38 +02:00
` )),console.log(t.split( `
2022-10-30 14:06:17 +01:00
` )[0]),console.log( ` % c $ { w . rightPad ( u [ 0 ] , i ) } ` ,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(l.join( `
` ))}function y2(e){return Ps(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function v2(e,t){if(me(e,()=>e.linkProgram(t)),!q().get("ENGINE_COMPILE_ONLY")&&e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function Ih(e,t){if(me(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function x2(e,t){let n=Ps(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return me(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),me(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function w2(e,t){let n=Ps(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return me(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),me(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function rY(){return q().getNumber("WEBGL_VERSION")===2?1:4}function I2(e){return Ps(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function k2(e,t){let n=q().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let r= ` [ $ { e } x$ { t } ] ` ;throw new Error("Requested texture size "+r+" is invalid.")}if(e>n||t>n){let r= ` [ $ { e } x$ { t } ] ` ,s= ` [ $ { n } x$ { n } ] ` ;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+s+".")}}function S2(e){return Ps(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function fv(e,t,n,r,s,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(me(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),me(e,()=>e.vertexAttribPointer(i,s,e.FLOAT,!1,a,o)),me(e,()=>e.enableVertexAttribArray(i)),!0)}function T2(e,t,n){A2(e,n),me(e,()=>e.activeTexture(e.TEXTURE0+n)),me(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function sY(e,t){A2(e,t),me(e,()=>e.activeTexture(e.TEXTURE0+t)),me(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function C2(e,t,n){return Ps(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function N2(e,t,n){return e.getUniformLocation(t,n)}function _2(e,t,n,r){me(e,()=>T2(e,t,r)),me(e,()=>e.uniform1i(n,r))}function aY(e){me(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),me(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),me(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function kh(e,t,n){me(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),me(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function mv(e,t){me(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),me(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Bl(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+E2(e,t))}function E2(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return ` unknown error $ { t } ` }}function Ps(e,t,n){let r=me(e,()=>t());if(r==null)throw new Error(n);return r}function A2(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n){let s= ` [ gl . TEXTURE0 , gl . TEXTURE$ { n } ] ` ;throw new Error( ` textureUnit must be in $ { s } . ` )}}function ho(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function fo(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function Wl(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[ho(e),...fo(e)]),t}function $ 2(e,t=!1){let n=q().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=q().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");r===1/0&&q().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(r=n/2),t&&(n=n*2,r=r*2,e=e.map((i,c)=>c>=e.length-2?w.nearestLargerEven(e[c]):e[c]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let s=w.sizeFromShape(e),a=null;e.length<=1&&s<=n?a=[1,s]:e.length===2&&e[0]<=n&&e[1]
2021-09-11 17:11:38 +02:00
bool isnan _custom ( float val ) {
2022-03-07 19:17:31 +01:00
uint floatToUint = floatBitsToUint ( val ) ;
return ( floatToUint & 0x7fffffff u ) > 0x7f800000 u ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan _custom ( val . x ) ,
isnan _custom ( val . y ) , isnan _custom ( val . z ) , isnan _custom ( val . w ) ) ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
# define isnan ( value ) isnan _custom ( value )
2022-10-30 14:06:17 +01:00
` :"",c="",u= `
2021-09-11 17:11:38 +02:00
# define round ( value ) newRound ( value )
int newRound ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
ivec4 newRound ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
2021-06-04 14:54:48 +02:00
}
2022-10-30 14:06:17 +01:00
` ):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",o="",i= `
2021-09-11 17:11:38 +02:00
# define isnan ( value ) isnan _custom ( value )
bool isnan _custom ( float val ) {
return ( val > 0. || val < 1. || val == 0. ) ? false : true ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan ( val . x ) , isnan ( val . y ) , isnan ( val . z ) , isnan ( val . w ) ) ;
2021-06-04 14:54:48 +02:00
}
2022-10-30 14:06:17 +01:00
` ,c= `
2021-09-11 17:11:38 +02:00
uniform float INFINITY ;
bool isinf ( float val ) {
return abs ( val ) == INFINITY ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isinf ( vec4 val ) {
return equal ( abs ( val ) , vec4 ( INFINITY ) ) ;
2021-06-04 14:54:48 +02:00
}
2022-03-07 19:17:31 +01:00
` ,u= `
2021-09-11 17:11:38 +02:00
int round ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
}
ivec4 round ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
}
2022-10-30 14:06:17 +01:00
` ),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:c,defineRound:u}}function Ii(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o= ` int $ { e [ a ] } = $ { n } / $ { s } ` ,i=a===r.length-1? ` int $ { e [ a + 1 ] } = $ { n } - $ { e [ a ] } * $ { s } ` : ` index -= $ { e [ a ] } * $ { s } ` ;return ` $ { o } ; $ { i } ; ` }).join("")}function Xm(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o= ` int $ { e [ a ] } = $ { n } / outShapeStrides [ $ { a } ] ` ,i=a===r.length-1? ` int $ { e [ a + 1 ] } = $ { n } - $ { e [ a ] } * outShapeStrides [ $ { a } ] ` : ` index -= $ { e [ a ] } * outShapeStrides [ $ { a } ] ` ;return ` $ { o } ; $ { i } ; ` }).join("")}function uY(e,t){let n=e.length,r=e.map(a=> ` $ { t } [ $ { a } ] ` ),s=new Array(n-1);s[n-2]=r[n-1];for(let a=n-3;a>=0;--a)s[a]= ` ( $ { s [ a + 1 ] } * $ { r [ a + 1 ] } ) ` ;return s}function lY(e,t,n="index"){let r=e.map((a,o)=>o),s=uY(r,t);return s.map((a,o)=>{let i= ` int $ { e [ o ] } = $ { n } / $ { s [ o ] } ` ,c=o===s.length-1? ` int $ { e [ o + 1 ] } = $ { n } - $ { e [ o ] } * $ { s [ o ] } ` : ` index -= $ { e [ o ] } * $ { s [ o ] } ` ;return ` $ { i } ; $ { c } ; ` }).join("")}function Z0(e){let t=w.computeStrides(e).map(n=>n.toString());return `
2021-09-11 17:11:38 +02:00
int getFlatIndex ( ivec3 coords ) {
return coords . x * $ { t [ 0 ] } + coords . y * $ { t [ 1 ] } + coords . z ;
}
2022-10-14 14:01:39 +02:00
` }function J0(){return `
2021-09-11 17:11:38 +02:00
int getFlatIndex ( ivec3 coords ) {
return coords . x * outShapeStrides [ 0 ] + coords . y * outShapeStrides [ 1 ] + coords . z ;
}
2022-10-30 14:06:17 +01:00
` }var L2= `
2021-09-11 17:11:38 +02:00
const float FLOAT _MAX = 1.70141184 e38 ;
const float FLOAT _MIN = 1.17549435 e - 38 ;
lowp vec4 encode _float ( highp float v ) {
if ( isnan ( v ) ) {
return vec4 ( 255 , 255 , 255 , 255 ) ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
highp float av = abs ( v ) ;
if ( av < FLOAT _MIN ) {
return vec4 ( 0.0 , 0.0 , 0.0 , 0.0 ) ;
} else if ( v > FLOAT _MAX ) {
return vec4 ( 0.0 , 0.0 , 128.0 , 127.0 ) / 255.0 ;
} else if ( v < - FLOAT _MAX ) {
return vec4 ( 0.0 , 0.0 , 128.0 , 255.0 ) / 255.0 ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
highp vec4 c = vec4 ( 0 , 0 , 0 , 0 ) ;
highp float e = floor ( log2 ( av ) ) ;
highp float m = exp2 ( fract ( log2 ( av ) ) ) - 1.0 ;
c [ 2 ] = floor ( 128.0 * m ) ;
m -= c [ 2 ] / 128.0 ;
c [ 1 ] = floor ( 32768.0 * m ) ;
m -= c [ 1 ] / 32768.0 ;
c [ 0 ] = floor ( 8388608.0 * m ) ;
highp float ebias = e + 127.0 ;
c [ 3 ] = floor ( ebias / 2.0 ) ;
ebias -= c [ 3 ] * 2.0 ;
c [ 2 ] += floor ( ebias ) * 128.0 ;
c [ 3 ] += 128.0 * step ( 0.0 , - v ) ;
return c / 255.0 ;
}
2022-10-30 14:06:17 +01:00
` ,{getBroadcastDims:z2}=N;function dY(e,t,n){let r=[];if(e.forEach(h=>{let f=w.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?r.push( ` uniform float $ { h . name } $ { f > 1 ? ` [ ${ f } ] ` : "" } ; ` ):(r.push( ` uniform sampler2D $ { h . name } ; ` ),r.push( ` uniform int offset$ { h . name } ; ` )),n.enableShapeUniforms){let{uniformShape:m}=Q0(n.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(m.length){case 1:r.push( ` uniform int $ { h . name } Shape ; ` );break;case 2:r.push( ` uniform ivec2 $ { h . name } Shape ; ` );break;case 3:r.push( ` uniform ivec3 $ { h . name } Shape ; ` );break;case 4:r.push( ` uniform ivec4 $ { h . name } Shape ; ` );break;default:break}r.push( ` uniform ivec2 $ { h . name } TexShape ; ` )}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;");break;default:break}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(h=>{r.push( ` uniform $ { h . type } $ { h . name } $ { h . arrayIndex ? ` [ ${ h . arrayIndex } ] ` : "" } ; ` )});let s=r.join( `
` ),a=e.map(h=>pY(h,t,n.packedInputs,n.enableShapeUniforms)).join( `
` ),o=t.texShape,i= $ n(),c=mY(i),u,l,p=yY(i);return t.isPacked?(u=hY(t.logicalShape,o,n.enableShapeUniforms),l=bY(i)):(u=fY(t.logicalShape,o,n.enableShapeUniforms),l=gY(i)),n.packedInputs&&(p+=IY),[p,c,l,s,u,a,n.userCode].join( `
` )}function Zu(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return RY(e,t);case 1:return OY(e,t);case 2:return LY(e,t);case 3:return BY(e,t);case 4:return VY(e,t);case 5:return UY(e);case 6:return GY(e);default:throw new Error( ` $ { n . length } - D input sampling is not yet supported ` )}}function B2(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return FY(e);case 1:return PY(e,t);case 2:return MY(e,t);case 3:return zY(e,t);default:return WY(e,t)}}function pY(e,t,n=!1,r){let s="";n?s+=B2(e,r):s+=Zu(e,r);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?s+=HY(e,t):s+=qY(e,t)),s}function hY(e,t,n){switch(e.length){case 0:return W2();case 1:return kY(e,t,n);case 2:return $ Y(e,t,n);case 3:return TY(e,t,n);default:return NY(e,t,n)}}function fY(e,t,n){switch(e.length){case 0:return W2();case 1:return SY(e,t,n);case 2:return DY(e,t,n);case 3:return CY(e,t,n);case 4:return _Y(e,t,n);case 5:return EY(e,t);case 6:return AY(e,t);default:throw new Error( ` $ { e . length } - D output sampling is not yet supported ` )}}function mY(e){return `
2021-09-11 17:11:38 +02:00
float sampleTexture ( sampler2D textureSampler , vec2 uv ) {
return $ { e . texture2D } ( textureSampler , uv ) . r ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function gY(e){return `
2021-09-11 17:11:38 +02:00
void setOutput ( float val ) {
$ { e . output } = vec4 ( val , 0 , 0 , 0 ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function bY(e){return `
2021-09-11 17:11:38 +02:00
void setOutput ( vec4 val ) {
$ { e . output } = val ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function yY(e){return ` $ { e . version }
2021-09-11 17:11:38 +02:00
precision highp float ;
precision highp int ;
precision highp sampler2D ;
$ { e . varyingFs } vec2 resultUV ;
$ { e . defineOutput }
const vec2 halfCR = vec2 ( 0.5 , 0.5 ) ;
struct ivec5
{
int x ;
int y ;
int z ;
int w ;
int u ;
} ;
struct ivec6
{
int x ;
int y ;
int z ;
int w ;
int u ;
int v ;
} ;
uniform float NAN ;
$ { e . defineSpecialNaN }
$ { e . defineSpecialInf }
$ { e . defineRound }
int imod ( int x , int y ) {
return x - y * ( x / y ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
int idiv ( int a , int b , float sign ) {
int res = a / b ;
int mod = imod ( a , b ) ;
if ( sign < 0. && mod != 0 ) {
res -= 1 ;
}
return res ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
# define HASHSCALE1 443.8975
float random ( float seed ) {
vec2 p = resultUV * seed ;
vec3 p3 = fract ( vec3 ( p . xyx ) * HASHSCALE1 ) ;
p3 += dot ( p3 , p3 . yzx + 19.19 ) ;
return fract ( ( p3 . x + p3 . y ) * p3 . z ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
$ { vY }
$ { xY }
$ { wY }
` }var vY= `
2021-09-11 17:11:38 +02:00
vec2 uvFromFlat ( int texNumR , int texNumC , int index ) {
int texR = index / texNumC ;
int texC = index - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
vec2 packedUVfrom1D ( int texNumR , int texNumC , int index ) {
int texelIndex = index / 2 ;
int texR = texelIndex / texNumC ;
int texC = texelIndex - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2022-10-30 14:06:17 +01:00
` ,xY= `
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom2D ( int texelsInLogicalRow , int texNumR ,
int texNumC , int row , int col ) {
int texelIndex = ( row / 2 ) * texelsInLogicalRow + ( col / 2 ) ;
int texR = texelIndex / texNumC ;
int texC = texelIndex - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2022-10-30 14:06:17 +01:00
` ,wY= `
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom3D ( int texNumR , int texNumC ,
int texelsInBatch , int texelsInLogicalRow , int b ,
int row , int col ) {
int index = b * texelsInBatch + ( row / 2 ) * texelsInLogicalRow + ( col / 2 ) ;
int texR = index / texNumC ;
int texC = index - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2022-10-30 14:06:17 +01:00
` ,IY= `
2021-09-11 17:11:38 +02:00
float getChannel ( vec4 frag , vec2 innerDims ) {
vec2 modCoord = mod ( innerDims , 2. ) ;
return modCoord . x == 0. ?
( modCoord . y == 0. ? frag . r : frag . g ) :
( modCoord . y == 0. ? frag . b : frag . a ) ;
}
float getChannel ( vec4 frag , int dim ) {
float modCoord = mod ( float ( dim ) , 2. ) ;
return modCoord == 0. ? frag . r : frag . g ;
}
2022-10-30 14:06:17 +01:00
` ;function W2(){return `
2021-09-11 17:11:38 +02:00
int getOutputCoords ( ) {
return 0 ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function kY(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return r[0]===1?n? `
2021-09-11 17:11:38 +02:00
int getOutputCoords ( ) {
return 2 * int ( resultUV . x * ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
}
` : `
int getOutputCoords ( ) {
2022-10-30 14:06:17 +01:00
return 2 * int ( resultUV . x * $ { r [ 1 ] } . 0 ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` :r[1]===1?n? `
2021-09-11 17:11:38 +02:00
int getOutputCoords ( ) {
return 2 * int ( resultUV . y * ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) ) ;
}
` : `
int getOutputCoords ( ) {
2022-10-30 14:06:17 +01:00
return 2 * int ( resultUV . y * $ { r [ 0 ] } . 0 ) ;
2021-09-11 17:11:38 +02:00
}
` :n? `
int getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
return 2 * ( resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2022-10-30 14:06:17 +01:00
vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
return 2 * ( resTexRC . x * $ { r [ 1 ] } + resTexRC . y ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function SY(e,t,n){return t[0]===1?n? `
2021-09-11 17:11:38 +02:00
int getOutputCoords ( ) {
return int ( resultUV . x * float ( outTexShape [ 1 ] ) ) ;
}
` : `
int getOutputCoords ( ) {
return int ( resultUV . x * $ { t [ 1 ] } . 0 ) ;
}
` :t[1]===1?n? `
int getOutputCoords ( ) {
return int ( resultUV . y * float ( outTexShape [ 0 ] ) ) ;
}
` : `
int getOutputCoords ( ) {
return int ( resultUV . y * $ { t [ 0 ] } . 0 ) ;
}
` :n? `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
return resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
return resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function TY(e,t,n){if(n)return `
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
int texelsInLogicalRow = int ( ceil ( float ( outShape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatch = texelsInLogicalRow * int ( ceil ( float ( outShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
int index = resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ;
int b = index / texelsInBatch ;
index -= b * texelsInBatch ;
int r = 2 * ( index / texelsInLogicalRow ) ;
int c = imod ( index , texelsInLogicalRow ) * 2 ;
return ivec3 ( b , r , c ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return `
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2022-10-30 14:06:17 +01:00
vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
int index = resTexRC . x * $ { r [ 1 ] } + resTexRC . y ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
int b = index / $ { a } ;
index -= b * $ { a } ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
int r = 2 * ( index / $ { s } ) ;
int c = imod ( index , $ { s } ) * 2 ;
2021-09-11 17:11:38 +02:00
return ivec3 ( b , r , c ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function CY(e,t,n){if(n)return `
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
2022-10-30 14:06:17 +01:00
$ { Xm ( [ "r" , "c" , "d" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
}
2022-10-30 14:06:17 +01:00
` ;let r=Ii(["r","c","d"],e);return `
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2022-10-30 14:06:17 +01:00
$ { r }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function NY(e,t,n){if(n)return `
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
int index = resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ;
int texelsInLogicalRow = int ( ceil ( float ( outShape [ 3 ] ) / 2.0 ) ) ;
int texelsInBatch = texelsInLogicalRow * int ( ceil ( float ( outShape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatchN = texelsInBatch * outShape [ 1 ] ;
int b2 = index / texelsInBatchN ;
index -= b2 * texelsInBatchN ;
int b = index / texelsInBatch ;
index -= b * texelsInBatch ;
int r = 2 * ( index / texelsInLogicalRow ) ;
int c = imod ( index , texelsInLogicalRow ) * 2 ;
return ivec4 ( b2 , b , r , c ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2),o=a,i="",c="b, r, c";for(let u=2;u<e.length-1;u++)o*=e[e.length-u-1],i= `
int b$ { u } = index / $ { o } ;
index -= b$ { u } * $ { o } ;
` +i,c= ` b$ { u } , ` +c;return `
2021-09-11 17:11:38 +02:00
ivec$ { e . length } getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2022-10-30 14:06:17 +01:00
vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
int index = resTexRC . x * $ { r [ 1 ] } + resTexRC . y ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
$ { i }
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
int b = index / $ { a } ;
index -= b * $ { a } ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
int r = 2 * ( index / $ { s } ) ;
int c = imod ( index , $ { s } ) * 2 ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
return ivec$ { e . length } ( $ { c } ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function _Y(e,t,n){if(n)return `
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
2022-10-30 14:06:17 +01:00
$ { Xm ( [ "r" , "c" , "d" , "d2" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec4 ( r , c , d , d2 ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let r=Ii(["r","c","d","d2"],e);return `
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2022-10-30 14:06:17 +01:00
$ { r }
2021-09-11 17:11:38 +02:00
return ivec4 ( r , c , d , d2 ) ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function EY(e,t){let n=Ii(["r","c","d","d2","d3"],e);return `
2021-09-11 17:11:38 +02:00
ivec5 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( $ { t [ 0 ] } ,
$ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { n }
ivec5 outShape = ivec5 ( r , c , d , d2 , d3 ) ;
return outShape ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function AY(e,t){let n=Ii(["r","c","d","d2","d3","d4"],e);return `
2021-09-11 17:11:38 +02:00
ivec6 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { n }
ivec6 result = ivec6 ( r , c , d , d2 , d3 , d4 ) ;
return result ;
2021-05-18 14:11:17 +02:00
}
2022-10-30 14:06:17 +01:00
` }function $ Y(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return n? `
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
return 2 * ivec2 ( resultUV . yx * vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
}
` : `
ivec2 getOutputCoords ( ) {
2022-10-30 14:06:17 +01:00
return 2 * ivec2 ( resultUV . yx * vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let s=Math.ceil(e[1]/2);return n? `
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
int texelsInLogicalRow = int ( ceil ( float ( outShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
int index = resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ;
int r = 2 * ( index / texelsInLogicalRow ) ;
int c = imod ( index , texelsInLogicalRow ) * 2 ;
return ivec2 ( r , c ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2022-10-30 14:06:17 +01:00
vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
int index = resTexRC . x * $ { r [ 1 ] } + resTexRC . y ;
int r = 2 * ( index / $ { s } ) ;
int c = imod ( index , $ { s } ) * 2 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return ivec2 ( r , c ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }function DY(e,t,n){return w.arraysEqual(e,t)?n? `
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords ( ) {
return ivec2 ( resultUV . yx * vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
return ivec2 ( resultUV . yx * vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` :e[1]===1?n? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
return ivec2 ( index , 0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
return ivec2 ( index , 0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` :e[0]===1?n? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
return ivec2 ( 0 , index ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
return ivec2 ( 0 , index ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` :n? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
int r = index / outShape [ 1 ] ;
int c = index - r * outShape [ 1 ] ;
return ivec2 ( r , c ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
int r = index / $ { e [ 1 ] } ;
int c = index - r * $ { e [ 1 ] } ;
return ivec2 ( r , c ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }function ki(e){return ` offset$ { e } ` }function FY(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r= $ n();return `
2021-09-11 17:11:38 +02:00
vec4 $ { n } ( ) {
2022-10-30 14:06:17 +01:00
return $ { r . texture2D } ( $ { t } , halfCR ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }function RY(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return ` float $ { r } ( ) { return $ { n } ; } ` ;let[s,a]=e.shapeInfo.texShape;if(s===1&&a===1)return `
float $ { r } ( ) {
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , halfCR ) ;
}
2022-10-30 14:06:17 +01:00
` ;let o=ki(n);if(t)return `
float $ { r } ( ) {
vec2 uv = uvFromFlat ( $ { n } TexShape [ 0 ] , $ { n } TexShape [ 1 ] , $ { o } ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let[i,c]=e.shapeInfo.texShape;return `
float $ { r } ( ) {
vec2 uv = uvFromFlat ( $ { i } , $ { c } , $ { o } ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }function PY(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a= $ n();if(t)return `
vec4 $ { r } ( int index ) {
2021-09-11 17:11:38 +02:00
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { n } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { n } TexShape [ 1 ] ) / 2.0 ) ) ;
vec2 uv = packedUVfrom1D (
packedTexShape [ 0 ] , packedTexShape [ 1 ] , index ) ;
2022-10-30 14:06:17 +01:00
return $ { a . texture2D } ( $ { n } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return `
vec4 $ { r } ( int index ) {
2021-09-11 17:11:38 +02:00
vec2 uv = packedUVfrom1D (
2022-10-30 14:06:17 +01:00
$ { o [ 0 ] } , $ { o [ 1 ] } , index ) ;
return $ { a . texture2D } ( $ { n } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }function OY(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return `
float $ { r } ( int index ) {
2022-10-14 14:01:39 +02:00
$ { Ju ( e ) }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let s=e.shapeInfo.texShape,a=s[0],o=s[1];if(o===1&&a===1)return `
float $ { r } ( int index ) {
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , halfCR ) ;
}
2022-10-30 14:06:17 +01:00
` ;let i=ki(n);return o===1?t? `
float $ { r } ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + $ { i } ) + 0.5 ) / float ( $ { n } TexShape [ 0 ] ) ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
` : `
2022-10-30 14:06:17 +01:00
float $ { r } ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + $ { i } ) + 0.5 ) / $ { a } . 0 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
2022-10-30 14:06:17 +01:00
` :a===1?t? `
float $ { r } ( int index ) {
vec2 uv = vec2 ( ( float ( index + $ { i } ) + 0.5 ) / float ( $ { n } TexShape [ 1 ] ) , 0.5 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
` : `
2022-10-30 14:06:17 +01:00
float $ { r } ( int index ) {
vec2 uv = vec2 ( ( float ( index + $ { i } ) + 0.5 ) / $ { o } . 0 , 0.5 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
` :t? `
2022-10-30 14:06:17 +01:00
float $ { r } ( int index ) {
vec2 uv = uvFromFlat ( $ { n } TexShape [ 0 ] , $ { n } TexShape [ 1 ] , index + $ { i } ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
` : `
2022-10-30 14:06:17 +01:00
float $ { r } ( int index ) {
vec2 uv = uvFromFlat ( $ { a } , $ { o } , index + $ { i } ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
2022-10-30 14:06:17 +01:00
` }function MY(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=a[0],i=a[1],c= $ n();if(a!=null&&w.arraysEqual(n,a))return t? `
vec4 $ { s } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
return $ { c . texture2D } ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
vec4 $ { s } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { i } . 0 , $ { o } . 0 ) ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
return $ { c . texture2D } ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` ;if(t)return `
2022-10-30 14:06:17 +01:00
vec4 $ { s } ( int row , int col ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { r } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { r } TexShape [ 1 ] ) / 2.0 ) ) ;
int valuesPerRow = int ( ceil ( float ( $ { r } Shape [ 1 ] ) / 2.0 ) ) ;
2021-09-11 17:11:38 +02:00
vec2 uv = packedUVfrom2D ( valuesPerRow , packedTexShape [ 0 ] , packedTexShape [ 1 ] , row , col ) ;
2022-10-30 14:06:17 +01:00
return $ { c . texture2D } ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],l=Math.ceil(n[1]/2);return `
vec4 $ { s } ( int row , int col ) {
vec2 uv = packedUVfrom2D ( $ { l } , $ { u [ 0 ] } , $ { u [ 1 ] } , row , col ) ;
return $ { c . texture2D } ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }function LY(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(a!=null&&w.arraysEqual(n,a)){if(t)return `
float $ { s } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` ;let d=a[0],h=a[1];return `
float $ { s } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { h } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }let{newShape:o,keptDims:i}=w.squeezeShape(n),c=o;if(c.length<n.length){let d=Qu(e,c),h=["row","col"];return `
$ { Zu ( d , t ) }
float $ { s } ( int row , int col ) {
return $ { s } ( $ { el ( h , i ) } ) ;
2021-09-11 17:11:38 +02:00
}
` }if(e.shapeInfo.isUniform)return `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col ) {
2021-09-11 17:11:38 +02:00
int index = round ( dot ( vec2 ( row , col ) , vec2 ( $ { n [ 1 ] } , 1 ) ) ) ;
2022-10-14 14:01:39 +02:00
$ { Ju ( e ) }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let u=a[0],l=a[1],p=ki(r);return l===1?t? `
float $ { s } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { p } ) , vec3 ( $ { r } Shape [ 1 ] , 1 , 1 ) ) ;
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / float ( $ { r } TexShape [ 0 ] ) ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { p } ) , vec3 ( $ { n [ 1 ] } , 1 , 1 ) ) ;
2022-03-07 19:17:31 +01:00
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / $ { u } . 0 ) ;
2022-10-30 14:06:17 +01:00
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-03-07 19:17:31 +01:00
` :u===1?t? `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { p } ) , vec3 ( $ { r } Shape [ 1 ] , 1 , 1 ) ) ;
vec2 uv = vec2 ( ( index + 0.5 ) / float ( $ { r } TexShape [ 1 ] ) , 0.5 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { p } ) , vec3 ( $ { n [ 1 ] } , 1 , 1 ) ) ;
vec2 uv = vec2 ( ( index + 0.5 ) / $ { l } . 0 , 0.5 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` :t? `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col ) {
2021-09-11 17:11:38 +02:00
// Explicitly use integer operations as dot() only works on floats.
2022-10-30 14:06:17 +01:00
int index = row * $ { r } Shape [ 1 ] + col + $ { p } ;
vec2 uv = uvFromFlat ( $ { r } TexShape [ 0 ] , $ { r } TexShape [ 1 ] , index ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col ) {
2021-09-11 17:11:38 +02:00
// Explicitly use integer operations as dot() only works on floats.
2022-10-30 14:06:17 +01:00
int index = row * $ { n [ 1 ] } + col + $ { p } ;
vec2 uv = uvFromFlat ( $ { u } , $ { l } , index ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }function zY(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(n[0]===1){let d=n.slice(1),h=[1,2],f=Qu(e,d),m=["b","row","col"];return `
$ { B2 ( f , t ) }
vec4 $ { s } ( int b , int row , int col ) {
return $ { s } ( $ { el ( m , h ) } ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }let i= $ n();if(t)return `
vec4 $ { s } ( int b , int row , int col ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { r } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { r } TexShape [ 1 ] ) / 2.0 ) ) ;
int valuesPerRow = int ( ceil ( float ( $ { r } Shape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatch = valuesPerRow * int ( ceil ( float ( $ { r } Shape [ 1 ] ) / 2.0 ) ) ;
2021-09-11 17:11:38 +02:00
vec2 uv = packedUVfrom3D (
packedTexShape [ 0 ] , packedTexShape [ 1 ] , texelsInBatch , valuesPerRow , b , row , col ) ;
2022-10-30 14:06:17 +01:00
return $ { i . texture2D } ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let c=o[0],u=o[1],l=Math.ceil(n[2]/2),p=l*Math.ceil(n[1]/2);return `
vec4 $ { s } ( int b , int row , int col ) {
2021-09-11 17:11:38 +02:00
vec2 uv = packedUVfrom3D (
2022-10-30 14:06:17 +01:00
$ { c } , $ { u } , $ { p } , $ { l } , b , row , col ) ;
return $ { i . texture2D } ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }function BY(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],o=n[2],{newShape:i,keptDims:c}=w.squeezeShape(n),u=i;if(u.length<n.length){let m=Qu(e,u),g=["row","col","depth"];return `
$ { Zu ( m , t ) }
float $ { s } ( int row , int col , int depth ) {
return $ { s } ( $ { el ( g , c ) } ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` }if(e.shapeInfo.isUniform)return `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col , int depth ) {
2021-09-11 17:11:38 +02:00
int index = round ( dot ( vec3 ( row , col , depth ) ,
2022-10-30 14:06:17 +01:00
vec3 ( $ { a } , $ { o } , 1 ) ) ) ;
2022-10-14 14:01:39 +02:00
$ { Ju ( e ) }
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let l=e.shapeInfo.texShape,p=l[0],d=l[1],h=e.shapeInfo.flatOffset;if(d===a&&h==null)return t? `
float $ { s } ( int row , int col , int depth ) {
int stride1 = $ { r } Shape [ 2 ] ;
2021-09-11 17:11:38 +02:00
float texR = float ( row ) ;
float texC = dot ( vec2 ( col , depth ) , vec2 ( stride1 , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col , int depth ) {
2021-09-11 17:11:38 +02:00
float texR = float ( row ) ;
2022-10-30 14:06:17 +01:00
float texC = dot ( vec2 ( col , depth ) , vec2 ( $ { o } , 1 ) ) ;
2021-09-11 17:11:38 +02:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { d } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ;if(d===o&&h==null)return t? `
float $ { s } ( int row , int col , int depth ) {
float texR = dot ( vec2 ( row , col ) , vec2 ( $ { r } Shape [ 1 ] , 1 ) ) ;
2021-09-11 17:11:38 +02:00
float texC = float ( depth ) ;
2022-10-30 14:06:17 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col , int depth ) {
2021-09-11 17:11:38 +02:00
float texR = dot ( vec2 ( row , col ) , vec2 ( $ { n [ 1 ] } , 1 ) ) ;
float texC = float ( depth ) ;
2022-10-30 14:06:17 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { d } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let f=ki(r);return t? `
float $ { s } ( int row , int col , int depth ) {
2021-09-11 17:11:38 +02:00
// Explicitly use integer operations as dot() only works on floats.
2022-10-30 14:06:17 +01:00
int stride0 = $ { r } Shape [ 1 ] * $ { r } Shape [ 2 ] ;
int stride1 = $ { r } Shape [ 2 ] ;
int index = row * stride0 + col * stride1 + depth + $ { f } ;
vec2 uv = uvFromFlat ( $ { r } TexShape [ 0 ] , $ { r } TexShape [ 1 ] , index ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col , int depth ) {
2021-09-11 17:11:38 +02:00
// Explicitly use integer operations as dot() only works on floats.
2022-10-30 14:06:17 +01:00
int index = row * $ { a } + col * $ { o } + depth + $ { f } ;
vec2 uv = uvFromFlat ( $ { p } , $ { d } , index ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }function WY(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s= $ n();if(t)return `
vec4 $ { r } ( int b2 , int b , int row , int col ) {
2021-09-11 17:11:38 +02:00
int valuesPerRow = int ( ceil ( float ( $ { n } Shape [ 3 ] ) / 2.0 ) ) ;
int texelsInBatch = valuesPerRow * int ( ceil ( float ( $ { n } Shape [ 2 ] ) / 2.0 ) ) ;
int index = b * texelsInBatch + ( row / 2 ) * valuesPerRow + ( col / 2 ) ;
texelsInBatch *= $ { n } Shape [ 1 ] ;
index = b2 * texelsInBatch + index ;
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { n } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { n } TexShape [ 1 ] ) / 2.0 ) ) ;
int texR = index / packedTexShape [ 1 ] ;
int texC = index - texR * packedTexShape [ 1 ] ;
2022-10-30 14:06:17 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( packedTexShape [ 1 ] , packedTexShape [ 0 ] ) ; return $ { s . texture2D } ( $ { n } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],u=c[0],l=c[1],p=Math.ceil(a[o-1]/2),d=p*Math.ceil(a[o-2]/2),h="int b, int row, int col",f= ` b * $ { d } + ( row / 2 ) * $ { p } + ( col / 2 ) ` ;for(let m=2;m<o-1;m++)h= ` int b$ { m } , ` +h,d*=a[o-m-1],f= ` b$ { m } * $ { d } + ` +f;return `
vec4 $ { r } ( $ { h } ) {
int index = $ { f } ;
int texR = index / $ { l } ;
int texC = index - texR * $ { l } ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { l } , $ { u } ) ;
return $ { s . texture2D } ( $ { n } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }function VY(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:c,keptDims:u}=w.squeezeShape(n);if(c.length<n.length){let y=Qu(e,c),v=["row","col","depth","depth2"];return `
$ { Zu ( y , t ) }
float $ { s } ( int row , int col , int depth , int depth2 ) {
return $ { s } ( $ { el ( v , u ) } ) ;
2021-09-11 17:11:38 +02:00
}
` }if(e.shapeInfo.isUniform)return `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col , int depth , int depth2 ) {
2021-09-11 17:11:38 +02:00
int index = round ( dot ( vec4 ( row , col , depth , depth2 ) ,
2022-10-30 14:06:17 +01:00
vec4 ( $ { i } , $ { o } , $ { a } , 1 ) ) ) ;
2022-10-14 14:01:39 +02:00
$ { Ju ( e ) }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let l=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],h=p[1],f= ` int stride2 = $ { r } Shape [ 3 ] ; ` ,m= ` int stride1 = $ { r } Shape [ 2 ] * stride2 ; ` ,g= ` int stride0 = $ { r } Shape [ 1 ] * stride1 ; ` ;if(h===i&&l==null)return t? `
float $ { s } ( int row , int col , int depth , int depth2 ) {
2022-10-18 13:23:49 +02:00
$ { f }
2022-10-30 14:06:17 +01:00
$ { m }
2021-09-11 17:11:38 +02:00
float texR = float ( row ) ;
float texC =
dot ( vec3 ( col , depth , depth2 ) ,
vec3 ( stride1 , stride2 , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col , int depth , int depth2 ) {
2021-09-11 17:11:38 +02:00
float texR = float ( row ) ;
float texC =
dot ( vec3 ( col , depth , depth2 ) ,
2022-10-30 14:06:17 +01:00
vec3 ( $ { o } , $ { a } , 1 ) ) ;
2021-09-11 17:11:38 +02:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { h } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;if(h===a&&l==null)return t? `
float $ { s } ( int row , int col , int depth , int depth2 ) {
2021-09-11 17:11:38 +02:00
float texR = dot ( vec3 ( row , col , depth ) ,
2022-10-30 14:06:17 +01:00
vec3 ( $ { r } Shape [ 1 ] * $ { r } Shape [ 2 ] , $ { r } Shape [ 2 ] , 1 ) ) ;
2021-09-11 17:11:38 +02:00
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col , int depth , int depth2 ) {
2021-09-11 17:11:38 +02:00
float texR = dot ( vec3 ( row , col , depth ) ,
vec3 ( $ { n [ 1 ] * n [ 2 ] } , $ { n [ 2 ] } , 1 ) ) ;
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { h } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let b=ki(r);return t? `
float $ { s } ( int row , int col , int depth , int depth2 ) {
2021-09-11 17:11:38 +02:00
// Explicitly use integer operations as dot() only works on floats.
2022-10-18 13:23:49 +02:00
$ { f }
2022-10-30 14:06:17 +01:00
$ { m }
2021-09-11 17:11:38 +02:00
$ { g }
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2 ;
2022-10-30 14:06:17 +01:00
vec2 uv = uvFromFlat ( $ { r } TexShape [ 0 ] , $ { r } TexShape [ 1 ] , index + $ { b } ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
2022-10-30 14:06:17 +01:00
float $ { s } ( int row , int col , int depth , int depth2 ) {
2021-09-11 17:11:38 +02:00
// Explicitly use integer operations as dot() only works on floats.
2022-10-30 14:06:17 +01:00
int index = row * $ { i } + col * $ { o } +
depth * $ { a } + depth2 ;
vec2 uv = uvFromFlat ( $ { d } , $ { h } , index + $ { b } ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }function UY(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,o=t[2]*a,i=t[1]*o,{newShape:c,keptDims:u}=w.squeezeShape(t);if(c.length<t.length){let m=Qu(e,c),g=["row","col","depth","depth2","depth3"];return `
$ { Zu ( m ) }
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
return $ { r } ( $ { el ( g , u ) } ) ;
2021-09-11 17:11:38 +02:00
}
` }if(e.shapeInfo.isUniform)return `
2022-10-30 14:06:17 +01:00
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
2021-09-11 17:11:38 +02:00
float index = dot (
vec4 ( row , col , depth , depth2 ) ,
2022-10-30 14:06:17 +01:00
vec4 ( $ { i } , $ { o } , $ { a } , $ { s } ) ) +
2021-09-11 17:11:38 +02:00
depth3 ;
2022-10-14 14:01:39 +02:00
$ { Ju ( e ) }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let l=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],h=p[1];if(h===i&&l==null)return `
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
2021-09-11 17:11:38 +02:00
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
2022-10-30 14:06:17 +01:00
vec4 ( $ { o } , $ { a } , $ { s } , 1 ) ) ;
2021-09-11 17:11:38 +02:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { h } . 0 , $ { d } . 0 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
2022-10-30 14:06:17 +01:00
` ;if(h===s&&l==null)return `
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
2021-09-11 17:11:38 +02:00
float texR = dot (
vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { t [ 1 ] * t [ 2 ] * t [ 3 ] } ,
$ { t [ 2 ] * t [ 3 ] } , $ { t [ 3 ] } , 1 ) ) ;
int texC = depth3 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { h } . 0 , $ { d } . 0 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
2022-10-30 14:06:17 +01:00
` ;let f=ki(n);return `
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
2021-09-11 17:11:38 +02:00
// Explicitly use integer operations as dot() only works on floats.
2022-10-30 14:06:17 +01:00
int index = row * $ { i } + col * $ { o } + depth * $ { a } +
depth2 * $ { s } + depth3 + $ { f } ;
vec2 uv = uvFromFlat ( $ { d } , $ { h } , index ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
2022-10-30 14:06:17 +01:00
` }function GY(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=w.squeezeShape(t);if(s.length<t.length){let g=Qu(e,s),b=["row","col","depth","depth2","depth3","depth4"];return `
2022-10-14 14:01:39 +02:00
$ { Zu ( g ) }
2022-10-30 14:06:17 +01:00
float $ { r } ( int row , int col , int depth ,
2021-09-11 17:11:38 +02:00
int depth2 , int depth3 , int depth4 ) {
2022-10-30 14:06:17 +01:00
return $ { r } ( $ { el ( b , a ) } ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }let o=t[5],i=t[4]*o,c=t[3]*i,u=t[2]*c,l=t[1]*u;if(e.shapeInfo.isUniform)return `
float $ { r } ( int row , int col , int depth ,
2021-09-11 17:11:38 +02:00
int depth2 , int depth3 , int depth4 ) {
int index = round ( dot (
vec4 ( row , col , depth , depth2 ) ,
2022-10-30 14:06:17 +01:00
vec4 ( $ { l } , $ { u } , $ { c } , $ { i } ) ) +
2021-09-11 17:11:38 +02:00
dot (
vec2 ( depth3 , depth4 ) ,
2022-10-30 14:06:17 +01:00
vec2 ( $ { o } , 1 ) ) ) ;
2022-10-14 14:01:39 +02:00
$ { Ju ( e ) }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],f=d[1];if(f===l&&p==null)return `
float $ { r } ( int row , int col , int depth ,
2021-09-11 17:11:38 +02:00
int depth2 , int depth3 , int depth4 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
2022-10-30 14:06:17 +01:00
vec4 ( $ { u } , $ { c } , $ { i } , $ { o } ) ) +
2021-09-11 17:11:38 +02:00
float ( depth4 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { f } . 0 , $ { h } . 0 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
2022-10-30 14:06:17 +01:00
` ;if(f===o&&p==null)return `
float $ { r } ( int row , int col , int depth ,
2021-09-11 17:11:38 +02:00
int depth2 , int depth3 , int depth4 ) {
float texR = dot ( vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { t [ 1 ] * t [ 2 ] * t [ 3 ] * t [ 4 ] } ,
$ { t [ 2 ] * t [ 3 ] * t [ 4 ] } ,
$ { t [ 3 ] * t [ 4 ] } ,
$ { t [ 4 ] } ) ) + float ( depth3 ) ;
int texC = depth4 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { f } . 0 , $ { h } . 0 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
2022-10-30 14:06:17 +01:00
` ;let m=ki(n);return `
float $ { r } ( int row , int col , int depth ,
2021-09-11 17:11:38 +02:00
int depth2 , int depth3 , int depth4 ) {
// Explicitly use integer operations as dot() only works on floats.
2022-10-30 14:06:17 +01:00
int index = row * $ { l } + col * $ { u } + depth * $ { c } +
depth2 * $ { i } + depth3 * $ { o } + depth4 + $ { m } ;
vec2 uv = uvFromFlat ( $ { h } , $ { f } , index ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
}
2022-10-30 14:06:17 +01:00
` }function Ju(e){let t=e.name,n=w.sizeFromShape(e.shapeInfo.logicalShape);return n<2? ` return $ { t } ; ` : `
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < $ { n } ; i ++ ) {
if ( i == index ) {
return $ { t } [ i ] ;
}
}
2022-10-30 14:06:17 +01:00
` }function HY(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=z2(e.shapeInfo.logicalShape,t.logicalShape),c=mt(o),u=o-a,l,p=["x","y","z","w","u","v"];a===0?l="":o<2&&i.length>=1?l="coords = 0;":l=i.map(y=> ` coords . $ { p [ y + u ] } = 0 ; ` ).join( `
` );let d="";o<2&&a>0?d="coords":d=e.shapeInfo.logicalShape.map((y,v)=> ` coords . $ { p [ v + u ] } ` ).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,b=w.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!b)h= `
2021-09-11 17:11:38 +02:00
return vec4 ( outputValue . xy , outputValue . xy ) ;
2022-10-30 14:06:17 +01:00
` ;else if(m&&!b)o===1?h= `
2021-09-11 17:11:38 +02:00
return vec4 ( outputValue . x , outputValue . x , 0. , 0. ) ;
` :h= `
return vec4 ( outputValue . x ) ;
2022-10-30 14:06:17 +01:00
` ;else if(i.length){let y=a-2,v=a-1;i.indexOf(y)>-1&&i.indexOf(v)>-1?h="return vec4(outputValue.x);":i.indexOf(y)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(v)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return `
vec4 $ { s } ( ) {
$ { c } coords = getOutputCoords ( ) ;
$ { l }
vec4 outputValue = get$ { r } ( $ { d } ) ;
2021-09-11 17:11:38 +02:00
$ { h }
}
2022-10-30 14:06:17 +01:00
` }function qY(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===c&&e.shapeInfo.flatOffset==null&&w.arraysEqual(o,a))return `
float $ { s } ( ) {
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , resultUV ) ;
}
2022-10-30 14:06:17 +01:00
` ;let u=mt(c),l=z2(e.shapeInfo.logicalShape,t.logicalShape),p=c-i,d,h=["x","y","z","w","u","v"];i===0?d="":c<2&&l.length>=1?d="coords = 0;":d=l.map(m=> ` coords . $ { h [ m + p ] } = 0 ; ` ).join( `
` );let f="";return c<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=> ` coords . $ { h [ g + p ] } ` ).join(", "), `
float $ { s } ( ) {
2022-03-07 19:17:31 +01:00
$ { u } coords = getOutputCoords ( ) ;
2022-10-30 14:06:17 +01:00
$ { d }
return get$ { r } ( $ { f } ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }function mt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error( ` GPU for rank $ { e } is not yet supported ` )}function Q0(e,t,n){let{newShape:r,keptDims:s}=w.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):r,c=!e&&a>1&&!w.arraysEqual(t,n)&&r.length<a||o;return{useSqueezeShape:c,uniformShape:c?i:t,keptDims:s}}function Qu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function el(e,t){return t.map(n=>e[n]).join(", ")}function jY(e,t,n,r){let s=n.map((l,p)=>{let d={logicalShape:l.shape,texShape:l.isUniform?null:l.texData.texShape,isUniform:l.isUniform,isPacked:l.isUniform?!1:l.texData.isPacked,flatOffset:null};return l.texData!=null&&l.texData.slice!=null&&l.texData.slice.flatOffset>0&&(d.flatOffset=l.texData.slice.flatOffset),{name:t.variableNames[p],shapeInfo:d}}),a=s.map(l=>l.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=dY(s,o,t),c=b2(e.gl,i),u=e.createProgram(c);return q().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:c,source:i,webGLProgram:u,inShapeInfos:a,outShapeInfo:o,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:c,source:i,webGLProgram:u,inShapeInfos:a,outShapeInfo:o},V2(e,t,u))}function V2(e,t,n){let r={},s={},a={},o=[],i,c,u,l=null,p=null;p=e.getUniformLocation(n,"NAN",!1),q().getNumber("WEBGL_VERSION")===1&&(l=e.getUniformLocation(n,"INFINITY",!1));let d=!1;for(let h=0;h<t.variableNames.length;h++){let f=t.variableNames[h];r[f]=e.getUniformLocation(n,f,d),r[ ` offset$ { f } ` ]=e.getUniformLocation(n, ` offset$ { f } ` ,d),t.enableShapeUniforms&&(s[ ` $ { f } Shape ` ]=e.getUniformLocation(n, ` $ { f } Shape ` ,d),a[ ` $ { f } TexShape ` ]=e.getUniformLocation(n, ` $ { f } TexShape ` ,d))}return t.enableShapeUniforms&&(i=e.getUniformLocation(n,"outShape",d),u=e.getUniformLocation(n,"outShapeStrides",d),c=e.getUniformLocation(n,"outTexShape",d)),t.customUniforms&&t.customUniforms.forEach((h,f)=>{o[f]=e.getUniformLocation(n,h.name,d)}),{uniformLocations:r,customUniformLocations:o,infLoc:l,nanLoc:p,inShapesLocations:s,inTexShapesLocations:a,outShapeLocation:i,outShapeStridesLocation:u,outTexShapeLocation:c}}function h1(e,t){if(e.length!==t.length)throw Error( ` Binary was compiled with $ { e . length } inputs , but was executed with $ { t . length } inputs ` );e.forEach((n,r)=>{let s=n.logicalShape,a=t[r],o=a.shape;if(!w.arraysEqual(s,o))throw Error( ` Binary was compiled with different shapes than the current args . Shapes $ { s } and $ { o } must match ` );if(n.isUniform&&a.isUniform)return;let i=n.texShape,c=a.isUniform?null:a.texData.texShape;if(!w.arraysEqual(i,c))throw Error( ` Binary was compiled with different texture shapes than the current args . Shape $ { i } and $ { c } must match ` )})}function KY(e,t,n,r,s){t.program.enableShapeUniforms||(h1(t.inShapeInfos,n),h1([t.outShapeInfo],[r]));let a=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,o[0],o[1]):e.setOutputMatrixTexture(a.texture,o[0],o[1]),e.setProgram(t.webGLProgram),q().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((c,u)=>{let l=t.program.variableNames[u],p=t.uniformLocations[l],d=t.uniformLocations[ ` offset$ { l } ` ],h=t.inShapesLocations[ ` $ { l } Shape ` ],f=t.inTexShapesLocations[ ` $ { l } TexShape ` ];if(h){let{uniformShape:m}=Q0(t.program.packedInputs,c.shape,c.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,c.texData.texShape[0],c.texData.texShape[1]),p!=null){if(c.isUniform){if(w.sizeFromShape(c.shape)<2)e.gl.uniform1f(p,c.uniformValues[0]);else{let m=c.uniformValu
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2022-10-30 14:06:17 +01:00
$ { this . enableShapeUniforms ? Xm ( [ "r" , "c" , "d" ] , e ) : Ii ( [ "r" , "c" , "d" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( texShape [ 0 ] , texShape [ 1 ] ) ) ;
int index = 4 * ( resTexRC . x * texShape [ 1 ] + resTexRC . y ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < 4 ; i ++ ) {
int flatIndex = index + i ;
ivec3 rc = outCoordsFromFlatIndex ( flatIndex ) ;
result [ i ] = getA ( rc . x , rc . y , rc . z ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { t . output } = result ;
}
2022-10-30 14:06:17 +01:00
` }},ZY=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=sd.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t= $ n();this.outputShape=e,this.enableShapeUniforms=Dn(this.outputShape.length),this.userCode= `
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2022-10-30 14:06:17 +01:00
$ { this . enableShapeUniforms ? Xm ( [ "r" , "c" , "d" ] , e ) : Ii ( [ "r" , "c" , "d" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( texShape [ 0 ] , texShape [ 1 ] ) ) ;
int index = 4 * ( resTexRC . x * texShape [ 1 ] + resTexRC . y ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < 4 ; i ++ ) {
int flatIndex = index + i ;
ivec3 rc = outCoordsFromFlatIndex ( flatIndex ) ;
result [ i ] = getChannel ( getA ( rc . x , rc . y , rc . z ) , vec2 ( rc . y , rc . z ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
$ { t . output } = result ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},JY=class{constructor(e){this.variableNames=["A"],this.outTexUsage=ur.DOWNLOAD;let t= $ n();this.outputShape=e,this.userCode= `
$ { L2 }
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
float x = getAAtOutCoords ( ) ;
$ { t . output } = encode _float ( x ) ;
}
2022-10-30 14:06:17 +01:00
` }},QY=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ur.DOWNLOAD;let t= $ n();this.outputShape=e,this.userCode= `
$ { L2 }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
float x = getChannel ( getAAtOutCoords ( ) , vec2 ( coords . y , coords . z ) ) ;
$ { t . output } = encode _float ( x ) ;
}
2022-10-30 14:06:17 +01:00
` }},e9={R:0,G:1,B:2,A:3},f1=class{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let r= $ n();this.outputShape=e,this.enableShapeUniforms=Dn(this.outputShape.length);let s="result";t&&(s="floor(result * 255. + 0.5)");let a="";for(let o=0;o<n.length;o++){let i=n[o];a+= `
if ( offset == $ { o } ) {
result = values [ $ { e9 [ i ] } ] ;
2022-10-14 14:01:39 +02:00
} ` }this.userCode= `
$ { this . enableShapeUniforms ? J0 ( ) : Z0 ( e ) }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int flatIndex = getFlatIndex ( coords ) ;
2022-10-14 14:01:39 +02:00
float result = 0. ;
int offset = imod ( flatIndex , $ { n . length } ) ;
2021-04-01 19:39:54 +02:00
2022-10-14 14:01:39 +02:00
flatIndex = idiv ( flatIndex , $ { n . length } , 1. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int r = flatIndex / texShape [ 1 ] ;
2022-10-14 14:01:39 +02:00
if ( r < texShape [ 0 ] ) {
int c = imod ( flatIndex , texShape [ 1 ] ) ;
vec2 uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( texShape [ 1 ] , texShape [ 0 ] ) ;
2022-10-30 14:06:17 +01:00
vec4 values = $ { r . texture2D } ( A , uv ) ;
$ { a }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
$ { r . output } = vec4 ( $ { s } , 0. , 0. , 0. ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }},t9=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n= $ n();this.outputShape=e,this.enableShapeUniforms=Dn(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let o=0;o<=1;o++){let i=a*2+o;r+= `
2021-09-11 17:11:38 +02:00
localCoords = coords ;
2022-10-30 14:06:17 +01:00
if ( localCoords [ 2 ] + $ { o } < $ { this . enableShapeUniforms ? "outShape[2]" : ` ${ e [ 2 ] } ` } ) {
localCoords [ 2 ] += $ { o } ;
if ( localCoords [ 1 ] + $ { a } < $ { this . enableShapeUniforms ? "outShape[1]" : ` ${ e [ 1 ] } ` } ) {
localCoords [ 1 ] += $ { a } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = getFlatIndex ( localCoords ) ;
offset = imod ( flatIndex , 4 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int r = flatIndex / texShape [ 1 ] ;
int c = imod ( flatIndex , texShape [ 1 ] ) ;
vec2 uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( texShape [ 1 ] , texShape [ 0 ] ) ;
values = $ { n . texture2D } ( A , uv ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( offset == 0 ) {
2022-10-30 14:06:17 +01:00
result [ $ { i } ] = values [ 0 ] ;
2021-09-11 17:11:38 +02:00
} else if ( offset == 1 ) {
2022-10-30 14:06:17 +01:00
result [ $ { i } ] = values [ 1 ] ;
2021-09-11 17:11:38 +02:00
} else if ( offset == 2 ) {
2022-10-30 14:06:17 +01:00
result [ $ { i } ] = values [ 2 ] ;
2021-09-11 17:11:38 +02:00
} else {
2022-10-30 14:06:17 +01:00
result [ $ { i } ] = values [ 3 ] ;
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
` }this.userCode= `
2022-10-14 14:01:39 +02:00
$ { this . enableShapeUniforms ? J0 ( ) : Z0 ( e ) }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
int flatIndex , r , c , offset ;
ivec3 localCoords ;
vec2 uv ;
vec4 values ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { r }
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { n . output } = $ { s } ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},U2={};Ae(U2,{bindVertexProgramAttributeStreams:()=>J2,createBufferFromOutputTexture:()=>tE,createFloat16MatrixTexture:()=>K2,createFloat16PackedMatrixTexture:()=>Z2,createFloat32MatrixTexture:()=>j2,createIndexBuffer:()=>q2,createPackedMatrixTexture:()=>Y2,createUnsignedBytesMatrixTexture:()=>X2,createVertexBuffer:()=>H2,createVertexShader:()=>G2,downloadByteEncodedFloatMatrixFromOutputTexture:()=>rE,downloadFloat32MatrixFromBuffer:()=>nE,downloadMatrixFromPackedOutputTexture:()=>aE,downloadPackedMatrixFromBuffer:()=>sE,getInternalFormatForFloat16MatrixTexture:()=>tI,getInternalFormatForFloat16PackedMatrixTexture:()=>sI,getInternalFormatForFloat32MatrixTexture:()=>eI,getInternalFormatForPackedMatrixTexture:()=>rI,getInternalFormatForUnsignedBytesMatrixTexture:()=>nI,uploadDenseMatrixToTexture:()=>Q2,uploadPixelDataToTexture:()=>eE});function G2(e){let t= $ n(),n= ` $ { t . version }
2021-09-11 17:11:38 +02:00
precision highp float ;
$ { t . attribute } vec3 clipSpacePos ;
$ { t . attribute } vec2 uv ;
$ { t . varyingVs } vec2 resultUV ;
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
gl _Position = vec4 ( clipSpacePos , 1 ) ;
resultUV = uv ;
2022-10-30 14:06:17 +01:00
} ` ;return g2(e,n)}function H2(e){let t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return x2(e,t)}function q2(e){let t=new Uint16Array([0,1,2,2,1,3]);return w2(e,t)}function ip(e,t,n,r,s,a){k2(t,n);let o=I2(e),i=e.TEXTURE_2D;return me(e,()=>e.bindTexture(i,o)),me(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),me(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),me(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),me(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),q().getNumber("WEBGL_VERSION")===1?me(e,()=>e.texImage2D(i,0,r,t,n,0,s,a,null)):me(e,()=>e.texStorage2D(i,1,r,t,n)),me(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:o,texShape:[n,t]}}function eI(e){return e.internalFormatFloat}function j2(e,t,n,r){let[s,a]=op(t,n);return ip(e,s,a,eI(r),r.textureFormatFloat,e.FLOAT)}function tI(e){return e.internalFormatHalfFloat}function K2(e,t,n,r){let[s,a]=op(t,n);return ip(e,s,a,tI(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function nI(e){return e.downloadTextureFormat}function X2(e,t,n,r){let[s,a]=op(t,n);return ip(e,s,a,nI(r),e.RGBA,e.UNSIGNED_BYTE)}function rI(e){return e.internalFormatPackedFloat}function Y2(e,t,n,r){let[s,a]=Xu(t,n);return ip(e,s,a,rI(r),e.RGBA,e.FLOAT)}function sI(e){return e.internalFormatPackedHalfFloat}function Z2(e,t,n,r){let[s,a]=Xu(t,n);return ip(e,s,a,sI(r),e.RGBA,r.textureTypeHalfFloat)}function J2(e,t,n){return me(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),fv(e,t,"clipSpacePos",n,3,20,0)&&fv(e,t,"uv",n,2,20,12)}function Q2(e,t,n,r,s,a){me(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,i,c;s instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,c=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,c=a.internalFormatPackedFloat),o.set(s),q().getNumber("WEBGL_VERSION")===2?me(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o)):me(e,()=>e.texImage2D(e.TEXTURE_2D,0,c,n,r,0,e.RGBA,i,o)),me(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function eE(e,t,n){me(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?q().getNumber("WEBGL_VERSION")===2?me(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):me(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):q().getNumber("WEBGL_VERSION")===2?me(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):me(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),me(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function tE(e,t,n,r){let s=e.createBuffer();me(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));let i=4*4*t*n;return me(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),me(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),me(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function nE(e,t,n){let r=e,s=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,s),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),s}function rE(e,t,n,r){let[s,a]=op(t,n),o=4,i=new Uint8Array(Z7(t*n,o));return me(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function sE(e,t,n,r,s,a,o,i){let c=e,u=new Float32Array(J7(a,o));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,u),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),u}function aE(e,t,n){let r=new Float32Array(t*n*4);return me(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}var Ch=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=q().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,h2(t,e)):this.gl=Kr(t);let n="WEBGL_color_buffer_float",r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),q().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=zl(this.gl,s),lr(this.gl,a))this.textureHalfFloatExtension=zl(this.gl,a);else if(q().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environm
2021-09-11 17:11:38 +02:00
void main ( ) {
setOutput ( vec4 ( getA ( ) , 0. , 0. , 0. ) ) ;
}
2022-10-30 14:06:17 +01:00
` ;else{let t=Tn("rc",this.rank),n=mt(this.rank),r=this.getOutOfBoundsCondition(t),s=this.getSetup(t),a=this.getOutput(t);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2021-12-09 20:22:22 +01:00
$ { n } rc = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { r } ) {
2021-09-11 17:11:38 +02:00
setOutput ( vec4 ( 0 ) ) ;
} else {
2022-10-30 14:06:17 +01:00
$ { s }
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
setOutput ( vec4 ( $ { a } ) ) ;
2021-04-01 19:39:54 +02:00
}
}
2022-10-30 14:06:17 +01:00
` }}getSourceCoordsArr(e){let t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let s= ` $ { n === 0 ? "r" : "rp1" } , $ { r === 0 ? "c" : "cp1" } ` ;for(let a=2;a<this.rank;a++)s= ` $ { e [ e . length - 1 - a ] } , ` +s;t.push(s)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return ` rc > $ { this . enableShapeUniforms ? "outShape" : this . outputShape [ 0 ] } ` ;let t="";for(let n=this.rank-2;n<this.rank;n++)t+= ` $ { e [ n ] } >= $ { this . enableShapeUniforms ? ` outShape[ ${ n } ] ` : this . outputShape [ n ] } ` ,n<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),n=this.enableShapeUniforms? ` outShape [ $ { this . rank } - 1 ] ` :this.outputShape[this.rank-1],r=this.enableShapeUniforms? ` outShape [ $ { this . rank } - 2 ] ` :this.outputShape[this.rank-2];return `
2021-12-09 20:22:22 +01:00
int r = $ { t [ 0 ] } ;
int c = $ { t [ 1 ] } ;
int rp1 = r + 1 ;
int cp1 = c + 1 ;
bool cEdge = cp1 >= $ { n } ;
2022-10-30 14:06:17 +01:00
bool rEdge = rp1 >= $ { r } ;
2022-01-14 16:04:13 +01:00
` }getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1? ` getA ( rc ) , ( rc + 1 >= $ { this . enableShapeUniforms ? "outShape" : this . outputShape [ 0 ] } ? 0. : getA ( rc + 1 ) ) , 0 , 0 ` : ` getA ( $ { t [ 0 ] } ) ,
2021-12-09 20:22:22 +01:00
cEdge ? 0. : getA ( $ { t [ 1 ] } ) ,
rEdge ? 0. : getA ( $ { t [ 2 ] } ) ,
2022-10-30 14:06:17 +01:00
rEdge || cEdge ? 0. : getA ( $ { t [ 3 ] } ) ` }},lE=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Dn(this.outputShape.length);let n="";for(let r=0;r<4;r++){let s="thisRC = rc;";r%2===1&&(s+="thisRC.z += 1;"),r>1&&(s+="thisRC.y += 1;"),n+= `
$ { s }
$ { r > 0 ? "if(thisRC.y < rows && thisRC.z < cols){" : "" }
2021-09-11 17:11:38 +02:00
int flatIndex = getFlatIndex ( thisRC ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 inputRC = inputCoordsFromReshapedOutCoords ( flatIndex ) ;
vec2 inputRCInnerDims = vec2 ( float ( inputRC . y ) , float ( inputRC . z ) ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
result [ $ { r } ] =
2021-09-11 17:11:38 +02:00
getChannel ( getA ( inputRC . x , inputRC . y , inputRC . z ) , inputRCInnerDims ) ;
2022-10-30 14:06:17 +01:00
$ { r > 0 ? "}" : "" }
2021-09-11 17:11:38 +02:00
` }this.userCode= `
2022-10-30 14:06:17 +01:00
$ { K9 ( t , this . enableShapeUniforms ) }
2022-10-14 14:01:39 +02:00
$ { this . enableShapeUniforms ? J0 ( ) : Z0 ( e ) }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 thisRC ;
int rows = $ { this . enableShapeUniforms ? "outShape[1]" : e [ 1 ] } ;
int cols = $ { this . enableShapeUniforms ? "outShape[2]" : e [ 2 ] } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { n }
2021-04-01 19:39:54 +02:00
setOutput ( result ) ;
}
2022-10-30 14:06:17 +01:00
` }};function K9(e,t){return `
2021-09-11 17:11:38 +02:00
ivec3 inputCoordsFromReshapedOutCoords ( int index ) {
2022-10-30 14:06:17 +01:00
$ { t ? lY ( [ "r" , "c" , "d" ] , "inputShape" ) : Ii ( [ "r" , "c" , "d" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }var X9=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){let r=g1(t,n),s=b1(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=m1(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let i=this.freeTextures[s].shift();return this.usedTextures[s].push(i),i}let o;return r===cn.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===cn.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===cn.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===cn.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===cn.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(e,t,n,r){if(this.freeTextures==null)return;let s=g1(n,r),a=b1(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);let o=m1(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=q().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let c=this.usedTextures[a],u=c.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used", ` $ { this . numFreeTextures } / $ { this . numUsedTextures } ` , ` ( $ { e } ) ` );let t=this._numBytesFree/this._numBytesAllocated;console.log( ` Bytes allocated : $ { this . _numBytesAllocated } ` ),console.log( ` Bytes unused : $ { this . _numBytesFree } ( $ { Math . round ( 100 * t ) } % ) ` )}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function Y9(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error( ` Unknown internal format $ { t } ` )}function m1(e,t,n,r,s){let a=Z9(t,r),o;if(s){let[c,u]=Xu(e[0],e[1]);o=c*u}else{let[c,u]=op(e[0],e[1]);o=c*u}let i=Y9(n,a);return o*i}function Z9(e,t){switch(e){case cn.PACKED_2X2_FLOAT32:return rI(t);case cn.PACKED_2X2_FLOAT16:return sI(t);case cn.UNPACKED_FLOAT32:return eI(t);case cn.UNPACKED_FLOAT16:return tI(t);case cn.PACKED_4X1_UNSIGNED_BYTE:return nI(t);default:throw new Error( ` Unknown physical texture type $ { e } ` )}}function J9(e){return q().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?cn.PACKED_2X2_FLOAT32:cn.UNPACKED_FLOAT32:e?cn.PACKED_2X2_FLOAT16:cn.UNPACKED_FLOAT16}function g1(e,t){if(e===ur.UPLOAD)return cn.PACKED_2X2_FLOAT32;if(e===ur.RENDER||e==null)return J9(t);if(e===ur.DOWNLOAD||e===ur.PIXELS)return cn.PACKED_4X1_UNSIGNED_BYTE;throw new Error( ` Unknown logical texture type $ { e } ` )}function b1(e,t,n){return ` $ { e [ 0 ] } _$ { e [ 1 ] } _$ { t } _$ { n } ` }var Ns=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Dn(this.outputShape.length),this.userCode= `
2021-09-11 17:11:38 +02:00
float unaryOperation ( float x ) {
$ { t }
2021-04-15 22:59:35 +02:00
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
float x = getAAtOutCoords ( ) ;
float y = unaryOperation ( x ) ;
2021-04-15 22:59:35 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( y ) ;
}
2022-10-30 14:06:17 +01:00
` }},Or="if (isnan(x)) return x;",Q9="return x;",y1="return abs(x);",eZ="return (x >= 0.0) ? x : (exp(x) - 1.0);",tZ=Or+ `
2021-09-11 17:11:38 +02:00
return ( x < 0.0 ) ? 0.0 : x ;
2022-10-30 14:06:17 +01:00
` ,nZ=Or+ `
2021-09-11 17:11:38 +02:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2022-10-30 14:06:17 +01:00
` ,sc="return x;",rZ="return 1.0 / (1.0 + exp(-1.0 * x));",sZ="return x;",aZ= `
2021-09-11 17:11:38 +02:00
vec4 result ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result . r = ( x . r >= 0.0 ) ? x . r : ( exp ( x . r ) - 1.0 ) ;
result . g = ( x . g >= 0.0 ) ? x . g : ( exp ( x . g ) - 1.0 ) ;
result . b = ( x . b >= 0.0 ) ? x . b : ( exp ( x . b ) - 1.0 ) ;
result . a = ( x . a >= 0.0 ) ? x . a : ( exp ( x . a ) - 1.0 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,oZ= `
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,iZ= `
2021-09-11 17:11:38 +02:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,cZ="return 1.0 / (1.0 + exp(-1.0 * x));",Ka=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Dn(this.outputShape.length),this.userCode= `
2021-09-11 17:11:38 +02:00
vec4 unaryOperation ( vec4 x ) {
$ { t }
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main ( ) {
vec4 x = getAAtOutCoords ( ) ;
vec4 y = unaryOperation ( x ) ;
setOutput ( y ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},uZ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=Dn(this.outputShape.length);let t=e.length,n=Tn("rc",t),r=mt(t),s=q9(t,n),a=n.slice(-2),o=t<=1?"rc": ` vec2 ( $ { a . join ( "," ) } ) ` ;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { r } rc = getOutputCoords ( ) ;
vec4 packedInput = getA ( $ { s } ) ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
setOutput ( getChannel ( packedInput , $ { o } ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},lZ=fs.whereImpl,dZ=1e-7,pZ=1e-4,bh={};function hZ(e){return e in bh||(bh[e]={}),bh[e]}var fZ=q().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),mZ=600;function gZ(){return q().global.screen==null?1024:q().global.screen.height*q().global.screen.width*window.devicePixelRatio*mZ/1024/1024}var Ym=class extends ld{constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!q().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof Ch)t=e;else{let n=Kr(q().getNumber("WEBGL_VERSION"),e);t=new Ch(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Kr(q().getNumber("WEBGL_VERSION"));t=new Ch(n),this.binaryCache=hZ(q().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new X9(this.gpgpu),this.numMBBeforeWarning=gZ(),this.texData=new uf(this,Er())}nextDataId(){return Ym.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,r,s,a){let o=this.makeTensorInfo(t,n),i=this.texData.get(o.dataId);i.isPacked=!1,i.texture={texture:e,texShape:[r,s]},i.texShape=[r,s];let c=Wl(t),u=new f1(c,!1,a),l=this.runWebGLProgram(u,[o],n,[[r,s]]);return l.shape=t,i.texture=null,this.disposeIntermediateTensorInfo(o),l.dataId}write(e,t,n){if((q().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||q().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:ur.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,r,s){if(q().getBool("DEBUG")&&this.checkNumericalProblems(t),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:ur.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:s,slice:a,shape:o,isPacked:i}=t;if(a!=null){let p;i?p=new Ka(o,sc):p=new Ns(o,sc);let d=this.runWebGLProgram(p,[{dataId:e,shape:o,dtype:r}],r),h=this.readSync(d.dataId);return this.disposeIntermediateTensorInfo(d),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return n;let c=this.activeTimers!=null,u;c&&(u=w.now());let l;if(r==="complex64"){let p=this.readSync(s.real.dataId),d=this.readSync(s.imag.dataId);l=N.mergeRealAndImagArrays(p,d)}else l=this.getValuesFromTexture(e);return c&&(this.downloadWaitMs+=w.now()-u),this.convertAndCacheOnCPU(e,l)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(s!=null){let h;i?h=new Ka(r,sc):h=new Ns(r,sc);let f=this.runWebGLProgram(h,[{dataId:e,shape:r,dtype:a}],a),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(n!=null)return this.convertAndCacheOnCPU(e);if(q().getBool("DEBUG")&&!q().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&q().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c=null,u;if(a!=="complex64"&&q().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let h=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(h.texture.texture,...mh(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let l;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];l=N.mergeRealAndImagArrays(f,m)}else if(c==null)l=this.getValuesFromTextu
2021-09-11 17:11:38 +02:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2022-10-30 14:06:17 +01:00
` , $ c=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=N.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=Dn(this.outputShape.length),this.userCode= `
2021-09-11 17:11:38 +02:00
float binaryOperation ( float a , float b ) {
$ { e }
2021-04-01 19:39:54 +02:00
}
void main ( ) {
2021-09-11 17:11:38 +02:00
float a = getAAtOutCoords ( ) ;
float b = getBAtOutCoords ( ) ;
setOutput ( binaryOperation ( a , b ) ) ;
}
2022-10-30 14:06:17 +01:00
` }},cp= `
2022-10-09 19:40:33 +02:00
result . r = isNaN . r ? NAN : result . r ;
result . g = isNaN . g ? NAN : result . g ;
result . b = isNaN . b ? NAN : result . b ;
result . a = isNaN . a ? NAN : result . a ;
2022-10-30 14:06:17 +01:00
` ,up=class{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=N.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length;this.enableShapeUniforms=Dn(s);let a="";if(r)if(s===0||w.sizeFromShape(this.outputShape)===1)a= `
2021-09-11 17:11:38 +02:00
result . y = 0. ;
result . z = 0. ;
result . w = 0. ;
2022-10-30 14:06:17 +01:00
` ;else if(a= `
$ { mt ( s ) } coords = getOutputCoords ( ) ;
` ,s===1)this.enableShapeUniforms?a+= `
2021-09-11 17:11:38 +02:00
result . y = ( coords + 1 ) >= outShape ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
2022-10-30 14:06:17 +01:00
` :a+= `
2021-09-11 17:11:38 +02:00
result . y = ( coords + 1 ) >= $ { this . outputShape [ 0 ] } ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
2022-10-30 14:06:17 +01:00
` ;else{let i=Tn("coords",s);this.enableShapeUniforms?a+= `
2021-09-11 17:11:38 +02:00
bool nextRowOutOfBounds =
2022-10-30 14:06:17 +01:00
( $ { i [ s - 2 ] } + 1 ) >= outShape [ $ { s } - 2 ] ;
2021-09-11 17:11:38 +02:00
bool nextColOutOfBounds =
2022-10-30 14:06:17 +01:00
( $ { i [ s - 1 ] } + 1 ) >= outShape [ $ { s } - 1 ] ;
2021-09-11 17:11:38 +02:00
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
2022-10-30 14:06:17 +01:00
` :a+= `
2021-09-11 17:11:38 +02:00
bool nextRowOutOfBounds =
2022-10-30 14:06:17 +01:00
( $ { i [ s - 2 ] } + 1 ) >= $ { this . outputShape [ s - 2 ] } ;
2021-09-11 17:11:38 +02:00
bool nextColOutOfBounds =
2022-10-30 14:06:17 +01:00
( $ { i [ s - 1 ] } + 1 ) >= $ { this . outputShape [ s - 1 ] } ;
2021-09-11 17:11:38 +02:00
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
` }this.userCode= `
vec4 binaryOperation ( vec4 a , vec4 b ) {
$ { e }
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
vec4 a = getAAtOutCoords ( ) ;
vec4 b = getBAtOutCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = binaryOperation ( a , b ) ;
2022-10-30 14:06:17 +01:00
$ { a }
2021-04-01 19:39:54 +02:00
setOutput ( result ) ;
}
2022-10-30 14:06:17 +01:00
` }};function sr(e){let{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var xZ={kernelName:Oo,backendName:"webgl",kernelFunc:sr};function Ea(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(a.dataId),i=sr({inputs:{x:r},backend:n}),c=sr({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:c},a}var wZ={kernelName:gf,backendName:"webgl",kernelFunc:Ea},pE="return (a < 0.) ? b * a : a;",hE= `
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2022-10-30 14:06:17 +01:00
` ;function IZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=n.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),i=q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new up(hE,s.shape,o.shape):new $ c(pE,s.shape,o.shape),c=n.runWebGLProgram(i,[s,o],"float32");return n.disposeIntermediateTensorInfo(o),c}var kZ={kernelName:Mo,backendName:"webgl",kernelFunc:IZ},fE="return (a < 0.) ? b * a : a;",mE= `
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2022-10-30 14:06:17 +01:00
` ;function SZ(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new up(mE,r.shape,s.shape):new $ c(fE,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}var TZ={kernelName:Yo,backendName:"webgl",kernelFunc:SZ},tl="if (isnan(x)) return x;";function Ye({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{let{x:o}=s,i=a,c=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let p=i.texData.get(o.dataId),d=n(p.values,c);return i.makeTensorInfo(o.shape,c,d)}let u=q().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,l;return u?l=new Ka(o.shape,t):l=new Ns(o.shape,e),i.runWebGLProgram(l,[o],c)}}function dn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:o,backend:i})=>{let{a:c,b:u}=o,l=i;if(r&&c.dtype==="complex64"){let f=l.texData.get(c.dataId),m=l.texData.get(u.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(v=>{let[x,k]=v,S={dataId:x.dataId,dtype:x.dtype,shape:c.shape},C={dataId:k.dataId,dtype:k.dtype,shape:u.shape},E=new $ c(e,c.shape,u.shape);return l.runWebGLProgram(E,[S,C],hr(x.dtype,k.dtype))}),y=Ea({inputs:{real:g,imag:b},backend:l});return l.disposeIntermediateTensorInfo(g),l.disposeIntermediateTensorInfo(b),y}let p=a||hr(c.dtype,u.dtype);if((c.dtype==="string"||u.dtype==="string"||l.shouldExecuteOnCPU([c,u]))&&s!=null){let f=l.texData.get(c.dataId).values,m=l.texData.get(u.dataId).values,g=c.dtype==="string"?N.fromUint8ToStringArray(f):f,b=c.dtype==="string"?N.fromUint8ToStringArray(m):m,[y,v]=s(c.shape,u.shape,g,b,p),x=l.makeTensorInfo(v,p),k=l.texData.get(x.dataId);return k.values=y,x}let d=q().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return d?h=new up(t,c.shape,u.shape,n):h=new $ c(e,c.shape,u.shape),l.runWebGLProgram(h,[c,u],p)}}function od(e,t=!1){if(e==="linear")return t?sZ:Q9;if(e==="relu")return t?oZ:tZ;if(e==="elu")return t?aZ:eZ;if(e==="relu6")return t?iZ:nZ;if(e==="prelu")return t?mE:fE;if(e==="leakyrelu")return t?hE:pE;if(e==="sigmoid")return t?cZ:rZ;throw new Error( ` Activation $ { e } has not been implemented for the WebGL backend . ` )}var gE=class{constructor(e,t,n,r=!1,s=!1,a=!1,o=null,i=!1,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=Dn(this.outputShape.length);let u=r?e[1]:e[2],l=Math.ceil(u/2),p=r?"i * 2, rc.y":"rc.y, i * 2",d=s?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m= ` vec4 activation ( vec4 a ) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
2022-10-30 14:06:17 +01:00
$ { o }
} ` :c?m= ` vec4 activation ( vec4 a ) {
2021-09-11 17:11:38 +02:00
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
2022-10-30 14:06:17 +01:00
$ { o }
} ` :m= ` vec4 activation ( vec4 x ) {
$ { o }
} ` ,g="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let y="rc.x",v="rc.x";e[0]<t[0]?y= ` int ( min ( float ( rc . x ) , $ { e [ 0 ] - 1 } . ) ) ` :t[0]<e[0]&&(v= ` int ( min ( float ( rc . x ) , $ { t [ 0 ] - 1 } . ) ) ` ),this.userCode= `
$ { m }
2021-09-11 17:11:38 +02:00
// Don't use uniform for sharedDimensionPacked for performance.
2022-10-30 14:06:17 +01:00
const float sharedDimension = $ { l } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 dot2x2ARowBCol ( ivec3 rc ) {
vec4 result = vec4 ( 0 ) ;
2022-10-30 14:06:17 +01:00
for ( int i = 0 ; i < $ { l } ; i ++ ) {
int batchA = $ { y } ;
int batchB = $ { v } ;
vec4 a = getMatrixA ( batchA , $ { p } ) ;
vec4 b = getMatrixB ( batchB , $ { d } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
2022-10-30 14:06:17 +01:00
result += ( $ { h [ 0 ] } * $ { f [ 0 ] } ) ;
result += ( $ { h [ 1 ] } * $ { f [ 1 ] } ) ;
2021-09-11 17:11:38 +02:00
}
return result ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
vec4 result = dot2x2ARowBCol ( rc ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { b }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { g }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
}
2022-10-30 14:06:17 +01:00
` }},v1={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},x1=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=N.assertAndGetBroadcastShape(t,n),this.userCode= `
2021-09-11 17:11:38 +02:00
float binaryOpComplex (
float areal , float aimag , float breal , float bimag ) {
$ { e }
}
void main ( ) {
float areal = getARealAtOutCoords ( ) ;
float aimag = getAImagAtOutCoords ( ) ;
float breal = getBRealAtOutCoords ( ) ;
float bimag = getBImagAtOutCoords ( ) ;
setOutput ( binaryOpComplex ( areal , aimag , breal , bimag ) ) ;
}
2022-10-30 14:06:17 +01:00
` }},w1="return a * b;";function iI(e){let{inputs:t,backend:n}=e,{a:r,b:s}=t,a=N.upcastType(r.dtype,s.dtype);if(r.dtype==="complex64"){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),u=new x1(v1.REAL,r.shape,s.shape),l=new x1(v1.IMAG,r.shape,s.shape),p=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:r.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape}],d=n.runWebGLProgram(u,p,"float32"),h=n.runWebGLProgram(l,p,"float32"),f=Ea({inputs:{real:d,imag:h},backend:n});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),f}if(n.shouldExecuteOnCPU([r,s])){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),[u,l]=k9(r.shape,s.shape,i.values,c.values,a),p=n.makeTensorInfo(l,a),d=n.texData.get(p.dataId);return d.values=u,p}let o;return q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?o=new up(w1,r.shape,s.shape):o=new $ c(w1,r.shape,s.shape),n.runWebGLProgram(o,[r,s],a)}var CZ={kernelName:qo,backendName:"webgl",kernelFunc:iI};function NZ(e,t,n){let r=[ho(e.shape),...fo(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[ho(t),...fo(t)],o=new lE(a,r),i=!0,c=[r],u=n.runWebGLProgram(o,[s],e.dtype,c,i);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function he(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=n,i=w.sizeFromShape(s.shape),c=w.inferFromImplicitShape(a,i),u=w.sizeFromShape(c);w.assert(i===u,()=> ` The new shape ( $ { c } ) has $ { u } elements and the old shape ( $ { s . shape } ) has $ { i } elements . The new shape and old shape must have the same number of elements . ` );let l=o.texData.get(s.dataId);return l.isPacked&&!ad(s.shape,c)&&!(l.texture!==null&&ad(l.shape,c))?NZ(s,c,o):(o.incRef(s.dataId),{dataId:s.dataId,shape:c,dtype:s.dtype})}var _Z={kernelName:xu,backendName:"webgl",kernelFunc:he},I1=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o=Math.floor(n/4)*4,i=n%4,c="sumValue += dot(values, ones);";if(t!=null){let l=1/t;c= ` sumValue += dot ( values * $ { w . isInt ( l ) ? l . toPrecision ( 2 ) : l } , ones ) ; ` }let u="";s%n>0&&(u= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
2021-09-11 17:11:38 +02:00
return 0.0 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` ),this.userCode= `
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
2022-03-07 19:17:31 +01:00
$ { u }
2021-09-11 17:11:38 +02:00
return getX ( batch , inIdx ) ;
2021-04-01 19:39:54 +02:00
}
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
int batch = coords [ 0 ] ;
2021-09-11 17:11:38 +02:00
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * $ { n } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0 ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
for ( int i = 0 ; i < $ { o } ; i += 4 ) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { c }
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
int inIdx = inOffset + $ { o } ;
if ( $ { i === 1 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 ( getValue ( batch , inIdx ) , 0.0 , 0.0 , 0.0 ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { c }
} else if ( $ { i === 2 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) , 0.0 , 0.0 ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { c }
} else if ( $ { i === 3 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) , 0.0 ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { c }
2021-09-11 17:11:38 +02:00
}
setOutput ( sumValue ) ;
}
2022-10-30 14:06:17 +01:00
` }},EZ=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let c= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="sum"?c="sumValue":t==="prod"?c="prodValue":t==="all"?c="allValue":t==="any"&&(c="anyValue");let u=Math.floor(n/4)*4,l=n%4,p= `
2021-09-11 17:11:38 +02:00
if ( $ { t === "sum" } ) {
sumValue += dot ( values , ones ) ;
} else if ( $ { t === "prod" } ) {
vec2 tmp = vec2 ( values [ 0 ] , values [ 1 ] ) * vec2 ( values [ 2 ] , values [ 3 ] ) ;
prodValue *= tmp [ 0 ] * tmp [ 1 ] ;
} else {
2022-10-30 14:06:17 +01:00
minMaxValue = $ { i } ( values , minMaxValue ) ;
2021-09-11 17:11:38 +02:00
if ( $ { t === "min" } || $ { t === "max" } ) {
2022-10-30 14:06:17 +01:00
minMaxValue = $ { i } ( values , minMaxValue ) ;
2021-09-11 17:11:38 +02:00
bvec4 isNaN = isnan ( values ) ;
if ( isNaN . r || isNaN . g || isNaN . b || isNaN . a ) {
minMaxValue = vec4 ( NAN ) ;
2021-04-01 19:39:54 +02:00
}
}
}
2022-10-30 14:06:17 +01:00
` ,d="vec4";t==="all"?(o="1.0",p= `
2021-09-11 17:11:38 +02:00
bool reducedAllValue = all ( values ) ;
float floatedReducedAllValue = float ( reducedAllValue ) ;
allValue = float ( allValue >= 1.0 && floatedReducedAllValue >= 1.0 ) ;
2022-10-30 14:06:17 +01:00
` ,d="bvec4"):t==="any"&&(o="0.0",p= `
2021-09-11 17:11:38 +02:00
bool reducedAnyValue = any ( values ) ;
float floatedReducedAnyValue = float ( reducedAnyValue ) ;
anyValue = float ( anyValue >= 1.0 || floatedReducedAnyValue >= 1.0 ) ;
2022-10-30 14:06:17 +01:00
` ,d="bvec4");let h="";s%n>0&&(h= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
2021-09-11 17:11:38 +02:00
return initializationValue ;
}
` ),this.userCode= `
2022-10-30 14:06:17 +01:00
const float initializationValue = $ { o } ;
2021-09-11 17:11:38 +02:00
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
$ { h }
return getX ( batch , inIdx ) ;
2021-04-01 19:39:54 +02:00
}
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * $ { n } ;
2022-10-30 14:06:17 +01:00
vec4 minMaxValue = vec4 ( $ { o } ) ;
2021-09-11 17:11:38 +02:00
float prodValue = 1.0 ;
float sumValue = 0.0 ;
float allValue = 1.0 ;
float anyValue = 0.0 ;
2022-03-07 19:17:31 +01:00
for ( int i = 0 ; i < $ { u } ; i += 4 ) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i ;
2022-10-30 14:06:17 +01:00
$ { d } values = $ { d } (
2021-09-11 17:11:38 +02:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { p }
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
2022-03-07 19:17:31 +01:00
int inIdx = inOffset + $ { u } ;
2022-10-30 14:06:17 +01:00
if ( $ { l === 1 } ) {
$ { d } values = $ { d } (
2021-09-11 17:11:38 +02:00
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { p }
} else if ( $ { l === 2 } ) {
$ { d } values = $ { d } (
2021-09-11 17:11:38 +02:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { p }
} else if ( $ { l === 3 } ) {
$ { d } values = $ { d } (
2021-09-11 17:11:38 +02:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { p }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
setOutput ( $ { c } ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function AZ(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],r=N.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}function Si(e,t,n,r){let s=AZ(e.shape),a=e;for(let o=0;o<s.length;o++){let{inSize:i,windowSize:c,outSize:u}=s[o],l,p;n==="mean"?l=o===0?new I1({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u},i):new I1({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u}):l=new EZ({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u},n),p=a,a=r.runWebGLProgram(l,[a],t),p.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(p)}return a}var $ Z=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];this.outputShape=n,this.rank=n.length;let r=mt(this.rank),s=DZ(t);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { r } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { s } ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function DZ(e){let t=e.length;if(t>6)throw Error( ` Transpose for rank $ { t } is not yet supported ` );let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let s=0;s<e.length;s++)r[e[s]]=n[s];return r.join()}var FZ=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let u=0;u<n.length;u++)n[u]=e[t[u]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error( ` Packed transpose for rank $ { this . rank } is not yet supported . ` );let r=mt(this.rank),s=uE("rc",this.rank),a=new Array(this.rank);for(let u=0;u<t.length;u++)a[t[u]]=s[u];let o= ` vec2 ( $ { a . slice ( - 2 ) . join ( ) } ) ` ,i= ` ++ $ { s [ this . rank - 1 ] } < $ { n [ this . rank - 1 ] } ` ,c= ` getChannel ( getA ( $ { a . join ( ) } ) , $ { o } ) ` ;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { r } rc = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2022-10-30 14:06:17 +01:00
result [ 0 ] = $ { c } ;
if ( $ { i } ) {
result [ 1 ] = $ { c } ;
}
-- $ { s [ this . rank - 1 ] } ;
if ( ++ $ { s [ this . rank - 2 ] } < $ { n [ this . rank - 2 ] } ) {
result [ 2 ] = $ { c } ;
if ( $ { i } ) {
result [ 3 ] = $ { c } ;
2021-04-15 22:59:35 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2021-04-15 22:59:35 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function Zm(e,t,n){let r=q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new FZ(e.shape,t):new $ Z(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function RZ(e,t,n,r){let s=t,a=e.shape.length,o=w.parseAxisParam(s,e.shape),i=o,c=N.getAxesPermutation(i,a),u=c!=null,l=e;u&&(l=Zm(e,c,r),i=N.getInnerMostAxes(i.length,a)),N.assertAxesAreInnerMostDims("sum",i,a);let[p,d]=N.computeOutAndReduceShapes(l.shape,i),h=p;n&&(h=N.expandShapeToKeepDim(p,o));let f=w.sizeFromShape(d),g=w.sizeFromShape(e.shape)/f,b=he({inputs:{x:l},attrs:{shape:[g,f]},backend:r}),y=Hf(e.dtype),v=Si(b,y,"sum",r),x=he({inputs:{x:v},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(v),u&&r.disposeIntermediateTensorInfo(l),x}function Jm(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return RZ(s,a,o,n)}var PZ={kernelName:ci,backendName:"webgl",kernelFunc:Jm};function Nn(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,o=n,i=s.shape.length,c=new Array(i);for(let l=0;l<c.length;l++)c[l]=s.shape[a[l]];let u;if(o.shouldExecuteOnCPU([s])){let p=o.texData.get(s.dataId).values,d=aI(p,s.shape,s.dtype,a,c);u=o.makeTensorInfo(c,s.dtype);let h=o.texData.get(u.dataId);h.values=d}else u=Zm(s,a,o);return u}var OZ={kernelName:_s,backendName:"webgl",kernelFunc:Nn},bE=1e3;function rf({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:c=null}){let u=e.shape.length,l=t.shape.length,p=n?e.shape[u-2]:e.shape[u-1],d=r?t.shape[l-1]:t.shape[l-2],h=n?e.shape[u-1]:e.shape[u-2],f=r?t.shape[l-2]:t.shape[l-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=w.sizeFromShape(m),y=w.sizeFromShape(g),x=Mu.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);w.assert(p===d,()=> ` Error in matMul : inner shapes ( $ { p } ) and ( $ { d } ) of Tensors with shapes $ { e . shape } and $ { t . shape } and transposeA = $ { n } and transposeB = $ { r } must match . ` );let k=n?[b,p,h]:[b,h,p],S=r?[y,f,d]:[y,d,f],C=he({inputs:{x:e},backend:s,attrs:{shape:k}}),E=he({inputs:{x:t},backend:s,attrs:{shape:S}}), $ =[C,E],F=Math.max(b,y),A=n?C.shape[1]:C.shape[2],R=a!=null,T=o!=null,L=c==="leakyrelu",V=c!=null?od(c,!0):null,G=R||T||L||V!=null,j;if((h===1||f===1)&&A>bE&&G===!1){let Z=C,J=E;n&&(Z=Nn({inputs:{x:C},backend:s,attrs:{perm:[0,2,1]}}), $ .push(Z)),r&&(J=Nn({inputs:{x:E},backend:s,attrs:{perm:[0,2,1]}}), $ .push(J));let ee=f!==1,re=f===1,te=Z;ee&&(te=he({inputs:{x:Z},backend:s,attrs:{shape:[F,A,1]}}), $ .push(te));let ie=f===1?2:1,ne=J;re&&(ne=he({inputs:{x:J},backend:s,attrs:{shape:[F,1,A]}}), $ .push(ne));let le=iI({inputs:{a:te,b:ne},backend:s});j=Jm({inputs:{x:le},backend:s,attrs:{axis:ie,keepDims:!0}}), $ .push(le)}else{let Z=hr(e.dtype,t.dtype),J=new gE(k,S,[F,h,f],n,r,R,V,T,L),ee=[C,E];if(a!=null&&ee.push(a),T&&ee.push(o),L){let re=s.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));ee.push(re), $ .push(re)}j=s.runWebGLProgram(J,ee,Z)}let H=he({inputs:{x:j},backend:s,attrs:{shape:x}}); $ .push(j);for(let Z of $ )s.disposeIntermediateTensorInfo(Z);return H}function MZ(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:c,transposeB:u,activation:l,leakyreluAlpha:p}=r;return rf({a:s,b:a,transposeA:c,transposeB:u,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:l})}var LZ={kernelName:eo,backendName:"webgl",kernelFunc:MZ},k1="return abs(x);";function zZ(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&r.dtype!=="complex64"){let a=n.texData.get(r.dataId),o=iE(a.values);return n.makeTensorInfo(r.shape,r.dtype,o)}let s;return q().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Ka(r.shape,k1):s=new Ns(r.shape,k1),n.runWebGLProgram(s,[r],r.dtype)}var BZ={kernelName:Fc,backendName:"webgl",kernelFunc:zZ},WZ=Or+ `
2021-09-11 17:11:38 +02:00
if ( abs ( x ) > 1. ) {
return NAN ;
2021-04-15 22:59:35 +02:00
}
2021-09-11 17:11:38 +02:00
return acos ( x ) ;
2022-10-30 14:06:17 +01:00
` ,VZ=Ye({opSnippet:WZ}),UZ={kernelName:Rc,backendName:"webgl",kernelFunc:VZ},GZ=Or+ `
2021-09-11 17:11:38 +02:00
if ( x < 1.0 ) return NAN ;
2022-10-30 14:06:17 +01:00
return log ( x + sqrt ( x * x - 1.0 ) ) ; ` ,HZ=Ye({opSnippet:GZ}),qZ={kernelName:Pc,backendName:"webgl",kernelFunc:HZ},S1="return a + b;",jZ=dn({opSnippet:S1,packedOpSnippet:S1,supportsComplex:!0,cpuKernelImpl:r9}),KZ={kernelName:ba,backendName:"webgl",kernelFunc:jZ},XZ=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=> ` T$ { a } ` );let n=[];this.variableNames.forEach(s=>{n.push( ` float v$ { s } = get$ { s } AtOutCoords ( ) ; ` )});let r=this.variableNames.map(s=> ` v$ { s } ` ).join(" + ");this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { n . join ( `
` )}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
float result = $ { r } ;
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},YZ=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=> ` T$ { a } ` );let n=[];this.variableNames.forEach(s=>{n.push( ` vec4 v$ { s } = get$ { s } AtOutCoords ( ) ; ` )});let r=this.variableNames.map(s=> ` v$ { s } ` ).join(" + ");this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { n . join ( `
` )}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
vec4 result = $ { r } ;
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function Nh(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return sr({inputs:{x:r[0]},backend:n});if(r.length>q().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),u=Nh({inputs:r.slice(0,c),backend:n}),l=Nh({inputs:r.slice(c),backend:n});return Nh({inputs:[u,l],backend:n})}let s=r.map(c=>c.dtype).reduce((c,u)=>hr(c,u)),a=r.map(c=>c.shape),i=q().getBool("WEBGL_PACK")?new YZ(r[0].shape,a):new XZ(r[0].shape,a);return n.runWebGLProgram(i,r,s)}var ZZ={kernelName:bo,backendName:"webgl",kernelFunc:Nh};function JZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=N.getAxesPermutation(u,i),p=s;l!=null&&(p=Nn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=N.getInnerMostAxes(u.length,i)),N.assertAxesAreInnerMostDims("all",u,i);let[d,h]=N.computeOutAndReduceShapes(p.shape,u),f=w.sizeFromShape(h),m=he({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}}),g=Si(m,m.dtype,"all",n),b;if(o){let y=N.expandShapeToKeepDim(d,c);b=he({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=he({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(p),b}var QZ={kernelName:Oc,backendName:"webgl",kernelFunc:JZ};function eJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=N.getAxesPermutation(u,i),p=s;l!=null&&(p=Nn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=N.getInnerMostAxes(u.length,i)),N.assertAxesAreInnerMostDims("any",u,i);let[d,h]=N.computeOutAndReduceShapes(p.shape,u),f=w.sizeFromShape(h),m=he({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}}),g=Si(m,m.dtype,"any",n),b;if(o){let y=N.expandShapeToKeepDim(d,c);b=he({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=he({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(p),b}var tJ={kernelName:Mc,backendName:"webgl",kernelFunc:eJ},nJ=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let o=t==="max"?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
2022-10-30 14:06:17 +01:00
int inOffset = outIdx * $ { r } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int bestIndex = inOffset ;
float bestValue = getA ( batch , bestIndex ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
for ( int i = 0 ; i < $ { r } ; i ++ ) {
int inIdx = $ { i } ;
2021-09-11 17:11:38 +02:00
float candidate = getA ( batch , inIdx ) ;
2022-10-30 14:06:17 +01:00
if ( candidate $ { o } bestValue ) {
2021-09-11 17:11:38 +02:00
bestValue = candidate ;
bestIndex = inIdx ;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( float ( bestIndex ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},rJ=class{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=> ` Packed arg$ { n . charAt ( 0 ) . toUpperCase ( ) + n . slice ( 1 ) } supports only inputs with rank above 2. ` );let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,c=mt(i),u=Tn("coords",i),l,p;if(a===1){p=i+1;let C=mt(p);l= `
2022-10-09 19:40:33 +02:00
$ { C } sourceLocR = $ { C } ( $ { u . join ( ) } , 0 ) ;
2022-10-30 14:06:17 +01:00
++ $ { u [ i - 1 ] } ;
2022-10-09 19:40:33 +02:00
$ { C } sourceLocG = $ { C } ( $ { u . join ( ) } , 0 ) ;
2022-10-30 14:06:17 +01:00
++ $ { u [ i - 2 ] } ;
2022-10-09 19:40:33 +02:00
$ { C } sourceLocA = $ { C } ( $ { u . join ( ) } , 0 ) ;
2022-10-30 14:06:17 +01:00
-- $ { u [ i - 1 ] } ;
2022-10-09 19:40:33 +02:00
$ { C } sourceLocB = $ { C } ( $ { u . join ( ) } , 0 ) ;
2022-10-30 14:06:17 +01:00
-- $ { u [ i - 2 ] } ; ` }else p=i,l= `
$ { c } sourceLocR = coords ;
++ $ { u [ i - 1 ] } ;
$ { c } sourceLocG = coords ;
++ $ { u [ i - 2 ] } ;
$ { c } sourceLocA = coords ;
-- $ { u [ i - 1 ] } ;
$ { c } sourceLocB = coords ;
-- $ { u [ i - 2 ] } ; ` ;let d=["x","y","z","w","u","v"].slice(0,p),h="."+d[p-1],f=d.map(C=>"int "+C),m=Tn("sourceLocR",p-1).concat("inIdx.r"),g=Tn("sourceLocG",p-1).concat("inIdx.g"),b=Tn("sourceLocB",p-1).concat("inIdx.b"),y=Tn("sourceLocA",p-1).concat("inIdx.a"),v=n==="max"?"greaterThan":"lessThan",x=r?"": `
inIdx = round ( vec4 ( getBestIndicesAChannel ( $ { m . join ( ) } ) ,
2021-09-11 17:11:38 +02:00
getBestIndicesAChannel ( $ { g . join ( ) } ) ,
2022-10-30 14:06:17 +01:00
getBestIndicesAChannel ( $ { b . join ( ) } ) ,
getBestIndicesAChannel ( $ { y . join ( ) } ) ) ) ; ` ,k= ` vec4 (
getAChannel ( $ { m . join ( ) } ) ,
2021-09-11 17:11:38 +02:00
hasNextCol ? getAChannel ( $ { g . join ( ) } ) : 0. ,
2022-10-30 14:06:17 +01:00
hasNextRow ? getAChannel ( $ { b . join ( ) } ) : 0. ,
hasNextRow && hasNextCol ? getAChannel ( $ { y . join ( ) } ) : 0. ) ` ,S=r?"": `
float getBestIndicesAChannel ( $ { f . join ( ) } ) {
return getChannel ( getBestIndicesA ( $ { d . join ( ) } ) ,
vec2 ( $ { d . slice ( - 2 ) . join ( ) } ) ) ;
2021-09-11 17:11:38 +02:00
} ` ;this.userCode= `
2022-10-30 14:06:17 +01:00
float getAChannel ( $ { f . join ( ) } ) {
return getChannel ( getA ( $ { d . join ( ) } ) ,
vec2 ( $ { d . slice ( - 2 ) . join ( ) } ) ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
$ { S }
2021-04-01 19:39:54 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { c } coords = getOutputCoords ( ) ;
bool hasNextCol = $ { u [ i - 1 ] } < $ { o [ i - 1 ] - 1 } ;
bool hasNextRow = $ { u [ i - 2 ] } < $ { o [ i - 2 ] - 1 } ;
$ { l }
2021-09-11 17:11:38 +02:00
ivec4 srcIdx = ivec4 ( sourceLocR$ { h } , sourceLocG$ { h } ,
sourceLocB$ { h } , sourceLocA$ { h } ) * $ { t } ;
ivec4 inIdx = srcIdx ;
vec4 bestIndex = vec4 ( inIdx ) ;
2022-10-30 14:06:17 +01:00
vec4 bestValue = $ { k } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < $ { t } ; i ++ ) {
inIdx = srcIdx ;
2022-10-30 14:06:17 +01:00
$ { x }
vec4 candidate = $ { k } ;
2021-09-11 17:11:38 +02:00
bvec4 nan = isnan ( candidate ) ;
bvec4 replace = bvec4 (
2022-10-30 14:06:17 +01:00
vec4 ( $ { v } ( candidate , bestValue ) ) * ( vec4 ( 1.0 ) - vec4 ( nan ) ) ) ;
2021-09-11 17:11:38 +02:00
bestValue = vec4 ( replace . x ? candidate . x : bestValue . x ,
replace . y ? candidate . y : bestValue . y ,
replace . z ? candidate . z : bestValue . z ,
replace . w ? candidate . w : bestValue . w ) ;
bestIndex = mix ( bestIndex , vec4 ( inIdx ) , vec4 ( replace ) ) ;
srcIdx ++ ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( bestIndex ) ;
}
2022-10-30 14:06:17 +01:00
` }};function yE(e,t,n,r=null){let s=t.shape[0],a=t.shape[1];r!=null&&(s=r.shape[0],a=r.shape[1]);let o=N.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:s,outSize:Math.ceil(a/o)},c=new nJ(i,n,r==null),u=[t];r!=null&&u.push(r);let l=e.runWebGLProgram(c,u,"int32");if(l.shape[1]===1)return l;let p=yE(e,t,n,l);return e.disposeIntermediateTensorInfo(l),p}function vE(e,t,n,r=null){let s=r!=null?r.shape:t.shape,a=s[s.length-1],o=N.computeOptimalWindowSize(a),i=new rJ(s,o,n,r==null),c=r==null?[t]:[t,r],u=e.runWebGLProgram(i,c,"int32");if(u.shape.length===t.shape.length){let l=vE(e,t,n,u);return e.disposeIntermediateTensorInfo(u),l}return u}function xE(e,t,n,r){let s=[n];if(N.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!q().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let a=[],o=e.texData.get(t.dataId),i=o!==null&&o.isPacked,c=t;i&&(c=e.unpackTensor(t),a.push(c));let[u,l]=N.computeOutAndReduceShapes(c.shape,s),p=w.sizeFromShape(l),d=he({inputs:{x:c},backend:e,attrs:{shape:[-1,p]}});a.push(d);let h=yE(e,d,r);a.push(h);let f=he({inputs:{x:h},backend:e,attrs:{shape:u}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return vE(e,t,r)}function sJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=N.getAxesPermutation(o,s.shape.length),c=s,u=[];i!=null&&(c=Nn({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(c),o=N.getInnerMostAxes(o.length,c.shape.length)),N.assertAxesAreInnerMostDims("argMax",[o[0]],c.shape.length);let l=xE(n,c,o[0],"max");return u.forEach(p=>n.disposeIntermediateTensorInfo(p)),l}var aJ={kernelName:yo,backendName:"webgl",kernelFunc:sJ};function oJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=N.getAxesPermutation(o,s.shape.length),c=s,u=[];i!=null&&(c=Nn({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(c),o=N.getInnerMostAxes(o.length,c.shape.length)),N.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);let l=xE(n,c,o[0],"min");return u.forEach(p=>n.disposeIntermediateTensorInfo(p)),l}var iJ={kernelName:dd,backendName:"webgl",kernelFunc:oJ},cJ=Or+ `
2021-09-11 17:11:38 +02:00
if ( abs ( x ) > 1. ) {
2021-04-01 19:39:54 +02:00
return NAN ;
}
2021-09-11 17:11:38 +02:00
return asin ( x ) ;
2022-10-30 14:06:17 +01:00
` ,uJ=Ye({opSnippet:cJ}),lJ={kernelName:Lc,backendName:"webgl",kernelFunc:uJ},dJ=Or+"return log(x + sqrt(x * x + 1.0));",pJ=Ye({opSnippet:dJ}),hJ={kernelName:zc,backendName:"webgl",kernelFunc:pJ},fJ=Or+ `
2021-09-11 17:11:38 +02:00
return atan ( x ) ;
2022-10-30 14:06:17 +01:00
` ,mJ=Ye({opSnippet:fJ}),gJ={kernelName:Bc,backendName:"webgl",kernelFunc:mJ},bJ=oI+ `
2021-09-11 17:11:38 +02:00
return atan ( a , b ) ;
2022-10-30 14:06:17 +01:00
` ,yJ= `
2021-09-11 17:11:38 +02:00
vec4 result = atan ( a , b ) ;
2022-10-09 19:40:33 +02:00
bvec4 isNaNA = isnan ( a ) ;
bvec4 isNaNB = isnan ( b ) ;
bvec4 isNaN = bvec4 ( isNaNA . x || isNaNB . x , isNaNA . y || isNaNB . y , isNaNA . z || isNaNB . z , isNaNA . w || isNaNB . w ) ;
2022-10-30 14:06:17 +01:00
` +cp+ `
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,vJ=dn({opSnippet:bJ,packedOpSnippet:yJ}),xJ={kernelName:Vc,backendName:"webgl",kernelFunc:vJ},wJ=Or+ `
2021-09-11 17:11:38 +02:00
if ( ( x < - 1.0 ) || ( x > 1.0 ) ) return NAN ;
2022-10-30 14:06:17 +01:00
return ( log ( 1.0 + x ) - log ( 1.0 - x ) ) / 2.0 ; ` ,IJ=Ye({opSnippet:wJ}),kJ={kernelName:Wc,backendName:"webgl",kernelFunc:IJ},id=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,c=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m= ` ( ( batch * $ { e . inHeight } + xR ) * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,g= ` ( xR * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,b="0.0";if(f||(b="-1.0 / 1e-20"),n){let C=">=";this.userCode= `
const ivec2 strides = ivec2 ( $ { o } , $ { i } ) ;
const ivec2 pads = ivec2 ( $ { d } , $ { h } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d = coords [ 3 ] ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
float avgValue = 0.0 ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { l } ;
wR += $ { c } ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { p } ;
2022-03-07 19:17:31 +01:00
wC += $ { u } ) {
2021-09-11 17:11:38 +02:00
int xC = xCCorner + wC ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float value = getX ( batch , xR , xC , d ) ;
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
2022-10-09 19:40:33 +02:00
if ( value $ { C } currMinMaxValue ) {
2021-09-11 17:11:38 +02:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
2022-10-30 14:06:17 +01:00
minMaxPosition = $ { r ? s ? m : g : ` wR * ${ p } + wC ` } ;
2021-09-11 17:11:38 +02:00
}
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( float ( minMaxPosition ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ;return}let y="max",v= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(v="avgValue / count");let x=Math.floor(a/4)*4,k=a%4,S= `
if ( $ { f } ) {
2021-09-11 17:11:38 +02:00
avgValue += dot ( values , ones ) ;
2021-04-01 19:39:54 +02:00
} else {
2022-10-30 14:06:17 +01:00
minMaxValue = $ { y } ( values , minMaxValue ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` ;this.userCode= `
2022-10-30 14:06:17 +01:00
const ivec2 strides = ivec2 ( $ { o } , $ { i } ) ;
const ivec2 pads = ivec2 ( $ { d } , $ { h } ) ;
const float initializationValue = $ { b } ;
2021-09-11 17:11:38 +02:00
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float count = 0.0 ;
float getValue ( int batch , int xR , int xC , int d ) {
if ( xC < 0 || xC >= $ { e . inWidth } ) {
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xR , xC , d ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
int batch = coords [ 0 ] ;
2021-04-01 19:39:54 +02:00
int d = coords [ 3 ] ;
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
2022-10-30 14:06:17 +01:00
vec4 minMaxValue = vec4 ( $ { b } ) ;
2021-09-11 17:11:38 +02:00
float avgValue = 0.0 ;
count = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { l } ;
wR += $ { c } ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { x } ; wC += 4 ) {
2022-03-07 19:17:31 +01:00
int xC = xCCorner + wC * $ { u } ;
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2022-03-07 19:17:31 +01:00
getValue ( batch , xR , xC + $ { u } , d ) ,
getValue ( batch , xR , xC + 2 * $ { u } , d ) ,
getValue ( batch , xR , xC + 3 * $ { u } , d )
2021-09-11 17:11:38 +02:00
) ;
2022-10-30 14:06:17 +01:00
$ { S }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
int xC = xCCorner + $ { x } ;
if ( $ { k === 1 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2022-10-30 14:06:17 +01:00
$ { S }
} else if ( $ { k === 2 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2022-03-07 19:17:31 +01:00
getValue ( batch , xR , xC + $ { u } , d ) ,
2021-09-11 17:11:38 +02:00
initializationValue ,
initializationValue
) ;
2022-10-30 14:06:17 +01:00
$ { S }
} else if ( $ { k === 3 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2022-03-07 19:17:31 +01:00
getValue ( batch , xR , xC + $ { u } , d ) ,
getValue ( batch , xR , xC + 2 * $ { u } , d ) ,
2021-09-11 17:11:38 +02:00
initializationValue
) ;
2022-10-30 14:06:17 +01:00
$ { S }
2021-04-01 19:39:54 +02:00
}
}
2022-10-30 14:06:17 +01:00
setOutput ( $ { v } ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},cI=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,c=e.strideWidth,u=e.dilationDepth,l=e.dilationHeight,p=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",v="0.0";if(y||(v="-1.0 / 1e-20"),n){let $ =">=";this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec3 strides =
2022-10-30 14:06:17 +01:00
ivec3 ( $ { o } , $ { i } , $ { c } ) ;
const ivec3 pads = ivec3 ( $ { m } , $ { g } , $ { b } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
for ( int wD = 0 ; wD < $ { d } ;
2022-03-07 19:17:31 +01:00
wD += $ { u } ) {
2021-09-11 17:11:38 +02:00
int xD = xDCorner + wD ;
if ( xD < 0 || xD >= $ { e . inDepth } ) {
continue ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for ( int wR = 0 ; wR < $ { h } ;
2022-10-30 14:06:17 +01:00
wR += $ { l } ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { f } ;
wC += $ { p } ) {
2021-09-11 17:11:38 +02:00
int xC = xCCorner + wC ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float value = getX ( batch , xD , xR , xC , ch ) ;
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
2022-10-30 14:06:17 +01:00
if ( value $ { $ } currMinMaxValue ) {
2021-09-11 17:11:38 +02:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
2022-10-30 14:06:17 +01:00
minMaxPosition = $ { r ? s ? ` (((batch * ${ e . inDepth } + xD) * ${ e . inHeight } + xR) * ${ e . inWidth } + xC) * ${ e . inChannels } + ch ` : ` ((xD * ${ e . inHeight } + xR) * ${ e . inWidth } + xC) * ${ e . inChannels } + ch ` : ` wD * ${ h } * ${ f } +
wR * $ { f } + wC ` };
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput ( float ( minMaxPosition ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ;return}let x="max",k= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(k="avgValue / count");let S=Math.floor(a/4)*4,C=a%4,E= `
if ( $ { y } ) {
2021-09-11 17:11:38 +02:00
avgValue += dot ( values , ones ) ;
} else {
2022-10-30 14:06:17 +01:00
minMaxValue = $ { x } ( values , minMaxValue ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` ;this.userCode= `
const ivec3 strides =
2022-10-30 14:06:17 +01:00
ivec3 ( $ { o } , $ { i } , $ { c } ) ;
const ivec3 pads = ivec3 ( $ { m } , $ { g } , $ { b } ) ;
const float initializationValue = $ { v } ;
2021-09-11 17:11:38 +02:00
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float count = 0.0 ;
float getValue ( int batch , int xD , int xR , int xC , int ch ) {
if ( xC < 0 || xC >= $ { e . inWidth } ) {
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xD , xR , xC , ch ) ;
}
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2022-10-30 14:06:17 +01:00
vec4 minMaxValue = vec4 ( $ { v } ) ;
2021-09-11 17:11:38 +02:00
float avgValue = 0.0 ;
count = 0.0 ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
for ( int wD = 0 ; wD < $ { d } ;
2022-03-07 19:17:31 +01:00
wD += $ { u } ) {
2021-09-11 17:11:38 +02:00
int xD = xDCorner + wD ;
if ( xD < 0 || xD >= $ { e . inDepth } ) {
continue ;
}
for ( int wR = 0 ; wR < $ { h } ;
2022-10-30 14:06:17 +01:00
wR += $ { l } ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { S } ; wC += 4 ) {
int xC = xCCorner + wC * $ { p } ;
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2022-10-30 14:06:17 +01:00
getValue ( batch , xD , xR , xC + $ { p } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { p } , ch ) ,
getValue ( batch , xD , xR , xC + 3 * $ { p } , ch )
2021-09-11 17:11:38 +02:00
) ;
2022-10-09 19:40:33 +02:00
$ { E }
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
int xC = xCCorner + $ { S } ;
2022-10-09 19:40:33 +02:00
if ( $ { C === 1 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2022-10-09 19:40:33 +02:00
$ { E }
} else if ( $ { C === 2 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2022-10-30 14:06:17 +01:00
getValue ( batch , xD , xR , xC + $ { p } , ch ) ,
2021-09-11 17:11:38 +02:00
initializationValue ,
initializationValue
) ;
2022-10-09 19:40:33 +02:00
$ { E }
} else if ( $ { C === 3 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2022-10-30 14:06:17 +01:00
getValue ( batch , xD , xR , xC + $ { p } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { p } , ch ) ,
2021-09-11 17:11:38 +02:00
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2022-10-09 19:40:33 +02:00
$ { E }
2021-04-01 19:39:54 +02:00
}
}
2022-10-30 14:06:17 +01:00
setOutput ( $ { k } ) ;
2021-04-01 19:39:54 +02:00
}
}
2022-10-30 14:06:17 +01:00
` }};function SJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Yu(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,u=1;w.assert(N.eitherStridesOrDilationsAreOne(o,u),()=> ` Error in avgPool : Either strides or dilations must be 1. Got strides $ { o } and dilations '${u}' ` );let l=N.computePool2DInfo(s.shape,a,o,u,i,c);if(l.filterWidth===1&&l.filterHeight===1&&w.arraysEqual(l.inShape,l.outShape))return sr({inputs:{x:s},backend:n});let p=new id(l,"avg",!1);return n.runWebGLProgram(p,[s],"float32")}var TJ={kernelName:vo,backendName:"webgl",kernelFunc:SJ};function CJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:u}=r,l=[1,1,1],p=N.computePool3DInfo(s.shape,a,o,l,i,c,u),d=new cI(p,"avg",!1);return n.runWebGLProgram(d,[s],"float32")}var NJ={kernelName:pd,backendName:"webgl",kernelFunc:CJ},_J=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=i-1-e.padInfo.top,l=c-1-e.padInfo.left,p=1/(t*n);this.userCode= `
const ivec2 pads = ivec2 ( $ { u } , $ { l } ) ;
const float avgMultiplier = float ( $ { p } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { i } ;
wR += $ { a } ) {
float dyR = float ( dyRCorner + wR ) / $ { r } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2021-04-01 19:39:54 +02:00
continue ;
}
int idyR = int ( dyR ) ;
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { c } ;
wC += $ { o } ) {
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2021-04-01 19:39:54 +02:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( b , idyR , idyC , d ) ;
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier ;
2021-04-01 19:39:54 +02:00
}
}
setOutput ( dotProd ) ;
}
2022-10-30 14:06:17 +01:00
` }},EJ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,h=l-1-e.padInfo.front,f=p-1-e.padInfo.top,m=d-1-e.padInfo.left,g=1/(t*n*r);this.userCode= `
const ivec3 pads = ivec3 ( $ { h } , $ { f } , $ { m } ) ;
2021-09-11 17:11:38 +02:00
const float avgMultiplier = float ( $ { g } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
2021-09-11 17:11:38 +02:00
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
2021-04-01 19:39:54 +02:00
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int wD = 0 ; wD < $ { l } ;
wD += $ { i } ) {
float dyD = float ( dyDCorner + wD ) / $ { s } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
2021-04-01 19:39:54 +02:00
continue ;
}
int idyD = int ( dyD ) ;
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { p } ;
wR += $ { c } ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
2021-04-01 19:39:54 +02:00
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { d } ;
2022-03-07 19:17:31 +01:00
wC += $ { u } ) {
2022-10-30 14:06:17 +01:00
float dyC = float ( dyCCorner + wC ) / $ { o } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2021-04-01 19:39:54 +02:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier ;
2021-04-01 19:39:54 +02:00
}
}
}
setOutput ( dotProd ) ;
}
2022-10-30 14:06:17 +01:00
` }};function AJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:u,dimRoundingMode:l}=r,p=[1,1,1],d=N.computePool3DInfo(o.shape,i,c,p,u,l),h=new EJ(d);return n.runWebGLProgram(h,[s],o.dtype)}var $ J={kernelName:hf,backendName:"webgl",kernelFunc:AJ};function DJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Yu([s,a],"avgPoolGrad");let{filterSize:i,strides:c,pad:u}=r,l=N.computePool2DInfo(o.shape,i,c,1,u),p=new _J(l);return n.runWebGLProgram(p,[s],o.dtype)}var FJ={kernelName:pf,backendName:"webgl",kernelFunc:DJ};function RJ(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return rf({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var PJ={kernelName:xo,backendName:"webgl",kernelFunc:RJ},OJ=class{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,n);let o="0.0";r!=null&&(N.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";s!=null&&(N.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
float x = getXAtOutCoords ( ) ;
float mean = getMeanAtOutCoords ( ) ;
float variance = getVarianceAtOutCoords ( ) ;
2022-10-30 14:06:17 +01:00
float offset = $ { o } ;
float scale = $ { i } ;
float inv = scale * inversesqrt ( variance + float ( $ { a } ) ) ;
2021-09-11 17:11:38 +02:00
setOutput ( dot ( vec3 ( x , - mean , offset ) , vec3 ( inv , inv , 1 ) ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},MJ=class{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";r!=null&&(N.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";s!=null&&(N.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
vec4 offset = $ { o } ;
vec4 scale = $ { i } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 x = getXAtOutCoords ( ) ;
vec4 mean = getMeanAtOutCoords ( ) ;
vec4 variance = getVarianceAtOutCoords ( ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
vec4 inv = scale * inversesqrt ( variance + vec4 ( $ { a } ) ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( ( x - mean ) * inv + offset ) ;
}
2022-10-30 14:06:17 +01:00
` }},LJ=({inputs:e,backend:t,attrs:n})=>{let{x:r,mean:s,variance:a,offset:o,scale:i}=e;w.assert(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(o==null||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(i==null||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:c}=n;c==null&&(c=.001);let u=[r,s,a],l=null;o!=null&&(l=o.shape,u.push(o));let p=null;i!=null&&(p=i.shape,u.push(i));let d=q().getBool("WEBGL_PACK_NORMALIZATION")?new MJ(r.shape,s.shape,a.shape,l,p,c):new OJ(r.shape,s.shape,a.shape,l,p,c);return t.runWebGLProgram(d,u,u[0].dtype)},zJ={kernelName:Ro,backendName:"webgl",kernelFunc:LJ},BJ=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=mt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=WJ(this.rank),r,s=e.map((a,o)=> ` sourceLoc . $ { yv [ o ] } = start [ $ { o } ] + coords . $ { yv [ o ] } ; ` );r= `
2021-09-11 17:11:38 +02:00
$ { t } sourceLoc ;
$ { t } coords = getOutputCoords ( ) ;
2022-10-30 14:06:17 +01:00
$ { s . join ( `
2021-09-11 17:11:38 +02:00
` )}
` ,this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { r }
2021-09-11 17:11:38 +02:00
setOutput ( getSource ( $ { n } ) ) ;
}
2022-10-30 14:06:17 +01:00
` }},yv=["x","y","z","w","u","v"];function WJ(e){if(e===1)return"sourceLoc";if(e<=6)return yv.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error( ` Slicing for rank $ { e } is not yet supported ` )}var VJ=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=mt(this.rank),n=Tn("coords",this.rank),r=Tn("sourceLoc",this.rank),s=this.rank===1?"sourceLoc": ` vec2 ( $ { r . slice ( - 2 ) . join ( ) } ) ` ,a= ` getChannel ( getSource ( $ { r . join ( ) } ) , $ { s } ) ` ,o= `
result . x = $ { a } ;
2021-09-11 17:11:38 +02:00
if ( ++ $ { n [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
2022-10-30 14:06:17 +01:00
++ $ { r [ this . rank - 1 ] } ;
result . y = $ { a } ;
-- $ { r [ this . rank - 1 ] } ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ,i=this.rank===1?"": `
2021-09-11 17:11:38 +02:00
-- $ { n [ this . rank - 1 ] } ;
if ( ++ $ { n [ this . rank - 2 ] } < $ { e [ this . rank - 2 ] } ) {
2022-10-30 14:06:17 +01:00
++ $ { r [ this . rank - 2 ] } ;
result . z = $ { a } ;
2021-09-11 17:11:38 +02:00
if ( ++ $ { n [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
2022-10-30 14:06:17 +01:00
++ $ { r [ this . rank - 1 ] } ;
result . w = $ { a } ;
2021-09-11 17:11:38 +02:00
}
}
2022-10-30 14:06:17 +01:00
` ,c=this.rank<=4? ` sourceLoc = coords +
$ { t } ( $ { e . map ( ( u , l ) => ` start[ ${ l } ] ` ) . join ( ) } ) ; ` :e.map((u,l)=> ` $ { r [ l ] } = $ { n [ l ] } + start [ $ { l } ] ; ` ).join( `
2021-09-11 17:11:38 +02:00
` );this.userCode= `
void main ( ) {
$ { t } coords = getOutputCoords ( ) ;
$ { t } sourceLoc ;
2022-10-30 14:06:17 +01:00
$ { c }
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2022-10-18 13:23:49 +02:00
$ { o }
2022-10-30 14:06:17 +01:00
$ { i }
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
}
2022-10-30 14:06:17 +01:00
` }};function UJ(e,t,n,r){let s=r.texData.get(e.dataId),a=r.makeTensorInfo(n,e.dtype),o=r.texData.get(a.dataId);Object.assign(o,s),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=qt.computeFlatOffset(t,w.computeStrides(e.shape));s.slice&&(i+=s.slice.flatOffset),o.slice={flatOffset:i,origDataId:s.slice&&s.slice.origDataId||e.dataId};let c=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,c+1),a}function nl(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,c]=qt.parseSliceParams(s,a,o);if(qt.assertParamsValid(s,i,c),w.sizeFromShape(c)===0)return n.makeTensorInfo(c,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||s.dtype==="string"){let p=n.texData.get(s.dataId),d=R9(p.values,i,c,s.shape,s.dtype);return n.makeTensorInfo(c,s.dtype,d)}let{isPacked:u}=n.texData.get(s.dataId),l=qt.isSliceContinous(s.shape,i,c);if(u||!l){let p=q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new VJ(c):new BJ(c),d=[i];return n.runWebGLProgram(p,[s],s.dtype,d)}return n.uploadToGPU(s.dataId),UJ(s,i,c,n)}var GJ={kernelName:Su,backendName:"webgl",kernelFunc:nl},HJ=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;w.assert(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,v)=>y*v),c=N.getReshaped(s.shape,a,i),u=N.getPermuted(c.length,a.length),l=N.getReshapedPermuted(s.shape,a,i),p=N.getSliceBeginCoords(o,a.length),d=N.getSliceSize(l,o,a.length),h=[],f=he({inputs:{x:s},backend:n,attrs:{shape:c}}),m=Nn({inputs:{x:f},backend:n,attrs:{perm:u}}),g=he({inputs:{x:m},backend:n,attrs:{shape:l}}),b=nl({inputs:{x:g},backend:n,attrs:{begin:p,size:d}});return h.push(f),h.push(m),h.push(g),h.forEach(y=>n.disposeIntermediateTensorInfo(y)),b},qJ={kernelName:Uc,backendName:"webgl",kernelFunc:HJ};function jJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.readSync(s.dataId),c=n.readSync(a.dataId),u=oE(i,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}var KJ={kernelName:ff,backendName:"webgl",kernelFunc:jJ};function XJ(e){let{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),o=n.readSync(s.dataId),i=N.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var YJ={kernelName:mf,backendName:"webgl",kernelFunc:XJ},ZJ="return float(a != b);",wE=dn({opSnippet:ZJ,cpuKernelImpl:T9,dtype:"bool"}),JJ={kernelName:hu,backendName:"webgl",kernelFunc:wE};function lp(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return sr({inputs:{x:s.complexTensorInfos.real},backend:n})}var QJ={kernelName:Lf,backendName:"webgl",kernelFunc:lp},eQ="return float(int(x));";function tQ(e,t){let n=new Ns(e.shape,eQ),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function vv(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return sr({inputs:{x:s},backend:n});let o=kt(s.shape),i=vv({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),c=Ea({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),c}if(s.dtype==="complex64"){let o=lp({inputs:{input:s},backend:n}),i=vv({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=sr({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(n.shouldExecuteOnCPU([s])){let o=n.texData.get(s.dataId).values,[i,c,u]=a9(o,s.shape,s.dtype,a);return n.makeTensorInfo(i,c,u)}if(a==="int32")return tQ(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),c=wE({inputs:{a:s,b:o},backend:n});return n.disposeIntermediateTensorInfo(o),c}throw new Error( ` Error in Cast : failed to cast $ { s . dtype } to $ { a } ` )}var nQ={kernelName:wo,backendName:"webgl",kernelFunc:vv},T1="return ceil(x);",rQ=Ye({opSnippet:T1,packedOpSnippet:T1,cpuKernelImpl:o9}),sQ={kernelName:Io,backendName:"webgl",kernelFunc:rQ},aQ=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"max
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
float value = getAAtOutCoords ( ) ;
if ( isnan ( value ) ) {
setOutput ( value ) ;
return ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( clamp ( value , minVal , maxVal ) ) ;
}
2022-10-30 14:06:17 +01:00
` }},oQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
vec4 value = getAAtOutCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( any ( isnan ( value ) ) ) {
setOutput ( value ) ;
return ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( clamp ( value , vec4 ( minVal ) , vec4 ( maxVal ) ) ) ;
}
2022-10-30 14:06:17 +01:00
` }};function iQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i;q().getBool("WEBGL_PACK_CLIP")?i=new oQ(s.shape):i=new aQ(s.shape);let c=[[a],[o]];return n.runWebGLProgram(i,[s],s.dtype,c)}var cQ={kernelName:ya,backendName:"webgl",kernelFunc:iQ},uQ=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
float re = abs ( getRealAtOutCoords ( ) ) ;
float im = abs ( getImagAtOutCoords ( ) ) ;
float mx = max ( re , im ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput (
mx == 0.0 ? 0.0 : mx * length ( vec2 ( 1 , min ( re , im ) / mx ) )
) ;
}
2022-10-30 14:06:17 +01:00
` }};function C1(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function lQ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new uQ(r.shape),o=[C1(r,s.complexTensorInfos.real),C1(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var dQ={kernelName:hd,backendName:"webgl",kernelFunc:lQ},pQ=class{constructor(e){this.outputShape=[],this.outputShape=N.computeOutShape(e,1),this.variableNames=e.map((a,o)=> ` T$ { o } ` );let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[ ` if ( yC < $ { t [ 0 ] } ) setOutput ( getT0 ( yR , yC ) ) ; ` ];for(let a=1;a<t.length;a++){let o=t[a-1];n.push( ` else if ( yC < $ { t [ a ] } ) setOutput ( getT$ { a } ( yR , yC - $ { o } ) ) ; ` )}let r=t.length,s=t[t.length-1];n.push( ` else setOutput ( getT$ { r } ( yR , yC - $ { s } ) ) ; ` ),this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int yR = coords . x ;
int yC = coords . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { n . join ( `
` )}
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},hQ=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=N.computeOutShape(e,t);let n=this.outputShape,r=n.length,s=mt(r),a=Tn("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((f,m)=> ` T$ { m } ` );let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let c=o[t],u=o.slice(-2),l=o.join(),p= ` if ( $ { c } < $ { i [ 0 ] } ) {
2021-09-11 17:11:38 +02:00
return getChannel (
2022-10-30 14:06:17 +01:00
getT0 ( $ { l } ) , vec2 ( $ { u . join ( ) } ) ) ;
} ` ;for(let f=1;f<i.length;f++){let m=i[f-1];p+= `
if ( $ { c } < $ { i [ f ] } && $ { c } >= $ { i [ f - 1 ] } ) {
2021-09-11 17:11:38 +02:00
return getChannel (
2022-10-30 14:06:17 +01:00
getT$ { f } ( $ { yh ( o , c , m ) } ) ,
vec2 ( $ { yh ( u , c , m ) } ) ) ;
} ` }let d=i.length,h=i[i.length-1];p+= `
2021-09-11 17:11:38 +02:00
return getChannel (
2022-10-30 14:06:17 +01:00
getT$ { d } ( $ { yh ( o , c , h ) } ) ,
vec2 ( $ { yh ( u , c , h ) } ) ) ; ` ,this.userCode= `
float getValue ( $ { o . map ( f => "int " + f ) } ) {
$ { p }
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { s } coords = getOutputCoords ( ) ;
vec4 result = vec4 ( getValue ( $ { a } ) , 0. , 0. , 0. ) ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
$ { a [ r - 1 ] } = $ { a [ r - 1 ] } + 1 ;
if ( $ { a [ r - 1 ] } < $ { n [ r - 1 ] } ) {
result . g = getValue ( $ { a } ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
$ { a [ r - 2 ] } = $ { a [ r - 2 ] } + 1 ;
if ( $ { a [ r - 2 ] } < $ { n [ r - 2 ] } ) {
result . a = getValue ( $ { a } ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
$ { a [ r - 1 ] } = $ { a [ r - 1 ] } - 1 ;
if ( $ { a [ r - 2 ] } < $ { n [ r - 2 ] } &&
$ { a [ r - 1 ] } < $ { n [ r - 1 ] } ) {
result . b = getValue ( $ { a } ) ;
2021-09-11 17:11:38 +02:00
}
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function yh(e,t,n){let r=e.indexOf(t);return e.map((a,o)=>o===r? ` $ { a } - $ { n } ` :a).join()}function Qm(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return sr({inputs:{x:s.complexTensorInfos.imag},backend:n})}var fQ={kernelName:_f,backendName:"webgl",kernelFunc:Qm};function Vl(e,t,n){let r=e[0].dtype;if(r==="complex64"){let p=e.map(g=>lp({inputs:{input:g},backend:n})),d=e.map(g=>Qm({inputs:{input:g},backend:n})),h=Vl(p,t,n),f=Vl(d,t,n),m=Ea({inputs:{real:h,imag:f},backend:n});return p.forEach(g=>n.disposeIntermediateTensorInfo(g)),d.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),m}let s=n.shouldExecuteOnCPU(e);if(r==="string"&&(s=!0),s){let p=e.map(y=>{let x=[-1,w.sizeFromShape(y.shape.slice(t))];return he({inputs:{x:y},backend:n,attrs:{shape:x}})}),d=p.map(y=>({vals:n.readSync(y.dataId),shape:y.shape})),h=N.computeOutShape(p.map(y=>y.shape),1),f=p[0].shape[0]===1,m=i9(d,h,r,f),g=N.computeOutShape(e.map(y=>y.shape),t),b=n.makeTensorInfo(g,r,m);return p.forEach(y=>n.disposeIntermediateTensorInfo(y)),b}let a=q().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(e.length>a){let p=[];for(let h=0;h<e.length;h+=a){let f=e.slice(h,h+a);p.push(Vl(f,t,n))}let d=Vl(p,t,n);for(let h of p)n.disposeIntermediateTensorInfo(h);return d}if(q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let p=new hQ(e.map(d=>d.shape),t);return n.runWebGLProgram(p,e,r)}let{tensors2D:o,outShape:i}=mQ(e,t,n),c=new pQ(o.map(p=>p.shape)),u=n.runWebGLProgram(c,o,r);o.forEach(p=>n.disposeIntermediateTensorInfo(p));let l=he({inputs:{x:u},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(u),l}function mQ(e,t,n){let r=N.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>he({inputs:{x:a},attrs:{shape:[-1,w.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:r}}function IE(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=t.map(u=>u.shape);N.assertParamsConsistent(o,a);let i=N.computeOutShape(t.map(u=>u.shape),a);if(w.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let c=t.filter(u=>w.sizeFromShape(u.shape)>0);return c.length===1?sr({inputs:{x:c[0]},backend:n}):Vl(c,a,n)}var gQ={kernelName:Gc,backendName:"webgl",kernelFunc:IE},kE=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,c=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,b=m?2:3,y=m?3:1,v="",x="";n&&(r?v= ` float activation ( float a ) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
2022-10-30 14:06:17 +01:00
} ` :s?v= ` float activation ( float a ) {
2021-09-11 17:11:38 +02:00
float b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
2022-10-30 14:06:17 +01:00
} ` :v= `
2021-09-11 17:11:38 +02:00
float activation ( float x ) {
$ { n }
}
2022-10-30 14:06:17 +01:00
` ,x="result = activation(result);");let k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { v }
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
const ivec2 strides = ivec2 ( $ { i } , $ { c } ) ;
const ivec2 pads = ivec2 ( $ { a } , $ { o } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
int batch = coords [ 0 ] ;
2022-10-30 14:06:17 +01:00
int d2 = coords [ $ { y } ] ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner =
2022-10-30 14:06:17 +01:00
ivec2 ( coords [ $ { g } ] , coords [ $ { b } ] ) * strides - pads ;
2021-09-11 17:11:38 +02:00
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { p } ; wR ++ ) {
2022-03-07 19:17:31 +01:00
int xR = xRCorner + wR * $ { u } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { d } ; wC ++ ) {
int xC = xCCorner + wC * $ { l } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int d1 = 0 ; d1 < $ { h } ; d1 += 4 ) {
vec4 wValues = vec4 (
getW ( wR , wC , d1 , d2 ) ,
getW ( wR , wC , d1 + 1 , d2 ) ,
getW ( wR , wC , d1 + 2 , d2 ) ,
getW ( wR , wC , d1 + 3 , d2 )
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { m } ) {
2021-09-11 17:11:38 +02:00
vec4 xValues = vec4 (
getX ( batch , xR , xC , d1 ) ,
getX ( batch , xR , xC , d1 + 1 ) ,
getX ( batch , xR , xC , d1 + 2 ) ,
getX ( batch , xR , xC , d1 + 3 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec4 xValues = vec4 (
getX ( batch , d1 , xR , xC ) ,
getX ( batch , d1 + 1 , xR , xC ) ,
getX ( batch , d1 + 2 , xR , xC ) ,
getX ( batch , d1 + 3 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
}
2021-03-31 13:01:22 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { f === 1 } ) {
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { m } ) {
2021-09-11 17:11:38 +02:00
dotProd +=
getX ( batch , xR , xC , $ { h } ) *
getW ( wR , wC , $ { h } , d2 ) ;
} else {
dotProd +=
getX ( batch , $ { h } , xR , xC ) *
getW ( wR , wC , $ { h } , d2 ) ;
}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
} else if ( $ { f === 2 } ) {
2021-09-11 17:11:38 +02:00
vec2 wValues = vec2 (
getW ( wR , wC , $ { h } , d2 ) ,
getW ( wR , wC , $ { h } + 1 , d2 )
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { m } ) {
2021-09-11 17:11:38 +02:00
vec2 xValues = vec2 (
getX ( batch , xR , xC , $ { h } ) ,
getX ( batch , xR , xC , $ { h } + 1 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec2 xValues = vec2 (
getX ( batch , $ { h } , xR , xC ) ,
getX ( batch , $ { h } + 1 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
} else if ( $ { f === 3 } ) {
2021-09-11 17:11:38 +02:00
vec3 wValues = vec3 (
getW ( wR , wC , $ { h } , d2 ) ,
getW ( wR , wC , $ { h } + 1 , d2 ) ,
getW ( wR , wC , $ { h } + 2 , d2 )
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { m } ) {
2021-09-11 17:11:38 +02:00
vec3 xValues = vec3 (
getX ( batch , xR , xC , $ { h } ) ,
getX ( batch , xR , xC , $ { h } + 1 ) ,
getX ( batch , xR , xC , $ { h } + 2 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec3 xValues = vec3 (
getX ( batch , $ { h } , xR , xC ) ,
getX ( batch , $ { h } + 1 , xR , xC ) ,
getX ( batch , $ { h } + 2 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd ;
2022-10-30 14:06:17 +01:00
$ { k }
$ { x }
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
}
2022-10-30 14:06:17 +01:00
` }},bQ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,l=e.filterDepth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode= `
const ivec3 strides = ivec3 ( $ { s } , $ { a } , $ { o } ) ;
const ivec3 pads = ivec3 ( $ { t } , $ { n } , $ { r } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d2 = coords . u ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xFRCCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xFCorner = xFRCCorner . x ;
int xRCorner = xFRCCorner . y ;
int xCCorner = xFRCCorner . z ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int wF = 0 ; wF < $ { l } ; wF ++ ) {
int xF = xFCorner + wF * $ { i } ;
2021-09-11 17:11:38 +02:00
if ( xF < 0 || xF >= $ { e . inDepth } ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { p } ; wR ++ ) {
int xR = xRCorner + wR * $ { c } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { d } ; wC ++ ) {
2022-03-07 19:17:31 +01:00
int xC = xCCorner + wC * $ { u } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int d1 = 0 ; d1 < $ { h } ; d1 += 4 ) {
vec4 xValues = vec4 (
getX ( batch , xF , xR , xC , d1 ) ,
getX ( batch , xF , xR , xC , d1 + 1 ) ,
getX ( batch , xF , xR , xC , d1 + 2 ) ,
getX ( batch , xF , xR , xC , d1 + 3 )
) ;
vec4 wValues = vec4 (
getW ( wF , wR , wC , d1 , d2 ) ,
getW ( wF , wR , wC , d1 + 1 , d2 ) ,
getW ( wF , wR , wC , d1 + 2 , d2 ) ,
getW ( wF , wR , wC , d1 + 3 , d2 )
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dot ( xValues , wValues ) ;
}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { f === 1 } ) {
2021-09-11 17:11:38 +02:00
dotProd +=
getX ( batch , xF , xR , xC , $ { h } ) *
getW ( wF , wR , wC , $ { h } , d2 ) ;
2022-10-30 14:06:17 +01:00
} else if ( $ { f === 2 } ) {
2021-09-11 17:11:38 +02:00
vec2 xValues = vec2 (
getX ( batch , xF , xR , xC , $ { h } ) ,
getX ( batch , xF , xR , xC , $ { h } + 1 )
) ;
vec2 wValues = vec2 (
getW ( wF , wR , wC , $ { h } , d2 ) ,
getW ( wF , wR , wC , $ { h } + 1 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
2022-10-30 14:06:17 +01:00
} else if ( $ { f === 3 } ) {
2021-09-11 17:11:38 +02:00
vec3 xValues = vec3 (
getX ( batch , xF , xR , xC , $ { h } ) ,
getX ( batch , xF , xR , xC , $ { h } + 1 ) ,
getX ( batch , xF , xR , xC , $ { h } + 2 )
) ;
vec3 wValues = vec3 (
getW ( wF , wR , wC , $ { h } , d2 ) ,
getW ( wF , wR , wC , $ { h } + 1 , d2 ) ,
getW ( wF , wR , wC , $ { h } + 2 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},SE=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Dn(this.outputShape.length);let a=e.padInfo.left,o=e.strideWidth,i=e.dilationWidth,c=e.filterHeight,u=e.filterWidth,l=u,p= `
2022-08-24 14:21:15 +02:00
int xR ; int xC ; int xCOffset ;
2022-10-30 14:06:17 +01:00
vec4 wTexel ; vec4 previous ; vec4 final ; ` ;for(let m=0;m<u;m++)p+= `
vec4 xTexelC$ { m * 2 } ;
int xTexelC$ { m * 2 } Ready ;
vec4 xTexelC$ { m * 2 + 1 } ;
int xTexelC$ { m * 2 + 1 } Ready ;
vec4 xC$ { m } ; ` ;p+= `
for ( int r = 0 ; r < $ { c } ; r ++ ) {
2022-08-24 14:21:15 +02:00
for ( int d1 = 0 ; d1 < $ { e . inChannels } ; d1 += 2 ) {
2022-10-30 14:06:17 +01:00
` ;for(let m=0;m<u;m++)p+= `
xTexelC$ { m * 2 } = vec4 ( 0.0 ) ;
xTexelC$ { m * 2 } Ready = 0 ;
xTexelC$ { m * 2 + 1 } = vec4 ( 0.0 ) ;
xTexelC$ { m * 2 + 1 } Ready = 0 ;
xC$ { m } = vec4 ( 0.0 ) ; ` ;p+= `
2022-08-24 14:21:15 +02:00
xR = xRCorner + r * dilations [ 0 ] ;
if ( xR >= 0 && xR < inDims [ 0 ] ) {
2022-10-30 14:06:17 +01:00
` ;for(let m=0;m<(l+1)/2;m++){let g=m*2;if(p+= `
xC = xCCorner + $ { g * i } ;
` ,o===1){if(g<u&&(a%2===1?(p+= `
2022-08-24 14:21:15 +02:00
xCOffset = xC + 1 ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { g } Ready == 0 ) {
xTexelC$ { g } = getX ( batch , xR , xCOffset , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
xTexelC$ { g } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { g } Ready = 1 ;
}
2022-10-30 14:06:17 +01:00
` ,i===1&&g>0?p+= `
2022-08-24 14:21:15 +02:00
xC$ { g } = vec4 ( xTexelC$ { g - 2 } . zw , xTexelC$ { g } . xy ) ;
2022-10-30 14:06:17 +01:00
` :p+= `
2022-08-24 14:21:15 +02:00
xCOffset = xC + 1 - 2 ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
previous = getX ( batch , xR , xCOffset , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
previous . zw = vec2 ( 0.0 ) ;
}
xC$ { g } = vec4 ( previous . zw , xTexelC$ { g } . xy ) ;
} else {
xC$ { g } = vec4 ( 0.0 , 0.0 , xTexelC$ { g } . xy ) ;
}
2022-10-30 14:06:17 +01:00
` ):p+= `
2022-08-24 14:21:15 +02:00
if ( xC >= 0 && xC < inDims [ 1 ] && xTexelC$ { g } Ready == 0 ) {
xTexelC$ { g } = getX ( batch , xR , xC , d1 ) ;
if ( xC + 1 >= inDims [ 1 ] ) {
xTexelC$ { g } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { g } Ready = 1 ;
}
xC$ { g } = xTexelC$ { g } ;
2022-10-30 14:06:17 +01:00
` ,g+1<u)){let b=a%2===0?w.nearestLargerEven(i):i;i%2===0&&a%2===1||i%2!==0&&a%2!==1?(p+= `
xCOffset = xC + imod ( pads [ 1 ] , 2 ) + $ { b } ;
2022-08-24 14:21:15 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { g + 1 } Ready == 0 ) {
xTexelC$ { g + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
xTexelC$ { g + 1 } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { g + 1 } Ready = 1 ;
}
2022-10-30 14:06:17 +01:00
` ,i>1?p+= `
2022-08-24 14:21:15 +02:00
xCOffset -= 2 ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
previous = getX ( batch , xR , xCOffset , d1 ) ;
xC$ { g + 1 } = vec4 ( previous . zw , xTexelC$ { g + 1 } . xy ) ;
} else {
xC$ { g + 1 } = vec4 ( 0.0 , 0.0 , xTexelC$ { g + 1 } . xy ) ;
}
2022-10-30 14:06:17 +01:00
` :p+= `
2022-08-24 14:21:15 +02:00
xC$ { g + 1 } = vec4 ( xTexelC$ { g } . zw , xTexelC$ { g + 1 } . xy ) ;
2022-10-30 14:06:17 +01:00
` ):b===1?p+= `
2022-08-24 14:21:15 +02:00
xC$ { g + 1 } = xTexelC$ { g } ;
2022-10-30 14:06:17 +01:00
` :p+= `
xCOffset = xC + $ { b } ;
2022-08-24 14:21:15 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { g + 1 } Ready == 0 ) {
xTexelC$ { g + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
if ( xCOffset + 1 >= inDims [ 1 ] ) {
xTexelC$ { g + 1 } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { g + 1 } Ready = 1 ;
}
xC$ { g + 1 } = xTexelC$ { g + 1 } ;
2022-10-30 14:06:17 +01:00
` }}else g<u&&(a%2===1?(p+= `
2022-08-24 14:21:15 +02:00
xCOffset = xC + 1 - strides [ 1 ] ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { g } Ready == 0 ) {
xTexelC$ { g } = getX ( batch , xR , xCOffset , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
xTexelC$ { g } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { g } Ready = 1 ;
}
if ( xC + 1 >= 0 && xC + 1 < inDims [ 1 ] && xTexelC$ { g + 1 } Ready == 0 ) {
xTexelC$ { g + 1 } = getX ( batch , xR , xC + 1 , d1 ) ;
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xC + 2 >= inDims [ 1 ] ) {
xTexelC$ { g + 1 } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { g + 1 } Ready = 1 ;
}
xC$ { g } = vec4 ( xTexelC$ { g } . zw , xTexelC$ { g + 1 } . zw ) ;
2022-10-30 14:06:17 +01:00
` ,g+1<u&&(p+= `
2022-08-24 14:21:15 +02:00
final = vec4 ( 0.0 ) ;
xCOffset = xC + 1 + strides [ 1 ] ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
final = getX ( batch , xR , xCOffset , d1 ) ;
}
xC$ { g + 1 } = vec4 ( xTexelC$ { g + 1 } . xy , final . xy ) ;
2022-10-30 14:06:17 +01:00
` )):(p+= `
2022-08-24 14:21:15 +02:00
if ( xC >= 0 && xC < inDims [ 1 ] && xTexelC$ { g } Ready == 0 ) {
xTexelC$ { g } = getX ( batch , xR , xC , d1 ) ;
if ( xC + 1 >= inDims [ 1 ] ) {
xTexelC$ { g } . zw = vec2 ( 0.0 ) ;
}
xTexelC$ { g } Ready = 1 ;
}
xCOffset = xC + strides [ 1 ] ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { g + 1 } Ready == 0 ) {
xTexelC$ { g + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
if ( xCOffset + 1 >= inDims [ 1 ] ) {
xTexelC$ { g + 1 } . zw = vec2 ( 0. ) ;
}
xTexelC$ { g + 1 } Ready = 1 ;
}
xC$ { g } = vec4 (
xTexelC$ { g } . xy , xTexelC$ { g + 1 } . xy ) ;
2022-10-30 14:06:17 +01:00
` ,g+1<u&&(p+= `
2022-08-24 14:21:15 +02:00
xC$ { g + 1 } = vec4 ( xTexelC$ { g } . zw , xTexelC$ { g + 1 } . zw ) ;
2022-10-30 14:06:17 +01:00
` )));g<u&&(p+= `
2022-08-24 14:21:15 +02:00
wTexel = getW ( r , $ { g } , d1 , d2 ) ;
dotProd += xC$ { g } . xxzz * vec4 ( wTexel . xy , wTexel . xy ) ;
if ( d1 + 1 < $ { e . inChannels } ) {
dotProd += xC$ { g } . yyww * vec4 ( wTexel . zw , wTexel . zw ) ;
}
2022-10-30 14:06:17 +01:00
` ,g+1<u&&(p+= `
2022-08-24 14:21:15 +02:00
wTexel = getW ( r , $ { g + 1 } , d1 , d2 ) ;
dotProd += xC$ { g + 1 } . xxzz * vec4 ( wTexel . xy , wTexel . xy ) ;
if ( d1 + 1 < $ { e . inChannels } ) {
dotProd += xC$ { g + 1 } . yyww * vec4 ( wTexel . zw , wTexel . zw ) ;
}
2022-10-30 14:06:17 +01:00
` ))}p+= `
2022-08-24 14:21:15 +02:00
}
2022-10-30 14:06:17 +01:00
` ,p+= `
2022-08-24 14:21:15 +02:00
}
2022-10-30 14:06:17 +01:00
` ,p+= `
2022-08-24 14:21:15 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let d="",h="";n&&(r?d= ` vec4 activation ( vec4 a ) {
2022-08-24 14:21:15 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
2022-10-30 14:06:17 +01:00
} ` :s?d= ` vec4 activation ( vec4 a ) {
2022-08-24 14:21:15 +02:00
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
2022-10-30 14:06:17 +01:00
} ` :d= ` vec4 activation ( vec4 x ) {
2022-08-24 14:21:15 +02:00
$ { n }
2022-10-30 14:06:17 +01:00
} ` ,h="result = activation(result);");let f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { d }
2022-08-24 14:21:15 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4 ( 0.000000000000001 ) ;
2022-10-30 14:06:17 +01:00
$ { p }
2022-08-24 14:21:15 +02:00
vec4 result = dotProd - vec4 ( 0.000000000000001 ) ;
2022-10-30 14:06:17 +01:00
$ { f }
2022-08-24 14:21:15 +02:00
$ { h }
setOutput ( result ) ;
}
2022-10-30 14:06:17 +01:00
` }},yQ=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=Dn(this.outputShape.length);let{dataFormat:n}=t,r= $ n(),s=n==="channelsLast",a=s?1:2,o=s?2:3,i=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {": ` if ( blockIndex < $ { e [ 2 ] } && pos < $ { e [ 1 ] } ) { ` ,c="";for(let u=0;u<=1;u++)for(let l=0;l<=1;l++)c+= `
blockIndex = rc . z + $ { l } ;
2022-07-25 14:23:57 +02:00
pos = rc . y + $ { u } ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { i }
2021-09-11 17:11:38 +02:00
offsetY = int ( blockIndex / outWidth ) * stride [ 0 ] - pad [ 0 ] ;
d0 = offsetY + dilation [ 0 ] * ( pos / itemsPerBlockRow ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( d0 < inputShape [ $ { a } ] && d0 >= 0 ) {
2021-09-11 17:11:38 +02:00
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod ( blockIndex , outWidth ) * stride [ 1 ] - pad [ 1 ] ;
d1 = offsetX + dilation [ 1 ] * ( imod ( pos , itemsPerBlockRow ) /
inChannels ) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( d1 < inputShape [ $ { o } ] && d1 >= 0 ) {
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
ch = imod ( pos , inChannels ) ;
2021-04-30 18:01:04 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { s } ) {
2021-09-11 17:11:38 +02:00
innerDims = vec2 ( d1 , ch ) ;
2022-10-30 14:06:17 +01:00
result [ $ { u * 2 + l } ] = getChannel (
2022-07-25 14:23:57 +02:00
getA ( rc . x , d0 , int ( innerDims . x ) ,
2021-09-11 17:11:38 +02:00
int ( innerDims . y ) ) , innerDims ) ;
} else {
innerDims = vec2 ( d0 , d1 ) ;
2022-10-30 14:06:17 +01:00
result [ $ { u * 2 + l } ] = getChannel (
2022-07-25 14:23:57 +02:00
getA ( rc . x , ch , int ( innerDims . x ) ,
2021-09-11 17:11:38 +02:00
int ( innerDims . y ) ) , innerDims ) ;
}
}
}
}
` ;this.userCode= `
2021-04-30 18:01:04 +02:00
void main ( ) {
2022-07-25 14:23:57 +02:00
ivec3 rc = getOutputCoords ( ) ;
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0 ) ;
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
int blockIndex , pos , offsetY , d0 , offsetX , d1 , ch ;
vec2 innerDims ;
2021-04-30 18:01:04 +02:00
2022-10-30 14:06:17 +01:00
$ { c }
2021-04-30 18:01:04 +02:00
2022-10-30 14:06:17 +01:00
$ { r . output } = result ;
2021-04-30 18:01:04 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function sf(e,t){let n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&n===1&&e[0]>1?[e[0],1]:null}function TE({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let c=e.shape,u=r.texData.get(e.dataId),l=n.inChannels,p=c[0]*c[1]*c[2],d=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,b=[];if(a!=null){let x=sf(a.shape,h);x!=null&&(a=he({inputs:{x:a},backend:r,attrs:{shape:x}}),b.push(a))}if(s!=null){let x=sf(s.shape,h);x!=null&&(s=he({inputs:{x:s},backend:r,attrs:{shape:x}}),b.push(s))}if(!((p===1||d===1)&&l>bE)&&u.isPacked&&h&&u.texture!=null&&c[2]%2!==0&&w.arraysEqual(u.shape.slice(-3),c.slice(-3))){let x=c[0]*c[1]*(c[2]+1),k={dataId:e.dataId,shape:[1,x,n.inChannels],dtype:e.dtype},S=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,w.assert(ad(u.shape,k.shape),()=> ` packed reshape $ { u . shape } to $ { k . shape } isn ' t free ` );let C=he({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(C);let E=rf({a:k,b:C,backend:r,transposeA:f,transposeB:m,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}), $ =r.texData.get(E.dataId);w.assert( $ .isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=S, $ .shape=n.outShape,g=sr({inputs:{x:E},backend:r}),g.shape=n.outShape,b.push(E)}else{let x=n.outHeight*n.outWidth,k=he({inputs:{x:e},backend:r,attrs:{shape:h?[n.batchSize,x,n.inChannels]:[n.batchSize,n.inChannels,x]}}),S=he({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),C=rf({a:h?k:S,b:h?S:k,transposeA:!h,transposeB:m,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=he({inputs:{x:C},backend:r,attrs:{shape:n.outShape}}),b.push(k),b.push(S),b.push(C)}for(let x of b)r.disposeIntermediateTensorInfo(x);return g}function CE({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:c,filterHeight:u,inChannels:l,outWidth:p,outHeight:d,dataFormat:h}=n,f=h==="channelsLast",m=c*u*l,g=d*p,b=[n.batchSize,m,g],y=!0,v=!1,x=[];if(a!=null){let H=sf(a.shape,f);H!=null&&(a=he({inputs:{x:a},backend:r,attrs:{shape:H}}),x.push(a))}if(s!=null){let H=sf(s.shape,f);H!=null&&(s=he({inputs:{x:s},backend:r,attrs:{shape:H}}),x.push(s))}let k=he({inputs:{x:t},backend:r,attrs:{shape:[1,m,w.sizeFromShape(t.shape)/m]}});x.push(k);let S=new yQ(b,n),C=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],E=r.runWebGLProgram(S,[e],"float32",C), $ =he({inputs:{x:E},backend:r,attrs:{shape:b}});x.push(E),x.push( $ );let F=s!=null,A=a!=null,R=i==="leakyrelu",T=i?od(i,!0):null,L=new gE(f? $ .shape:k.shape,f?k.shape: $ .shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],y,v,F,T,A,R),V=f?[ $ ,k]:[k, $ ];if(s&&V.push(s),A&&V.push(a),R){let H=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));V.push(H),x.push(H)}let G=r.runWebGLProgram(L,V,"float32"),j=he({inputs:{x:G},backend:r,attrs:{shape:n.outShape}});x.push(G);for(let H of x)r.disposeIntermediateTensorInfo(H);return j}function vQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:c,dilations:u,dimRoundingMode:l}=r,p=N.convertConv2DDataFormat(c),d=N.computeConv2DInfo(s.shape,a.shape,o,u,i,l,!1,p),h;if(d.filterHeight===1&&d.filterWidth===1&&d.dilationHeight===1&&d.dilationWidth===1&&d.strideHeight===1&&d.strideWidth===1&&(d.padInfo.type==="SAME"||d.padInfo.type==="VALID"))h=TE({x:s,filter:a,convInfo:d,backend:n});else if(d.strideWidth<=2&&p==="channelsLast"&&q().getBool("WEBGL_EXP_CONV")){let m=new SE(d),g=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];h=n.runWebGLProgram(m,[s,a],"float32",g)}else if(q().getBool("WEBGL_CONV_IM2COL"))h=CE({x:s,filter:a,convInfo:d,backend:n});else{let m=new kE(d);h=n.runWebGLProgram(m,[s,a],"float32")}let f=he({inputs:{x:h},backend:n,attrs:{shape:d.outShape
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int d2 = coords . w ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
2022-10-30 14:06:17 +01:00
int xR = wR + yR * $ { t } - $ { r } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
2022-10-30 14:06:17 +01:00
int xC = wC + yC * $ { n } - $ { s } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { a } ) {
2021-09-11 17:11:38 +02:00
float dyValue = getDy ( b , yR , yC , d2 ) ;
float xValue = getX ( b , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
} else {
float dyValue = getDy ( b , d2 , yR , yC ) ;
float xValue = getX ( b , d1 , xR , xC ) ;
dotProd += ( xValue * dyValue ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput ( dotProd ) ;
}
2022-10-30 14:06:17 +01:00
` }},IQ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,c=a?1:2,u=a?2:3,l=a?3:1;this.userCode= `
const ivec2 pads = ivec2 ( $ { o } , $ { i } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2022-10-30 14:06:17 +01:00
int d1 = coords [ $ { l } ] ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
ivec2 dyCorner = ivec2 ( coords [ $ { c } ] , coords [ $ { u } ] ) - pads ;
2021-09-11 17:11:38 +02:00
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
2022-10-30 14:06:17 +01:00
float dyR = float ( dyRCorner + wR ) / $ { r } . 0 ;
2021-09-11 17:11:38 +02:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2021-09-11 17:11:38 +02:00
int idyR = int ( dyR ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = $ { t } - 1 - wR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
2022-10-30 14:06:17 +01:00
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2021-09-11 17:11:38 +02:00
int idyC = int ( dyC ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = $ { n } - 1 - wC ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { a } ) {
2021-09-11 17:11:38 +02:00
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
} else {
float xValue = getDy ( batch , d2 , idyR , idyC ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},kQ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int wF = coords . x ;
int wR = coords . y ;
int wC = coords . z ;
int d1 = coords . w ;
int d2 = coords . u ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0 ;
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yF = 0 ; yF < $ { e . outDepth } ; yF ++ ) {
2022-10-30 14:06:17 +01:00
int xF = wF + yF * $ { t } - $ { s } ;
2021-09-11 17:11:38 +02:00
if ( xF < 0 || xF >= $ { e . inDepth } ) {
continue ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
2022-10-30 14:06:17 +01:00
int xR = wR + yR * $ { n } - $ { a } ;
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
2022-10-30 14:06:17 +01:00
int xC = wC + yC * $ { r } - $ { o } ;
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float dyValue = getDy ( b , yF , yR , yC , d2 ) ;
float xValue = getX ( b , xF , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},SQ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,c=n-1-e.padInfo.top,u=r-1-e.padInfo.left;this.userCode= `
const ivec3 pads = ivec3 ( $ { i } , $ { c } , $ { u } ) ;
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyFCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
float dotProd = 0.0 ;
for ( int wF = 0 ; wF < $ { t } ; wF ++ ) {
2022-10-30 14:06:17 +01:00
float dyF = float ( dyFCorner + wF ) / $ { s } . 0 ;
2021-09-11 17:11:38 +02:00
if ( dyF < 0.0 || dyF >= $ { e . outDepth } . 0 || fract ( dyF ) > 0.0 ) {
continue ;
}
int idyF = int ( dyF ) ;
int wFPerm = $ { t } - 1 - wF ;
for ( int wR = 0 ; wR < $ { n } ; wR ++ ) {
2022-10-30 14:06:17 +01:00
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
2021-09-11 17:11:38 +02:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
int wRPerm = $ { n } - 1 - wR ;
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { r } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { o } . 0 ;
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2022-10-30 14:06:17 +01:00
int wCPerm = $ { r } - 1 - wC ;
2021-09-11 17:11:38 +02:00
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
float xValue = getDy ( batch , idyF , idyR , idyC , d2 ) ;
float wValue = getW ( wFPerm , wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
}
}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function TQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:c,dimRoundingMode:u,filterShape:l}=r,p=N.convertConv2DDataFormat(c),d=N.computeConv2DInfo(s.shape,l,o,1,i,u,!1,p),h=new wQ(d);return n.runWebGLProgram(h,[s,a],"float32")}var CQ={kernelName:bf,backendName:"webgl",kernelFunc:TQ};function NQ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:c,dataFormat:u,dimRoundingMode:l}=r,p=N.convertConv2DDataFormat(u),d=N.computeConv2DInfo(o,a.shape,i,1,c,l,!1,p),h=new IQ(d);return n.runWebGLProgram(h,[s,a],"float32")}var _Q={kernelName:So,backendName:"webgl",kernelFunc:NQ};function EQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,u=N.computeConv3DInfo(s.shape,a.shape,o,c,i),l=new bQ(u);return n.runWebGLProgram(l,[s,a],"float32")}var AQ={kernelName:fd,backendName:"webgl",kernelFunc:EQ};function $ Q(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:c}=r,u=N.computeConv3DInfo(s.shape,c,o,1,i),l=new kQ(u);return n.runWebGLProgram(l,[s,a],"float32")}var DQ={kernelName:yf,backendName:"webgl",kernelFunc: $ Q};function FQ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:c}=r,u=N.computeConv3DInfo(c,a.shape,i,1,o),l=new SQ(u);return n.runWebGLProgram(l,[s,a],"float32")}var RQ={kernelName:vf,backendName:"webgl",kernelFunc:FQ},PQ=tl+ `
2021-09-11 17:11:38 +02:00
return cos ( x ) ;
2022-10-30 14:06:17 +01:00
` ,OQ=Ye({opSnippet:PQ}),MQ={kernelName:To,backendName:"webgl",kernelFunc:OQ},LQ= `
2021-09-11 17:11:38 +02:00
float e2x = exp ( - x ) ;
return ( e2x + 1.0 / e2x ) / 2.0 ;
2022-10-30 14:06:17 +01:00
` ,zQ=Ye({opSnippet:LQ}),BQ={kernelName:Co,backendName:"webgl",kernelFunc:zQ},WQ=class{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,c]=e,[u]=t,[l,p]=n;this.outputShape=[u,l,p,c];let d=r==="bilinear"?1:0,[h,f]=[ ` $ { o - 1 } . 0 ` , ` $ { i - 1 } . 0 ` ],[m,g,b]=l>1?[ ` $ { ( o - 1 ) / ( l - 1 ) } ` ,"(y2-y1) * height_ratio", ` y1 * $ { h } + float ( y ) * ( height _scale ) ` ]:["0.0","0.0", ` 0.5 * ( y1 + y2 ) * $ { h } ` ],[y,v,x]=p>1?[ ` $ { ( i - 1 ) / ( p - 1 ) } ` ,"(x2-x1) * width_ratio", ` x1 * $ { f } + float ( x ) * ( width _scale ) ` ]:["0.0","0.0", ` 0.5 * ( x1 + x2 ) * $ { f } ` ];this.userCode= `
const float height _ratio = float ( $ { m } ) ;
const float width _ratio = float ( $ { y } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int y = coords [ 1 ] ;
int x = coords [ 2 ] ;
int d = coords [ 3 ] ;
// get box vals
float y1 = getBoxes ( b , 0 ) ;
float x1 = getBoxes ( b , 1 ) ;
float y2 = getBoxes ( b , 2 ) ;
float x2 = getBoxes ( b , 3 ) ;
// get image in batch index
int bInd = round ( getBoxInd ( b ) ) ;
2022-10-30 14:06:17 +01:00
if ( bInd < 0 || bInd >= $ { a } ) {
2021-09-11 17:11:38 +02:00
return ;
2021-04-01 19:39:54 +02:00
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float height _scale = $ { g } ;
2022-10-30 14:06:17 +01:00
float width _scale = $ { v } ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
float in _y = $ { b } ;
2021-09-11 17:11:38 +02:00
if ( in _y < 0.0 || in _y > $ { h } ) {
2022-10-30 14:06:17 +01:00
setOutput ( float ( $ { s } ) ) ;
2021-09-11 17:11:38 +02:00
return ;
}
2022-10-30 14:06:17 +01:00
float in _x = $ { x } ;
if ( in _x < 0.0 || in _x > $ { f } ) {
setOutput ( float ( $ { s } ) ) ;
2021-09-11 17:11:38 +02:00
return ;
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
vec2 sourceFracIndexCR = vec2 ( in _x , in _y ) ;
2022-10-30 14:06:17 +01:00
if ( $ { d } == 1 ) {
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2 ( sourceFracIndexCR ) ;
ivec2 sourceCeilCR = ivec2 ( ceil ( sourceFracIndexCR ) ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float topLeft = getImage ( b , sourceFloorCR . y , sourceFloorCR . x , d ) ;
float bottomLeft = getImage ( b , sourceCeilCR . y , sourceFloorCR . x , d ) ;
float topRight = getImage ( b , sourceFloorCR . y , sourceCeilCR . x , d ) ;
float bottomRight = getImage ( b , sourceCeilCR . y , sourceCeilCR . x , d ) ;
vec2 fracCR = sourceFracIndexCR - vec2 ( sourceFloorCR ) ;
float top = topLeft + ( topRight - topLeft ) * fracCR . x ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracCR . x ;
float newValue = top + ( bottom - top ) * fracCR . y ;
setOutput ( newValue ) ;
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2 ( floor (
sourceFracIndexCR + vec2 ( 0.5 , 0.5 ) ) ) ;
float newValue = getImage ( b , sourceNearestCR . y , sourceNearestCR . x , d ) ;
setOutput ( newValue ) ;
}
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},VQ=e=>{let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:c,extrapolationValue:u}=r,l=new WQ(s.shape,a.shape,i,c,u);return n.runWebGLProgram(l,[s,a,o],"float32")},UQ={kernelName:qc,backendName:"webgl",kernelFunc:VQ},cd;(function(e){e.Prod="*",e.Sum="+"})(cd||(cd={}));var N1=class{constructor(e,t,n,r){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let s=this.outputShape.length,a=this.op===cd.Prod?"1.0":"0.0",o=n?a: ` getX ( $ { _1 ( s , "coords" , this . op ) } ) ` ,i=this.outputShape[this.outputShape.length-1],c="",u="";n?(c=r? ` end != $ { i - 1 } ` :"end != 0",u=r?"end + 1":"end - 1"):(c=r? ` end + pow2 < $ { i } ` :"end >= pow2",u=r?"end + pow2":"end - pow2"),this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { mt ( s ) } coords = getOutputCoords ( ) ;
int end = $ { E1 ( s , "coords" , this . op ) } ;
float val = $ { o } ;
2021-09-11 17:11:38 +02:00
int pow2 = int ( pow ( 2.0 , index ) ) ;
2022-10-30 14:06:17 +01:00
if ( $ { c } ) {
2022-05-18 14:36:05 +02:00
int idx = $ { u } ;
2022-10-30 14:06:17 +01:00
$ { E1 ( s , "coords" , this . op ) } = idx ;
val $ { this . op } = getX ( $ { _1 ( s , "coords" , this . op ) } ) ;
2021-09-11 17:11:38 +02:00
}
setOutput ( val ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function _1(e,t,n){if(e===1)return ` $ { t } ` ;if(e===2)return ` $ { t } . x , $ { t } . y ` ;if(e===3)return ` $ { t } . x , $ { t } . y , $ { t } . z ` ;if(e===4)return ` $ { t } . x , $ { t } . y , $ { t } . z , $ { t } . w ` ;throw new Error( ` Cumulative $ { n } for rank $ { e } is not yet supported ` )}function E1(e,t,n){if(e===1)return ` $ { t } ` ;if(e===2)return ` $ { t } . y ` ;if(e===3)return ` $ { t } . z ` ;if(e===4)return ` $ { t } . w ` ;throw new Error( ` Cumulative $ { n } for rank $ { e } is not yet supported ` )}function NE(e,t,n,r,s,a){let o=t.shape.length,i=N.getAxesPermutation([r],o),c=t;i!=null&&(c=Nn({inputs:{x:t},backend:n,attrs:{perm:i}}));let u=N.getInnerMostAxes(1,o)[0];if(u!==o-1)throw new Error( ` WebGL cumprod shader expects an inner - most axis = $ { t . shape . length - 1 } but got axis = $ { r } ` );let l=c.shape[u],p=sr({inputs:{x:c},backend:n});for(let d=0;d<=Math.ceil(Math.log2(l))-1;d++){let h=new N1(e,c.shape,!1,a),f=[[d]],m=p;p=n.runWebGLProgram(h,[p],p.dtype,f),n.disposeIntermediateTensorInfo(m)}if(s){let d=new N1(e,c.shape,s,a),h=p;p=n.runWebGLProgram(d,[p],p.dtype),n.disposeIntermediateTensorInfo(h)}if(i!=null){let d=N.getUndoAxesPermutation(i),h=Nn({inputs:{x:p},backend:n,attrs:{perm:d}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(c),h}return p}function GQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r;return NE(cd.Prod,s,n,a,o,i)}var HQ={kernelName:Hc,backendName:"webgl",kernelFunc:GQ};function qQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r;return NE(cd.Sum,s,n,a,o,i)}var jQ={kernelName:No,backendName:"webgl",kernelFunc:qQ};function KQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let c=n.readSync(s.dataId),u=n.readSync(a.dataId),l=oE(c,u,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,l)}else if(s.shape.length===2){let c=n.bufferSync(s),u=n.bufferSync(a),l=s9(c,u,o,i);return n.makeTensorInfo(l.shape,a.dtype,l.values)}throw new Error( ` Error in denseBincount : input must be at most rank 2 , but got rank$ { s . shape . length } . ` )}var XQ={kernelName:xf,backendName:"webgl",kernelFunc:KQ},YQ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int h = $ { this . getHeightCoordString ( ) } ;
int w = $ { this . getWidthCoordString ( ) } ;
int d = $ { this . getDepthCoordString ( ) } ;
int in _h = h / $ { t } ;
int offset _h = imod ( h , $ { t } ) ;
int in _w = w / $ { t } ;
int offset _w = imod ( w , $ { t } ) ;
int offset _d = ( offset _h * $ { t } + offset _w ) *
$ { this . getOutputDepthSize ( ) } ;
int in _d = d + offset _d ;
float result = $ { this . getInputSamplingString ( ) } ;
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function ZQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r,i=s.shape[0],c=o==="NHWC"?s.shape[1]:s.shape[2],u=o==="NHWC"?s.shape[2]:s.shape[3],l=o==="NHWC"?s.shape[3]:s.shape[1],p=c*a,d=u*a,h=l/(a*a),f=o==="NHWC"?[i,p,d,h]:[i,h,p,d],m=new YQ(f,a,o);return n.runWebGLProgram(m,[s],s.dtype)}var JQ={kernelName:jc,backendName:"webgl",kernelFunc:ZQ},_E=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Dn(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,c="",u="";n&&(r?c= ` float activation ( float a ) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
2022-10-30 14:06:17 +01:00
} ` :s?c= ` float activation ( float a ) {
2021-09-11 17:11:38 +02:00
float b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
2022-10-30 14:06:17 +01:00
} ` :c= `
2021-09-11 17:11:38 +02:00
float activation ( float x ) {
$ { n }
}
2022-10-30 14:06:17 +01:00
` ,u="result = activation(result);");let l=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { c }
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
2022-10-30 14:06:17 +01:00
int d1 = d2 / $ { i } ;
int q = d2 - d1 * $ { i } ;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { a } ; wR ++ ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR * dilations [ 0 ] ;
if ( xR < 0 || xR >= inDims [ 0 ] ) {
continue ;
}
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { o } ; wC ++ ) {
2021-09-11 17:11:38 +02:00
int xC = xCCorner + wC * dilations [ 1 ] ;
if ( xC < 0 || xC >= inDims [ 1 ] ) {
continue ;
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
float xVal = getX ( batch , xR , xC , d1 ) ;
float wVal = getW ( wR , wC , d1 , q ) ;
dotProd += xVal * wVal ;
}
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd ;
2022-10-30 14:06:17 +01:00
$ { l }
2021-12-06 12:34:50 +01:00
$ { u }
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
}
2022-10-30 14:06:17 +01:00
` }},EE=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Dn(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,c=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,p=l,d= `
2021-09-11 17:11:38 +02:00
int xR ; int xC ; int xCOffset ;
2022-10-30 14:06:17 +01:00
vec4 wTexel ; vec4 previous ; vec4 final ; ` ;for(let g=0;g<l;g++)d+= `
2021-09-11 17:11:38 +02:00
vec4 xTexelC$ { g * 2 } ;
int xTexelC$ { g * 2 } Ready ;
vec4 xTexelC$ { g * 2 + 1 } ;
int xTexelC$ { g * 2 + 1 } Ready ;
2022-10-30 14:06:17 +01:00
vec4 xC$ { g } ; ` ;d+= `
2022-03-07 19:17:31 +01:00
for ( int r = 0 ; r < $ { u } ; r ++ ) {
2022-10-30 14:06:17 +01:00
` ;for(let g=0;g<l;g++)d+= `
2021-10-22 15:06:43 +02:00
xTexelC$ { g * 2 } = vec4 ( 0.0 ) ;
xTexelC$ { g * 2 } Ready = 0 ;
xTexelC$ { g * 2 + 1 } = vec4 ( 0.0 ) ;
xTexelC$ { g * 2 + 1 } Ready = 0 ;
2022-10-30 14:06:17 +01:00
xC$ { g } = vec4 ( 0.0 ) ; ` ;d+= `
2021-10-22 15:06:43 +02:00
xR = xRCorner + r * dilations [ 0 ] ;
2021-09-11 17:11:38 +02:00
if ( xR >= 0 && xR < inDims [ 0 ] ) {
2022-10-30 14:06:17 +01:00
` ;for(let g=0;g<(p+1)/2;g++){let b=g*2;if(d+= `
xC = xCCorner + $ { b * c } ;
` ,i===1){if(b<l&&(o%2===1?(d+= `
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1 ;
2022-10-30 14:06:17 +01:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xCOffset , d1 ) ;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2022-10-30 14:06:17 +01:00
xTexelC$ { b } . zw = vec2 ( 0.0 ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
xTexelC$ { b } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ,c===1&&b>0?d+= `
xC$ { b } = vec4 ( xTexelC$ { b - 2 } . zw , xTexelC$ { b } . xy ) ;
` :d+= `
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1 - 2 ;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
previous = getX ( batch , xR , xCOffset , d1 ) ;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
previous . zw = vec2 ( 0.0 ) ;
}
2021-07-29 15:05:49 +02:00
2022-10-30 14:06:17 +01:00
xC$ { b } = vec4 ( previous . zw , xTexelC$ { b } . xy ) ;
2021-04-01 19:39:54 +02:00
} else {
2022-10-30 14:06:17 +01:00
xC$ { b } = vec4 ( 0.0 , 0.0 , xTexelC$ { b } . xy ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ):d+= `
if ( xC >= 0 && xC < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xC , d1 ) ;
2021-09-11 17:11:38 +02:00
if ( xC + 1 >= inDims [ 1 ] ) {
2022-10-30 14:06:17 +01:00
xTexelC$ { b } . zw = vec2 ( 0.0 ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
xTexelC$ { b } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
xC$ { b } = xTexelC$ { b } ;
` ,b+1<l)){let y=o%2===0?w.nearestLargerEven(c):c;c%2===0&&o%2===1||c%2!==0&&o%2!==1?(d+= `
xCOffset = xC + imod ( pads [ 1 ] , 2 ) + $ { y } ;
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b + 1 } Ready == 0 ) {
xTexelC$ { b + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2022-10-30 14:06:17 +01:00
xTexelC$ { b + 1 } . zw = vec2 ( 0.0 ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
xTexelC$ { b + 1 } Ready = 1 ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` ,c>1?d+= `
2021-09-11 17:11:38 +02:00
xCOffset -= 2 ;
2022-08-24 14:21:15 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
previous = getX ( batch , xR , xCOffset , d1 ) ;
2022-10-30 14:06:17 +01:00
xC$ { b + 1 } = vec4 ( previous . zw , xTexelC$ { b + 1 } . xy ) ;
2022-08-24 14:21:15 +02:00
} else {
2022-10-30 14:06:17 +01:00
xC$ { b + 1 } = vec4 ( 0.0 , 0.0 , xTexelC$ { b + 1 } . xy ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` :d+= `
xC$ { b + 1 } = vec4 ( xTexelC$ { b } . zw , xTexelC$ { b + 1 } . xy ) ;
` ):y===1?d+= `
xC$ { b + 1 } = xTexelC$ { b } ;
` :d+= `
xCOffset = xC + $ { y } ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b + 1 } Ready == 0 ) {
xTexelC$ { b + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
2021-09-11 17:11:38 +02:00
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2022-10-30 14:06:17 +01:00
xTexelC$ { b + 1 } . zw = vec2 ( 0.0 ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
xTexelC$ { b + 1 } Ready = 1 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
xC$ { b + 1 } = xTexelC$ { b + 1 } ;
` }}else b<l&&(o%2===1?(d+= `
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1 - strides [ 1 ] ;
2022-10-30 14:06:17 +01:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xCOffset , d1 ) ;
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2022-10-30 14:06:17 +01:00
xTexelC$ { b } . zw = vec2 ( 0.0 ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
xTexelC$ { b } Ready = 1 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2022-10-30 14:06:17 +01:00
if ( xC + 1 >= 0 && xC + 1 < inDims [ 1 ] && xTexelC$ { b + 1 } Ready == 0 ) {
xTexelC$ { b + 1 } = getX ( batch , xR , xC + 1 , d1 ) ;
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xC + 2 >= inDims [ 1 ] ) {
2022-10-30 14:06:17 +01:00
xTexelC$ { b + 1 } . zw = vec2 ( 0.0 ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
xTexelC$ { b + 1 } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
xC$ { b } = vec4 ( xTexelC$ { b } . zw , xTexelC$ { b + 1 } . zw ) ;
` ,b+1<l&&(d+= `
2021-09-11 17:11:38 +02:00
final = vec4 ( 0.0 ) ;
xCOffset = xC + 1 + strides [ 1 ] ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
final = getX ( batch , xR , xCOffset , d1 ) ;
}
2022-10-30 14:06:17 +01:00
xC$ { b + 1 } = vec4 ( xTexelC$ { b + 1 } . xy , final . xy ) ;
` )):(d+= `
if ( xC >= 0 && xC < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xC , d1 ) ;
2021-09-11 17:11:38 +02:00
if ( xC + 1 >= inDims [ 1 ] ) {
2022-10-30 14:06:17 +01:00
xTexelC$ { b } . zw = vec2 ( 0.0 ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
xTexelC$ { b } Ready = 1 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xCOffset = xC + strides [ 1 ] ;
2022-10-30 14:06:17 +01:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b + 1 } Ready == 0 ) {
xTexelC$ { b + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
2021-09-11 17:11:38 +02:00
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2022-10-30 14:06:17 +01:00
xTexelC$ { b + 1 } . zw = vec2 ( 0. ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
xTexelC$ { b + 1 } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
xC$ { b } = vec4 (
xTexelC$ { b } . xy , xTexelC$ { b + 1 } . xy ) ;
` ,b+1<l&&(d+= `
xC$ { b + 1 } = vec4 ( xTexelC$ { b } . zw , xTexelC$ { b + 1 } . zw ) ;
` )));b<l&&(d+= `
wTexel = getW ( r , $ { b } , d1 , q ) ;
dotProd += xC$ { b } * vec4 ( wTexel . xz , wTexel . xz ) ;
` ,b+1<l&&(d+= `
wTexel = getW ( r , $ { b + 1 } , d1 , q ) ;
dotProd += xC$ { b + 1 } * vec4 ( wTexel . xz , wTexel . xz ) ;
` ))}d+= `
2021-10-22 15:06:43 +02:00
}
2022-10-30 14:06:17 +01:00
` ,d+= `
2021-10-22 15:06:43 +02:00
}
2022-10-30 14:06:17 +01:00
` ;let h="",f="";n&&(r?h= ` vec4 activation ( vec4 a ) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
2022-10-30 14:06:17 +01:00
} ` :s?h= ` vec4 activation ( vec4 a ) {
2021-09-11 17:11:38 +02:00
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
} ` :h= ` vec4 activation ( vec4 x ) {
$ { n }
2022-10-30 14:06:17 +01:00
} ` ,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
2021-09-11 17:11:38 +02:00
$ { h }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
2022-10-30 14:06:17 +01:00
int d1 = d2 / $ { a } ;
int q = d2 - d1 * $ { a } ;
2021-09-11 17:11:38 +02:00
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4 ( 0.000000000000001 ) ;
2022-10-30 14:06:17 +01:00
$ { d }
2021-09-11 17:11:38 +02:00
vec4 result = dotProd - vec4 ( 0.000000000000001 ) ;
2022-10-18 13:23:49 +02:00
$ { m }
2022-10-30 14:06:17 +01:00
$ { f }
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function QQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c,dimRoundingMode:u}=r,l=c;l==null&&(l=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(o,l),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { o } and dilations '${l}' ` );let p=N.computeConv2DInfo(s.shape,a.shape,o,l,i,u,!0),d;q().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels===1?d=new EE(p):d=new _E(p);let h=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return n.runWebGLProgram(d,[s,a],"float32",h)}var eee={kernelName:_o,backendName:"webgl",kernelFunc:QQ},tee=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int dm = coords . w ;
2022-10-30 14:06:17 +01:00
int d2 = d1 * $ { a } + dm ;
2021-09-11 17:11:38 +02:00
float dotProd = 0.0 ;
// TO DO: Vec4 over the batch size
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
2022-10-30 14:06:17 +01:00
int xR = wR + yR * $ { t } - $ { r } ;
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
2022-10-30 14:06:17 +01:00
int xC = wC + yC * $ { n } - $ { s } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float dyValue = getDy ( b , yR , yC , d2 ) ;
float xValue = getX ( b , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
}
}
}
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},nee=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode= `
const ivec2 pads = ivec2 ( $ { a } , $ { o } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
int batch = coords [ 0 ] ;
2021-09-11 17:11:38 +02:00
int d1 = coords [ 3 ] ;
ivec2 dyCorner = coords . yz - pads ;
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
2022-10-30 14:06:17 +01:00
float dyR = float ( dyRCorner + wR ) / $ { r } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = $ { t } - 1 - wR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
2022-10-30 14:06:17 +01:00
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = $ { n } - 1 - wC ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// TO DO: Vec4 over the channelMul
2022-10-30 14:06:17 +01:00
for ( int dm = 0 ; dm < $ { i } ; dm ++ ) {
int d2 = d1 * $ { i } + dm ;
2021-09-11 17:11:38 +02:00
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , dm ) ;
dotProd += xValue * wValue ;
}
}
}
setOutput ( dotProd ) ;
}
2022-10-30 14:06:17 +01:00
` }};function ree(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:u,filterShape:l}=r,p=N.computeConv2DInfo(s.shape,l,o,i,c,u,!0),d=new tee(p);return n.runWebGLProgram(d,[s,a],"float32")}var see={kernelName:wf,backendName:"webgl",kernelFunc:ree};function aee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:u,inputShape:l}=r,p=N.computeConv2DInfo(l,a.shape,o,i,c,u,!0),d=new nee(p);return n.runWebGLProgram(d,[s,a],"float32")}var oee={kernelName:If,backendName:"webgl",kernelFunc:aee},iee=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
float val = coords [ 0 ] == coords [ 1 ] ? getX ( coords [ 0 ] ) : 0.0 ;
setOutput ( val ) ;
}
2022-10-30 14:06:17 +01:00
` }};function cee(e){let{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=w.sizeFromShape(r.shape),o=he({inputs:{x:r},backend:n,attrs:{shape:[a]}}),i=new iee(a),c=n.runWebGLProgram(i,[o],o.dtype),u=he({inputs:{x:c},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),u}var uee={kernelName:kf,backendName:"webgl",kernelFunc:cee},lee=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:c,dilationWidth:u}=e,{top:l,left:p}=r;this.userCode= `
const ivec2 strides = ivec2 ( $ { s } , $ { a } ) ;
const ivec2 pads = ivec2 ( $ { l } , $ { p } ) ;
2021-09-11 17:11:38 +02:00
const float neg _infinity = - 3.4 e38 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . w ;
ivec2 outTopLeftCorner =
coords . yz * strides - pads ;
int hBeg = outTopLeftCorner . x ;
int wBeg = outTopLeftCorner . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float curVal = neg _infinity ;
2022-10-30 14:06:17 +01:00
for ( int h = 0 ; h < $ { o } ; h ++ ) {
int hIn = hBeg + h * $ { c } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if ( hIn >= 0 && hIn < $ { t } ) {
2022-10-30 14:06:17 +01:00
for ( int w = 0 ; w < $ { i } ; w ++ ) {
2022-03-07 19:17:31 +01:00
int wIn = wBeg + w * $ { u } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( wIn >= 0 && wIn < $ { n } ) {
float xVal = getX ( batch , hIn , wIn , d1 ) ;
float wVal = getW ( h , w , d1 ) ;
float val = xVal + wVal ;
if ( val > curVal ) {
curVal = val ;
}
}
}
}
2021-07-29 15:05:49 +02:00
}
2021-09-11 17:11:38 +02:00
float result = curVal ;
setOutput ( result ) ;
2021-07-29 15:05:49 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function dee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,u=N.computeDilation2DInfo(s.shape,a.shape,o,i,"NHWC",c),l,p=new lee(u);l=n.runWebGLProgram(p,[s,a],"float32");let d=he({inputs:{x:l},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(l),d}var pee={kernelName:md,backendName:"webgl",kernelFunc:dee};function hee(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:c}=N.decodeEinsumEquation(s,a.length);N.checkEinsumDimSizes(o.length,c,a);let{path:u,steps:l}=N.getEinsumComputePath(i,c),p=l.length,d=null,h=o.length,f=[];for(let m=0;m<p;++m){for(let g of l[m]){let{permutationIndices:b,expandDims:y}=N.getEinsumPermutation(h,c[g]),v;N.isIdentityPermutation(b)?v=a[g]:(v=Nn({inputs:{x:a[g]},backend:n,attrs:{perm:b}}),f.push(v));let x=v.shape.slice();for(let k=0;k<y.length;++k)x.splice(y[k],0,1);w.arraysEqual(v.shape,x)||(v=he({inputs:{x:v},backend:n,attrs:{shape:x}}),f.push(v)),d===null?d=v:(d=iI({inputs:{a:v,b:d},backend:n}),f.push(d))}m<p-1&&(u[m]>=0&&(d=Jm({inputs:{x:d},backend:n,attrs:{axis:u[m]-(o.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&n.disposeIntermediateTensorInfo(m);return d}var fee={kernelName:Sf,backendName:"webgl",kernelFunc:hee},mee="return (x >= 0.0) ? x : (exp(x) - 1.0);",gee= `
2021-09-11 17:11:38 +02:00
vec4 result ;
result . r = ( x . r >= 0.0 ) ? x . r : ( exp ( x . r ) - 1.0 ) ;
result . g = ( x . g >= 0.0 ) ? x . g : ( exp ( x . g ) - 1.0 ) ;
result . b = ( x . b >= 0.0 ) ? x . b : ( exp ( x . b ) - 1.0 ) ;
result . a = ( x . a >= 0.0 ) ? x . a : ( exp ( x . a ) - 1.0 ) ;
return result ;
2022-10-30 14:06:17 +01:00
` ,bee=Ye({opSnippet:mee,packedOpSnippet:gee}),yee={kernelName:Ao,backendName:"webgl",kernelFunc:bee},vee="return (b >= 1.0) ? a : a * (b + 1.0);",xee= `
2021-09-11 17:11:38 +02:00
vec4 bGTEZero = vec4 ( greaterThanEqual ( b , vec4 ( 0. ) ) ) ;
return ( bGTEZero * a ) + ( ( vec4 ( 1.0 ) - bGTEZero ) * ( a * ( b + vec4 ( 1.0 ) ) ) ) ;
2022-10-30 14:06:17 +01:00
` ,wee=e=>{let{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new up(xee,r.shape,s.shape):new $ c(vee,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)},Iee={kernelName:Tf,backendName:"webgl",kernelFunc:wee},kee= `
2021-09-11 17:11:38 +02:00
return vec4 ( equal ( a , b ) ) ;
2022-10-30 14:06:17 +01:00
` ,See="return float(a == b);",Tee=dn({opSnippet:See,packedOpSnippet:kee,dtype:"bool",cpuKernelImpl:c9}),Cee={kernelName:Xc,backendName:"webgl",kernelFunc:Tee},Nee= `
2021-09-11 17:11:38 +02:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2022-10-09 19:40:33 +02:00
float p = $ { N . ERF _P } ;
float a1 = $ { N . ERF _A1 } ;
float a2 = $ { N . ERF _A2 } ;
float a3 = $ { N . ERF _A3 } ;
float a4 = $ { N . ERF _A4 } ;
float a5 = $ { N . ERF _A5 } ;
2021-09-11 17:11:38 +02:00
float sign = sign ( x ) ;
x = abs ( x ) ;
float t = 1.0 / ( 1.0 + p * x ) ;
return sign * ( 1.0 - ( ( ( ( ( a5 * t + a4 ) * t ) + a3 ) * t + a2 ) * t + a1 ) * t * exp ( - x * x ) ) ;
2022-10-30 14:06:17 +01:00
` ,_ee=Ye({opSnippet:Nee}),Eee={kernelName:Kc,backendName:"webgl",kernelFunc:_ee},Aee=tl+ `
2022-01-14 16:04:13 +01:00
return exp ( x ) ;
2022-10-30 14:06:17 +01:00
` , $ ee= `
2022-01-14 16:04:13 +01:00
vec4 result = exp ( x ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-10-30 14:06:17 +01:00
` ,AE=Ye({opSnippet:Aee,packedOpSnippet: $ ee,cpuKernelImpl:u9,dtype:"float32"}),Dee={kernelName: $ o,backendName:"webgl",kernelFunc:AE};function xv(e){let{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),c=s;return s<0&&(w.assert(-(o+1)<=s,()=> ` Axis must be in the interval [ $ { - ( o + 1 ) } , $ { o } ] ` ),c=o+s+1),i.splice(c,0,1),he({inputs:{x:a},backend:r,attrs:{shape:i}})}var Fee={kernelName:Yc,backendName:"webgl",kernelFunc:xv},A1="return exp(x) - 1.0;",Ree=Ye({opSnippet:A1,packedOpSnippet:A1,cpuKernelImpl:l9}),Pee={kernelName:Zc,backendName:"webgl",kernelFunc:Ree}, $ 1=class{constructor(e,t,n){this.variableNames=["real","imag"];let r=t[1];this.outputShape=t;let s=n? ` 2.0 * $ { Math . PI } ` : ` - 2.0 * $ { Math . PI } ` ,a=n? ` $ { r } . 0 ` :"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error( ` FFT component must be either "real" or "imag" , got $ { e } . ` );this.userCode= `
const float exponentMultiplier = $ { s } ;
2021-09-11 17:11:38 +02:00
float unaryOpComplex ( float real , float expR , float imag , float expI ) {
2022-10-30 14:06:17 +01:00
$ { o }
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
float mulMatDFT ( int batch , int index ) {
2022-10-30 14:06:17 +01:00
float indexRatio = float ( index ) / float ( $ { r } ) ;
2021-09-11 17:11:38 +02:00
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio ;
float result = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int i = 0 ; i < $ { r } ; i ++ ) {
2021-09-11 17:11:38 +02:00
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float ( i ) ;
float expR = cos ( x ) ;
float expI = sin ( x ) ;
float real = getReal ( batch , i ) ;
float imag = getImag ( batch , i ) ;
result +=
2022-10-30 14:06:17 +01:00
unaryOpComplex ( real , expR , imag , expI ) / $ { a } ;
2021-09-11 17:11:38 +02:00
}
return result ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
setOutput ( mulMatDFT ( coords [ 0 ] , coords [ 1 ] ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function $ E(e,t,n){let r=n.texData.get(e.dataId),s=w.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=s/a,i=he({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),c=i.shape,u=new $ 1("real",c,t),l=new $ 1("imag",c,t),p=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:c},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:c}],d=n.runWebGLProgram(u,p,"float32"),h=n.runWebGLProgram(l,p,"float32"),f=Ea({inputs:{real:d,imag:h},backend:n});n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h);let m=he({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function Oee(e){let{inputs:t,backend:n}=e,{input:r}=t;return $ E(r,!1,n)}var Mee={kernelName:Cf,backendName:"webgl",kernelFunc:Oee},Lee=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
// Input can be obtained from uniform value.
setOutput ( value ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function dp(e){let{backend:t,attrs:n}=e,{shape:r,value:s}=n,{dtype:a}=n;if(a=a||w.inferDtype(s),a==="string"){let o=w.getArrayFromDType(a,w.sizeFromShape(r));return o.fill(s),t.makeTensorInfo(r,a,o)}else{let o=new Lee(r,s),i=[[s]];return t.runWebGLProgram(o,[],a,i)}}var zee={kernelName:gd,backendName:"webgl",kernelFunc:dp},Bee=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
int coordX = $ { t } - x - 1 ;
float outputValue ;
if ( coordX >= 0 && coordX < $ { t } ) {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coordX , coords [ 3 ] ) ;
} else {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coords [ 2 ] , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2022-10-30 14:06:17 +01:00
` }},Wee={kernelName:Jc,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new Bee(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},D1="return floor(x);",Vee=Ye({opSnippet:D1,packedOpSnippet:D1,cpuKernelImpl:d9}),Uee={kernelName:Do,backendName:"webgl",kernelFunc:Vee},Gee= `
2021-09-11 17:11:38 +02:00
float s = sign ( a ) * sign ( b ) ;
int ia = round ( a ) ;
int ib = round ( b ) ;
if ( ib != 0 ) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float ( idiv ( ia , ib , s ) ) ;
} else {
return NAN ;
2021-04-30 18:01:04 +02:00
}
2022-10-30 14:06:17 +01:00
` ,Hee= `
2021-09-11 17:11:38 +02:00
ivec4 ia = round ( a ) ;
ivec4 ib = round ( b ) ;
bvec4 cond = notEqual ( ib , ivec4 ( 0 ) ) ;
ivec4 result = ivec4 ( 0 ) ;
vec4 s = sign ( a ) * sign ( b ) ;
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if ( cond [ 0 ] ) {
result [ 0 ] = idiv ( ia [ 0 ] , ib [ 0 ] , s [ 0 ] ) ;
2021-04-30 18:01:04 +02:00
}
2021-09-11 17:11:38 +02:00
if ( cond [ 1 ] ) {
result [ 1 ] = idiv ( ia [ 1 ] , ib [ 1 ] , s [ 1 ] ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( cond [ 2 ] ) {
result [ 2 ] = idiv ( ia [ 2 ] , ib [ 2 ] , s [ 2 ] ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( cond [ 3 ] ) {
result [ 3 ] = idiv ( ia [ 3 ] , ib [ 3 ] , s [ 3 ] ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return vec4 ( result ) ;
2022-10-30 14:06:17 +01:00
` ,qee=dn({opSnippet:Gee,packedOpSnippet:Hee,dtype:"int32"}),jee={kernelName:Fo,backendName:"webgl",kernelFunc:qee},Kee=class{constructor(e){this.variableNames=["A"];let t= $ n(),[n,r]=e;this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
2022-10-30 14:06:17 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { r } . 0 , $ { n } . 0 ) ;
2021-09-11 17:11:38 +02:00
vec4 values = $ { t . texture2D } ( A , uv ) ;
float value ;
if ( depth == 0 ) {
value = values . r ;
} else if ( depth == 1 ) {
value = values . g ;
} else if ( depth == 2 ) {
value = values . b ;
} else if ( depth == 3 ) {
value = values . a ;
2021-03-31 13:01:22 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( floor ( value * 255.0 + 0.5 ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},Xee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t= $ n(),[n,r]=e;this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
vec4 result = vec4 ( 0. ) ;
for ( int row = 0 ; row <= 1 ; row ++ ) {
for ( int col = 0 ; col <= 1 ; col ++ ) {
texC = coords [ 1 ] + row ;
depth = coords [ 2 ] + col ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2022-10-30 14:06:17 +01:00
vec2 ( $ { r } . 0 , $ { n } . 0 ) ;
2021-09-11 17:11:38 +02:00
vec4 values = $ { t . texture2D } ( A , uv ) ;
float value ;
if ( depth == 0 ) {
value = values . r ;
} else if ( depth == 1 ) {
value = values . g ;
} else if ( depth == 2 ) {
value = values . b ;
} else if ( depth == 3 ) {
value = values . a ;
}
result [ row * 2 + col ] = floor ( value * 255.0 + 0.5 ) ;
}
2021-03-31 13:01:22 +02:00
}
2021-09-11 17:11:38 +02:00
$ { t . output } = result ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},Yee={kernelName:Fh,backendName:"webgl",kernelFunc:Zee},ac,Ty=q().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Zee(e){let{inputs:t,backend:n,attrs:r}=e,{pixels:s}=t,{numChannels:a}=r,o=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,[c,u]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],l=[u,c],p=[u,c,a];if(i||o){let m=q().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(ac==null||m!==Ty)&&(Ty=m,ac=document.createElement("canvas").getContext("2d",{willReadFrequently:Ty})),ac.canvas.width=c,ac.canvas.height=u,ac.drawImage(s,0,0,c,u),s=ac.canvas}let d=n.makeTensorInfo(l,"int32");n.texData.get(d.dataId).usage=ur.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(d.dataId),s);let h=q().getBool("WEBGL_PACK")?new Xee(p):new Kee(p),f=n.runWebGLProgram(h,[d],"int32");return n.disposeData(d.dataId),f}function Jee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:u,dataFormat:l,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=r,m=N.convertConv2DDataFormat(l),g=N.computeConv2DInfo(s.shape,a.shape,c,p,u,d,!1,m),b,y=[],v=o!=null,x=i!=null,k=h==="leakyrelu",S=()=>{let E=[s,a], $ =(F,A)=>{if(A==="NCHW"&&F.shape.length===1&&F.shape[0]!==1){let R=he({inputs:{x:F},backend:n,attrs:{shape:[F.shape[0],1,1]}});return y.push(R),R}return F};if(v&&E.push( $ (o,l)),x&&E.push( $ (i,l)),k){let F=n.makeTensorInfo([],"float32",w.createScalarValue(f,"float32"));E.push(F),y.push(F)}return E};if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))b=TE({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(g.strideWidth<=2&&m==="channelsLast"&&q().getBool("WEBGL_EXP_CONV")){let E=h?od(h,!0):null, $ =new SE(g,v,E,x,k),F=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],A=S();b=n.runWebGLProgram( $ ,A,"float32",F)}else if(q().getBool("WEBGL_CONV_IM2COL"))b=CE({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let E=h?od(h,!1):null, $ =new kE(g,v,E,x,k),F=S();b=n.runWebGLProgram( $ ,F,"float32")}let C=he({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return y.push(b),y.forEach(E=>n.disposeIntermediateTensorInfo(E)),C}var Qee={kernelName:to,backendName:"webgl",kernelFunc:Jee};function ete(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:u,dilations:l,dimRoundingMode:p,activation:d,leakyreluAlpha:h}=r,f=[],m=l;m==null&&(m=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(c,m),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { c } and dilations '${m}' ` );let g=N.computeConv2DInfo(s.shape,a.shape,c,m,u,p,!0),b=q().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,y=d?od(d,b):null,v=[s,a],x=o!=null,k=i!=null,S=d==="leakyrelu";if(x&&v.push(o),k&&v.push(i),S){let F=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));v.push(F),f.push(F)}let C;b?C=new EE(g,x,y,k,S):C=new _E(g,x,y,k,S);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]], $ =n.runWebGLProgram(C,v,"float32",E);return f.forEach(F=>n.disposeIntermediateTensorInfo(F)), $ }var tte={kernelName:no,backendName:"webgl",kernelFunc:ete},nte=class{constructor(e,t,n,r){this.sliceDim=e,this.strides=t,this.paramsShape=r,this.variableNames=["x","indices"],this.outputShape=n;let s=mt(n.length),a= `
int index ; ` ;for(let o=0;o<this.sliceDim;o++)a+= `
index = round ( getIndices ( coords [ 0 ] , $ { o } ) ) ;
2022-10-09 19:40:33 +02:00
out _of _bounds = out _of _bounds || index < 0 ;
2022-10-30 14:06:17 +01:00
out _of _bounds = out _of _bounds || index >= $ { this . paramsShape [ o ] } ;
flattenIndex += index * $ { this . strides [ o ] } ; ` ;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { s } coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
int flattenIndex = 0 ;
2022-07-25 14:23:57 +02:00
bool out _of _bounds = false ;
2022-10-09 19:40:33 +02:00
2022-10-30 14:06:17 +01:00
$ { a }
2022-10-09 19:40:33 +02:00
2022-07-25 14:23:57 +02:00
setOutput ( out _of _bounds ? 0.0 : getX ( flattenIndex , coords [ 1 ] ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function rte(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,o=a[a.length-1],i=w.sizeFromShape(r.shape),[c,u,l,p]=N.prepareAndValidate(r,s),d=he({inputs:{x:s},backend:n,attrs:{shape:[u,o]}}),h=he({inputs:{x:r},backend:n,attrs:{shape:[w.sizeFromShape(r.shape)/l,l]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.readSync(s.dataId),y=n.bufferSync(r),v=p9(b,y,r.dtype,u,o,l,p,r.shape,i);return n.makeTensorInfo(c,r.dtype,v.values)}let f=new nte(o,p,[u,l],r.shape),m=n.runWebGLProgram(f,[h,d],h.dtype),g=he({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var ste={kernelName:eu,backendName:"webgl",kernelFunc:rte},ate=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=mt(this.rank),r=ote(e,2);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { n } resRC = getOutputCoords ( ) ;
2022-01-14 16:04:13 +01:00
int index = int ( getIndices ( resRC . x , resRC . z ) ) ;
float inBounds = ( index >= 0 ) && ( index < $ { e [ 2 ] } ) ? 1.0 : 0.0 ;
2022-10-30 14:06:17 +01:00
setOutput ( inBounds * getA ( $ { r } ) ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function ote(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let s=0;s<e.length;s++)s===2?r.push("index"):r.push( ` $ { n [ s ] } ` );return r.join()}function DE(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,c=w.parseAxisParam(o,s.shape)[0];if(q().get("DEBUG")){let y=n.readSync(a.dataId),v=s.shape[c];for(let x=0;x<y.length;++x){let k=y[x];w.assert(k<=v-1&&k>=0,()=> ` GatherV2 : the index value $ { k } is not in [ 0 , $ { v - 1 } ] ` )}}let u=N.segment_util.collectGatherOpShapeInfo(s,a,c,i),l=w.sizeFromShape(a.shape),p=[],d=he({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=he({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,l/u.batchSize]}});p.push(d),p.push(h);let f=[u.batchSize,u.outerSize,l/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([s,a])||s.dtype==="string"){let y=n.bufferSync(h),v=n.bufferSync(d),x=h9(v,y,f);return p.forEach(k=>n.disposeIntermediateTensorInfo(k)),n.makeTensorInfo(u.outputShape,x.dtype,x.values)}let m=new ate(d.shape,f),g=n.runWebGLProgram(m,[d,h],d.dtype);p.push(g);let b=he({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return p.forEach(y=>n.disposeIntermediateTensorInfo(y)),b}var ite={kernelName:Qc,backendName:"webgl",kernelFunc:DE},cte="return float(a > b);",ute= `
2021-09-11 17:11:38 +02:00
return vec4 ( greaterThan ( a , b ) ) ;
2022-10-30 14:06:17 +01:00
` ,lte=dn({opSnippet:cte,packedOpSnippet:ute,cpuKernelImpl:f9,dtype:"bool"}),dte={kernelName:tu,backendName:"webgl",kernelFunc:lte},pte="return float(a >= b);",hte= `
2021-09-11 17:11:38 +02:00
return vec4 ( greaterThanEqual ( a , b ) ) ;
2022-10-30 14:06:17 +01:00
` ,fte=dn({opSnippet:pte,packedOpSnippet:hte,dtype:"bool",cpuKernelImpl:m9}),mte={kernelName:Po,backendName:"webgl",kernelFunc:fte};function gte(e){let{inputs:t,backend:n}=e,{input:r}=t;return $ E(r,!0,n)}var bte={kernelName:Nf,backendName:"webgl",kernelFunc:gte},yte="return float(!isnan(x) && !isinf(x));",vte=Ye({opSnippet:yte,dtype:"bool"}),xte={kernelName:nu,backendName:"webgl",kernelFunc:vte},wte="return float(isinf(x));",Ite=Ye({opSnippet:wte,dtype:"bool"}),kte={kernelName:ru,backendName:"webgl",kernelFunc:Ite},Ste="return float(isnan(x));",Tte=Ye({opSnippet:Ste,dtype:"bool"}),Cte={kernelName:su,backendName:"webgl",kernelFunc:Tte},Nte="return float(a < b);",_te= `
2021-09-11 17:11:38 +02:00
return vec4 ( lessThan ( a , b ) ) ;
2022-10-30 14:06:17 +01:00
` ,Ete=dn({opSnippet:Nte,packedOpSnippet:_te,cpuKernelImpl:g9,dtype:"bool"}),Ate={kernelName:au,backendName:"webgl",kernelFunc:Ete}, $ te="return float(a <= b);",Dte= `
2021-09-11 17:11:38 +02:00
return vec4 ( lessThanEqual ( a , b ) ) ;
2022-10-30 14:06:17 +01:00
` ,Fte=dn({opSnippet: $ te,packedOpSnippet:Dte,cpuKernelImpl:b9,dtype:"bool"}),Rte={kernelName:ou,backendName:"webgl",kernelFunc:Fte};function Pte(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=y9(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var Ote={kernelName:Ef,backendName:"webgl",kernelFunc:Pte},Mte=tl+ `
2022-01-14 16:04:13 +01:00
return x < 0.0 ? 0. / 0. : log ( x ) ;
2022-10-30 14:06:17 +01:00
` ,Lte= `
2021-09-11 17:11:38 +02:00
vec4 result = log ( x ) ;
2022-01-14 16:04:13 +01:00
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : ( x . r < 0.0 ? 0. / 0. : result . r ) ;
result . g = isNaN . g ? x . g : ( x . g < 0.0 ? 0. / 0. : result . g ) ;
result . b = isNaN . b ? x . b : ( x . b < 0.0 ? 0. / 0. : result . b ) ;
result . a = isNaN . a ? x . a : ( x . a < 0.0 ? 0. / 0. : result . a ) ;
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,zte=Ye({opSnippet:Mte,packedOpSnippet:Lte,cpuKernelImpl:v9}),Bte={kernelName:Lo,backendName:"webgl",kernelFunc:zte},Wte=tl+ `
2022-01-14 16:04:13 +01:00
return log ( 1.0 + x ) ;
2022-10-30 14:06:17 +01:00
` ,Vte=Ye({opSnippet:Wte}),Ute={kernelName:iu,backendName:"webgl",kernelFunc:Vte},Gte="return float(a >= 1.0 && b >= 1.0);",Hte= `
2021-09-11 17:11:38 +02:00
return vec4 (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) *
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ) ;
2022-10-30 14:06:17 +01:00
` ,qte=dn({opSnippet:Gte,packedOpSnippet:Hte,dtype:"bool"}),jte={kernelName:cu,backendName:"webgl",kernelFunc:qte},Kte="return float(!(x >= 1.0));",Xte=Ye({opSnippet:Kte}),Yte={kernelName:uu,backendName:"webgl",kernelFunc:Xte},Zte="return float(a >= 1.0 || b >= 1.0);",Jte= `
2021-09-11 17:11:38 +02:00
return min (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) +
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ,
vec4 ( 1.0 ) ) ;
2022-10-30 14:06:17 +01:00
` ,Qte=dn({opSnippet:Zte,packedOpSnippet:Jte,dtype:"bool"}),ene={kernelName:lu,backendName:"webgl",kernelFunc:Qte},tne=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,c= ` float ( $ { n } ) + float ( $ { r } ) * sum ` ;s===.5?i= ` inversesqrt ( $ { c } ) ` :s===1?i= ` 1.0 / ( $ { c } ) ` :i= ` exp ( log ( $ { c } ) * float ( - $ { s } ) ) ; ` ,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
int d = coords [ 3 ] ;
float x = getX ( b , r , c , d ) ;
float sum = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int j = - $ { a } ; j <= $ { a } ; j ++ ) {
2021-09-11 17:11:38 +02:00
int idx = d + j ;
2022-10-30 14:06:17 +01:00
if ( idx >= 0 && idx <= $ { o } ) {
2021-09-11 17:11:38 +02:00
float z = getX ( b , r , c , idx ) ;
sum += z * z ;
}
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
float val = x * $ { i } ;
2021-09-11 17:11:38 +02:00
setOutput ( val ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},nne=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,o=e[3]-1;this.outputShape=e;let i,c= ` float ( $ { n } ) + float ( $ { r } ) * sum ` ;s===.5?i= ` inversesqrt ( $ { c } ) ` :s===1?i= ` 1.0 / ( $ { c } ) ` :i= ` exp ( log ( $ { c } ) * float ( - $ { s } ) ) ; ` ,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords . x ;
int r = coords . y ;
int c = coords . z ;
int d = coords . w ;
bool hasNextCol = d < $ { this . outputShape [ 3 ] } ;
bool hasNextRow = c < $ { this . outputShape [ 2 ] } ;
vec4 sum = vec4 ( 0. ) ;
vec4 xFragAtOutputCoords = getX ( b , r , c , d ) ;
vec4 xAtOutputCoords = vec4 (
getChannel ( xFragAtOutputCoords , vec2 ( c , d ) ) ,
hasNextCol ?
getChannel ( xFragAtOutputCoords , vec2 ( c , d + 1 ) ) : 0.0 ,
hasNextRow ?
getChannel ( xFragAtOutputCoords , vec2 ( c + 1 , d ) ) : 0.0 ,
( hasNextRow && hasNextCol ) ?
getChannel ( xFragAtOutputCoords , vec2 ( c + 1 , d + 1 ) ) : 0.0
) ;
2022-10-30 14:06:17 +01:00
int firstChannel = d - $ { a } ;
2021-09-11 17:11:38 +02:00
vec2 cache = vec2 ( 0. ) ;
if ( firstChannel >= 0 ) {
vec4 firstChannelFrag = getX ( b , r , c , firstChannel ) ;
cache . x = getChannel ( firstChannelFrag , vec2 ( c , firstChannel ) ) ;
if ( hasNextRow ) {
cache . y = getChannel ( firstChannelFrag , vec2 ( c + 1 , firstChannel ) ) ;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
ivec2 depth = ivec2 ( d , d + 1 ) ;
2022-10-30 14:06:17 +01:00
for ( int j = - $ { a } ; j <= $ { a } ; j ++ ) {
2021-09-11 17:11:38 +02:00
ivec2 idx = depth + j ;
bvec2 aboveLowerBound = greaterThanEqual ( idx , ivec2 ( 0 ) ) ;
2022-10-30 14:06:17 +01:00
bvec2 belowUpperBound = lessThanEqual ( idx , ivec2 ( $ { o } ) ) ;
2021-09-11 17:11:38 +02:00
bool depthInRange = aboveLowerBound . x && belowUpperBound . x ;
bool depthPlusOneInRange = aboveLowerBound . y && belowUpperBound . y ;
if ( depthInRange || depthPlusOneInRange ) {
vec4 z = vec4 ( 0. ) ;
vec4 xFragAtCurrentDepth ;
z . xz = cache . xy ;
if ( depthPlusOneInRange && hasNextCol ) {
xFragAtCurrentDepth = idx . y != d ?
getX ( b , r , c , idx . y ) : xFragAtOutputCoords ;
z . y = getChannel ( xFragAtCurrentDepth , vec2 ( c , idx . y ) ) ;
if ( hasNextRow ) {
z . w = getChannel ( xFragAtCurrentDepth , vec2 ( c + 1 , idx . y ) ) ;
}
}
cache . xy = z . yw ;
sum += z * z ;
}
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
vec4 result = xAtOutputCoords * $ { i } ;
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},rne=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:c}=r,u=q().getBool("WEBGL_PACK_NORMALIZATION")?new nne(s.shape,a,o,i,c):new tne(s.shape,a,o,i,c);return n.runWebGLProgram(u,[s],s.dtype)},sne={kernelName:bd,backendName:"webgl",kernelFunc:rne},ane=class{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
float result = 0.0 ;
for ( int d = 0 ; d < $ { this . depth } ; ++ d ) {
int depthBegin = int ( max ( 0.0 , float ( d - $ { t } ) ) ) ;
int depthEnd = int ( min ( float ( $ { this . depth } ) ,
float ( d + $ { t } + 1 ) ) ) ;
const int MIN _DEPTH _BEGIN = 0 ;
const int MAX _DEPTH _END = $ { this . depth } ;
float norm = 0.0 ;
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
norm += getInputImage ( b , r , c , k ) * getInputImage ( b , r , c , k ) ;
}
else {
break ;
}
}
2022-10-30 14:06:17 +01:00
norm = float ( $ { r } ) * norm + float ( $ { n } ) ;
2021-09-11 17:11:38 +02:00
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
2022-10-30 14:06:17 +01:00
float dyi = - 2.0 * float ( $ { r } )
* float ( $ { s } )
2021-09-11 17:11:38 +02:00
* getInputImage ( b , r , c , k ) * getOutputImage ( b , r , c , d )
/ n o r m ;
if ( k == d ) {
2022-10-30 14:06:17 +01:00
dyi += pow ( norm , - 1.0 * $ { s } ) ;
2021-09-11 17:11:38 +02:00
}
if ( k == coords [ 3 ] ) {
dyi *= getDy ( b , r , c , d ) ;
result += dyi ;
}
}
else {
break ;
}
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2021-03-26 15:26:02 +01:00
}
2022-10-30 14:06:17 +01:00
` }},one=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:c,alpha:u,beta:l}=r,p=new ane(s.shape,i,c,u,l);return n.runWebGLProgram(p,[s,a,o],s.dtype)},ine={kernelName:Af,backendName:"webgl",kernelFunc:one};function cne(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=he({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=Si(i,e.dtype,"max",r),u=he({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),u}function FE(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=N.getAxesPermutation(u,i),p=l!=null,d=n.shouldExecuteOnCPU([s]),h=s;if(p){if(d){let v=n.texData.get(h.dataId).values,x=new Array(i);for(let C=0;C<x.length;C++)x[C]=s.shape[l[C]];let k=aI(v,s.shape,s.dtype,l,x);h=n.makeTensorInfo(x,s.dtype);let S=n.texData.get(h.dataId);S.values=k}else h=Zm(s,l,n);u=N.getInnerMostAxes(u.length,i)}N.assertAxesAreInnerMostDims("max",u,i);let[f,m]=N.computeOutAndReduceShapes(h.shape,u),g=f;o&&(g=N.expandShapeToKeepDim(f,c));let b;if(d){let v=n.texData.get(h.dataId).values,x=x9(v,w.sizeFromShape(m),g,s.dtype);b=n.makeTensorInfo(g,s.dtype);let k=n.texData.get(b.dataId);k.values=x}else b=cne(h,m,g,n);return p&&n.disposeIntermediateTensorInfo(h),b}var une={kernelName:zo,backendName:"webgl",kernelFunc:FE},lne=oI+ `
2021-09-11 17:11:38 +02:00
return max ( a , b ) ;
2022-10-30 14:06:17 +01:00
` ,dne= `
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( max ( a , b ) ) ;
2022-10-09 19:40:33 +02:00
bvec4 isNaNA = isnan ( a ) ;
bvec4 isNaNB = isnan ( b ) ;
bvec4 isNaN = bvec4 ( isNaNA . x || isNaNB . x , isNaNA . y || isNaNB . y , isNaNA . z || isNaNB . z , isNaNA . w || isNaNB . w ) ;
2022-10-30 14:06:17 +01:00
` +cp+ `
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,pne=dn({opSnippet:lne,packedOpSnippet:dne,cpuKernelImpl:w9}),hne={kernelName:Bo,backendName:"webgl",kernelFunc:pne};function fne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Yu(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,u=1;w.assert(N.eitherStridesOrDilationsAreOne(o,u),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { o } and dilations '${u}' ` );let l=N.computePool2DInfo(s.shape,a,o,u,i,c);if(l.filterWidth===1&&l.filterHeight===1&&w.arraysEqual(l.inShape,l.outShape))return sr({inputs:{x:s},backend:n});let p=new id(l,"max",!1);return n.runWebGLProgram(p,[s],s.dtype)}var mne={kernelName:Wo,backendName:"webgl",kernelFunc:fne};function gne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dataFormat:c,dimRoundingMode:u}=r,l=[1,1,1],p=N.computePool3DInfo(s.shape,a,o,l,i,u,c),d=new cI(p,"max",!1);return n.runWebGLProgram(d,[s],s.dtype)}var bne={kernelName:yd,backendName:"webgl",kernelFunc:gne},yne=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=s-1-e.padInfo.top,i=a-1-e.padInfo.left,c=s*a-1;this.userCode= `
const ivec2 pads = ivec2 ( $ { o } , $ { i } ) ;
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { s } ;
wR += $ { r } ) {
2021-09-11 17:11:38 +02:00
float dyR = float ( dyRCorner + wR ) / $ { t } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2022-10-30 14:06:17 +01:00
for ( int wC = 0 ; wC < $ { a } ; wC ++ ) {
2021-09-11 17:11:38 +02:00
float dyC = float ( dyCCorner + wC ) / $ { n } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( b , idyR , idyC , d ) ;
2022-10-30 14:06:17 +01:00
int maxPosValue = $ { c } - int ( getMaxPos ( b , idyR , idyC , d ) ) ;
2021-09-11 17:11:38 +02:00
// Get the current value, check it against the value from the
// position matrix.
2022-10-30 14:06:17 +01:00
int curPosValue = wR * $ { a } + wC ;
2021-09-11 17:11:38 +02:00
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask ;
}
}
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},vne=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,c=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=i-1-e.padInfo.front,p=c-1-e.padInfo.top,d=u-1-e.padInfo.left,h=i*c*u-1;this.userCode= `
const ivec3 pads = ivec3 ( $ { l } , $ { p } , $ { d } ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2022-10-30 14:06:17 +01:00
for ( int wD = 0 ; wD < $ { i } ;
wD += $ { s } ) {
2021-09-11 17:11:38 +02:00
float dyD = float ( dyDCorner + wD ) / $ { t } . 0 ;
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
continue ;
}
int idyD = int ( dyD ) ;
2022-10-30 14:06:17 +01:00
for ( int wR = 0 ; wR < $ { c } ;
wR += $ { a } ) {
2021-09-11 17:11:38 +02:00
float dyR = float ( dyRCorner + wR ) / $ { n } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2022-03-07 19:17:31 +01:00
for ( int wC = 0 ; wC < $ { u } ;
2022-10-30 14:06:17 +01:00
wC += $ { o } ) {
float dyC = float ( dyCCorner + wC ) / $ { r } . 0 ;
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
int maxPosValue = $ { h } -
int ( getMaxPos ( batch , idyD , idyR , idyC , ch ) ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
2022-10-30 14:06:17 +01:00
wD * $ { c } * $ { u } +
2022-03-07 19:17:31 +01:00
wR * $ { u } + wC ;
2021-09-11 17:11:38 +02:00
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask ;
}
}
}
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function xne(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:u,dimRoundingMode:l}=r,p=[1,1,1],d=N.computePool3DInfo(o.shape,i,c,p,u,l),h=new cI(d,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new vne(d),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var wne={kernelName:Df,backendName:"webgl",kernelFunc:xne};function Ine(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Yu([a,o],"maxPoolGrad");let{filterSize:c,strides:u,pad:l,dimRoundingMode:p}=r,d=N.computePool2DInfo(i.shape,c,u,1,l,p),h=!0,f=new id(d,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new yne(d),b=n.runWebGLProgram(g,[s,m],i.dtype);return n.disposeIntermediateTensorInfo(m),b}var kne={kernelName: $ f,backendName:"webgl",kernelFunc:Ine};function Sne(e,t,n,r){let s=new id(n,"max",!1),a=r.runWebGLProgram(s,[e],"float32");s=new id(n,"max",!0,!0,t);let o=r.runWebGLProgram(s,[e],"float32");return[a,o]}var Tne={kernelName:Ff,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,c=n;w.assert(r.shape.length===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { r . shape . length } . ` );let u=[1,1];w.assert(N.eitherStridesOrDilationsAreOne(a,u),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { a } and dilations '${u}' ` );let l=N.computePool2DInfo(r.shape,s,a,u,o),[p,d]=Sne(r,i,l,c);return[p,d]}};function Cne(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=he({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=Si(i,"float32","mean",r),u=he({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),u}var Nne={kernelName:Vo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{keepDims:s,axis:a}=t,o=n,i=r.shape.length,c=w.parseAxisParam(a,r.shape),u=c,l=N.getAxesPermutation(u,i),p=l!=null,d=o.shouldExecuteOnCPU([r]),h=[],f=r;if(p){if(d){let x=o.texData.get(f.dataId).values,k=new Array(i);for(let E=0;E<k.length;E++)k[E]=r.shape[l[E]];let S=aI(x,r.shape,r.dtype,l,k);f=o.makeTensorInfo(k,r.dtype);let C=o.texData.get(f.dataId);C.values=S}else f=Zm(r,l,o);h.push(f),u=N.getInnerMostAxes(u.length,i)}N.assertAxesAreInnerMostDims("sum",u,i);let[m,g]=N.computeOutAndReduceShapes(f.shape,u),b=m;s&&(b=N.expandShapeToKeepDim(m,c));let y=Cne(f,g,b,o);for(let v of h)o.disposeIntermediateTensorInfo(v);return y}};function _ne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=N.getAxesPermutation(u,i),p=s;l!=null&&(p=Nn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=N.getInnerMostAxes(u.length,s.shape.length)),N.assertAxesAreInnerMostDims("min",u,i);let[d,h]=N.computeOutAndReduceShapes(p.shape,u),f=w.sizeFromShape(h),m=he({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}}),g=Si(m,m.dtype,"min",n),b;if(o){let y=N.expandShapeToKeepDim(d,c);b=he({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=he({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(p),b}var Ene={kernelName:Uo,backendName:"webgl",kernelFunc:_ne},Ane=oI+ `
2021-09-11 17:11:38 +02:00
return min ( a , b ) ;
2022-10-30 14:06:17 +01:00
` , $ ne= `
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( min ( a , b ) ) ;
2022-10-09 19:40:33 +02:00
bvec4 isNaNA = isnan ( a ) ;
bvec4 isNaNB = isnan ( b ) ;
bvec4 isNaN = bvec4 ( isNaNA . x || isNaNB . x , isNaNA . y || isNaNB . y , isNaNA . z || isNaNB . z , isNaNA . w || isNaNB . w ) ;
2022-10-30 14:06:17 +01:00
` +cp+ `
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,Dne=dn({opSnippet:Ane,packedOpSnippet: $ ne,cpuKernelImpl:I9}),Fne={kernelName:Go,backendName:"webgl",kernelFunc:Dne},Rne=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,l)=>u[0]+e[l]+u[1]);let r=e.length,s=mt(r),a=t.map(u=>u[0]).join(","),o=t.map((u,l)=>u[0]+e[l]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),c=n==="reflect"?0:1;if(r===1){this.userCode= `
int start = $ { a } ;
int end = $ { o } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start ) {
2022-10-30 14:06:17 +01:00
outC = start * 2 - outC - $ { c } ;
2021-09-11 17:11:38 +02:00
} else if ( outC >= end ) {
2022-10-30 14:06:17 +01:00
outC = ( end - 1 ) * 2 - outC + $ { c } ;
2021-09-11 17:11:38 +02:00
}
setOutput ( getX ( outC - start ) ) ;
}
` ;return}this.userCode= `
2022-10-30 14:06:17 +01:00
$ { s } start = $ { s } ( $ { a } ) ;
$ { s } end = $ { s } ( $ { o } ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { s } outC = getOutputCoords ( ) ;
for ( int i = 0 ; i < $ { r } ; i ++ ) {
2021-09-11 17:11:38 +02:00
if ( outC [ i ] < start [ i ] ) {
2022-10-30 14:06:17 +01:00
outC [ i ] = start [ i ] * 2 - outC [ i ] - $ { c } ;
2021-09-11 17:11:38 +02:00
} else if ( outC [ i ] >= end [ i ] ) {
2022-10-30 14:06:17 +01:00
outC [ i ] = ( end [ i ] - 1 ) * 2 - outC [ i ] + $ { c } ;
2021-09-11 17:11:38 +02:00
}
}
2022-10-30 14:06:17 +01:00
$ { s } coords = outC - start ;
setOutput ( getX ( $ { i } ) ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }},Pne=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let r=e.length,s=mt(r),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=Tn("rc",r),c=Tn("source",r),u= ` $ { i [ r - 1 ] } < $ { this . outputShape [ r - 1 ] } ` ,l=r===1?"source": ` vec2 ( $ { c . slice ( - 2 ) . join ( ) } ) ` ,p=n==="reflect"?0:1,d="";if(r===1){let h= `
$ { s } source = rc ;
2021-09-11 17:11:38 +02:00
if ( source < start ) {
2022-10-30 14:06:17 +01:00
source = start * 2 - source - $ { p } ;
2021-09-11 17:11:38 +02:00
} else if ( source >= end ) {
2022-10-30 14:06:17 +01:00
source = ( end - 1 ) * 2 - source + $ { p } ;
2021-09-11 17:11:38 +02:00
}
source -= start ;
2022-10-30 14:06:17 +01:00
` ;d= `
$ { s } rc = outputLoc ;
2021-09-11 17:11:38 +02:00
$ { h }
2022-10-30 14:06:17 +01:00
result [ 0 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { l } ) ;
$ { i [ r - 1 ] } += 1 ;
2022-03-07 19:17:31 +01:00
if ( $ { u } ) {
2021-09-11 17:11:38 +02:00
$ { h }
2022-10-30 14:06:17 +01:00
result [ 1 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { l } ) ;
2021-09-11 17:11:38 +02:00
}
` }else{let h= `
2022-10-30 14:06:17 +01:00
$ { s } source = rc ;
$ { s } lt = $ { s } ( lessThan ( source , start ) ) ;
$ { s } gte = $ { s } ( greaterThanEqual ( source , end ) ) ;
$ { s } orig = 1 - ( lt + gte ) ;
2021-09-11 17:11:38 +02:00
source = orig * source +
2022-10-30 14:06:17 +01:00
lt * ( start * 2 - source - $ { p } ) +
gte * ( ( end - 1 ) * 2 - source + $ { p } ) ;
2021-09-11 17:11:38 +02:00
source -= start ;
2022-10-30 14:06:17 +01:00
` ;d= `
$ { s } rc = outputLoc ;
2021-09-11 17:11:38 +02:00
$ { h }
2022-10-30 14:06:17 +01:00
result [ 0 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { l } ) ;
$ { i [ r - 1 ] } += 1 ;
2022-03-07 19:17:31 +01:00
if ( $ { u } ) {
2021-09-11 17:11:38 +02:00
$ { h }
2022-10-30 14:06:17 +01:00
result [ 1 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { l } ) ;
2021-09-11 17:11:38 +02:00
}
rc = outputLoc ;
2022-10-30 14:06:17 +01:00
$ { i [ r - 2 ] } += 1 ;
if ( $ { i [ r - 2 ] } < $ { this . outputShape [ r - 2 ] } ) {
2021-09-11 17:11:38 +02:00
$ { h }
2022-10-30 14:06:17 +01:00
result [ 2 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { l } ) ;
$ { i [ r - 1 ] } += 1 ;
2022-03-07 19:17:31 +01:00
if ( $ { u } ) {
2021-09-11 17:11:38 +02:00
$ { h }
2022-10-30 14:06:17 +01:00
result [ 3 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { l } ) ;
2021-09-11 17:11:38 +02:00
}
}
` }this.userCode= `
2022-10-30 14:06:17 +01:00
const $ { s } start = $ { s } ( $ { a } ) ;
const $ { s } end = $ { s } ( $ { o } ) ;
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { s } outputLoc = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2022-10-30 14:06:17 +01:00
$ { d }
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2020-12-15 14:15:43 +01:00
}
2022-10-30 14:06:17 +01:00
` }},One=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{paddings:s,mode:a}=n,o=q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Pne(r.shape,s,a):new Rne(r.shape,s,a);return t.runWebGLProgram(o,[r],r.dtype)},Mne={kernelName:Ho,backendName:"webgl",kernelFunc:One},Lne= ` if ( b == 0.0 ) return NAN ;
return mod ( a , b ) ; ` ,zne= `
2021-09-11 17:11:38 +02:00
vec4 result = mod ( a , b ) ;
2022-10-09 19:40:33 +02:00
bvec4 isNaN = equal ( b , vec4 ( 0.0 ) ) ;
2022-10-30 14:06:17 +01:00
` +cp+ `
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,Bne=dn({opSnippet:Lne,packedOpSnippet:zne}),Wne={kernelName:du,backendName:"webgl",kernelFunc:Bne},Vne=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float r = random ( seed ) ;
float cdf = 0.0 ;
for ( int i = 0 ; i < $ { t - 1 } ; i ++ ) {
cdf += getProbs ( batch , i ) ;
if ( r < cdf ) {
setOutput ( float ( i ) ) ;
return ;
}
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// If no other event happened, last event happened.
setOutput ( float ( $ { t - 1 } ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},Une= `
2021-09-11 17:11:38 +02:00
if ( a == b ) {
return 1.0 ;
} ;
2022-10-30 14:06:17 +01:00
return a / b ; ` ,Gne= `
2021-09-11 17:11:38 +02:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b ;
if ( a . x == b . x ) {
result . x = 1. ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( a . y == b . y ) {
result . y = 1. ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( a . z == b . z ) {
result . z = 1. ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( a . w == b . w ) {
result . w = 1. ;
2021-04-01 19:39:54 +02:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,RE=dn({opSnippet:Une,packedOpSnippet:Gne,checkOutOfBounds:!0}),Hne={kernelName:Eo,backendName:"webgl",kernelFunc:RE},F1="return a - b;",PE=dn({opSnippet:F1,packedOpSnippet:F1,supportsComplex:!0,cpuKernelImpl:V9}),qne={kernelName:di,backendName:"webgl",kernelFunc:PE};function OE(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=w.parseAxisParam([a],s.shape),i=FE({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=N.expandShapeToKeepDim(i.shape,o),u=he({inputs:{x:i},backend:n,attrs:{shape:c}}),l=PE({inputs:{a:s,b:u},backend:n}),p=AE({inputs:{x:l},backend:n}),d=Jm({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),h=he({inputs:{x:d},backend:n,attrs:{shape:c}}),f=RE({inputs:{a:p,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),f}var jne={kernelName:ui,backendName:"webgl",kernelFunc:OE};function Kne(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r,c=i?s:OE({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),u=c.shape[0],l=c.shape[1],p=new Vne(u,l,a),d=[[o]],h=n.runWebGLProgram(p,[c],"int32",d);return i||n.disposeIntermediateTensorInfo(c),h}var Xne={kernelName:Rf,backendName:"webgl",kernelFunc:Kne},Yne=Or+ `
2022-01-14 16:04:13 +01:00
return - x ;
2022-10-30 14:06:17 +01:00
` ,Zne= `
2022-01-14 16:04:13 +01:00
vec4 result = - x ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-10-30 14:06:17 +01:00
` ;function Jne(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.texData.get(r.dataId),[o,i]=S9(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s;return q().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Ka(r.shape,Zne):s=new Ns(r.shape,Yne),n.runWebGLProgram(s,[r],r.dtype)}var Qne={kernelName:pu,backendName:"webgl",kernelFunc:Jne},ere=fs.nonMaxSuppressionV3Impl;function tre(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c}=r,u=n.readSync(s.dataId),l=n.readSync(a.dataId),{selectedIndices:p}=ere(u,l,o,i,c);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var nre={kernelName:fu,backendName:"webgl",kernelFunc:tre},rre=fs.nonMaxSuppressionV4Impl;function sre(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,padToMaxOutputSize:u}=r,l=n.readSync(s.dataId),p=n.readSync(a.dataId),{selectedIndices:d,validOutputs:h}=rre(l,p,o,i,c,u);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var are={kernelName:mu,backendName:"webgl",kernelFunc:sre},ore=fs.nonMaxSuppressionV5Impl;function ire(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,softNmsSigma:u}=r,l=n.readSync(s.dataId),p=n.readSync(a.dataId),d=o,h=i,f=c,m=u,{selectedIndices:g,selectedScores:b}=ore(l,p,d,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var cre={kernelName:gu,backendName:"webgl",kernelFunc:ire},ure=class{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int index = round ( getIndices ( coords . x ) ) ;
2022-10-30 14:06:17 +01:00
setOutput ( mix ( float ( $ { r } ) , float ( $ { n } ) ,
2021-09-11 17:11:38 +02:00
float ( index == coords . y ) ) ) ;
2021-03-26 15:26:02 +01:00
}
2022-10-30 14:06:17 +01:00
` }},lre=e=>{let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{dtype:a,depth:o,onValue:i,offValue:c}=r,u=w.sizeFromShape(s.shape),l=new ure(u,o,i,c),p=he({inputs:{x:s},backend:n,attrs:{shape:[u]}}),d=n.runWebGLProgram(l,[p],a);n.disposeIntermediateTensorInfo(p);let h=[...s.shape,o],f=he({inputs:{x:d},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(d),f},dre={kernelName:jo,backendName:"webgl",kernelFunc:lre};function af(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=lp({inputs:{input:r},backend:n}),a=af({inputs:{x:s},backend:n}),o=Qm({inputs:{input:r},backend:n}),i=af({inputs:{x:o},backend:n}),c=Ea({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return dp({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var pre={kernelName:Pu,backendName:"webgl",kernelFunc:af};function ME(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(r.dtype==="complex64"){let s=lp({inputs:{input:r},backend:n}),a=ME({inputs:{x:s},backend:n}),o=Qm({inputs:{input:r},backend:n}),i=af({inputs:{x:o},backend:n}),c=Ea({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return dp({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var hre={kernelName:bu,backendName:"webgl",kernelFunc:ME};function fre(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return xv({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(l=>{w.assertShapesMatch(a,l.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===l.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(l=>{let p=xv({inputs:{input:l},backend:n,attrs:{dim:s}});return i.push(p),p}),u=IE({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(l=>n.disposeIntermediateTensorInfo(l)),u}var mre={kernelName:yu,backendName:"webgl",kernelFunc:fre},gre=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((c,u)=>c[0]+e[u]+c[1]);let r=e.length,s=mt(r),a=t.map(c=>c[0]).join(","),o=t.map((c,u)=>c[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode= `
int start = $ { a } ;
int end = $ { o } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start || outC >= end ) {
setOutput ( value ) ;
} else {
setOutput ( getX ( outC - start ) ) ;
}
}
` ;return}this.userCode= `
2022-10-30 14:06:17 +01:00
$ { s } start = $ { s } ( $ { a } ) ;
$ { s } end = $ { s } ( $ { o } ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { s } outC = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
if ( any ( lessThan ( outC , start ) ) || any ( greaterThanEqual ( outC , end ) ) ) {
setOutput ( value ) ;
} else {
2022-10-30 14:06:17 +01:00
$ { s } coords = outC - start ;
setOutput ( getX ( $ { i } ) ) ;
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},bre=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let r=e.length,s=mt(r),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=Tn("rc",r),c=Tn("source",r),u= ` $ { i [ r - 1 ] } < $ { this . outputShape [ r - 1 ] } ` ,l=r===1?"source": ` vec2 ( $ { c . slice ( - 2 ) . join ( ) } ) ` ,p=[ ` $ { s } rc = outputLoc ; ` , ` $ { i [ r - 1 ] } += 1 ;
2022-03-07 19:17:31 +01:00
if ( $ { u } ) {
2022-10-30 14:06:17 +01:00
` ,r===1?"": ` }
2021-09-11 17:11:38 +02:00
rc = outputLoc ;
2022-10-30 14:06:17 +01:00
$ { i [ r - 2 ] } += 1 ;
if ( $ { i [ r - 2 ] } < $ { this . outputShape [ r - 2 ] } ) { ` ,r===1?"": ` $ { i [ r - 1 ] } += 1 ;
if ( $ { u } ) { ` ],d=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=r===1?2:4;f<m;f++)h+= `
$ { p [ f ] }
if ( $ { d } ) {
result [ $ { f } ] = float ( value ) ;
2021-09-11 17:11:38 +02:00
} else {
2022-10-30 14:06:17 +01:00
$ { s } source = rc - start ;
result [ $ { f } ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { l } ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` ;h+=r===1?"} ":"}}",this.userCode= `
const $ { s } start = $ { s } ( $ { a } ) ;
const $ { s } end = $ { s } ( $ { o } ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { s } outputLoc = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
$ { h }
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},LE=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(w.sizeFromShape(s.shape)===0){let u=a.map((l,p)=>l[0]+s.shape[p]+l[1]);return dp({backend:n,attrs:{shape:u,value:o,dtype:s.dtype}})}let i=q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new bre(s.shape,a,o):new gre(s.shape,a,o),c=[[o]];return n.runWebGLProgram(i,[s],s.dtype,c)},yre={kernelName:Ko,backendName:"webgl",kernelFunc:LE},vre= `
2021-09-11 17:11:38 +02:00
if ( a < 0.0 && floor ( b ) < b ) {
return NAN ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( b == 0.0 ) {
return 1.0 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return ( round ( mod ( b , 2.0 ) ) != 1 ) ?
pow ( abs ( a ) , b ) : sign ( a ) * pow ( abs ( a ) , b ) ;
2022-10-30 14:06:17 +01:00
` ,xre= `
2021-09-11 17:11:38 +02:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4 ( equal ( round ( mod ( b , 2.0 ) ) , ivec4 ( 1 ) ) ) ;
vec4 multiplier = sign ( a ) * isModRound1 + ( vec4 ( 1.0 ) - isModRound1 ) ;
vec4 result = multiplier * pow ( abs ( a ) , b ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal ( b , vec4 ( 0.0 ) ) ;
result . r = isExpZero . r ? 1.0 : result . r ;
result . g = isExpZero . g ? 1.0 : result . g ;
result . b = isExpZero . b ? 1.0 : result . b ;
result . a = isExpZero . a ? 1.0 : result . a ;
2020-10-11 18:41:17 +02:00
2022-10-09 19:40:33 +02:00
bvec4 isNaN1 = lessThan ( a , vec4 ( 0.0 ) ) ;
bvec4 isNaN2 = lessThan ( floor ( b ) , b ) ;
bvec4 isNaN = bvec4 ( isNaN1 . x && isNaN2 . x , isNaN1 . y && isNaN2 . y , isNaN1 . z && isNaN2 . z , isNaN1 . w && isNaN2 . w ) ;
2022-10-30 14:06:17 +01:00
` +cp+ `
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,wre=dn({opSnippet:vre,packedOpSnippet:xre}),Ire={kernelName:Xo,backendName:"webgl",kernelFunc:wre};function kre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=[],u=w.parseAxisParam(a,s.shape),l=u,p=N.getAxesPermutation(l,i),d=s;p!=null&&(d=Nn({inputs:{x:s},backend:n,attrs:{perm:p}}),l=N.getInnerMostAxes(l.length,i),c.push(d)),N.assertAxesAreInnerMostDims("prod",l,i);let h;if(n.shouldExecuteOnCPU([d])){let f=n.texData.get(d.dataId).values,{outVals:m,outShape:g,outDtype:b}=C9(d.shape,d.dtype,f,l);h=n.makeTensorInfo(g,b,m)}else{let[f,m]=N.computeOutAndReduceShapes(d.shape,l),g=w.sizeFromShape(m),b=he({inputs:{x:d},backend:n,attrs:{shape:[-1,g]}}),y=Hf(s.dtype),v=Si(b,y,"prod",n);h=he({inputs:{x:v},backend:n,attrs:{shape:f}}),c.push(b),c.push(v)}if(o){c.push(h);let f=N.expandShapeToKeepDim(h.shape,u);h=he({inputs:{x:h},backend:n,attrs:{shape:f}})}return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var Sre={kernelName:Zo,backendName:"webgl",kernelFunc:kre};function Tre(e){let{inputs:t,backend:n,attrs:r}=e,{paramsNestedSplits:s,paramsDenseValues:a,indices:o}=t,{outputRaggedRank:i}=r,c=s.map(b=>n.readSync(b.dataId)),u=s.map(b=>b.shape),l=n.readSync(a.dataId),p=n.readSync(o.dataId),[d,h,f]=N9(c,u,l,a.shape,a.dtype,p,o.shape,i),m=d.map(b=>n.makeTensorInfo([b.length],"int32",b)),g=n.makeTensorInfo(f,a.dtype,h);return m.concat([g])}var Cre={kernelName:Pf,backendName:"webgl",kernelFunc:Tre};function Nre(e){let{inputs:t,backend:n}=e,{starts:r,limits:s,deltas:a}=t,o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[u,l]=_9(o,r.shape,r.dtype,i,s.shape,c,a.shape),p=n.makeTensorInfo([u.length],"int32",u),d=n.makeTensorInfo([l.length],r.dtype,l);return[p,d]}var _re={kernelName:Of,backendName:"webgl",kernelFunc:Nre};function Ere(e){let{inputs:t,backend:n,attrs:r}=e,{shape:s,values:a,defaultValue:o,rowPartitionTensors:i}=t,{rowPartitionTypes:c}=r,u=n.readSync(s.dataId),l=n.readSync(a.dataId),p=n.readSync(o.dataId),d=i.map(g=>n.readSync(g.dataId)),h=i.map(g=>g.shape),[f,m]=E9(u,s.shape,l,a.shape,a.dtype,p,o.shape,d,h,c);return n.makeTensorInfo(f,a.dtype,m)}var Are={kernelName:Mf,backendName:"webgl",kernelFunc:Ere},zE=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=A9(r,s,a,o);return t.makeTensorInfo([i.length],o,i)}, $ re={kernelName:vd,backendName:"webgl",kernelFunc:zE},Dre="return 1.0 / x;",Fre=Ye({opSnippet:Dre}),Rre={kernelName:vu,backendName:"webgl",kernelFunc:Fre},Pre=Or+ `
2021-09-11 17:11:38 +02:00
return ( x < 0.0 ) ? 0.0 : x ;
2022-10-30 14:06:17 +01:00
` ,Ore= `
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-10-30 14:06:17 +01:00
` ,Mre=Ye({opSnippet:Pre,packedOpSnippet:Ore}),Lre={kernelName:Jo,backendName:"webgl",kernelFunc:Mre},zre=Or+ `
2021-09-11 17:11:38 +02:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2022-10-30 14:06:17 +01:00
` ,Bre= `
2021-09-11 17:11:38 +02:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-10-30 14:06:17 +01:00
` ,Wre=Ye({opSnippet:zre,packedOpSnippet:Bre}),Vre={kernelName:ti,backendName:"webgl",kernelFunc:Wre},Ure=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],p;s?p="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
2022-10-30 14:06:17 +01:00
$ { u [ 0 ] / l [ 0 ] } ,
$ { u [ 1 ] / l [ 1 ] } ) ;
const vec2 inputShapeRC = vec2 ( $ { o } . 0 , $ { i } . 0 ) ;
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
2022-10-30 14:06:17 +01:00
vec2 sourceFracIndexRC = $ { p } ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2 ( max ( sourceFracIndexRC , vec2 ( 0.0 ) ) ) ;
ivec2 sourceCeilRC = ivec2 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float topLeft = getA ( b , sourceFloorRC . x , sourceFloorRC . y , d ) ;
float bottomLeft = getA ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ;
float topRight = getA ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ;
float bottomRight = getA ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec2 fracRC = sourceFracIndexRC - vec2 ( sourceFloorRC ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float top = topLeft + ( topRight - topLeft ) * fracRC . y ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracRC . y ;
float newValue = top + ( bottom - top ) * fracRC . x ;
setOutput ( newValue ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},Gre=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],p;s?p="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
2022-10-30 14:06:17 +01:00
$ { u [ 0 ] / l [ 0 ] } ,
$ { u [ 1 ] / l [ 1 ] } ,
$ { u [ 1 ] / l [ 1 ] } ) ;
const vec3 inputShapeRC = vec3 ( $ { o } . 0 , $ { i } . 0 ,
$ { i } . 0 ) ;
2021-09-11 17:11:38 +02:00
float getAValue ( int b , int r , int c , int d ) {
return getChannel ( getA ( b , r , c , d ) , vec2 ( c , d ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
// Calculate values for next column in yRC.z.
ivec3 yRC = coords . yzz + ivec3 ( 0 , 0 , 1 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
2022-10-30 14:06:17 +01:00
vec3 sourceFracIndexRC = $ { p } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3 ( max ( sourceFracIndexRC , vec3 ( 0.0 ) ) ) ;
ivec3 sourceCeilRC = ivec3 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
2022-10-30 14:06:17 +01:00
bool hasNextCol = d < $ { c - 1 } ;
2021-09-11 17:11:38 +02:00
bool hasNextRow = coords . z < $ { n - 1 } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4 (
getAValue ( b , sourceFloorRC . x , sourceFloorRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceFloorRC . x , sourceFloorRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceFloorRC . x , sourceFloorRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceFloorRC . x , sourceFloorRC . z , d + 1 ) : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 bottomLeft = vec4 (
getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d + 1 ) : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 topRight = vec4 (
getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 bottomRight = vec4 (
getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec3 fracRC = sourceFracIndexRC - vec3 ( sourceFloorRC ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 top = mix ( topLeft , topRight , fracRC . yyzz ) ;
vec4 bottom = mix ( bottomLeft , bottomRight , fracRC . yyzz ) ;
vec4 newValue = mix ( top , bottom , fracRC . x ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( newValue ) ;
}
2022-10-30 14:06:17 +01:00
` }};function Hre(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,u]=i,l=q().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Gre(s.shape,c,u,a,o):new Ure(s.shape,c,u,a,o);return n.runWebGLProgram(l,[s],"float32")}var qre={kernelName:ei,backendName:"webgl",kernelFunc:Hre},jre=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],u=i[0]/c[0],l=i[1]/c[1],p=1/u,d=1/l,h=Math.ceil(p)*2+2,f=Math.ceil(d)*2+2;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float accumulator = 0.0 ;
2020-10-11 18:41:17 +02:00
2022-03-07 19:17:31 +01:00
const float heightScale = float ( $ { u } ) ;
2022-10-30 14:06:17 +01:00
const float widthScale = float ( $ { l } ) ;
2020-10-11 18:41:17 +02:00
2022-10-30 14:06:17 +01:00
const float invHeightScale = float ( $ { p } ) ;
const float invWidthScale = float ( $ { d } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
const int winHeight = int ( $ { h } ) ;
2022-10-30 14:06:17 +01:00
const int winWidth = int ( $ { f } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor ( float ( r ) * invHeightScale ) ;
int startDyR = int ( startRLerp - float ( winHeight / 2 ) ) ;
2021-05-27 22:04:17 +02:00
2021-09-11 17:11:38 +02:00
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( startCLerp - float ( winWidth / 2 ) ) ;
2021-05-27 22:04:17 +02:00
2021-09-11 17:11:38 +02:00
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
2022-10-30 14:06:17 +01:00
if ( dyR < 0 || dyR >= $ { a } ) {
2021-09-11 17:11:38 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
2022-10-30 14:06:17 +01:00
if ( dyC < 0 || dyC >= $ { o } ) {
2021-09-11 17:11:38 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float dxR = float ( dyR ) * heightScale ;
int topDxRIndex = int ( floor ( dxR ) ) ;
2022-10-30 14:06:17 +01:00
int bottomDxRIndex = int ( min ( ceil ( dxR ) , $ { r - 1 } . 0 ) ) ;
2021-09-11 17:11:38 +02:00
float dxRLerp = dxR - float ( topDxRIndex ) ;
float inverseDxRLerp = 1.0 - dxRLerp ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float dxC = float ( dyC ) * widthScale ;
int leftDxCIndex = int ( floor ( dxC ) ) ;
2022-10-30 14:06:17 +01:00
int rightDxCIndex = int ( min ( ceil ( dxC ) , $ { s - 1 } . 0 ) ) ;
2021-09-11 17:11:38 +02:00
float dxCLerp = dxC - float ( leftDxCIndex ) ;
float inverseDxCLerp = 1.0 - dxCLerp ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
if ( r == topDxRIndex && c == leftDxCIndex ) {
// topLeft
accumulator +=
getDy ( b , dyR , dyC , d ) * inverseDxRLerp * inverseDxCLerp ;
}
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
if ( r == topDxRIndex && c == rightDxCIndex ) {
// topRight
accumulator += getDy ( b , dyR , dyC , d ) * inverseDxRLerp * dxCLerp ;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if ( r == bottomDxRIndex && c == leftDxCIndex ) {
// bottomLeft
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * inverseDxCLerp ;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if ( r == bottomDxRIndex && c == rightDxCIndex ) {
// bottomRight
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * dxCLerp ;
}
}
}
// End loop over dy
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput ( accumulator ) ;
2021-03-31 13:01:22 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function Kre(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new jre(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Xre={kernelName:Bf,backendName:"webgl",kernelFunc:Kre},Yre=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=r?"0.5":"0.0",d;s?d="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
2022-10-30 14:06:17 +01:00
$ { u [ 0 ] / l [ 0 ] } ,
$ { u [ 1 ] / l [ 1 ] } ) ;
const vec2 inputShapeRC = vec2 ( $ { o } . 0 , $ { i } . 0 ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
2022-10-30 14:06:17 +01:00
vec2 sourceFracIndexRC = $ { d } ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2 (
2022-10-30 14:06:17 +01:00
min ( inputShapeRC - 1.0 , floor ( sourceFracIndexRC + $ { p } ) ) ) ;
2021-09-11 17:11:38 +02:00
float newValue = getA ( b , sourceNearestRC . x , sourceNearestRC . y , d ) ;
setOutput ( newValue ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }},Zre=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=r?"0.5":"0.0",d;s?d="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
2022-10-30 14:06:17 +01:00
$ { u [ 0 ] / l [ 0 ] } ,
$ { u [ 1 ] / l [ 1 ] } ,
$ { u [ 1 ] / l [ 1 ] } ) ;
const vec3 inputShapeRC = vec3 ( $ { o } . 0 , $ { i } . 0 ,
$ { i } . 0 ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float getAValue ( int b , int r , int c , int d ) {
return getChannel ( getA ( b , r , c , d ) , vec2 ( c , d ) ) ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
// Calculate values for next column in yRC.z.
ivec3 yRC = coords . yzz + ivec3 ( 0 , 0 , 1 ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
2022-10-30 14:06:17 +01:00
vec3 sourceFracIndexRC = $ { d } ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3 (
2022-10-30 14:06:17 +01:00
min ( inputShapeRC - 1.0 , floor ( sourceFracIndexRC + $ { p } ) ) ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
2022-10-30 14:06:17 +01:00
bool hasNextCol = d < $ { c - 1 } ;
2021-09-11 17:11:38 +02:00
bool hasNextRow = coords . z < $ { n - 1 } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 newValue = vec4 (
getAValue ( b , sourceNearestRC . x , sourceNearestRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceNearestRC . x , sourceNearestRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceNearestRC . x , sourceNearestRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceNearestRC . x , sourceNearestRC . z , d + 1 ) : 0.0 ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput ( newValue ) ;
}
2022-10-30 14:06:17 +01:00
` }};function Jre(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,u]=i,l=q().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Zre(s.shape,c,u,a,o):new Yre(s.shape,c,u,a,o);return n.runWebGLProgram(l,[s],s.dtype)}var Qre={kernelName:Qo,backendName:"webgl",kernelFunc:Jre},ese=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],u=i[0]/c[0],l=i[1]/c[1],p=1/u,d=1/l,h=Math.ceil(p)*2+2,f=Math.ceil(d)*2+2;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float accumulator = 0.0 ;
2020-12-15 14:15:43 +01:00
2022-03-07 19:17:31 +01:00
const float heightScale = float ( $ { u } ) ;
2022-10-30 14:06:17 +01:00
const float widthScale = float ( $ { l } ) ;
2020-12-15 14:15:43 +01:00
2022-10-30 14:06:17 +01:00
const float invHeightScale = float ( $ { p } ) ;
const float invWidthScale = float ( $ { d } ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const int winHeight = int ( $ { h } ) ;
2022-10-30 14:06:17 +01:00
const int winWidth = int ( $ { f } ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor ( float ( r ) * invHeightScale ) ;
int startDyR = int ( floor ( startRLerp - float ( winHeight / 2 ) ) ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( floor ( startCLerp - float ( winWidth / 2 ) ) ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
2022-10-30 14:06:17 +01:00
if ( dyR < 0 || dyR >= $ { a } ) {
2021-09-11 17:11:38 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
2022-10-30 14:06:17 +01:00
if ( dyC < 0 || dyC >= $ { o } ) {
2021-09-11 17:11:38 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracRow =
2022-10-30 14:06:17 +01:00
float ( $ { i [ 0 ] } ) *
( float ( dyR ) / float ( $ { c [ 0 ] } ) ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracCol =
2022-10-30 14:06:17 +01:00
float ( $ { i [ 1 ] } ) *
( float ( dyC ) / float ( $ { c [ 1 ] } ) ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int sourceNearestRow = int ( min (
2022-10-30 14:06:17 +01:00
float ( int ( $ { r } ) - 1 ) ,
2021-09-11 17:11:38 +02:00
$ { n } ? float ( round ( sourceFracRow ) ) :
float ( floor ( sourceFracRow ) ) ) ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
int sourceNearestCol = int ( min (
2022-10-30 14:06:17 +01:00
float ( int ( $ { s } ) - 1 ) ,
2021-09-11 17:11:38 +02:00
$ { n } ? float ( round ( sourceFracCol ) ) :
float ( floor ( sourceFracCol ) ) ) ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( r == sourceNearestRow && c == sourceNearestCol ) {
accumulator += getDy ( b , dyR , dyC , d ) ;
}
}
}
// End loop over dy
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( accumulator ) ;
}
2022-10-30 14:06:17 +01:00
` }};function tse(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new ese(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var nse={kernelName:zf,backendName:"webgl",kernelFunc:tse},rse=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error( ` WebGL backend : Reverse of rank - $ { n } tensor is not yet supported ` );if(this.outputShape=e,n===1){this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
int coord = getOutputCoords ( ) ;
setOutput ( getX ( $ { e [ 0 ] } - coord - 1 ) ) ;
}
2022-10-30 14:06:17 +01:00
` ;return}let r=o=>t.indexOf(o)!==-1&&e[o]!==1? ` $ { e [ o ] } - coords [ $ { o } ] - 1 ` : ` coords [ $ { o } ] ` ,s=e.map((o,i)=>r(i)).join(","),a=mt(n);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { a } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { s } ) ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }},sse=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error( ` WebGL backend : Reverse of rank - $ { n } tensor is not yet supported ` );this.outputShape=e;let r=Tn("rc",n),s= ` $ { r [ n - 1 ] } + 1 < $ { this . outputShape [ n - 1 ] } ` ,a= ` $ { r [ n - 2 ] } + 1 < $ { this . outputShape [ n - 2 ] } ` ,o=mt(n);n===1?this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
int rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result . r = getChannel ( getX ( $ { e [ 0 ] } - rc - 1 ) ,
$ { e [ 0 ] } - rc - 1 ) ;
2022-10-30 14:06:17 +01:00
if ( $ { s } ) {
2021-09-11 17:11:38 +02:00
result . g = getChannel ( getX ( $ { e [ 0 ] } - ( rc + 1 ) - 1 ) ,
$ { e [ 0 ] } - ( rc + 1 ) - 1 ) ;
}
setOutput ( result ) ;
}
` :this.userCode= `
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { o } rc = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2022-10-30 14:06:17 +01:00
result . r = $ { i ( r . slice ( ) ) } ;
if ( $ { s } ) {
result . g = $ { c ( r . slice ( ) ) } ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
if ( $ { a } ) {
result . b = $ { u ( r . slice ( ) ) } ;
if ( $ { s } ) {
result . a = $ { l ( r . slice ( ) ) } ;
2021-09-11 17:11:38 +02:00
}
}
setOutput ( result ) ;
}
2022-10-30 14:06:17 +01:00
` ;function i(h){return p(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",p(h)}function u(h){return h[n-2]="("+h[n-2]+" + 1)",p(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",p(h)}function p(h){let f=e.map((b,y)=>d(y,h)),m=f.join(","),g=f.slice(-2).join(",");return ` getChannel ( getX ( $ { m } ) , vec2 ( $ { g } ) ) ` }function d(h,f){return t.indexOf(h)!==-1&&e[h]!==1? ` $ { e [ h ] } - $ { f [ h ] } - 1 ` : ` $ { f [ h ] } ` }}};function ase(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=s.shape.length,i=w.parseAxisParam(a,s.shape);if(o===0)return sr({inputs:{x:s},backend:n});let c=q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new sse(s.shape,i):new rse(s.shape,i);return n.runWebGLProgram(c,[s],s.dtype)}var ose={kernelName:ni,backendName:"webgl",kernelFunc:ase},ise=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],r=e[2];this.outputShape=e;let s="";typeof t=="number"?s= ` float outputValue = $ { t . toFixed ( 2 ) } ; ` :s= `
2021-09-11 17:11:38 +02:00
vec3 fill = vec3 ( $ { t . join ( "," ) } ) ;
float outputValue = fill [ coords [ 3 ] ] ; ` ,this.userCode= `
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
int y = coords [ 1 ] ;
float coordXFloat = ( float ( x ) - params [ 0 ] ) * params [ 3 ] -
( float ( y ) - params [ 1 ] ) * params [ 2 ] ;
float coordYFloat = ( float ( x ) - params [ 0 ] ) * params [ 2 ] +
( float ( y ) - params [ 1 ] ) * params [ 3 ] ;
int coordX = int ( round ( coordXFloat + params [ 0 ] ) ) ;
int coordY = int ( round ( coordYFloat + params [ 1 ] ) ) ;
2022-10-30 14:06:17 +01:00
$ { s }
if ( coordX >= 0 && coordX < $ { r } && coordY >= 0 && coordY < $ { n } ) {
2021-09-11 17:11:38 +02:00
outputValue = getImage ( coords [ 0 ] , coordY , coordX , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2022-10-30 14:06:17 +01:00
` }},cse={kernelName:Ou,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,c=new ise(r.shape,a),[u,l]=N.getImageCenter(o,r.shape[1],r.shape[2]),p=[[u,l,Math.sin(s),Math.cos(s)]];return i.runWebGLProgram(c,[r],r.dtype,p)}},use= `
2021-09-11 17:11:38 +02:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor ( x ) ;
if ( ( x - base ) < 0.5 ) {
return floor ( x ) ;
} else if ( ( x - base ) > 0.5 ) {
return ceil ( x ) ;
} else {
if ( mod ( base , 2.0 ) == 0.0 ) {
return base ;
} else {
return base + 1.0 ;
2021-04-01 19:39:54 +02:00
}
}
2022-10-30 14:06:17 +01:00
` ,lse=Ye({opSnippet:use}),dse={kernelName:ri,backendName:"webgl",kernelFunc:lse},pse="return inversesqrt(x);",hse=Ye({opSnippet:pse,cpuKernelImpl: $ 9}),fse={kernelName:si,backendName:"webgl",kernelFunc:hse},BE=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=mt(s.length),c=mt(a.length),u="";n===1?u="i":n===2&&(u="i, j");let l= ` getIndices ( $ { u } ) ` ,p="";r===1?p="i":r===2&&(p="i, coords[1]");let d= ` getUpdates ( $ { p } ) ` ,h=t>1?"strides[j]":"strides";this.userCode= `
$ { i } strides = $ { i } ( $ { s } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { c } coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
float sum = 0.0 ;
bool found = false ;
for ( int i = 0 ; i < $ { e } ; i ++ ) {
int flattenedIndex = 0 ;
for ( int j = 0 ; j < $ { t } ; j ++ ) {
2022-10-30 14:06:17 +01:00
int index = round ( $ { l } ) ;
2021-09-11 17:11:38 +02:00
flattenedIndex += index * $ { h } ;
}
if ( flattenedIndex == coords [ 0 ] ) {
2022-10-30 14:06:17 +01:00
sum += $ { d } ;
2021-09-11 17:11:38 +02:00
found = true ;
}
}
setOutput ( mix ( getDefaultValue ( ) , sum , float ( found ) ) ) ;
}
2022-10-30 14:06:17 +01:00
` }};function mse(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:c,sliceSize:u,strides:l,outputSize:p}=N.calculateShapes(a,s,o),d=[p/u,u];if(p===0)return n.makeTensorInfo(o,s.dtype);let h=he({inputs:{x:s},backend:n,attrs:{shape:[c,i]}}),f=he({inputs:{x:a},backend:n,attrs:{shape:[c,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new BE(c,i,h.shape.length,f.shape.length,l,d),b=n.runWebGLProgram(g,[f,h,m],f.dtype),y=he({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(m),y}var gse={kernelName:wu,backendName:"webgl",kernelFunc:mse},bse=class{constructor(e,t,n,r){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];let s="while (left < right) {",a= ` for ( int i = 0 ; i < $ { Math . ceil ( Math . log2 ( t + 1 ) ) } ; ++ i ) { if ( left >= right ) break ; ` ,o=q().getNumber("WEBGL_VERSION")===2?s:a,i=r==="left"?"<":"<=";this.userCode= `
2022-05-18 14:36:05 +02:00
int findBound ( int batch , float value ) {
int left = 0 ;
int right = numInputs ;
int mid ;
2022-10-30 14:06:17 +01:00
$ { o }
2022-05-18 14:36:05 +02:00
mid = ( left + right ) / 2 ;
2022-10-30 14:06:17 +01:00
if ( getSortedSequence ( batch , mid ) $ { i } value ) {
2022-05-18 14:36:05 +02:00
left = mid + 1 ;
} else {
right = mid ;
}
}
return right ;
}
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int valueIndex = coords [ 1 ] ;
float value = getValues ( batch , valueIndex ) ;
setOutput ( float ( findBound ( batch , value ) ) ) ;
}
2022-10-30 14:06:17 +01:00
` }};function yse(e){let{inputs:t,backend:n,attrs:r}=e,{sortedSequence:s,values:a}=t,{side:o}=r,i=new bse(s.shape[0],s.shape[1],a.shape[1],o),c=[[s.shape[1]]];return n.runWebGLProgram(i,[s,a],"int32",c)}var vse={kernelName:Wf,backendName:"webgl",kernelFunc:yse},xse=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let r,s;if(n>4)throw Error( ` Where for rank $ { n } is not yet supported ` );if(n===1)s="resRC",r="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],c=[];for(let u=0;u<t.length;u++)c.push( ` $ { o [ u ] } ` ),u<e&&i.push( ` $ { o [ u ] } ` );r=i.join(),s=c.join()}let a=mt(n);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { a } resRC = getOutputCoords ( ) ;
float cVal = getC ( $ { r } ) ;
2021-09-11 17:11:38 +02:00
if ( cVal >= 1.0 ) {
2022-10-30 14:06:17 +01:00
setOutput ( getA ( $ { s } ) ) ;
2021-09-11 17:11:38 +02:00
} else {
2022-10-30 14:06:17 +01:00
setOutput ( getB ( $ { s } ) ) ;
2021-09-11 17:11:38 +02:00
}
2021-03-26 15:26:02 +01:00
}
2022-10-30 14:06:17 +01:00
` }};function wse(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new xse(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(o,[r,s,a],hr(s.dtype,a.dtype))}var Ise={kernelName:Iu,backendName:"webgl",kernelFunc:wse},kse= `
2021-09-11 17:11:38 +02:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2022-10-09 19:40:33 +02:00
float scaleAlpha = $ { N . SELU _SCALEALPHA } ;
float scale = $ { N . SELU _SCALE } ;
2021-09-11 17:11:38 +02:00
return ( x >= 0.0 ) ? scale * x : scaleAlpha * ( exp ( x ) - 1.0 ) ;
2022-10-30 14:06:17 +01:00
` ,Sse=Ye({opSnippet:kse}),Tse={kernelName:ku,backendName:"webgl",kernelFunc:Sse},Cse=tl+ `
2022-01-14 16:04:13 +01:00
return 1.0 / ( 1.0 + exp ( - 1.0 * x ) ) ;
2022-10-30 14:06:17 +01:00
` ,Nse= `
2022-01-14 16:04:13 +01:00
vec4 result = 1.0 / ( 1.0 + exp ( - 1.0 * x ) ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2022-10-30 14:06:17 +01:00
` ,_se=Ye({opSnippet:Cse,packedOpSnippet:Nse,cpuKernelImpl:F9}),Ese={kernelName:oi,backendName:"webgl",kernelFunc:_se},Ase= `
2021-09-11 17:11:38 +02:00
if ( isnan ( x ) ) { return 0.0 ; }
return sign ( x ) ;
2022-10-30 14:06:17 +01:00
` , $ se=Ye({opSnippet:Ase}),Dse={kernelName:Cu,backendName:"webgl",kernelFunc: $ se},Fse=tl+ `
2021-09-11 17:11:38 +02:00
return sin ( x ) ;
2022-10-30 14:06:17 +01:00
` ,Rse=Ye({opSnippet:Fse}),Pse={kernelName:ai,backendName:"webgl",kernelFunc:Rse},Ose= `
2021-09-11 17:11:38 +02:00
float e2x = exp ( x ) ;
return ( e2x - 1.0 / e2x ) / 2.0 ;
2022-10-30 14:06:17 +01:00
` ,Mse=Ye({opSnippet:Ose}),Lse={kernelName:Tu,backendName:"webgl",kernelFunc:Mse},zse= `
2021-09-11 17:11:38 +02:00
float epsilon = 1.1920928955078125 e - 7 ;
float threshold = log ( epsilon ) + 2.0 ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
bool too _large = x > - threshold ;
bool too _small = x < threshold ;
float result ;
float exp _x = exp ( x ) ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
if ( too _large ) {
result = x ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
else if ( too _small ) {
result = exp _x ;
}
else {
result = log ( exp _x + 1.0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return result ;
2022-10-30 14:06:17 +01:00
` ,Bse=Ye({opSnippet:zse}),Wse={kernelName:Nu,backendName:"webgl",kernelFunc:Bse},Vse=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;w.assert(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((b,y)=>b*y),c=[[0,0]];c.push(...o);for(let b=1+a.length;b<s.shape.length;++b)c.push([0,0]);let u=[],l=LE({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),p=N.getReshaped(l.shape,a,i,!1),d=N.getPermuted(p.length,a.length,!1),h=N.getReshapedPermuted(l.shape,a,i,!1),f=he({inputs:{x:l},backend:n,attrs:{shape:p}}),m=Nn({inputs:{x:f},backend:n,attrs:{perm:d}}),g=he({inputs:{x:m},backend:n,attrs:{shape:h}});return u.push(l),u.push(f),u.push(m),u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g},Use={kernelName:_u,backendName:"webgl",kernelFunc:Vse};function Gse(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error( ` Dense shape must be a vector , saw :
$ { a . shape } ` );if(r.shape.length!==2)throw new Error( ` Indices must be a matrix , saw :
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Values must be a vector , saw :
$ { s . shape } ` );if(o.shape.length!==0)throw new Error( ` Default value must be a scalar , saw :
$ { o . shape } ` );let i=n.readSync(r.dataId),c=n.readSync(s.dataId),u=n.readSync(a.dataId),l=n.readSync(o.dataId)[0],[p,d,h,f,m]=P9(i,r.shape,r.dtype,c,s.dtype,u,l);return[n.makeTensorInfo(d,r.dtype,p),n.makeTensorInfo([d[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var Hse={kernelName:xd,backendName:"webgl",kernelFunc:Gse};function qse(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error( ` Input indices should be a matrix but received shape $ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape $ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Target shape should be a vector but received shape $ { a . shape } ` );let o=Array.from(n.readSync(s.dataId)),i=n.readSync(r.dataId),c=Array.from(n.readSync(a.dataId)),[u,l,p]=O9(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(l,r.dtype,u),n.makeTensorInfo([p.length],a.dtype,new Int32Array(p))]}var jse={kernelName:Au,backendName:"webgl",kernelFunc:qse};function Kse(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
$ { a . shape } ` );let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[u,l]=cE(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(l,r.dtype,u)}var Xse={kernelName:wd,backendName:"webgl",kernelFunc:Kse};function Yse(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
$ { a . shape } ` );let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[u,l]=cE(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(l,r.dtype,u)}var Zse={kernelName:Id,backendName:"webgl",kernelFunc:Yse};function Jse(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:u,sliceSize:l,strides:p,outputSize:d}=N.calculateShapes(a,s,i),h=!1;if(a.dtype==="string"){let b=n.bufferSync(s),y=n.bufferSync(a),v=w.decodeString(n.readSync(o.dataId)[0]),x=D9(b,y,i,d,l,u,c,p,v,h);return n.makeTensorInfo(i,x.dtype,x.values)}let f=new BE(u,c,s.shape.length,a.shape.length,p,[d,1],h),m=n.runWebGLProgram(f,[a,s,o],a.dtype),g=he({inputs:{x:m},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(m),g}var Qse={kernelName:Vf,backendName:"webgl",kernelFunc:Jse};function eae(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],c=N.prepareSplitSize(s,a,i),u=s.shape.length,l=new Array(u).fill(0),p=s.shape.slice();return c.map(d=>{let h=[...p];h[i]=d;let f=nl({inputs:{x:s},backend:n,attrs:{begin:l,size:h}});return l[i]+=d,f})}var tae={kernelName:Eu,backendName:"webgl",kernelFunc:eae},R1="return sqrt(x);",nae=Ye({opSnippet:R1,packedOpSnippet:R1,cpuKernelImpl:M9}),rae={kernelName:ii,backendName:"webgl",kernelFunc:nae},sae="return x * x;",aae=Ye({opSnippet:sae}),oae={kernelName:kd,backendName:"webgl",kernelFunc:aae},P1="return (a - b) * (a - b);",iae=dn({opSnippet:P1,packedOpSnippet:P1}),cae={kernelName:li,backendName:"webgl",kernelFunc:iae};function uae({inputs:e,attrs:t,backend:n}){let{x:r}=e,s=Or+ `
2021-09-11 17:11:38 +02:00
return x > 0.0 ? 1.0 : float ( $ { t . alpha } ) ;
2022-10-30 14:06:17 +01:00
` ,a=new Ns(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}var lae={kernelName:xa,backendName:"webgl",kernelFunc:uae},dae=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let r=n.length,s=mt(n.length),a=mt(n.length),o="";if(r===1)o="coords * strides + begin";else{let i=0;o=n.map((c,u)=>(i++,n.length===1? ` coords * strides [ $ { u } ] + begin [ $ { u } ] ` : ` coords [ $ { i - 1 } ] * strides [ $ { u } ] + begin [ $ { u } ] ` )).join(",")}this.userCode= `
$ { s } begin = $ { s } ( $ { e } ) ;
$ { s } strides = $ { s } ( $ { t } ) ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { a } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { o } ) ) ;
2021-04-01 19:39:54 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function pae(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:u,ellipsisMask:l,newAxisMask:p,shrinkAxisMask:d}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=qt.sliceInfo(s.shape,a,o,i,c,u,l,p,d),k;if(m)k=he({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||b){w.assert(s.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { s . shape . length } ` );let C=qt.computeOutShape(y,v,x),E=nl({inputs:{x:s},backend:n,attrs:{begin:y,size:C}});k=he({inputs:{x:E},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(E)}else if(n.shouldExecuteOnCPU([s])){let E=n.readSync(s.dataId), $ =Me(s.shape,s.dtype,E),F=L9(h, $ ,x,y);k=n.makeTensorInfo(f,s.dtype,F.values)}else{let E=new dae(y,x,h);k=n.runWebGLProgram(E,[s],s.dtype)}let S=he({inputs:{x:k},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(k),S}var hae={kernelName: $ u,backendName:"webgl",kernelFunc:pae};function fae(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:u}=r,{data:l,dataSplits:p}=t,d=n.readSync(l.dataId),h=n.readSync(p.dataId),[f,m]=z9(d,h,s,a,o,i,c,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(p.shape,"int32",m)]}var mae={kernelName:Sd,backendName:"webgl",kernelFunc:fae};function gae(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error( ` Input must be a vector , got shape : $ { a . shape } ` );if(o.shape.length!==0)throw new Error( ` Delimiter must be a scalar , got shape : $ { o . shape } ` );let i=n.readSync(a.dataId),c=n.readSync(o.dataId)[0],[u,l,p]=B9(i,c,s),d=l.length;return[n.makeTensorInfo([d,2],"int32",u),n.makeTensorInfo([d],"string",l),n.makeTensorInfo([2],"int32",new Int32Array(p))]}var bae={kernelName:Td,backendName:"webgl",kernelFunc:gae};function yae(e){let{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");let o=n.readSync(a.dataId),i=W9(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var vae={kernelName:Cd,backendName:"webgl",kernelFunc:yae},xae="return tan(x);",wae=Ye({opSnippet:xae}),Iae={kernelName:pi,backendName:"webgl",kernelFunc:wae},kae= `
2021-09-11 17:11:38 +02:00
float e2x = exp ( - 2.0 * abs ( x ) ) ;
return sign ( x ) * ( 1.0 - e2x ) / ( 1.0 + e2x ) ;
2022-10-30 14:06:17 +01:00
` ,Sae=Ye({opSnippet:kae}),Tae={kernelName:hi,backendName:"webgl",kernelFunc:Sae},Cae=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[a]*t[a];this.outputShape=n,this.rank=n.length;let r=mt(this.rank),s=Nae(e);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2022-10-30 14:06:17 +01:00
$ { r } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { s } ) ) ;
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
` }};function Nae(e){let t=e.length;if(t>5)throw Error( ` Tile for rank $ { t } is not yet supported ` );if(t===1)return ` imod ( resRC , $ { e [ 0 ] } ) ` ;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let s=0;s<e.length;s++)r.push( ` imod ( $ { n [ s ] } , $ { e [ s ] } ) ` );return r.join()}function WE(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if(s.dtype==="string"||s.shape.length>5){let c=n.readSync(s.dataId),u=s.dtype==="string"?c.map(d=>w.decodeString(d)):c,l=Me(s.shape,s.dtype,u),p=U9(l,a);return n.makeTensorInfo(p.shape,p.dtype,p.values)}let o=new Cae(s.shape,a);return n.runWebGLProgram(o,[s],s.dtype)}var _ae={kernelName:va,backendName:"webgl",kernelFunc:WE},Eae=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int elemIdx = coords [ 1 ] ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
bool isFirstInPair = imod ( elemIdx , 2 * inc ) < inc ;
int i = isFirstInPair ? elemIdx : elemIdx - inc ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i0 = firstPass == 1 ? i : int ( getIndices ( batch , i ) ) ;
int i1 = firstPass == 1 ? i + inc : int ( getIndices ( batch , i + inc ) ) ;
float x0 = i0 < n ? getX ( batch , i0 ) : negativeInf ;
float x1 = i1 < n ? getX ( batch , i1 ) : negativeInf ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod ( elemIdx , 2 * dir ) >= dir ;
bool isGreater = x0 > x1 || ( x0 == x1 && i1 > i0 ) ;
if ( reverse == isGreater ) { // Elements in opposite order of direction
int iTemp = i0 ;
i0 = i1 ;
i1 = iTemp ;
}
if ( isFirstInPair ) {
setOutput ( float ( i0 ) ) ;
} else {
setOutput ( float ( i1 ) ) ;
}
}
2022-10-30 14:06:17 +01:00
` }},Aae=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int elemIdx = coords [ 1 ] ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i = elemIdx < k ? elemIdx : ( elemIdx * 2 - imod ( elemIdx , k ) ) ;
int i0 = firstPass == 1 ? i : int ( getIndices ( batch , i ) ) ;
int i1 = firstPass == 1 ? i + k : int ( getIndices ( batch , i + k ) ) ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float x0 = getX ( batch , i0 ) ;
float x1 = i1 < n ? getX ( batch , i1 ) : x0 ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput ( x0 >= x1 ? float ( i0 ) : float ( i1 ) ) ;
}
2022-10-30 14:06:17 +01:00
` }};function za(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function O1(e){let t=1;for(;t<e;)t*=2;return t}function $ ae(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r,i=q().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),c=q().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=s.shape,l=u[u.length-1];if(n.shouldExecuteOnCPU([s])||l<i||a>c){let F=n.readSync(s.dataId),[A,R]=G9(F,u,s.dtype,a,o);return[n.makeTensorInfo(A.shape,A.dtype,A.values),n.makeTensorInfo(R.shape,R.dtype,R.values)]}if(a===0)return u[u.length-1]=0,[n.makeTensorInfo(u,s.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(l===1)return[s,dp({attrs:{shape:u,dtype:"int32",value:0},backend:n})];let p=n.texData.get(s.dataId),d=p!==null&&p.isPacked,h=d?n.unpackTensor(s):s,m=w.sizeFromShape(u)/l,g=he({inputs:{x:h},attrs:{shape:[m,l]},backend:n});d&&za(n,h);let b=O1(a),y=O1(l),v=null,x=()=>v===null?[g,g]:[g,v],k=(F,A,R)=>{let T=x(),L=new Eae(R),G=[[l],[v===null?1:0],[Number.NEGATIVE_INFINITY],[F],[A]],j=v;v=n.runWebGLProgram(L,T,"int32",G),za(n,j)};for(let F=1;F<b;F*=2){let A=F*2;for(let R=F;R>=1;R/=2)k(A,R,[m,y])}for(let F=y;F>b;F/=2){let A=x(),R=new Aae([m,F/2]),L=[[l],[v===null?1:0],[b]],V=v;v=n.runWebGLProgram(R,A,"int32",L),za(n,V);let G=b/2,j=G*2;for(let H=G;H>=1;H/=2)k(j,H,v.shape)}let S=v;v=nl({inputs:{x:v},backend:n,attrs:{begin:0,size:[m,a]}}),za(n,S);let C=DE({inputs:{x:g,indices:v},backend:n,attrs:{axis:1,batchDims:1}});za(n,g);let E=u.slice(0,-1);E.push(a),S=v,v=he({inputs:{x:v},attrs:{shape:E},backend:n}),za(n,S);let $ =C;return C=he({inputs:{x:C},attrs:{shape:E},backend:n}),za(n, $ ),[C,v]}var Dae={kernelName:Du,backendName:"webgl",kernelFunc: $ ae},Fae=class{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(r){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode= `
2021-09-11 17:11:38 +02:00
float mapCoord ( float outCoord , float len ) {
float inCoord = outCoord ;
2022-10-30 14:06:17 +01:00
if ( $ { i } == 2 ) {
2021-09-11 17:11:38 +02:00
if ( inCoord < 0.0 ) {
if ( len <= 1.0 ) {
inCoord = 0.0 ;
} else {
float sz2 = 2.0 * len ;
if ( inCoord < sz2 ) {
inCoord = sz2 * float ( int ( float ( - inCoord / sz2 ) ) ) +
inCoord ;
}
inCoord = inCoord < - len ? inCoord + sz2 : - inCoord - 1.0 ;
}
} else if ( inCoord > len - 1.0 ) {
if ( len <= 1.0 ) {
inCoord = 0.0 ;
} else {
float sz2 = 2.0 * len ;
inCoord -= sz2 * float ( int ( float ( inCoord / sz2 ) ) ) ;
if ( inCoord >= len ) {
inCoord = sz2 - inCoord - 1.0 ;
}
}
}
return clamp ( inCoord , 0.0 , len - 1.0 ) ;
2022-10-30 14:06:17 +01:00
} else if ( $ { i } == 3 ) {
2021-09-11 17:11:38 +02:00
if ( inCoord < 0.0 ) {
if ( len <= 1.0 ) {
inCoord = 0.0 ;
} else {
float sz = len - 1.0 ;
inCoord += len * ( float ( int ( float ( - inCoord / sz ) ) ) + 1.0 ) ;
}
} else if ( inCoord > len - 1.0 ) {
if ( len <= 1.0 ) {
inCoord = 0.0 ;
} else {
float sz = len - 1.0 ;
inCoord -= len * float ( int ( float ( inCoord / sz ) ) ) ;
}
}
return clamp ( inCoord , 0.0 , len - 1.0 ) ;
2022-10-30 14:06:17 +01:00
} else if ( $ { i } == 4 ) {
2021-09-11 17:11:38 +02:00
return clamp ( outCoord , 0.0 , len - 1.0 ) ;
} else {
return outCoord ;
}
}
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float readWithFillValue ( int batch , int coordY , int coordX ,
int channel ) {
float outputValue ;
if ( 0 <= coordY && coordY < $ { e } && 0 <= coordX && coordX < $ { t } ) {
outputValue = getImage ( batch , coordY , coordX , channel ) ;
} else {
2022-10-30 14:06:17 +01:00
outputValue = float ( $ { s } ) ;
2021-09-11 17:11:38 +02:00
}
return outputValue ;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
float outputValue ;
int batch = coords [ 0 ] ;
int x = coords [ 2 ] ;
int y = coords [ 1 ] ;
int channel = coords [ 3 ] ;
float xf = float ( x ) ;
float yf = float ( y ) ;
float a1 = getTransforms ( batch , 0 ) ;
float a2 = getTransforms ( batch , 1 ) ;
float a3 = getTransforms ( batch , 2 ) ;
float b1 = getTransforms ( batch , 3 ) ;
float b2 = getTransforms ( batch , 4 ) ;
float b3 = getTransforms ( batch , 5 ) ;
float c1 = getTransforms ( batch , 6 ) ;
float c2 = getTransforms ( batch , 7 ) ;
float projection = c1 * xf + c2 * yf + 1.0 ;
if ( projection == 0.0 ) {
2022-10-30 14:06:17 +01:00
outputValue = float ( $ { s } ) ;
2021-09-11 17:11:38 +02:00
} else {
float inX = ( a1 * xf + a2 * yf + a3 ) / projection ;
float inY = ( b1 * xf + b2 * yf + b3 ) / projection ;
float mapX = mapCoord ( inX , float ( $ { t } ) ) ;
float mapY = mapCoord ( inY , float ( $ { e } ) ) ;
2021-03-31 13:01:22 +02:00
2022-10-30 14:06:17 +01:00
if ( $ { o } == 1 ) {
2021-09-11 17:11:38 +02:00
int coordY = int ( round ( mapY ) ) ;
int coordX = int ( round ( mapX ) ) ;
outputValue = readWithFillValue ( batch , coordY , coordX ,
channel ) ;
} else {
float yFloor = floor ( mapY ) ;
float xFloor = floor ( mapX ) ;
float yCeil = yFloor + 1.0 ;
float xCeil = xFloor + 1.0 ;
float valueYFloor = ( xCeil - mapX ) *
readWithFillValue ( batch , int ( yFloor ) , int ( xFloor ) , channel ) +
( mapX - xFloor ) *
readWithFillValue ( batch , int ( yFloor ) , int ( xCeil ) , channel ) ;
float valueYCeil = ( xCeil - mapX ) *
readWithFillValue ( batch , int ( yCeil ) , int ( xFloor ) , channel ) +
( mapX - xFloor ) *
readWithFillValue ( batch , int ( yCeil ) , int ( xCeil ) , channel ) ;
outputValue = ( yCeil - mapY ) * valueYFloor +
( mapY - yFloor ) * valueYCeil ;
}
}
setOutput ( outputValue ) ;
}
2022-10-30 14:06:17 +01:00
` }};function Rae(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:c,outputShape:u}=r,[l,p,d,h]=s.shape,[f,m]=u!=null?u:[p,d],g=[l,f,m,h],b=new Fae(p,d,o,i,c,g);return n.runWebGLProgram(b,[s,a],"float32")}var Pae={kernelName:Fu,backendName:"webgl",kernelFunc:Rae};function Oae(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Yu(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=r.readSync(a.dataId),{outputValues:i,outputShape:c,indices:u}=H9(o,s,a.shape,a.dtype);return[r.makeTensorInfo(c,a.dtype,i),r.makeTensorInfo([u.length],"int32",u)]}var Mae={kernelName:Uf,backendName:"webgl",kernelFunc:Oae};function Lae(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s,i=o.shape.length,c=s.shape[a],u=new Array(i-1),l=0;for(let m=0;m<i;m++)m!==a&&(u[l++]=o.shape[m]);let p=[],d=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(c);for(let m=0;m<f.length;m++){d[a]=m;let g=nl({inputs:{x:o},backend:n,attrs:{begin:d,size:h}}),b=he({inputs:{x:g},backend:n,attrs:{shape:u}});f[m]=b,p.push(g)}return p.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var zae={kernelName:Ru,backendName:"webgl",kernelFunc:Lae},Bae=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,o=a*Math.ceil(s/n);this.outputShape=[r,o];let i="0.0",c="sumValue",u=Math.floor(n/4)*4,l=n%4,p= `
2021-09-11 17:11:38 +02:00
sumValue += dot ( values , segFilter ) ;
2022-10-30 14:06:17 +01:00
` ,d="";s%n>0&&(d= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
2021-09-11 17:11:38 +02:00
return initializationValue ;
}
2022-10-30 14:06:17 +01:00
` );let h="";s%n>0&&(h= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
2021-09-11 17:11:38 +02:00
return - 1.0 ;
}
` ),this.userCode= `
2022-10-30 14:06:17 +01:00
const float initializationValue = $ { i } ;
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float getValue ( int batch , int inIdx ) {
2022-10-30 14:06:17 +01:00
$ { d }
2021-09-11 17:11:38 +02:00
return getX ( batch , inIdx ) ;
2021-03-26 15:26:02 +01:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float getSegmentIdAtIndex ( int inIdx ) {
$ { h }
return getSegmentIds ( inIdx ) ;
2021-03-31 13:01:22 +02:00
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = int ( floor ( float ( outIdx ) / float (
2022-10-30 14:06:17 +01:00
$ { a } ) ) * float ( $ { n } ) ) ;
int currentSeg = int ( mod ( float ( outIdx ) , float ( $ { a } ) ) ) ;
2021-03-09 23:32:33 +01:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0 ;
2021-03-09 23:32:33 +01:00
2022-03-07 19:17:31 +01:00
for ( int i = 0 ; i < $ { u } ; i += 4 ) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 2 ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 3 ) ) == currentSeg ? 1 : 0
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { p }
2020-12-15 14:15:43 +01:00
}
2020-10-29 05:16:50 +01:00
2022-03-07 19:17:31 +01:00
int inIdx = inOffset + $ { u } ;
2022-10-30 14:06:17 +01:00
if ( $ { l === 1 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int inIdxSeg = int ( getSegmentIdAtIndex ( inIdx ) ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
0 ,
0 ,
0
) ;
2021-03-26 15:26:02 +01:00
2022-10-30 14:06:17 +01:00
$ { p }
} else if ( $ { l === 2 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
0 ,
0
) ;
2021-04-01 19:39:54 +02:00
2022-10-30 14:06:17 +01:00
$ { p }
} else if ( $ { l === 3 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 2 ) ) == currentSeg ? 1 : 0 ,
0
) ;
2020-10-29 05:16:50 +01:00
2022-10-30 14:06:17 +01:00
$ { p }
2021-09-11 17:11:38 +02:00
}
2022-10-30 14:06:17 +01:00
setOutput ( $ { c } ) ;
2021-12-01 21:37:52 +01:00
}
2022-10-30 14:06:17 +01:00
` }};function Wae(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r,i=s.shape.length,c=[],u=0,l=N.getAxesPermutation([u],i),p=s;l!=null&&(p=Nn({inputs:{x:s},backend:n,attrs:{perm:l}}),c.push(p),u=N.getInnerMostAxes(1,i)[0]);let d=N.segment_util.computeOutShape(p.shape,u,o),h=w.sizeFromShape([p.shape[u]]),f=he({inputs:{x:p},backend:n,attrs:{shape:[-1,h]}});c.push(f);let m=Hf(s.dtype),g=(x,k,S,C,E)=>{let $ =x.shape[0],F=x.shape[1],A=N.segment_util.segOpComputeOptimalWindowSize(F,E),R={windowSize:A,inSize:F,batchSize: $ ,numSegments:E},T=new Bae(R,k),L=n.compileAndRun(T,[x,S],C);if(c.push(L),L.shape[1]===E)return L;let V=zE({backend:n,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),G=WE({inputs:{x:V},backend:n,attrs:{reps:[F/A]}});return c.push(V),c.push(G),g(L,k,G,C,E)},b=g(f,"unsortedSegmentSum",a,m,o),y=he({inputs:{x:b},backend:n,attrs:{shape:d}}),v=y;if(l!=null){c.push(y);let x=N.getUndoAxesPermutation(l);v=Nn({inputs:{x:v},backend:n,attrs:{perm:x}})}return c.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var Vae={kernelName:Nd,backendName:"webgl",kernelFunc:Wae},Uae=[LZ,BZ,UZ,qZ,KZ,ZZ,QZ,tJ,aJ,iJ,lJ,hJ,gJ,xJ,kJ,TJ,NJ, $ J,FJ,PJ,zJ,qJ,KJ,YJ,nQ,sQ,cQ,wZ,dQ,gQ,xQ,CQ,_Q,AQ,DQ,RQ,MQ,BQ,UQ,HQ,jQ,XQ,JQ,eee,see,oee,uee,pee,fee,yee,Iee,Cee,Eee,Dee,Fee,Pee,Mee,zee,Wee,Uee,jee,Yee,Qee,tte,ste,ite,dte,mte,xZ,bte,fQ,xte,kte,Cte,kZ,Ate,Rte,Ote,Bte,Ute,jte,Yte,ene,sne,ine,une,hne,mne,bne,wne,kne,Tne,Nne,Ene,Fne,Mne,Wne,Xne,CZ,Qne,nre,are,cre,JJ,dre,hre,mre,yre,Ire,TZ,Sre,Cre,_re,Are, $ re,QJ,Hne,Rre,Lre,Vre,_Z,qre,Xre,Qre,nse,ose,cse,dse,fse,gse,vse,Ise,Tse,Ese,Dse,Pse,Lse,GJ,jne,Wse,Use,Hse,jse,Xse,Zse,Qse,tae,rae,oae,cae,lae,hae,mae,bae,vae,qne,PZ,Iae,Tae,_ae,Dae,Pae,OZ,Mae,zae,Vae,pre];for(let e of Uae)_d(e);var Et;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})(Et||(Et={}));var ud;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(ud||(ud={}));var VE;function Gae(e){VE=e.wasm.cwrap(eo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Hae(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:c,transposeB:u,activation:l,leakyreluAlpha:p}=r,d=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let E=n.dataIdMap.get(o.dataId);if(E.shape.length!==1)throw new Error( ` _FusedMatMul only supports rank - 1 bias but got rank $ { E . shape . length } . ` );f=E.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=ud[l];if(g==null)throw new Error( ` $ { l } activation not yet supported for FusedConv2D in the wasm backend . ` );let b=c?s.shape[2]:s.shape[1],y=u?a.shape[1]:a.shape[2],v=Mu.assertAndGetBroadcastShape(s.shape.slice(0,-2),a.shape.slice(0,-2)),x=n.makeOutput([...v,b,y],s.dtype),k=n.dataIdMap.get(x.dataId).id,S=new Uint8Array(new Int32Array(s.shape).buffer),C=new Uint8Array(new Int32Array(a.shape).buffer);return VE(d,S,s.shape.length,h,C,a.shape.length,c,u,g,f,m,p||0,k),x}var qae={kernelName:eo,backendName:"wasm",setupFunc:Gae,kernelFunc:Hae};function rn(e,t){let n;function r(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function s(a){let{backend:o,inputs:{x:i}}=a,c=o.dataIdMap.get(i.dataId).id,u=o.makeOutput(i.shape,t||i.dtype),l=o.dataIdMap.get(u.dataId).id;return w.sizeFromShape(u.shape)===0||n(c,Et[i.dtype],l),u}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var jae=rn(Fc);function pn(e,t,n){let r;function s(o){r=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:c}=o,{a:u,b:l}=c,p=i.dataIdMap.get(u.dataId).id,d=i.dataIdMap.get(l.dataId).id,h=n!=null?n:u.dtype,f=N.assertAndGetBroadcastShape(u.shape,l.shape),m=i.makeOutput(f,h);if(w.sizeFromShape(f)===0)return m;l
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Target shape should be a vector but received shape $ { a . shape } ` );let o=t.dataIdMap.get(r.dataId).id,i=t.dataIdMap.get(s.dataId).id,c=t.dataIdMap.get(a.dataId).id,u=r.shape[0],l=w.sizeFromShape(a.shape),p=t.makeOutput([u,l],r.dtype),d=t.dataIdMap.get(p.dataId).id,h=t.makeOutput([l],a.dtype),f=t.dataIdMap.get(h.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;PA(o,i,c,u,d,f,g);let b=t.readSync(m.dataId),y;switch(b[0]){case 0:{y=N.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(b[1],b[2]);break}case 1:{y=N.getSparseReshapeNegativeOutputDimErrorMessage(b[1],b[2]);break}case 2:y=N.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let v=Array.from(t.readSync(s.dataId)),x=Array.from(t.readSync(h.dataId));y=N.getSparseReshapeInputOutputMultipleErrorMessage(v,x);break}case 4:{let v=Array.from(t.readSync(s.dataId)),x=Array.from(t.readSync(h.dataId));y=N.getSparseReshapeInputOutputMismatchErrorMessage(v,x);break}default:y=""}if(t.disposeData(m.dataId),y)throw t.disposeData(p.dataId),t.disposeData(h.dataId),new Error(y);return[p,h]}var Eue={kernelName:Au,backendName:"wasm",setupFunc:Nue,kernelFunc:_ue},OA;function MA(e){OA=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function LA(e,t){let{backend:n,inputs:r}=e,{data:s,indices:a,segmentIds:o}=r,i=a.shape[0],c=n.readSync(o.dataId,i-1,i)[0],l=i>0?c+1:0;if(l<0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=s.shape.slice();p[0]=l;let d=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=n.dataIdMap.get(o.dataId).id,m=n.makeOutput(p,s.dtype),g=n.dataIdMap.get(m.dataId).id,b=n.makeOutput([4],"int32"),y=n.dataIdMap.get(b.dataId).id;OA(d,Et[s.dtype],s.shape[0],h,f,g,y,t,0);let v=n.readSync(b.dataId),x;switch(v[0]){case 0:{x=N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=N.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=N.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(v[1],v[2]);break;case 3:x=N.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(v[1],v[2],v[3]);break;default:x=""}if(n.disposeData(b.dataId),x)throw n.disposeData(m.dataId),new Error(x);return m}function Aue(e){return LA(e,!0)}var $ ue={kernelName:wd,backendName:"wasm",setupFunc:MA,kernelFunc:Aue};function Due(e){return LA(e,!1)}var Fue={kernelName:Id,backendName:"wasm",setupFunc:MA,kernelFunc:Due};function Rue(e){let{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=n,i=w.parseAxisParam(o,s.shape)[0],c=N.prepareSplitSize(s,a,i),u=new Array(s.shape.length).fill(0),l=s.shape.slice();return c.map(p=>{let d=[...l];d[i]=p;let h=mo({inputs:{x:s},attrs:{begin:u,size:d},backend:r});return u[i]+=p,h})}var Pue={kernelName:Eu,backendName:"wasm",kernelFunc:Rue},Oue=rn(ii),Mue=rn(kd),Lue=!0,zue=pn(li,Lue),zA;function Bue(e){zA=e.wasm.cwrap(xa,null,["number","number","number","number"])}function Wue(e){let{backend:t,inputs:n,attrs:r}=e,{alpha:s}=r,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),c=t.dataIdMap.get(i.dataId).id;return zA(o,s,Et[a.dtype],c),i}var Vue={kernelName:xa,backendName:"wasm",setupFunc:Bue,kernelFunc:Wue},BA;function Uue(e){BA=e.wasm.cwrap( $ u,null,["number","array","number","array","array","array","array","array","number","number"])}function Gue(e){let{backend:t,inputs:n,attrs:r}=e,{x:s}=n,{begin:a,end:o,strides:i,beginMask:c,endMask:u,ellipsisMask:l,newAxisMask:p,shrinkAxisMask:d}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=qt.sliceInfo(s.shape,a,o,i,c,u,l,p,d),k;if(m)k=Bn({inputs:{x:s},backend:t,attrs:{shape:f}});else if(g||b){w.assert(s.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { s . shape . length } ` );let S=qt.computeOutShape(y,v,x),C=mo({inputs:{x:s},backend:t,attrs:{begin:y,size:S}});k=Bn({inputs:{x:C},backend:t,attrs:{shape:f}}),t.disposeData(C.dataId)}else{let S=t.makeOutput(h,"float32"),C=t.dataIdMap.get(