2020-12-02 22:46:41 +01:00
/ *
Face - API
homepage : < https : //github.com/vladmandic/face-api>
author : < https : //github.com/vladmandic>'
* /
2021-01-12 16:01:34 +01:00
var faceapi = ( ( ) => { var R _ = Object . create , Fd = Object . defineProperty , P _ = Object . getPrototypeOf , O _ = Object . prototype . hasOwnProperty , L _ = Object . getOwnPropertyNames , z _ = Object . getOwnPropertyDescriptor ; var Kw = e => Fd ( e , "__esModule" , { value : ! 0 } ) ; var B _ = ( e , t ) => ( ) => ( t || ( t = { exports : { } } , e ( t . exports , t ) ) , t . exports ) , oc = ( e , t ) => { Kw ( e ) ; for ( var n in t ) Fd ( e , n , { get : t [ n ] , enumerable : ! 0 } ) } , W _ = ( e , t , n ) => { if ( Kw ( e ) , t && typeof t == "object" || typeof t == "function" ) for ( let a of L _ ( t ) ) ! O _ . call ( e , a ) && a !== "default" && Fd ( e , a , { get : ( ) => t [ a ] , enumerable : ! ( n = z _ ( t , a ) ) || n . enumerable } ) ; return e } , V _ = e => e && e . _ _esModule ? e : W _ ( Fd ( e != null ? R _ ( P _ ( e ) ) : { } , "default" , { value : e , enumerable : ! 0 } ) , e ) ; var pC = B _ ( ( use , cC ) => { oc ( use , { isNodejs : ( ) => cse } ) ; function cse ( ) { return typeof global == "object" && ! 0 && typeof cC != "undefined" && typeof process != "undefined" && ! ! process . version } } ) ; var Ase = { } ; oc ( Ase , { AgeGenderNet : ( ) => Up , BoundingBox : ( ) => ro , Box : ( ) => ot , ComposableTask : ( ) => oa , ComputeAllFaceDescriptorsTask : ( ) => zr , ComputeFaceDescriptorsTaskBase : ( ) => Jp , ComputeSingleFaceDescriptorTask : ( ) => Br , DetectAllFaceLandmarksTask : ( ) => Qp , DetectAllFacesTask : ( ) => Hu , DetectFaceLandmarksTaskBase : ( ) => Zp , DetectFacesTaskBase : ( ) => td , DetectSingleFaceLandmarksTask : ( ) => ed , DetectSingleFaceTask : ( ) => nd , Dimensions : ( ) => cn , FACE _EXPRESSION _LABELS : ( ) => Vf , FaceDetection : ( ) => yt , FaceDetectionNet : ( ) => _w , FaceExpressionNet : ( ) => Wp , FaceExpressions : ( ) => Pr , FaceLandmark68Net : ( ) => ho , FaceLandmark68TinyNet : ( ) => Hp , FaceLandmarkNet : ( ) => Tw , FaceLandmarks : ( ) => Gn , FaceLandmarks5 : ( ) => pw , FaceLandmarks68 : ( ) => io , FaceMatch : ( ) => Au , FaceMatcher : ( ) => rd , FaceRecognitionNet : ( ) => mo , Gender : ( ) => pr , LabeledBox : ( ) => $u , LabeledFaceDescriptors : ( ) => lr , NetInput : ( ) => cr , NeuralNetwork : ( ) => nn , ObjectDetection : ( ) => Rr , Point : ( ) => De , PredictedBox : ( ) => dw , Rect : ( ) => so , SsdMobilenetv1 : ( ) => Ts , SsdMobilenetv1Options : ( ) => ia , TinyFaceDetector : ( ) => bo , TinyFaceDetectorOptions : ( ) => Yp , TinyYolov2 : ( ) => go , TinyYolov2Options : ( ) => Va , allFaces : ( ) => yE , allFacesSsdMobilenetv1 : ( ) => Pw , allFacesTinyYolov2 : ( ) => gE , awaitMediaLoaded : ( ) => Ef , bufferToImage : ( ) => _f , computeFaceDescriptor : ( ) => nE , createCanvas : ( ) => oo , createCanvasFromMedia : ( ) => Mu , createFaceDetectionNet : ( ) => BC , createFaceRecognitionNet : ( ) => AC , createSsdMobilenetv1 : ( ) => Ew , createTinyFaceDetector : ( ) => bE , createTinyYolov2 : ( ) => XC , detectAllFaces : ( ) => ad , detectFaceLandmarks : ( ) => $w , detectFaceLandmarksTiny : ( ) => tE , detectLandmarks : ( ) => mE , detectSingleFace : ( ) => fE , draw : ( ) => Gf , env : ( ) => st , euclideanDistance : ( ) => Kf , extendWithAge : ( ) => Kp , extendWithFaceDescriptor : ( ) => qp , extendWithFaceDetection : ( ) => xs , extendWithFaceExpressions : ( ) => Vp , extendWithFaceLandmarks : ( ) => po , extendWithGender : ( ) => Xp , extractFaceTensors : ( ) => uo , extractFaces : ( ) => lo , fetchImage : ( ) => dC , fetchJson : ( ) => $f , fetchNetWeights : ( ) => hC , fetchOrThrow : ( ) => Is , getContext2dOrThrow : ( ) => xn , getMediaDimensions : ( ) => ks , imageTensorToCanvas : ( ) => Ff , imageToSquare : ( ) => Af , inverseSigmoid : ( ) => uC , iou : ( ) => kf , isMediaElement : ( ) => Pp , isMediaLoaded : ( ) => Du , isWithAge : ( ) => $C , isWithFaceDetection : ( ) => Ba , isWithFaceExpressions : ( ) => Uf , isWithFaceLandmarks : ( ) => Ns , isWithGender : ( ) => DC , loadAgeGenderModel : ( ) => pE , loadFaceDetectionModel : ( ) => dE , loadFaceExpressionModel : ( ) => cE , loadFaceLandmarkModel : ( ) => oE , loadFaceLandmarkTinyModel : ( ) => lE , loadFaceRecognitionModel : ( ) => uE , loadSsdMobilenetv1Model : ( ) => Dw , loadTinyFaceDetectorModel : ( ) => sE , loadTinyYolov2Model : ( ) => iE , loadWeightMap : ( ) => Mf , locateFaces : ( ) => hE , matchDimensions : ( ) => mC , minBbox : ( ) => If , nets : ( ) => Qe , nonMaxSuppression : ( ) => Nf , normalize : ( ) => va , padToSquare : ( ) => Tf , predictAgeAndGender : ( ) => rE , recognizeFaceExpressions : ( ) => aE , resizeResults : ( ) => Ow , resolveInput : ( ) => vs , shuffleArray : ( ) => lC , sigmoid : ( ) => Fu , ssdMobilenetv1 : ( ) => Aw , tf : ( ) => Ad , tinyFaceDetector : ( ) => QC , tinyYolov2 : ( ) => eE , toNetInput : ( ) => ft , utils : ( ) => xf , validateConfig : ( ) => qf , version : ( ) => xE } ) ; var Ad = { } ; oc ( Ad , { Abs : ( ) => Lo , Acos : ( ) => zo , Acosh : ( ) => Bo , AdadeltaOptimizer : ( ) => am , AdagradOptimizer : ( ) => rm , AdamOptimizer : ( ) => sm , AdamaxOptimizer : ( ) => im , Add : ( ) => qr , AddN : ( ) => Rs , All : ( ) => Ld , Any : ( ) => zd , ArgMax : ( ) => Ps , ArgMin : ( ) => dc , Asin : ( ) => Wo , Asinh : ( ) => Vo , Atan : ( ) => Uo , Atan2 : ( ) => Ho , Atanh : ( ) => Go , AvgPool : ( ) => Os , AvgPool3D : ( ) => hc , AvgPool3DGrad : ( ) => Wd , AvgPoolGrad : ( ) => Bd , BackendWasm : ( ) => iC , BatchMatMul : ( ) => Ls , BatchToSpaceND : ( ) => mc , Bincount : (
` )),l.join( `
` )}function WF(e,t,n,a){let r=zt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?Mc(e):e;if(o>1)for(let c=0;c<r/s;c++){let u=c*s;for(let p=0;p<s;p++)i[p]=Math.max(i[p],Dc(l[u+p],0,n).length)}return i}function Dc(e,t,n){let a;return Array.isArray(e)?a= ` $ { parseFloat ( e [ 0 ] . toFixed ( py ) ) } + $ { parseFloat ( e [ 1 ] . toFixed ( py ) ) } j ` :Hr(e)?a= ` '${e}' ` :n==="bool"?a=g0(e):a=parseFloat(e.toFixed(py)).toString(),pc(a,t)}function g0(e){return e===0?"false":"true"}function bh(e,t,n,a,r,s=!0){let i=n==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(n==="complex64"){let f=Mc(e);return[Dc(f[0],0,n)]}return n==="bool"?[g0(e[0])]:[e[0].toString()]}if(l===1){if(o>f0){let g= $ c*i,y=Array.from(e.slice(0,g)),b=Array.from(e.slice((o- $ c)*i,o*i));return n==="complex64"&&(y=Mc(y),b=Mc(b)),["["+y.map((x,v)=>Dc(x,r[v],n)).join(", ")+", ..., "+b.map((x,v)=>Dc(x,r[o- $ c+v],n)).join(", ")+"]"]}let f=n==="complex64"?Mc(e):Array.from(e);return["["+f.map((g,y)=>Dc(g,r[y],n)).join(", ")+"]"]}let c=t.slice(1),u=a.slice(1),p=a[0]*i,d=[];if(o>f0){for(let f=0;f< $ c;f++){let g=f*p,y=g+p;d.push(...bh(e.slice(g,y),c,n,u,r,!1))}d.push("...");for(let f=o- $ c;f<o;f++){let g=f*p,y=g+p;d.push(...bh(e.slice(g,y),c,n,u,r,f===o-1))}}else for(let f=0;f<o;f++){let g=f*p,y=g+p;d.push(...bh(e.slice(g,y),c,n,u,r,f===o-1))}let h=l===2?",":"";d[0]="["+d[0]+h;for(let f=1;f<d.length-1;f++)d[f]=" "+d[f]+h;let m= ` ,
` ;for(let f=2;f<l;f++)m+= `
` ;return d[d.length-1]=" "+d[d.length-1]+"]"+(s?"":m),d}function Mc(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Bt=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=zt(e),n!=null){let a=n.length;F(a===this.size,()=> ` Length of values '${a}' 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||Qw(t,this.size),this.strides=Po(e)}set(e,...t){t.length===0&&(t=[0]),F(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 a of e){if(a<0||a>=this.shape[t]){let r= ` Requested out of range element at $ { e } . Buffer shape = $ { this . shape } ` ;throw new Error(r)}t++}let n=e[e.length-1];for(let a=0;a<e.length-1;++a)n+=this.strides[a]*e[a];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 Ha().makeTensor(this.values,this.shape,this.dtype)}},Ha=null,Wl=null,UF=null;function GF(e){Ha=e}function HF(e){Wl=e}function jF(e){UF=e}var z=class{constructor(e,t,n,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=zt(e),this.strides=Po(e),this.dataId=n,this.id=a,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Wl.buffer(this.shape,this.dtype,e)}bufferSync(){return Wl.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Oo(this.shape,e)}arraySync(){return Oo(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let e=Ha().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>yh(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}dataSync(){this.throwIfDisposed();let e=Ha().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>yh(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 Ha().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Ha().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Wl.print(this,e)}clone(){return this.throwIfDisposed(),Wl.clone(this)}toString(e=!1){let t=this.dataSync();return VF(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Wl.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ha().makeVariable(this,e,t,n)}};Object.defineProperty(z,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});var Yr=class extends z{constructor(e,t,n,a){super(e.shape,e.dtype,e.dataId,a);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(!xr(e.shape,this.shape))throw new Error( ` shape of the new value ( $ { e . shape } ) and previous value ( $ { this . shape } ) must match ` );Ha().disposeTensor(this),this.dataId=e.dataId,Ha().incRef(this,null)}dispose(){Ha().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Yr,Symbol.hasInstance,{value:e=>e instanceof z&&e.assign!=null&&e.assign instanceof Function});var Ta={};Oe(Ta,{assertTypesMatch:()=>y0,getTensorsInCont
Manifest JSON has weights with names : $ { o . join ( ", " ) } . ` )}let l=r.reduce((h,m,f)=>(m&&h.push(f),h),[]),c=[];l.forEach(h=>{t[h].paths.forEach(m=>{let f=n+(n.endsWith("/")?"":"/")+m;c.push(f)})});let u=await e(c),p={},d=0;return l.forEach(h=>{let m=t[h].paths.length,f=0;for(let x=0;x<m;x++)f+=u[d+x].byteLength;let g=new ArrayBuffer(f),y=new Uint8Array(g),b=0;for(let x=0;x<m;x++){let v=new Uint8Array(u[d+x]);y.set(v,b),b+=v.byteLength}s[h].forEach(x=>{let v=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),N=T0(v,[x.manifestEntry]);for(let T in N)p[T]=N[T]}),d+=m}),p}}var HA="application/octet-stream",jA="application/json",Cy=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?(F(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=ee().platform.fetch,F(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&F(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}],a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(a)],{type:jA}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:HA}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Oc(e),responses:[r]};throw new Error( ` BrowserHTTPRequest . save ( ) failed due to HTTP response status $ { r . 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(h){let m= ` Failed to parse model JSON of response from $ { this . path } . ` ;throw this.path.endsWith(".pb")?m+=" 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.":m+=" Please make sure the server is serving valid JSON for this request.",new Error(m)}let n=t.modelTopology,a=t.weightsManifest,r=t.generatedBy,s=t.convertedBy,i=t.format,o=t.signature,l=t.userDefinedMetadata;if(n==null&&a==null)throw new Error( ` The JSON from HTTP path $ { this . path } contains neither model topology or manifest for weights . ` );let c,u;a!=null&&([c,u]=await this.loadWeights(a));let p={modelTopology:n,weightSpecs:c,weightData:u,generatedBy:r,convertedBy:s,format:i};o!=null&&(p.signature=o),l!=null&&(p.userDefinedMetadata=l);let d=t.modelInitializer;return d&&(p.modelInitializer=d),p}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,a]=qA(t),r=this.weightPathPrefix||n,s=[];for(let c of e)s.push(...c.weights);let i=[],o=[];for(let c of e)for(let u of c.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(u)):i.push(r+u+a);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await L0(i,{requestInit:thi
Actual : $ { r } .
Expected : $ { s } . ` );for(let i=0;i<s.length;++i){let o=r[i],l=s[i];if(!n(o,l))throw new Error( ` Arrays differ : actual [ $ { i } ] = $ { o } , expected [ $ { i } ] = $ { l } .
Actual : $ { r } .
Expected : $ { s } . ` )}}function l $ (e,t){e().then(()=>t.fail(),()=>t())}function u $ (e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Hr(e)||Hr(e[0])||Hr(t)||Hr(t[0])?My(e,n,(a,r)=>a==r):My(e,t,(a,r)=>Ry(a,r,0))}function c $ (e,t,n){if(n==null&&(n=Dy()),!Ry(e,t,n))throw new Error( ` Numbers differ : actual === $ { e } , expected === $ { t } ` )}function Ry(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function p $ (e,t,n){for(let a=0;a<e.length;a++)if(e[a]<t||e[a]>n)throw new Error( ` Value out of range : $ { e [ a ] } low : $ { t } , high : $ { n } ` )}function d $ (e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function ak(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?ak(n):e[t]=Ac(n)}return e}var rk="2.8.3";function m $ (){ee().set("PROD",!0)}function f $ (){ee().set("DEBUG",!0)}function g $ (){ee().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Pt(e){ee().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}jF(Pt);function y $ (){P.disposeVariables()}function ns(){return P}function Th(){return P.memory()}function b $ (e){return P.profile(e)}function D(e,t){return P.tidy(e,t)}function Ae(e){dy(e).forEach(t=>t.dispose())}function Xt(e){return P.keep(e)}function x $ (e){return P.time(e)}function v $ (e){return P.setBackend(e)}function w $ (){return P.ready()}function k $ (){return P.backendName}function I $ (e){P.removeBackend(e)}function N $ (e){return P.findBackend(e)}function T $ (e){return P.findBackendFactory(e)}function Sh(e,t,n=1){return P.registerBackend(e,t,n)}function sk(){return P.backend}function S $ (e,t){ee().setPlatform(e,t)}function C $ (e,t){let n=C(e,"a","add"),a=C(t,"b","add");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(qr,r)}var Z=R({add_:C $ });function E $ (e,t){let n=C(e,"a","floorDiv"),a=C(t,"b","floorDiv");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(Ks,r)}var Ch=R({floorDiv_:E $ });function _ $ (e,t){let n=C(e,"a","div"),a=C(t,"b","div");if([n,a]=Tt(n,a),n.dtype==="int32"&&a.dtype==="int32")return Ch(n,a);let r={a:n,b:a},s={};return P.runKernel(Hs,r,s)}var ve=R({div_:_ $ });function F $ (e,t){let n=C(e,"a","mul"),a=C(t,"b","mul");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(si,r)}var L=R({mul_:F $ });function A $ (e){let t=C(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return P.runKernel(fc,n)}else{let n={x:t};return P.runKernel(Lo,n)}}var Wt=R({abs_:A $ });function $ $ (e){let t={x:C(e,"x","acos")};return P.runKernel(zo,t)}var Py=R({acos_: $ $ });function D $ (e){let t={x:C(e,"x","acosh")};return P.runKernel(Bo,t)}var Oy=R({acosh_:D $ });function M $ (e){F(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),F(e.length>=1,()=> ` Must pass at least one tensor to tf . addN ( ) , but got $ { e . length } ` );let t=e.map((r,s)=>C(r, ` tensors$ { s } ` ,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!xr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return P.runKernel(Rs,a)}var ik=R({addN_:M $ });function R $ (e,t=null,n=!1){let a={x:C(e,"x","all","bool")},r={axis:t,keepDims:n};return P.runKernel(Ld,a,r)}var Eh=R({all_:R $ });function P $ (e,t=null,n=!1){let a={x:C(e,"x","any","bool")},r={axis:t,keepDims:n};return P.runKernel(zd,a,r)}var Lc=R({any_:P $ });function O $ (e,t=0){let n={x:C(e,"x","argMax")},a={axis:t};return P.runKernel(Ps,n,a)}var zc=R({argMax_:O $ });function L $ (e,t=0){let n={x:C(e,"x","argMin")},a={axis:t};return P.runKernel(dc,n,a)}var Ly=R({argMin_:L $ });function z $ (e){let t={x:C(e,"x","asin")};return P.runKernel(Wo,t)}var zy=R({asin_:z $ });function B $ (e){let t={x:C(e,"x","asinh")};return P.runKernel(Vo,t)}var By=R({asinh_:B $ });function W $ (e){let t={x:C(e,"x","atan")};return P.runKernel(Uo,t)}var Wy=R({atan_:W $ });function V $ (e,t){let n=C(e,"a","atan2"),a=C(t,"b","atan2");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(Ho,r)}var Vy=R({atan2_:V $ });function U $ (e){let t=
with dtype $ { s . dtype } . ` )}),n.length===1)return es(n[0]);let a=n,r={axis:t};return P.runKernel(qo,a,r)}var Ze=R({concat_:Q $ });function eD(e){let t={x:C(e,"x","sigmoid")};return P.runKernel(yi,t)}var da=R({sigmoid_:eD});function tD(e,t,n){let a=C(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let r={x:a},s={begin:t,size:n};return P.runKernel(El,r,s)}var We=R({slice_:tD});function nD(e){let t={x:C(e,"x","tanh")};return P.runKernel(Ii,t)}var Kl=R({tanh_:nD});function aD(e,t,n,a,r,s){let i=C(e,"forgetBias","basicLSTMCell"),o=C(t,"lstmKernel","basicLSTMCell"),l=C(n,"lstmBias","basicLSTMCell"),c=C(a,"data","basicLSTMCell"),u=C(r,"c","basicLSTMCell"),p=C(s,"h","basicLSTMCell"),d=Ze([c,p],1),h=ze(d,o),m=Z(h,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],b=We(m,[0,0],y),x=We(m,[0,g],y),v=We(m,[0,g*2],y),N=We(m,[0,g*3],y),T=Z(L(da(b),Kl(x)),L(u,da(Z(i,v)))),E=L(Kl(T),da(N));return[T,E]}var rD=R({basicLSTMCell_:aD});function sD(e,t,n){let a=C(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);F(a.rank>=1+t.length,()=> ` input rank is $ { a . rank } but should be > than blockShape . length $ { t . length } ` ),F(n.length===t.length,()=> ` crops . length is $ { n . length } but should be equal to blockShape . length $ { t . length } ` ),F(a.shape[0]%r==0,()=> ` input tensor batch is $ { a . shape [ 0 ] } but is not divisible by the product of the elements of blockShape $ { t . join ( " * " ) } === $ { r } ` );let s={x:a},i={blockShape:t,crops:n};return P.runKernel(mc,s,i)}var Wc=R({batchToSpaceND_:sD});function iD(e){let t;return e.rank===0||e.rank===1?t=j(e,[1,1,1,e.size]):e.rank===2?t=j(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=j(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function oD(e,t,n,a,r,s){s==null&&(s=.001);let i=C(e,"x","batchNorm"),o=C(t,"mean","batchNorm"),l=C(n,"variance","batchNorm"),c;r!=null&&(c=C(r,"scale","batchNorm"));let u;a!=null&&(u=C(a,"offset","batchNorm")),F(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),F(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),F(c==null||o.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:iD(i),scale:c,offset:u,mean:o,variance:l},d={varianceEpsilon:s},h=P.runKernel(Xs,p,d);return j(h,i.shape)}var wr=R({batchNorm_:oD});function lD(e,t,n,a,r,s){let i=C(e,"x","batchNorm"),o=C(t,"mean","batchNorm"),l=C(n,"variance","batchNorm"),c;r!=null&&(c=C(r,"scale","batchNorm"));let u;return a!=null&&(u=C(a,"offset","batchNorm")),F(i.rank===2,()=> ` Error in batchNorm2D : x must be rank 2 but got rank $ { i . rank } . ` ),F(o.rank===2||o.rank===1,()=> ` Error in batchNorm2D : mean must be rank 2 or rank 1 but got rank $ { o . rank } . ` ),F(l.rank===2||l.rank===1,()=> ` Error in batchNorm2D : variance must be rank 2 or rank 1 but got rank $ { l . rank } . ` ),c!=null&&F(c.rank===2||c.rank===1,()=> ` Error in batchNorm2D : scale must be rank 2 or rank 1 but got rank $ { c . rank } . ` ),u!=null&&F(u.rank===2||u.rank===1,()=> ` Error in batchNorm2D : offset must be rank 2 or rank 1 but got rank $ { u . rank } . ` ),wr(i,o,l,u,c,s)}var ck=R({batchNorm2d_:lD});function uD(e,t,n,a,r,s){let i=C(e,"x","batchNorm"),o=C(t,"mean","batchNorm"),l=C(n,"variance","batchNorm"),c;r!=null&&(c=C(r,"scale","batchNorm"));let u;return a!=null&&(u=C(a,"offset","batchNorm")),F(i.rank===3,()=> ` Error in batchNorm3D : x must be rank 3 but got rank $ { i . rank } . ` ),F(o.rank===3||o.rank===1,()=> ` Error in batchNorm3D : mean must be rank 3 or rank 1 but got rank $ { o . rank } . ` ),F(l.rank===3||l.rank===1,()=> ` Error in batchNorm3D : variance must be rank 3 or rank 1 but got rank $ { l . rank } . ` ),c!=null&&F(c.rank===3||c.rank===1,()=> ` Error in batchNorm3D : scale must be rank 3 or rank 1 but got rank $ { c . rank } . ` ),u!=null&&F(u.rank===3||u.rank===1,()=> ` Error in batchNorm3D : offset must be rank 3 or rank 1 but got rank $ { u . rank } . ` ),wr(i,o,l,u,c,s)}var pk=R({batchNorm3d_:uD});function cD(e,t,n,a,r,s){let i=C(e,"x","batchNorm"),o=C(t,"mean","batchNorm"),l=C(n,"variance","batchNorm"),c;r!=null&&(c=C(r,"scale","batchNorm"));let u;return a!=nul
$ { r } and $ { t } for depthToSpace with input shape
$ { a . shape } ` ),F(s*t>=0,()=> ` Negative dimension size caused by overflow when multiplying
$ { s } and $ { t } for depthToSpace with input shape
$ { a . shape } ` ),F(i%(t*t)==0,()=> ` Dimension size must be evenly divisible by $ { t * t } but is $ { i } for depthToSpace with input shape $ { a . shape } ` );let o={x:a},l={blockSize:t,dataFormat:n};return P.runKernel(Yo,o,l)}var Yy=R({depthToSpace_:AD});function $ D(e,t,n,a,r="NHWC",s=[1,1],i){let o=C(e,"x","depthwiseConv2d"),l=C(t,"filter","depthwiseConv2d"),c=o,u=!1;o.rank===3&&(u=!0,c=j(o,[1,o.shape[0],o.shape[1],o.shape[2]])),F(c.rank===4,()=> ` Error in depthwiseConv2d : input must be rank 4 , but got rank $ { c . rank } . ` ),F(l.rank===4,()=> ` Error in depthwiseConv2d : filter must be rank 4 , but got rank $ { l . rank } . ` ),F(c.shape[3]===l.shape[2],()=> ` Error in depthwiseConv2d : number of input channels ( $ { c . shape [ 3 ] } ) must match the inChannels dimension in filter $ { l . shape [ 2 ] } . ` ),i!=null&&F(qt(a),()=> ` Error in depthwiseConv2d : pad must be an integer when using , dimRoundingMode $ { i } but got pad $ { a } . ` );let p={x:c,filter:l},d={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},h=P.runKernel(Gs,p,d);return u?j(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var kr=R({depthwiseConv2d_: $ D});function DD(e){let t={x:C(e,"x","diag")};return P.runKernel(Yd,t)}var MD=R({diag_:DD});function RD(e,t,n,a,r=[1,1],s="NHWC"){let i=C(e,"x","dilation2d"),o=C(t,"filter","dilation2d");F(i.rank===3||i.rank===4,()=> ` Error in dilation2d : input must be rank 3 or 4 , but got rank $ { i . rank } . ` ),F(o.rank===3,()=> ` Error in dilation2d : filter must be rank 3 , but got rank $ { o . rank } . ` ),F(s==="NHWC",()=> ` Error in dilation2d : Only NHWC is currently supported , but got dataFormat of $ { s } ` );let l=i,c=!1;i.rank===3&&(l=j(i,[1,i.shape[0],i.shape[1],i.shape[2]]),c=!0);let u={x:l,filter:o},p={strides:n,pad:a,dilations:r},d=P.runKernel(yc,u,p);return c?j(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Jy=R({dilation2d_:RD});function PD(e,t){let n=e.length,a=[];for(let r=0;r<n;r++){let s=n-1-r,i=e[s]||1;(t[t.length-1-r]||1)>1&&i===1&&a.unshift(s)}return a}function Vt(e,t){let n=[];for(let a=0;a<t.length;a++){let r=e[e.length-a-1],s=t.length-a-1,i=t[s];(r==null||r===1&&i>1)&&n.unshift(s)}return n}function vt(e,t){let n=[],a=Math.max(e.length,t.length);for(let r=0;r<a;r++){let s=e[e.length-r-1];s==null&&(s=1);let i=t[t.length-r-1];if(i==null&&(i=1),s===1)n.unshift(i);else if(i===1)n.unshift(s);else if(s!==i){let o= ` Operands could not be broadcast together with shapes $ { e } and $ { t } . ` ;throw Error(o)}else n.unshift(s)}return n}function OD(e,t){let n=C(e,"a","equal"),a=C(t,"b","equal");[n,a]=Tt(n,a),vt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(Qo,r)}var Ir=R({equal_:OD});function LD(e,t,n){let a=C(t,"a","where"),r=C(n,"b","where"),s=C(e,"condition","where","bool"),i=vt(a.shape,r.shape),o=Vc(a,i),l=Vc(r,i);s.rank===1&&F(s.shape[0]===a.shape[0],()=>"The first dimension of ` a ` must match the size of ` condition ` ."),s.rank!==1&&rt(s.shape,l.shape,"Error in where: ");let c={condition:s,t:o,e:l};return P.runKernel(Sl,c)}var In=R({where_:LD});function zD(e){let t={x:C(e,"x","zerosLike")};return P.runKernel(Ol,t)}var He=R({zerosLike_:zD});function BD(e,t){let n=C(e,"a","div"),a=C(t,"b","div");[n,a]=Tt(n,a);let r=ve(n,a),s=He(r),i=Ir(a,s);return In(i,s,r)}var Zy=R({divNoNan_:BD});function WD(e,t){let n=C(e,"t1","dot"),a=C(t,"t2","dot");F((n.rank===1||n.rank===2)&&(a.rank===1||a.rank===2),()=> ` Error in dot : inputs must all be rank 1 or 2 , but got ranks $ { n . rank } and $ { a . rank } . ` );let r=n.rank===1?n.size:n.shape[1],s=a.rank===1?a.size:a.shape[0];if(F(r===s,()=> ` Error in dot : inner dimensions of inputs must match , but got $ { r } and $ { s } . ` ),n.rank===1&&a.rank===1){let i=j(n,[1,-1]),o=j(a,[-1,1]),l=ze(i,o);return j(l,[])}else if(n.rank===1&&a.rank===2){let i=j(n,[1,-1]),o=j(a,[a.shape[0],a.shape[1]]),l=ze(i,o);return j(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=j(a,[-1,1]),o=ze(n,i);return j(o,[o.size])}else{let i=j(a,[a.shape[0],a.shape[1]]);return ze(n,i)}}var vk=R({dot_:WD});function VD(e){let t={x:C(e,"x","elu")};return P.runKernel(Jo,t)}var Xl=R({elu_:VD});function UD(e){let t=C(e,"x","erf");F(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be ` int32 ` or ` float32 ` ."),t.dtype=
rank $ { s . rank } . ` ),F(qt(t),()=> ` Error in localResponseNormalization : depthRadius must be an integer but got depthRadius $ { t } . ` );let i=s,o=!1;s.rank===3&&(o=!0,i=j(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},c={depthRadius:t,bias:n,alpha:a,beta:r},u=P.runKernel(wc,l,c);return o?j(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var nb=R({localResponseNormalization_:iM});function oM(e){let t={x:C(e,"x","log")};return P.runKernel(Zs,t)}var Dn=R({log_:oM});function lM(e){let t={x:C(e,"x","log1p")};return P.runKernel(dl,t)}var Rh=R({log1p_:lM});function uM(e){return F(jr(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=C(t,"x","tf.grad","string_or_numeric"),r=n!=null?C(n,"dy","tf.grad"):null;return P.tidy(()=>{let{value:s,grads:i}=P.gradients(()=>e(a),[a],r);return r!=null&&rt(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ph(i),i[0]})}}function cM(e){return F(jr(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{F(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of ` Tensor ` s or ` TensorLike ` s");let a=Pc(t,"args","tf.grads","string_or_numeric"),r=n!=null?C(n,"dy","tf.grads"):null;return P.tidy(()=>{let{value:s,grads:i}=P.gradients(()=>e(...a),a,r);return r!=null&&rt(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ph(i),i})}}function pM(e){return F(jr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{F(t instanceof z,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),F(n==null||n instanceof z,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=P.gradients(()=>e(t),[t],n);return Ph(a),{grad:a[0],value:r}}}function dM(e){return F(jr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{F(Array.isArray(t)&&t.every(r=>r instanceof z),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),F(n==null||n instanceof z,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=P.gradients(()=>e(...t),t,n);return n!=null&&rt(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ph(a.grads),a}}function Tk(e,t){F(jr(e),()=>"The f passed in variableGrads(f) must be a function"),F(t==null||Array.isArray(t)&&t.every(c=>c instanceof Yr),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in P.registeredVariables)t.push(P.registeredVariables[c])}let a=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),F(t.length>0,()=> ` variableGrads ( ) expects at least one of the input variables to be trainable , but none of the $ { r } variables is trainable . ` );let s=!0,{value:i,grads:o}=P.gradients(e,t,null,s);F(o.some(c=>c!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),F(i.rank===0,()=> ` The f passed in variableGrads ( f ) must return a scalar , but it returned a rank - $ { i . rank } tensor ` );let l={};return t.forEach((c,u)=>{o[u]!=null&&(l[c.name]=o[u])}),a!=null&&a.forEach(c=>l[c.name]=null),{value:i,grads:l}}function Xa(e){return P.customGrad(e)}function Ph(e){if(e.filter(t=>t==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 hM(e){let t={x:C(e,"x","neg")};return P.runKernel(fl,t)}var St=R({neg_:hM});function mM(e){let t={x:C(e,"x","softplus")};return P.runKernel(Al,t)}var Jl=R({softplus_:mM});function fM(e){let t=C(e,"x","logSigmoid");return Xa(n=>({value:St(Jl(St(n))),gradFunc:a=>L(a,da(St(n)))}))(t)}var Sk=R({logSigmoid_:fM});function gM(e,t=null,n=!1){let a={x:C(e,"x","max")},r={reductionIndices:t,keepDims:n};return P.runKernel(Qs,a,r)}var ta=R({max_:gM});function yM(e,t){let n=C(e,"a","sub"),a=C(t,"b","sub");[n,a]=Tt(n,a);let r={a:n,b:a};return P.runKernel(ki,r)}var fe=R({sub_:yM});function bM(e,t=null,n=!1){let a=C(e,"x","sum");a.dtype==="bool"&&(a=pe(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return P.runKernel(xi,r,s)}var Ce=R({sum_:bM});function xM(e,t=-1){let n=C(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 Xa((a,r)=>{let s=!0,i=ta(a,t,!0),o=fe(a,i),l=fe(pe(o,"float32"),Dn(Ce(mn(o),t,s)));return r([l]),{value:l,gradFunc:(c,u)=>{let[p]=u,d=!0,h=mn(p);return fe(c,L(Ce(c,t,d),h))}}})(n)}var Oh=R({logSoftmax_:xM});function ab(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Ck(e,t,n){let a=e.length+t.length,r=[],s=0,i=0;for(let o=0;o<a;o++)n.indexOf(o)===-1?r.push(e[s++]):r.push(t[i++]);return r}function Ek(e,t){let n=[],a=e.length;for(let s=0;s<a;s++)t.indexOf(s)===-1&&n.push(e[s]);let r=t.map(s=>e[s]);return[n,r]}function Ri(e,t){let n=t.map(a=>1);return Ck(e,n,t)}function vM(e,t,n){F(ab(t,n),()=> ` $ { e } supports only inner - most axes for now . Got axes $ { t } and rank - $ { n } input . ` )}function _k(e,t){if(ab(e,t))return null;let n=[];for(let a=0;a<t;++a)e.indexOf(a)===-1&&n.push(a);return e.forEach(a=>n.push(a)),n}function rb(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function wM(e,t){let n=[];for(let a=t-e;a<t;++a)n.push(a);return n}function kM(e,t=null,n=!1){let a=C(e,"x","logSumExp"),r=ca(t,a.shape),s=ta(a,r,!0),i=fe(a,s),o=mn(i),l=Ce(o,r),c=Dn(l),u=Z(j(s,c.shape),c);if(n){let p=Ri(u.shape,r);return j(u,p)}return u}var sb=R({logSumExp_:kM});function IM(e,t){let n=C(e,"a","logicalAnd","bool"),a=C(t,"b","logicalAnd","bool");vt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(hl,r)}var ha=R({logicalAnd_:IM});function NM(e){let t={x:C(e,"x","logicalNot","bool")};return P.runKernel(xc,t)}var jc=R({logicalNot_:NM});function TM(e,t){let n=C(e,"a","logicalOr","bool"),a=C(t,"b","logicalOr","bool");vt(n.shape,a.shape);let r={a:n,b:a};return P.runKernel(vc,r)}var Lh=R({logicalOr_:TM});function SM(e,t){let n=C(e,"a","logicalXor","bool"),a=C(t,"b","logicalXor","bool");return vt(n.shape,a.shape),ha(Lh(e,t),jc(ha(e,t)))}var Fk=R({logicalXor_:SM});function CM(e,t,n,a,r){let s=C(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=j(s,[1,s.shape[0],s.shape[1],s.shape[2]])),F(o.rank===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { o . rank } . ` ),F( $ n(n,i),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { n } and dilations '${i}' ` ),r!=null&&F(qt(a),()=> ` Error in maxPool : pad must be an integer when using , dimRoundingMode $ { r } but got pad $ { a } . ` );let c={x:o},u={filterSize:t,strides:n,pad:a,dimRoundingMode:r},p=P.runKernel(ti,c,u);return l?j(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Dt=R({maxPool_:CM});function EM(e,t=[1,1,1],n,a,r,s="NDHWC",i){i==null?i=[1,1,1]:Pt("dilations is deprecated, this field will be gone in v3.0.0.");let o=C(e,"x","maxPool3d"),l=o,c=!1;o.rank===4&&(c=!0,l=j(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),F(l.rank===5,()=> ` Error in maxPool3d : x must be rank 5 but got rank $ { l . rank } . ` ),F(s==="NDHWC",()=> ` Error in maxPool3d : Only NDHWC is currently supported , but got dataFormat of $ { s } ` ),F( $ n(n,i),()=> ` Error in maxPool3d : Either strides or dilations must be 1. Got strides $ { n } and dilations '${i}' ` ),r!=null&&F(qt(a),()=> ` Error in maxPool3d : pad must be an integer when using , dimRoundingMode $ { r } but got pad $ { a } . ` );
$ { s } ) . ` );if(n<a)throw new Error( ` batchDims ( $ { a } ) must be less than or equal to axis ( $ { n } ) . ` );for(let p=0;p<a;++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 i=e.shape[n],o=[],l=1,c=1,u=1;for(let p=0;p<a;++p)o.push(e.shape[p]),l*=e.shape[p];for(let p=a;p<n;p++)o.push(e.shape[p]),c*=e.shape[p];for(let p=a;p<r;p++)o.push(t.shape[p]);for(let p=n+1;p<s;p++)o.push(e.shape[p]),u*=e.shape[p];return{batchSize:l,sliceSize:u,outerSize:c,dimSize:i,outputShape:o}}function IL(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();let a=bt(e.shape),r=pe(e,"float32"),s=n.complex(r,a);return a.dispose(),r.dispose(),s}if(!n0(e.dtype,t))return P.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){let a=n.real(e),r=pe(a,t);return a.dispose(),r}if(t==="int32")return n.int(e);if(t==="bool"){let a=de(0,e.dtype),r=n.notEqual(e,a);return a.dispose(),r}else throw new Error( ` Error in Cast : failed to cast $ { e . dtype } to $ { t } ` )}function NL(e,t){return P.makeTensorFromDataId(e.dataId,t,e.dtype)}function TL(e){try{return e.map(t=>yh(t))}catch(t){throw new Error( ` Failed to decode encoded string bytes into utf - 8 , error : $ { t } ` )}}function SL(e){return e.map(t=>Ac(t))}var Qa={};Oe(Qa,{nonMaxSuppressionV3Impl:()=>l1,nonMaxSuppressionV4Impl:()=>u1,nonMaxSuppressionV5Impl:()=>c1,whereImpl:()=>Ok});var x1={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,nu(pe(n,"float32"),-1))}}},FL={kernelName:zo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=lt(pe(n,"float32")),r=rn(fe(de(1),a));return St(ve(e,r))}}}},AL={kernelName:Bo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=rn(fe(lt(pe(n,"float32")),1));return ve(e,a)}}}}, $ L={kernelName:qr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=vt(n.shape,a.shape);return{a:()=>{let s=e,i=Vt(n.shape,r);return i.length>0&&(s=Ce(s,i)),j(s,n.shape)},b:()=>{let s=e,i=Vt(a.shape,r);return i.length>0&&(s=Ce(s,i)),j(s,a.shape)}}}},DL={kernelName:Rs,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},ML={kernelName:Ps,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>He(n)}}},RL={kernelName:dc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>He(n)}}},PL={kernelName:Wo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,rn(fe(de(1),lt(pe(n,"float32")))))}}},OL={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=rn(Z(de(1),lt(pe(n,"float32"))));return ve(e,a)}}}},LL={kernelName:Ho,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=vt(n.shape,a.shape);return{a:()=>{let s=Z(lt(n),lt(a)),i=L(e,ve(a,s)),o=Vt(n.shape,r);return o.length>0&&(i=Ce(i,o)),j(i,n.shape)},b:()=>{let s=Z(lt(n),lt(a)),i=St(L(e,ve(n,s))),o=Vt(a.shape,r);return o.length>0&&(i=Ce(i,o)),j(i,a.shape)}}}},zL={kernelName:Uo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,Z(lt(pe(n,"float32")),1))}}},BL={kernelName:Go,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ve(e,fe(de(1),lt(pe(n,"float32"))))}}};function WL(e,t,n,a,r=[1,1,1],s,i){let o=C(e,"dy","avgPool3dGrad"),l=C(t,"input","avgPool3dGrad"),c=o,u=l,p=!1;l.rank===4&&(p=!0,c=j(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),u=j(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),F(c.rank===5,()=> ` Error in avgPool3dGrad : dy must be rank 5 but got rank $ { c . rank } . ` ),F(u.rank===5,()=> ` Error in avgPool3dGrad : input must be rank 5 but got rank $ { u . rank } . ` ),F( $ n(a,r),()=> ` Error in avgPool3dGrad : Either strides or dilations must be 1. Got strides $ { a } and dilations '${r}' ` ),i!=null&&F(qt(s),()=> ` Error in avgPool3dGrad : pad must be an integer when using , dimRoundingMode $ { i } but got pad $ { s } . ` );let d={dy:c,input:u},h={filterSize:n,strides:a,dilations:r,pad:s,dimRoundingMode:i},m=P.runKernel(Wd,d,h);return p?j(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var VL=R({avgPool3dGrad_:WL}),UL={kernelName:hc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,dilations:i,pad:o,dimRoundingMode:l}
1. The $ { a } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2. The custom $ { a } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );return i}else{let s=e;if(s.className==null||s.config==null)throw new B( ` $ { a } : Improper config format : $ { JSON . stringify ( s ) } .
'className' and 'config' must set . ` );let i=s.className,o,l;if(i in n?[o,l]=n[i]:i in ma?[o,l]=ma.className:i in t&&([o,l]=t[i]),o==null)throw new B( ` Unknown $ { a } : $ { i } . This may be due to one of the following reasons :
1. The $ { a } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2. The custom $ { a } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );if(l!=null){let c={};for(let h of Object.keys(ma))c[h]=ma[h];for(let h of Object.keys(n))c[h]=n[h];let u=s.config;u.customObjects=c;let p=Object.assign({},ma);for(let h of Object.keys(n))ma[h]=n[h];Sb(s.config);let d=l(o,s.config,n,r);return ma=Object.assign({},p),d}else{let c=Object.assign({},ma);for(let p of Object.keys(n))ma[p]=n[p];let u=new o(s.config);return ma=Object.assign({},c),u}}}function Pz(e,t){return e<t?-1:e>t?1:0}function cm(e,t){return-1*Pz(e,t)}function ls(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function Oz(e){if(e==null)throw new B( ` Invalid value in obj : $ { JSON . stringify ( e ) } ` );for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Vi(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new B( ` $ { n } is not a valid $ { t } . Valid values are $ { e } or null / undefined . ` )}function Cb(e,t,n=0,a=Infinity){return er(n>=0),er(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function Jt(e,t){Array.isArray(e)?(k.assert(e.length>0,()=> ` $ { t } is unexpectedly an empty array . ` ),e.forEach((n,a)=>Jt(n, ` element $ { a + 1 } of $ { t } ` ))):k.assert(Number.isInteger(e)&&e>0,()=> ` Expected $ { t } to be a positive integer , but got $ { F1 ( e ) } . ` )}function F1(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>F1(t)).join(",")+"]":typeof e=="string"? ` "${e}" ` : ` $ { e } ` }function Lz(e,t){let n=k.now(),a;return(...r)=>{let s=k.now();return s-n<t||(n=s,a=e(...r)),a}}function A1(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Eb(e,t){return D(()=>rn(Ce(L(e,e),t,!0)))}var np=class extends se.Serializable{getConfig(){return{}}},_b=class extends np{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return D(()=>{let t=Eb(e,this.axis),n=Yt(t,0,this.maxValue);return L(e,ve(n,Z(Ut(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};_b.className="MaxNorm";se.registerClass(_b);var Fb=class extends np{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return D(()=>ve(e,Z(Ut(),Eb(e,this.axis))))}getConfig(){return{axis:this.axis}}};Fb.className="UnitNorm";se.registerClass(Fb);var Ab=class extends np{apply(e){return Xe(e)}};Ab.className="NonNeg";se.registerClass(Ab);var $ b=class extends np{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return D(()=>{let t=Eb(e,this.axis),n=Z(L(this.rate,Yt(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,ve(n,Z(Ut(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}; $ b.className="MinMaxNorm";se.registerClass( $ b);var $ 1={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Gt(e){return Tb(e)}function D1(e,t={}){return tp(e,se.SerializationMap.getMap().classNameMap,t,"constraint")}function Ht(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in $ 1? $ 1[e]:e,config:{}};return D1(t)}else return e instanceof np?e:D1(e)}function Az(e){return new _b(e)}function $ z(e){return new Fb(e)}function Dz(){return new Ab}function Mz(e){return new $ b(e)}var M1={};Oe(M1,{constant:()=>Wz,glorotNormal:()=>Kz,glorotUniform:()=>qz,heNormal:()=>Xz,heUniform:()=>Yz,identity:()=>Hz,leCunNormal:()=>Jz,leCunUniform:()=>Zz,ones:()=>Bz,orthogonal:()=>Qz,randomNormal:()=>Uz,randomUniform:()=>Vz,truncatedNormal:()=>Gz,varianceScaling:()=>jz,zeros:()=>zz});var eB=["channelsFirst","channelsLast"],tB=["nearest","bilinear"],nB=["valid","same","causal"],aB=["max","avg"],rB=["sum","mul","concat","ave"],ru=new Map;function Rt(e){Vi(eB,"DataFormat",e)}function sB(
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),ya(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,Xt(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,a)=>this.write(n,t[a]))}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 a=0;a<this.size();a++)e.push(a)}if(e.length===0)return Yn([],[0].concat(this.elementShape));let n=this.readMany(e);return ya(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Mt(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 Yn([],[0].concat(this.elementShape));let t=[];for(let a=0;a<this.size();a++)t.push(a);let n=this.readMany(t);return ya(this.elementShape,n[0].shape, ` TensorArray shape mismatch : tensor array shape ( $ { this . elementShape } ) vs first tensor shape ( $ { n [ 0 ] . shape } ) ` ),Ze(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,pt(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,a=e.map(o=>(n+=o,n));if(n!==t.shape[0])throw new Error( ` Expected sum of lengths to be equal to
2020-10-11 18:41:17 +02:00
tensor . shape [ 0 ] , but sum of lengths is
2021-01-12 16:01:34 +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 r=n===0?0:t.size/n,s=[];D(()=>{t=j(t,[1,n,r]);for(let o=0;o<e.length;++o){let l=o===0?0:a[o-1],c=[0,l,0],u=[1,e[o],r];s[o]=j(We(t,c,u),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},xp=class{constructor(e,t,n,a=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(r=>{if(n!==r.dtype)throw new Error( ` Invalid data types ; op elements $ { n } , but list elements $ { r . dtype } ` );ya(t,r.shape,"TensorList shape mismatch: "),Xt(r)}),this.idTensor=de(0),this.maxNumElements=a,Xt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new xp([...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 . ` );return ya(e,this.elementShape,"TensorList shape mismatch: "),D(()=>{let a=this.tensors.map(r=>j(r,e));return Mt(a,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=this.tensors.pop();return ya(n.shape,e,"TensorList shape mismatch: "),j(n,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { e . dtype } , but list elements $ { this . elementDtype } ` );if(ya(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Xt(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error( ` TensorListResize expects size to be non - negative . Got : $ { e } ` );if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error( ` TensorListResize input size $ { e } is greater maxNumElement $ { this . maxNumElements } . ` );this.tensors.length=e}getItem(e,t,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 . ` );return ya(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t . dtype } , but list elements $ { this . elementDtype } ` );if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error( ` Trying to set element $ { e } in a list with max $ { this . maxNumElements } elements . ` );ya(this.elementShape,t.shape,"TensorList shape mismatch: "),Xt(t),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 } ` );return ya(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?Yn([],[0].concat(this.elementShape)):D(()=>{let a=e.map(r=>j(this.tensors[r],n));return Mt(a,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error( ` TensorList dtype is $ { this . elementDtype } but concat requested dtype $ { e } ` );return ya(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?Yn([],[0].concat(this.elementShape)):D(()=>{let n=this.tensors.map(a=>j(a,t));return Ze(n,0)})}};function BV(e,t,n){let a=e.dtype;if(e.shape.length<1)throw new Error( ` Tensor must be at least a vector , but saw shape : $ { e . shape } ` );if(e.dtype!==n)throw new Error( ` Invalid data types ; op elements $ { e . dtype } , but list elements $ { n } ` );let r=e.shape.slice(1);ya(r,t
2020-10-11 18:41:17 +02:00
tensor . shape [ 0 ] , but sum of lengths is
2021-01-12 16:01:34 +01:00
$ { a } , and tensor ' s shape is : $ { e . shape } ` );let s=a===0?0:e.size/a,i=D(()=>{let l=[];e=j(e,[1,a,s]);for(let c=0;c<t.length;++c){let u=c===0?0:r[c-1],p=[0,u,0],d=[1,t[c],s];l[c]=j(We(e,p,d),n)}return e.dispose(),l}),o=new xp([],n,e.dtype,t.length);for(let l=0;l<i.length;l++)o.setItem(l,i[l]);return o}var GV=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let a=I("thenBranch",e,t,n),r=I("elseBranch",e,t,n),s=I("cond",e,t,n),i=I("args",e,t,n);return(await s.data())[0]?n.functionMap[a].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let a=I("body",e,t,n),r=I("cond",e,t,n),s=I("args",e,t,n),i=await n.functionMap[r].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),o=s.map(u=>u.id),l=await i[0].data();i.forEach(u=>{!u.kept&&o.indexOf(u.id)===-1&&u.dispose()});let c=s;for(;l[0];){let u=c;c=await n.functionMap[a].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);let p=c.map(h=>h.id);u.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()});let d=await n.functionMap[r].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);l=await d[0].data(),d.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()})}return c}case"LoopCond":{let a=I("pred",e,t,n);return[Ar(a)]}case"Switch":{let a=I("pred",e,t,n),r=I("data",e,t,n);return r.kept||(r=Ar(r)),(await a.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let a=e.inputNames.find(r=>Cn(r,t,n)!==void 0);if(a){let r=Cn(a,t,n);return[Ar(r)]}return}case"Enter":{let a=I("frameName",e,t,n),r=I("tensor",e,t,n);return n.enterFrame(a),[Ar(r)]}case"Exit":{let a=I("tensor",e,t,n);return n.exitFrame(),[Ar(a)]}case"NextIteration":{let a=I("tensor",e,t,n);return n.nextIteration(),[Ar(a)]}case"TensorArrayV3":{let a=I("size",e,t,n),r=I("dtype",e,t,n),s=I("elementShape",e,t,n),i=I("dynamicSize",e,t,n),o=I("clearAfterRead",e,t,n),l=I("identicalElementShapes",e,t,n),c=I("name",e,t,n),u=new zV(c,r,a,s,l,i,o);return n.addTensorArray(u),[u.idTensor,de(1)]}case"TensorArrayWriteV3":{let a=I("tensorArrayId",e,t,n),r=I("index",e,t,n),s=I("tensor",e,t,n),i=n.getTensorArray(a.id);return i.write(r,s),[i.idTensor]}case"TensorArrayReadV3":{let a=I("tensorArrayId",e,t,n),r=I("index",e,t,n);return[n.getTensorArray(a.id).read(r)]}case"TensorArrayGatherV3":{let a=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),s=I("dtype",e,t,n);return[n.getTensorArray(a.id).gather(r,s)]}case"TensorArrayScatterV3":{let a=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),s=I("tensor",e,t,n),i=n.getTensorArray(a.id);return i.scatter(r,s),[i.idTensor]}case"TensorArrayConcatV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id),s=I("dtype",e,t,n);return[r.concat(s)]}case"TensorArraySplitV3":{let a=I("tensorArrayId",e,t,n),r=I("tensor",e,t,n),s=I("lengths",e,t,n),i=n.getTensorArray(a.id);return i.split(s,r),[i.idTensor]}case"TensorArraySizeV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return[de(r.size(),"int32")]}case"TensorArrayCloseV3":{let a=I("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let a=I("tensorListId",e,t,n),r=I("index",e,t,n),s=I("tensor",e,t,n),i=n.getTensorList(a.id);return i.setItem(r,s),[i.idTensor]}case"TensorListGetItem":{let a=I("tensorListId",e,t,n),r=I("index",e,t,n),s=I("elementShape",e,t,n),i=I("elementDType",e,t,n);return[n.getTensorList(a.id).getItem(r,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let a=I("indices",e,t,n),r=I("tensor",e,t,n),s=I("elementShape",e,t,n),i=I("numElements",e,t,n),o=VV(r,a,s,i);return n.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let a=I("elementShape",e,t,n),r=I("elementDType",e,t,n),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=I(s,e,t,n),o=WV(a,r,i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{let a=I("tensorListId",e,t,n),r=I("indices",e,t,n),s=I("elementShape",e,t,n),i=I("elementDType",e,t,n);return[n.getTensorList(a.id).gather(r,i,s)]}cas
$ { e } ` );let a;return this.size===Infinity||this.size==null?a=this.size:t?a=Math.ceil(this.size/e):a=Math.floor(this.size/e),zn(async()=>(await n.iterator()).columnMajorBatch(e,t,HU),a)}concatenate(e){let t=this,n;return this.size===Infinity||e.size===Infinity?n=Infinity:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,zn(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===Infinity?n=Infinity:n=null,zn(async()=>(await t.iterator()).filter(a=>D(()=>e(a))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return zn(async()=>(await t.iterator()).map(n=>D(()=>e(n))),this.size)}mapAsync(e){let t=this;return zn(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 zn(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=Infinity:n=null,zn(async()=>{let a=Iv(async()=>({value:await t.iterator(),done:!1}));return DU(a.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,zn(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 a = this , r = IU . alea ( t || k . now ( ) . toString ( ) ) ; return zn ( async ( ) => { let s = r . int32 ( ) ; return n && ( s += r . int32 ( ) ) , ( await a . iterator ( ) ) . shuffle ( e , s . 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 , zn ( async ( ) => ( await t . iterator ( ) ) . take ( e ) , n ) } async toArray ( ) { if ( this . size === Infinity ) throw new Error ( "Can not convert infinite data stream to array." ) ; return ( await this . iterator ( ) ) . toArray ( ) } async toArrayForTest ( ) { if ( this . size === Infinity ) throw new Error ( "Can not convert infinite data stream to array." ) ; return ( await this . iterator ( ) ) . toArrayForTest ( ) } } ; pu . MAX _BUFFER _SIZE = 1e4 ; function zn ( e , t = null ) { return new class extends pu { constructor ( ) { super ( ... arguments ) ; this . size = t } async iterator ( ) { return e ( ) } } } function gU ( e ) { return zn ( async ( ) => YN ( e ) , e . length ) } function yU ( e ) { if ( ! du ( 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 zn ( async ( ) => { let n = await KN ( e , a => { if ( a instanceof pu ) return { value : a . iterator ( ) , recurse : ! 1 } ; if ( du ( a ) ) return { value : null , recurse : ! 0 } ; throw new Error ( "Leaves of the structure passed to zip() must be Datasets, not primitives." ) } ) ; return RU ( n , fs . SHORTEST ) } , t ) } function HU ( e ) { if ( e === null ) return null ; let t = e [ 0 ] ; return EU ( t ) ? { value : jU ( e ) , recurse : ! 1 } : { value : null , recurse : ! 0 } } function jU ( e ) { if ( e . length === 0 ) throw new Error ( "Can't make a batch of zero elements." ) ; return e [ 0 ] instanceof z ? Mt ( e ) : Yn ( e ) } var WN = class extends pu { constructor ( e ) { super ( ) ; this . input = e } async iterator ( ) { return ( await this . input . iterator ( ) ) . decodeUTF8 ( ) . split ( `
` ).map(e=>(e.endsWith(" \r ")&&(e=e.slice(0,-1)),e))}},qm='"',vp=Symbol("out"),eT=Symbol("field"),Km=Symbol("quote"),Tv=Symbol("quoteafterquote"),tT=Symbol("quoteinquote"),VN=class extends pu{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 WN(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(k.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&&k.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((a,r)=>(a[r]=a[r]+1||1,a),{}),n=Object.keys(t).filter(a=>t[a]>1);if(k.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let a of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(a)===-1)throw new Error('The key "'+a+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let e=await(await this.base.iterator()).next();if(e.done)throw new Error("No data was found for CSV parsing.");let t=e.value;return this.parseRow(t,!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={},a={};for(let r=0;r<this.fullColumnNames.length;r++){let s=this.fullColumnNames[r],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[r],l=null;if(o==="")if(i&&i.default!==void 0)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error( ` Required column $ { s } is empty in this line : $ { e } ` );l=void 0}else{let c=Number(o);if(isNaN(c))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=c;else switch(i.dtype){case"float32":l=c;break;case"int32":l=Math.floor(c);break;case"bool":l=this.getBoolean(o);break;default:l=c}}i&&i.isLabel?a[s]=l:n[s]=l}}return Object.keys(a).length===0?n:{xs:n,ys:a}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],a=0,r=e.length,s=vp;for(let i=0;i<r;i++)switch(s){case vp:switch(e.charAt(i)){case qm:a=i+1,s=Km;break;case this.delimiter:if(a=i+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),s=vp;break;default:s=eT,a=i;break}break;case eT:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i)),s=vp,a=i+1;break;default:}break;case Km:switch(e.charAt(i)){case qm:s=Tv;break;default:}break;case Tv:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(a,i-1)),s=vp,a=i+1;break;case qm:s=Km;break;default:s=tT;break}break;case tT:switch(e.charAt(i)){case qm:s=Km;break;default:}break;default:}if(s===Tv?n.push(e.substring(a,r-1)):n.push(e.substring(a)),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}},nT=class extends Qt{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
2020-10-11 18:41:17 +02:00
=== === === === === === === === === =
2020-11-25 14:30:53 +01:00
Hi there \ u { 1 F44B } . Looks like you are running TensorFlow . js in Node . js . To speed things up dramatically , install our node backend , which binds to TensorFlow C ++ , by running npm i @ tensorflow / tfjs - node , or npm i @ tensorflow / tfjs - node - gpu if you have CUDA . Then call require ( '@tensorflow/tfjs-node' ) ; ( - gpu suffix for CUDA ) at the start of your program . Visit https : //github.com/tensorflow/tfjs-node for more details.
2021-01-12 16:01:34 +01:00
=== === === === === === === === === = ` ));let a={};return this.data.set(a,{values:e,dtype:n,refCount:1}),a}makeTensorInfo(e,t,n){let a;if(t==="string"&&n!=null&&n.length>0&&k.isString(n[0])){let r=n.map(s=>k.encodeString(s));a=this.write(r,e,t)}else a=this.write(n,e,t);return{dataId:a,shape:e,dtype:t}}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,a){this.data.set(e,{values:t,dtype:a,refCount:1})}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 a=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return _.mergeRealAndImagArrays(a,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(a=>k.decodeString(a))}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,n)}makeOutput(e,t,n){let a=this.write(e,t,n);return ns().makeTensorFromDataId(a,t,n,this)}disposeData(e){if(this.data.has(e)){let{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){let t=e.dataId;if(this.data.has(t)){let n=this.data.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}async time(e){let t=k.now();return e(),{kernelMs:k.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){ke([e],"where");let t=this.readSync(e.dataId);return eG(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},lT={};Oe(lT,{addImpl:()=>cT,bincountImpl:()=>Sv,bincountReduceImpl:()=>pT,ceilImpl:()=>dT,concatImpl:()=>Cv,expImpl:()=>hT,expm1Impl:()=>mT,floorImpl:()=>fT,gatherV2Impl:()=>gT,greaterImpl:()=>yT,lessImpl:()=>bT,linSpaceImpl:()=>xT,logImpl:()=>vT,maxImpl:()=>wT,maximumImpl:()=>kT,minimumImpl:()=>IT,multiplyImpl:()=>Ev,negImpl:()=>NT,notEqualImpl:()=>TT,prodImpl:()=>ST,rangeImpl:()=>Fv,rsqrtImpl:()=>CT,simpleAbsImpl:()=>uT,sliceImpl:()=>Xm,squaredDifferenceImpl:()=>ET,stridedSliceImpl:()=>_T,subImpl:()=>FT,tileImpl:()=>AT,topKImpl:()=> $ T,transposeImpl:()=>_v,uniqueImpl:()=>DT});function uT(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var nG=e=>{let{x:t}=e.inputs,n=e.backend;ke(t,"abs");let a=new Float32Array(k.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return a=uT(r),n.makeOutput(a,t.shape,"float32")},aG={kernelName:Lo,backendName:"cpu",kernelFunc:nG};function Ot(e){return(t,n,a,r,s)=>{let i=_.assertAndGetBroadcastShape(t,n),o=i.length,l=k.computeStrides(i),c=k.sizeFromShape(i),u=k.getTypedArrayFromDType(s,c),p=t.length,d=n.length,h=k.computeStrides(t),m=k.computeStrides(n),f=_.getBroadcastDims(t,i),g=_.getBroadcastDims(n,i);if(f.length+g.length===0)for(let y=0;y<u.length;++y)u[y]=e(a[y%a.length],r[y%r.length]);else for(let y=0;y<u.length;++y){let b=k.indexToLoc(y,o,l),x=b.slice(-p);f.forEach(E=>x[E]=0);let v=k.locToIndex(x,p,h),N=b.slice(-d);g.forEach(E=>N[E]=0);let T=k.locToIndex(N,d,m);u[y]=e(a[v],r[T])}return[u,i]}}function Bn(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(a.shape,"complex64"),l=n.data.get(o.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(a.shape,"float32",s),imag:n.makeTensorInfo(r.shape,"float32",i)},o}var rG={kernelName:Ud,backendName:"cpu",kernelFunc:Bn};function Ym(e,t,n="float32"){if(n==="complex64"){let r=Ym(e,t,"float32"),s=Ym(e,t,"float32");return Bn({inputs:{real:r,imag:s},backend:e})}let a=k.makeZerosTypedArray(k.sizeFromShape(t),n);return e.makeTensorInfo(t,n,a)}function sr(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var sG={kernelName:il,backendName:"cpu",kernelFunc:sr};function Xi(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.data.get(a.dataId).complexTensorInfos.real
` ),s=r.length.toString().length+2,i=r.map((p,d)=>k.rightPad((d+1).toString(),s)+p),o=0;for(let p=0;p<i.length;p++)o=Math.max(i[p].length,o);let l=i.slice(0,a-1),c=i.slice(a-1,a),u=i.slice(a);console.log(l.join( `
` )),console.log(t.split( `
` )[0]),console.log( ` % c $ { k . rightPad ( c [ 0 ] , o ) } ` ,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join( `
` ))}function qq(e){return $ r(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function Kq(e,t){if(Se(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function Vv(e,t){if(Se(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Xq(e,t){let n= $ r(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Se(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Se(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Yq(e,t){let n= $ r(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Se(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Se(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Jq(e){return $ r(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function Zq(e,t){let n=ee().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let a= ` [ $ { e } x$ { t } ] ` ;throw new Error("Requested texture size "+a+" is invalid.")}if(e>n||t>n){let a= ` [ $ { e } x$ { t } ] ` ,r= ` [ $ { n } x$ { n } ] ` ;throw new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU "+r+".")}}function Qq(e){return $ r(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function eS(e,t,n,a,r,s,i){let o=e.getAttribLocation(t,n);return o===-1?!1:(Se(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),Se(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),Se(e,()=>e.enableVertexAttribArray(o)),!0)}function t8(e,t,n){e8(e,n),Se(e,()=>e.activeTexture(e.TEXTURE0+n)),Se(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function n8(e,t,n){return $ r(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function a8(e,t,n){return e.getUniformLocation(t,n)}function r8(e,t,n,a){Se(e,()=>t8(e,t,a)),Se(e,()=>e.uniform1i(n,a))}function Uv(e,t,n){Se(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Se(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function tS(e,t){Se(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Se(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function tf(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+s8(e,t))}function s8(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 $ r(e,t,n){let a=Se(e,()=>t());if(a==null)throw new Error(n);return a}function e8(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,a=t+e.TEXTURE0;if(a<e.TEXTURE0||a>n){let r= ` [ gl . TEXTURE0 , gl . TEXTURE$ { n } ] ` ;throw new Error( ` textureUnit must be in $ { r } . ` )}}function bu(e,t=2){return k.sizeFromShape(e.slice(0,e.length-t))}function xu(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 Gv(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[bu(e),...xu(e)]),t}function i8(e,t=!1){let n=ee().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((r,s)=>s>=e.length-2?k.nearestLargerEven(e[s]):e[s]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=k.squeezeShape(e).newShape);let a=k.sizeFromShape(e);if(e.length<=1&&a<=n)return[1,a];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){let r=bu(e),s=2,i=2;return e.length&&([s,i]=xu(e)),a=r*(s/2)*(i/2),k.sizeToSquarishShape(a).map(o=>o*2)}return k.sizeToSquarishShape(a)}function nf(e){return e%2==0}function af(e,t){if(e=e.slice(-2),t=t.slice(-2),k.arr
2020-10-11 18:41:17 +02:00
bool isnan _custom ( float val ) {
return ( val > 0.0 || val < 0.0 ) ? false : val != 0.0 ;
}
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan _custom ( val . x ) ,
isnan _custom ( val . y ) , isnan _custom ( val . z ) , isnan _custom ( val . w ) ) ;
}
# define isnan ( value ) isnan _custom ( value )
2021-01-12 16:01:34 +01:00
` ,l="",c= `
2020-10-11 18:41:17 +02:00
# define round ( value ) newRound ( value )
int newRound ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
}
ivec4 newRound ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` ):(e="",t="attribute",n="varying",a="varying",r="texture2D",s="gl_FragColor",i="",o= `
2020-10-11 18:41:17 +02:00
# define isnan ( value ) isnan _custom ( value )
bool isnan _custom ( float val ) {
return ( val > 0. || val < 1. || val == 0. ) ? false : true ;
}
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan ( val . x ) , isnan ( val . y ) , isnan ( val . z ) , isnan ( val . w ) ) ;
}
2021-01-12 16:01:34 +01:00
` ,l= `
2020-10-11 18:41:17 +02:00
uniform float INFINITY ;
bool isinf ( float val ) {
return abs ( val ) == INFINITY ;
}
bvec4 isinf ( vec4 val ) {
return equal ( abs ( val ) , vec4 ( INFINITY ) ) ;
}
2021-01-12 16:01:34 +01:00
` ,c= `
2020-10-11 18:41:17 +02:00
int round ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
}
ivec4 round ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` ),{version:e,attribute:t,varyingVs:n,varyingFs:a,texture2D:r,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:c}}function Zi(e,t,n="index"){let a=k.computeStrides(t);return a.map((r,s)=>{let i= ` int $ { e [ s ] } = $ { n } / $ { r } ` ,o=s===a.length-1? ` int $ { e [ s + 1 ] } = $ { n } - $ { e [ s ] } * $ { r } ` : ` index -= $ { e [ s ] } * $ { r } ` ;return ` $ { i } ; $ { o } ; ` }).join("")}function Kv(e){let t=k.computeStrides(e).map(n=>n.toString());return `
2020-10-11 18:41:17 +02:00
int getFlatIndex ( ivec3 coords ) {
2021-01-12 16:01:34 +01:00
return coords . x * $ { t [ 0 ] } + coords . y * $ { t [ 1 ] } + coords . z ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }var aS= `
2020-10-11 18:41:17 +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 ) ;
}
highp float av = abs ( v ) ;
if ( av < FLOAT _MIN ) {
return vec4 ( 0.0 , 0.0 , 0.0 , 0.0 ) ;
} else if ( v > FLOAT _MAX ) {
return vec4 ( 0.0 , 0.0 , 128.0 , 127.0 ) / 255.0 ;
} else if ( v < - FLOAT _MAX ) {
return vec4 ( 0.0 , 0.0 , 128.0 , 255.0 ) / 255.0 ;
}
highp vec4 c = vec4 ( 0 , 0 , 0 , 0 ) ;
highp float e = floor ( log2 ( av ) ) ;
highp float m = exp2 ( fract ( log2 ( av ) ) ) - 1.0 ;
c [ 2 ] = floor ( 128.0 * m ) ;
m -= c [ 2 ] / 128.0 ;
c [ 1 ] = floor ( 32768.0 * m ) ;
m -= c [ 1 ] / 32768.0 ;
c [ 0 ] = floor ( 8388608.0 * m ) ;
highp float ebias = e + 127.0 ;
c [ 3 ] = floor ( ebias / 2.0 ) ;
ebias -= c [ 3 ] * 2.0 ;
c [ 2 ] += floor ( ebias ) * 128.0 ;
c [ 3 ] += 128.0 * step ( 0.0 , - v ) ;
return c / 255.0 ;
}
2021-01-12 16:01:34 +01:00
` ,m8=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=kp.DENSE;let t=Np(e),n=gn();this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2021-01-12 16:01:34 +01:00
$ { Zi ( [ "r" , "c" , "d" ] , e ) }
2020-12-15 14:15:43 +01:00
return ivec3 ( r , c , d ) ;
}
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = 4 * ( resTexRC . x * $ { t [ 1 ] } + resTexRC . y ) ;
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
for ( int i = 0 ; i < 4 ; i ++ ) {
int flatIndex = index + i ;
ivec3 rc = outCoordsFromFlatIndex ( flatIndex ) ;
result [ i ] = getA ( rc . x , rc . y , rc . z ) ;
}
2021-01-12 16:01:34 +01:00
$ { n . output } = result ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }},f8=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=kp.DENSE;let t=Np(e),n=gn();this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2021-01-12 16:01:34 +01:00
$ { Zi ( [ "r" , "c" , "d" ] , e ) }
2020-12-15 14:15:43 +01:00
return ivec3 ( r , c , d ) ;
}
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = 4 * ( resTexRC . x * $ { t [ 1 ] } + resTexRC . y ) ;
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
for ( int i = 0 ; i < 4 ; i ++ ) {
int flatIndex = index + i ;
ivec3 rc = outCoordsFromFlatIndex ( flatIndex ) ;
result [ i ] = getChannel ( getA ( rc . x , rc . y , rc . z ) , vec2 ( rc . y , rc . z ) ) ;
}
2021-01-12 16:01:34 +01:00
$ { n . output } = result ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }},g8=class{constructor(e){this.variableNames=["A"],this.outTexUsage=ra.DOWNLOAD;let t=gn();this.outputShape=e,this.userCode= `
$ { aS }
2020-12-15 14:15:43 +01:00
void main ( ) {
float x = getAAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { t . output } = encode _float ( x ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }},y8=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ra.DOWNLOAD;let t=gn();this.outputShape=e,this.userCode= `
$ { aS }
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
float x = getChannel ( getAAtOutCoords ( ) , vec2 ( coords . y , coords . z ) ) ;
2021-01-12 16:01:34 +01:00
$ { t . output } = encode _float ( x ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }},b8=class{constructor(e,t,n=!1){this.variableNames=["A"];let a=gn(),[r,s]=t;this.outputShape=e;let i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode= `
$ { Kv ( e ) }
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int flatIndex = getFlatIndex ( coords ) ;
int offset = imod ( flatIndex , 4 ) ;
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
2021-01-12 16:01:34 +01:00
int r = flatIndex / $ { s } ;
int c = imod ( flatIndex , $ { s } ) ;
vec2 uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( $ { s } . 0 , $ { r } . 0 ) ;
vec4 values = $ { a . texture2D } ( A , uv ) ;
2020-12-15 14:15:43 +01:00
float result ;
if ( offset == 0 ) {
result = values [ 0 ] ;
} else if ( offset == 1 ) {
result = values [ 1 ] ;
} else if ( offset == 2 ) {
result = values [ 2 ] ;
} else {
result = values [ 3 ] ;
}
2021-01-12 16:01:34 +01:00
$ { a . output } = vec4 ( $ { i } , 0. , 0. , 0. ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }},x8=class{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let a=gn(),[r,s]=t;this.outputShape=e;let i="",o="result";n&&(o="floor(result * 255. + 0.5)");for(let l=0;l<=1;l++)for(let c=0;c<=1;c++){let u=l*2+c;i+= `
2020-12-15 14:15:43 +01:00
localCoords = coords ;
2021-01-12 16:01:34 +01:00
if ( localCoords [ 2 ] + $ { c } < $ { e [ 2 ] } ) {
localCoords [ 2 ] += $ { c } ;
if ( localCoords [ 1 ] + $ { l } < $ { e [ 1 ] } ) {
localCoords [ 1 ] += $ { l } ;
2020-12-15 14:15:43 +01:00
flatIndex = getFlatIndex ( localCoords ) ;
offset = imod ( flatIndex , 4 ) ;
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
2021-01-12 16:01:34 +01:00
r = flatIndex / $ { s } ;
c = imod ( flatIndex , $ { s } ) ;
uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( $ { s } . 0 , $ { r } . 0 ) ;
values = $ { a . texture2D } ( A , uv ) ;
2020-12-15 14:15:43 +01:00
if ( offset == 0 ) {
2021-01-12 16:01:34 +01:00
result [ $ { u } ] = values [ 0 ] ;
2020-12-15 14:15:43 +01:00
} else if ( offset == 1 ) {
2021-01-12 16:01:34 +01:00
result [ $ { u } ] = values [ 1 ] ;
2020-12-15 14:15:43 +01:00
} else if ( offset == 2 ) {
2021-01-12 16:01:34 +01:00
result [ $ { u } ] = values [ 2 ] ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
result [ $ { u } ] = values [ 3 ] ;
2020-12-15 14:15:43 +01:00
}
}
}
` }this.userCode= `
2021-01-12 16:01:34 +01:00
$ { Kv ( e ) }
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
int flatIndex , r , c , offset ;
ivec3 localCoords ;
vec2 uv ;
vec4 values ;
2021-01-12 16:01:34 +01:00
$ { i }
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
$ { a . output } = $ { o } ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function v8(e){let t=gn(),n= ` $ { t . version }
2020-12-15 14:15:43 +01:00
precision highp float ;
2021-01-12 16:01:34 +01:00
$ { t . attribute } vec3 clipSpacePos ;
$ { t . attribute } vec2 uv ;
$ { t . varyingVs } vec2 resultUV ;
2020-12-15 14:15:43 +01:00
void main ( ) {
gl _Position = vec4 ( clipSpacePos , 1 ) ;
resultUV = uv ;
2021-01-12 16:01:34 +01:00
} ` ;return Uq(e,n)}function w8(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 Xq(e,t)}function k8(e){let t=new Uint16Array([0,1,2,2,1,3]);return Yq(e,t)}function Sp(e,t,n,a,r,s){Zq(t,n);let i=Jq(e),o=e.TEXTURE_2D;return Se(e,()=>e.bindTexture(o,i)),Se(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Se(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Se(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),Se(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),Se(e,()=>e.texImage2D(o,0,a,t,n,0,r,s,null)),Se(e,()=>e.bindTexture(e.TEXTURE_2D,null)),i}function rS(e){return e.internalFormatFloat}function I8(e,t,n,a){let[r,s]=Ip(t,n);return Sp(e,r,s,rS(a),a.textureFormatFloat,e.FLOAT)}function sS(e){return e.internalFormatHalfFloat}function N8(e,t,n,a){let[r,s]=Ip(t,n);return Sp(e,r,s,sS(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function iS(e){return e.downloadTextureFormat}function T8(e,t,n,a){let[r,s]=Ip(t,n);return Sp(e,r,s,iS(a),e.RGBA,e.UNSIGNED_BYTE)}function oS(e){return e.internalFormatPackedFloat}function S8(e,t,n,a){let[r,s]=yu(t,n);return Sp(e,r,s,oS(a),e.RGBA,e.FLOAT)}function lS(e){return e.internalFormatPackedHalfFloat}function C8(e,t,n,a){let[r,s]=yu(t,n);return Sp(e,r,s,lS(a),e.RGBA,a.textureTypeHalfFloat)}function E8(e,t,n){let a=0,r=3*4,s=3*4+2*4;return Se(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),eS(e,t,"clipSpacePos",n,3,s,a)&&eS(e,t,"uv",n,2,s,r)}function _8(e,t,n,a,r,s){Se(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;r instanceof Uint8Array?(i=new Uint8Array(n*a*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*a*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(r),Se(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,a,0,e.RGBA,o,i)),Se(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function F8(e,t,n){Se(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Se(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Se(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Se(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function A8(e,t,n,a){let r=e.createBuffer();Se(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*n;return Se(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),Se(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Se(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function $ 8(e,t,n){let a=e,r=new Float32Array(n);return a.bindBuffer(a.PIXEL_PACK_BUFFER,t),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,r),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),r}function D8(e,t,n,a){let[r,s]=Ip(t,n),i=4,o=new Uint8Array(Pq(t*n,i));return Se(e,()=>e.readPixels(0,0,r,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function M8(e,t,n,a,r,s,i,o){let l=e,c=new Float32Array(Oq(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function R8(e,t,n){let a=new Float32Array(t*n*4);return Se(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,a)),a}var O8=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=ee().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Dq(t,e)):this.gl=ir(t);let n="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(ee().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=ef(this.gl,r),xa(this.gl,s))this.textureHalfFloatExtension=ef(this.gl,s);else if(ee().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),xa(this.gl,a))this.colorBufferHalfFloatExtension=ef(this.gl,a);else if(ee().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",xa(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(xa(this.gl,a))t
` ),i=e.map(h=>L8(h,t,a)).join( `
` ),o=t.texShape,l=gn(),c=W8(l),u,p,d=G8(l);return t.isPacked?(u=z8(t.logicalShape,o),p=U8(l)):(u=B8(t.logicalShape,o),p=V8(l)),a&&(d+=H8),[d,c,p,s,u,i,n].join( `
` )}function vu(e){let t=e.shapeInfo.logicalShape;switch(t.length){case 0:return q8(e);case 1:return K8(e);case 2:return X8(e);case 3:return Y8(e);case 4:return J8(e);case 5:return Z8(e);case 6:return Q8(e);default:throw new Error( ` $ { t . length } - D input sampling is not yet supported ` )}}function cS(e){switch(e.shapeInfo.logicalShape.length){case 0:return eK(e);case 1:return tK(e);case 2:return nK(e);case 3:return aK(e);default:return rK(e)}}function L8(e,t,n=!1){let a="";n?a+=cS(e):a+=vu(e);let r=e.shapeInfo.logicalShape,s=t.logicalShape;return r.length<=s.length&&(n?a+=sK(e,t):a+=iK(e,t)),a}function z8(e,t){switch(e.length){case 0:return pS();case 1:return oK(e,t);case 2:return cK(e,t);case 3:return lK(e,t);default:return uK(e,t)}}function B8(e,t){switch(e.length){case 0:return pS();case 1:return pK(e,t);case 2:return gK(e,t);case 3:return dK(e,t);case 4:return hK(e,t);case 5:return mK(e,t);case 6:return fK(e,t);default:throw new Error( ` $ { e . length } - D output sampling is not yet supported ` )}}function W8(e){return `
2020-10-11 18:41:17 +02:00
float sampleTexture ( sampler2D textureSampler , vec2 uv ) {
2021-01-12 16:01:34 +01:00
return $ { e . texture2D } ( textureSampler , uv ) . r ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function V8(e){return `
2020-10-11 18:41:17 +02:00
void setOutput ( float val ) {
2021-01-12 16:01:34 +01:00
$ { e . output } = vec4 ( val , 0 , 0 , 0 ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function U8(e){return `
2020-10-11 18:41:17 +02:00
void setOutput ( vec4 val ) {
2021-01-12 16:01:34 +01:00
$ { e . output } = val ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function G8(e){return ` $ { e . version }
2020-10-11 18:41:17 +02:00
precision highp float ;
precision highp int ;
precision highp sampler2D ;
2021-01-12 16:01:34 +01:00
$ { e . varyingFs } vec2 resultUV ;
$ { e . defineOutput }
2020-10-11 18:41:17 +02:00
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 ;
2021-01-12 16:01:34 +01:00
$ { e . defineSpecialNaN }
$ { e . defineSpecialInf }
$ { e . defineRound }
2020-10-11 18:41:17 +02:00
int imod ( int x , int y ) {
return x - y * ( x / y ) ;
}
int idiv ( int a , int b , float sign ) {
int res = a / b ;
int mod = imod ( a , b ) ;
if ( sign < 0. && mod != 0 ) {
res -= 1 ;
}
return res ;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
# define HASHSCALE1 443.8975
float random ( float seed ) {
vec2 p = resultUV * seed ;
vec3 p3 = fract ( vec3 ( p . xyx ) * HASHSCALE1 ) ;
p3 += dot ( p3 , p3 . yzx + 19.19 ) ;
return fract ( ( p3 . x + p3 . y ) * p3 . z ) ;
}
2021-01-12 16:01:34 +01:00
$ { yK }
$ { bK }
$ { xK }
` }var yK= `
2020-10-11 18:41:17 +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 ) ;
}
2021-01-12 16:01:34 +01:00
` ,bK= `
2020-10-11 18:41:17 +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 ) ;
}
2021-01-12 16:01:34 +01:00
` ,xK= `
2020-10-11 18:41:17 +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 ) ;
}
2021-01-12 16:01:34 +01:00
` ,H8= `
2020-10-11 18:41:17 +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 ;
}
2021-01-12 16:01:34 +01:00
` ;function pS(){return `
2020-10-11 18:41:17 +02:00
int getOutputCoords ( ) {
return 0 ;
}
2021-01-12 16:01:34 +01:00
` }function oK(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1? `
2020-10-11 18:41:17 +02:00
int getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return 2 * int ( resultUV . x * $ { n [ 1 ] } . 0 ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` :n[1]===1? `
2020-10-11 18:41:17 +02:00
int getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return 2 * int ( resultUV . y * $ { n [ 0 ] } . 0 ) ;
2020-10-11 18:41:17 +02:00
}
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { n [ 0 ] } , $ { n [ 1 ] } ) ) ;
return 2 * ( resTexRC . x * $ { n [ 1 ] } + resTexRC . y ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function pK(e,t){return t[0]===1? `
2020-10-11 18:41:17 +02:00
int getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return int ( resultUV . x * $ { t [ 1 ] } . 0 ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` :t[1]===1? `
2020-10-11 18:41:17 +02:00
int getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return int ( resultUV . y * $ { t [ 0 ] } . 0 ) ;
2020-10-11 18:41:17 +02:00
}
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
return resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function lK(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),r=a*Math.ceil(e[1]/2);return `
2020-10-11 18:41:17 +02:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { n [ 0 ] } , $ { n [ 1 ] } ) ) ;
int index = resTexRC . x * $ { n [ 1 ] } + resTexRC . y ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int b = index / $ { r } ;
index -= b * $ { r } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int r = 2 * ( index / $ { a } ) ;
int c = imod ( index , $ { a } ) * 2 ;
2020-10-11 18:41:17 +02:00
return ivec3 ( b , r , c ) ;
}
2021-01-12 16:01:34 +01:00
` }function dK(e,t){let n=Zi(["r","c","d"],e);return `
2020-10-11 18:41:17 +02:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { n }
2020-10-11 18:41:17 +02:00
return ivec3 ( r , c , d ) ;
}
2021-01-12 16:01:34 +01:00
` }function uK(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),r=a*Math.ceil(e[e.length-2]/2),s=r,i="",o="b, r, c";for(let l=2;l<e.length-1;l++)s*=e[e.length-l-1],i= `
int b$ { l } = index / $ { s } ;
index -= b$ { l } * $ { s } ;
` +i,o= ` b$ { l } , ` +o;return `
ivec$ { e . length } getOutputCoords ( ) {
2020-10-11 18:41:17 +02:00
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { n [ 0 ] } , $ { n [ 1 ] } ) ) ;
int index = resTexRC . x * $ { n [ 1 ] } + resTexRC . y ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { i }
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int b = index / $ { r } ;
index -= b * $ { r } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int r = 2 * ( index / $ { a } ) ;
int c = imod ( index , $ { a } ) * 2 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
return ivec$ { e . length } ( $ { o } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function hK(e,t){let n=Zi(["r","c","d","d2"],e);return `
2020-10-11 18:41:17 +02:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { n }
2020-10-11 18:41:17 +02:00
return ivec4 ( r , c , d , d2 ) ;
}
2021-01-12 16:01:34 +01:00
` }function mK(e,t){let n=Zi(["r","c","d","d2","d3"],e);return `
2020-10-11 18:41:17 +02:00
ivec5 getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( $ { t [ 0 ] } ,
$ { t [ 1 ] } ) ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { n }
2020-10-11 18:41:17 +02:00
ivec5 outShape = ivec5 ( r , c , d , d2 , d3 ) ;
return outShape ;
}
2021-01-12 16:01:34 +01:00
` }function fK(e,t){let n=Zi(["r","c","d","d2","d3","d4"],e);return `
2020-10-11 18:41:17 +02:00
ivec6 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { n }
2020-10-11 18:41:17 +02:00
ivec6 result = ivec6 ( r , c , d , d2 , d3 , d4 ) ;
return result ;
}
2021-01-12 16:01:34 +01:00
` }function cK(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(k.arraysEqual(e,t))return `
2020-10-11 18:41:17 +02:00
ivec2 getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return 2 * ivec2 ( resultUV . yx * vec2 ( $ { n [ 0 ] } , $ { n [ 1 ] } ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let a=Math.ceil(e[1]/2);return `
2020-10-11 18:41:17 +02:00
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { n [ 0 ] } , $ { n [ 1 ] } ) ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int index = resTexRC . x * $ { n [ 1 ] } + resTexRC . y ;
int r = 2 * ( index / $ { a } ) ;
int c = imod ( index , $ { a } ) * 2 ;
2020-10-11 18:41:17 +02:00
return ivec2 ( r , c ) ;
}
2021-01-12 16:01:34 +01:00
` }function gK(e,t){return k.arraysEqual(e,t)? `
2020-10-11 18:41:17 +02:00
ivec2 getOutputCoords ( ) {
2021-01-12 16:01:34 +01:00
return ivec2 ( resultUV . yx * vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` :e[1]===1? `
2020-10-11 18:41:17 +02:00
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2020-10-11 18:41:17 +02:00
return ivec2 ( index , 0 ) ;
}
2021-01-12 16:01:34 +01:00
` :e[0]===1? `
2020-10-11 18:41:17 +02:00
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2020-10-11 18:41:17 +02:00
return ivec2 ( 0 , index ) ;
}
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
2021-01-12 16:01:34 +01:00
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
int r = index / $ { e [ 1 ] } ;
int c = index - r * $ { e [ 1 ] } ;
2020-10-11 18:41:17 +02:00
return ivec2 ( r , c ) ;
}
2021-01-12 16:01:34 +01:00
` }function Qi(e){return ` offset$ { e } ` }function eK(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),a=gn();return `
vec4 $ { n } ( ) {
return $ { a . texture2D } ( $ { t } , halfCR ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function q8(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return ` float $ { n } ( ) { return $ { t } ; } ` ;let[a,r]=e.shapeInfo.texShape;if(a===1&&r===1)return `
float $ { n } ( ) {
return sampleTexture ( $ { t } , halfCR ) ;
}
` ;let[s,i]=e.shapeInfo.texShape,o=Qi(t);return `
float $ { n } ( ) {
vec2 uv = uvFromFlat ( $ { s } , $ { i } , $ { o } ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function tK(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),a=e.shapeInfo.texShape,r=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=gn();return `
vec4 $ { n } ( int index ) {
2020-10-11 18:41:17 +02:00
vec2 uv = packedUVfrom1D (
2021-01-12 16:01:34 +01:00
$ { r [ 0 ] } , $ { r [ 1 ] } , index ) ;
return $ { s . texture2D } ( $ { t } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function K8(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return `
float $ { n } ( int index ) {
$ { wu ( e ) }
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let a=e.shapeInfo.texShape,r=a[0],s=a[1];if(s===1&&r===1)return `
float $ { n } ( int index ) {
return sampleTexture ( $ { t } , halfCR ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let i=Qi(t);return s===1? `
float $ { n } ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + $ { i } ) + 0.5 ) / $ { r } . 0 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` :r===1? `
float $ { n } ( int index ) {
vec2 uv = vec2 ( ( float ( index + $ { i } ) + 0.5 ) / $ { s } . 0 , 0.5 ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-10-11 18:41:17 +02:00
}
` : `
2021-01-12 16:01:34 +01:00
float $ { n } ( int index ) {
vec2 uv = uvFromFlat ( $ { r } , $ { s } , index + $ { i } ) ;
return sampleTexture ( $ { t } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function nK(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,s=r[0],i=r[1],o=gn();if(r!=null&&k.arraysEqual(t,r))return `
vec4 $ { a } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { i } . 0 , $ { s } . 0 ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
return $ { o . texture2D } ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let l=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],c=Math.ceil(t[1]/2);return `
vec4 $ { a } ( int row , int col ) {
vec2 uv = packedUVfrom2D ( $ { c } , $ { l [ 0 ] } , $ { l [ 1 ] } , row , col ) ;
return $ { o . texture2D } ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function X8(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape;if(r!=null&&k.arraysEqual(t,r)){let p=r[0],d=r[1];return `
float $ { a } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { d } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }let{newShape:s,keptDims:i}=k.squeezeShape(t),o=s;if(o.length<t.length){let p=ku(e,o),d=["row","col"];return `
$ { vu ( p ) }
float $ { a } ( int row , int col ) {
return $ { a } ( $ { Iu ( d , i ) } ) ;
}
` }if(e.shapeInfo.isUniform)return `
float $ { a } ( int row , int col ) {
int index = round ( dot ( vec2 ( row , col ) , vec2 ( $ { t [ 1 ] } , 1 ) ) ) ;
$ { wu ( e ) }
}
` ;let l=r[0],c=r[1],u=Qi(n);return c===1? `
float $ { a } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { u } ) , vec3 ( $ { t [ 1 ] } , 1 , 1 ) ) ;
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / $ { l } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` :l===1? `
float $ { a } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { u } ) , vec3 ( $ { t [ 1 ] } , 1 , 1 ) ) ;
vec2 uv = vec2 ( ( index + 0.5 ) / $ { c } . 0 , 0.5 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
` : `
2021-01-12 16:01:34 +01:00
float $ { a } ( int row , int col ) {
2020-10-11 18:41:17 +02:00
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { t [ 1 ] } + col + $ { u } ;
vec2 uv = uvFromFlat ( $ { l } , $ { c } , index ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function aK(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,s=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];if(t[0]===1){let p=t.slice(1),d=[1,2],h=ku(e,p),m=["b","row","col"];return `
$ { cS ( h ) }
vec4 $ { a } ( int b , int row , int col ) {
return $ { a } ( $ { Iu ( m , d ) } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }let i=s[0],o=s[1],l=Math.ceil(t[2]/2),c=l*Math.ceil(t[1]/2),u=gn();return `
vec4 $ { a } ( int b , int row , int col ) {
2020-10-11 18:41:17 +02:00
vec2 uv = packedUVfrom3D (
2021-01-12 16:01:34 +01:00
$ { i } , $ { o } , $ { c } , $ { l } , b , row , col ) ;
return $ { u . texture2D } ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function Y8(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[1]*t[2],s=t[2],{newShape:i,keptDims:o}=k.squeezeShape(t),l=i;if(l.length<t.length){let m=ku(e,l),f=["row","col","depth"];return `
$ { vu ( m ) }
float $ { a } ( int row , int col , int depth ) {
return $ { a } ( $ { Iu ( f , o ) } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }if(e.shapeInfo.isUniform)return `
float $ { a } ( int row , int col , int depth ) {
2020-10-11 18:41:17 +02:00
int index = round ( dot ( vec3 ( row , col , depth ) ,
2021-01-12 16:01:34 +01:00
vec3 ( $ { r } , $ { s } , 1 ) ) ) ;
$ { wu ( e ) }
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let c=e.shapeInfo.texShape,u=c[0],p=c[1],d=e.shapeInfo.flatOffset;if(p===r&&d==null)return `
float $ { a } ( int row , int col , int depth ) {
2020-10-11 18:41:17 +02:00
float texR = float ( row ) ;
2021-01-12 16:01:34 +01:00
float texC = dot ( vec2 ( col , depth ) , vec2 ( $ { s } , 1 ) ) ;
2020-10-11 18:41:17 +02:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { p } . 0 , $ { u } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;if(p===s&&d==null)return `
float $ { a } ( int row , int col , int depth ) {
float texR = dot ( vec2 ( row , col ) , vec2 ( $ { t [ 1 ] } , 1 ) ) ;
2020-10-11 18:41:17 +02:00
float texC = float ( depth ) ;
2021-01-12 16:01:34 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { p } . 0 , $ { u } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let h=Qi(n);return `
float $ { a } ( int row , int col , int depth ) {
2020-10-11 18:41:17 +02:00
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { r } + col * $ { s } + depth + $ { h } ;
vec2 uv = uvFromFlat ( $ { u } , $ { p } , index ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` }function rK(e){let t=e.shapeInfo.logicalShape,n=t.length,a=e.name,r="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],o=i[0],l=i[1],c=Math.ceil(t[n-1]/2),u=c*Math.ceil(t[n-2]/2),p="int b, int row, int col",d= ` b * $ { u } + ( row / 2 ) * $ { c } + ( col / 2 ) ` ;for(let m=2;m<n-1;m++)p= ` int b$ { m } , ` +p,u*=t[n-m-1],d= ` b$ { m } * $ { u } + ` +d;let h=gn();return `
vec4 $ { r } ( $ { p } ) {
int index = $ { d } ;
int texR = index / $ { l } ;
int texC = index - texR * $ { l } ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { l } , $ { o } ) ;
return $ { h . texture2D } ( $ { a } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function J8(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[3],s=t[2]*r,i=t[1]*s,{newShape:o,keptDims:l}=k.squeezeShape(t);if(o.length<t.length){let m=ku(e,o),f=["row","col","depth","depth2"];return `
$ { vu ( m ) }
float $ { a } ( int row , int col , int depth , int depth2 ) {
return $ { a } ( $ { Iu ( f , l ) } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }if(e.shapeInfo.isUniform)return `
float $ { a } ( int row , int col , int depth , int depth2 ) {
2020-10-11 18:41:17 +02:00
int index = round ( dot ( vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { i } , $ { s } , $ { r } , 1 ) ) ) ;
$ { wu ( e ) }
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let c=e.shapeInfo.flatOffset,u=e.shapeInfo.texShape,p=u[0],d=u[1];if(d===i&&c==null)return `
float $ { a } ( int row , int col , int depth , int depth2 ) {
2020-10-11 18:41:17 +02:00
float texR = float ( row ) ;
float texC =
dot ( vec3 ( col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec3 ( $ { s } , $ { r } , 1 ) ) ;
2020-10-11 18:41:17 +02:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { d } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;if(d===r&&c==null)return `
float $ { a } ( int row , int col , int depth , int depth2 ) {
2020-10-11 18:41:17 +02:00
float texR = dot ( vec3 ( row , col , depth ) ,
2021-01-12 16:01:34 +01:00
vec3 ( $ { t [ 1 ] * t [ 2 ] } , $ { t [ 2 ] } , 1 ) ) ;
2020-10-11 18:41:17 +02:00
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { d } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let h=Qi(n);return `
float $ { a } ( int row , int col , int depth , int depth2 ) {
2020-10-11 18:41:17 +02:00
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { i } + col * $ { s } +
depth * $ { r } + depth2 ;
vec2 uv = uvFromFlat ( $ { p } , $ { d } , index + $ { h } ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function Z8(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[4],s=t[3]*r,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:c}=k.squeezeShape(t);if(l.length<t.length){let f=ku(e,l),g=["row","col","depth","depth2","depth3"];return `
$ { vu ( f ) }
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
return $ { a } ( $ { Iu ( g , c ) } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }if(e.shapeInfo.isUniform)return `
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-10-11 18:41:17 +02:00
float index = dot (
vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { o } , $ { i } , $ { s } , $ { r } ) ) +
2020-10-11 18:41:17 +02:00
depth3 ;
2021-01-12 16:01:34 +01:00
$ { wu ( e ) }
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let u=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],h=p[1];if(h===o&&u==null)return `
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-10-11 18:41:17 +02:00
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { i } , $ { s } , $ { r } , 1 ) ) ;
2020-10-11 18:41:17 +02:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { h } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;if(h===r&&u==null)return `
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-10-11 18:41:17 +02:00
float texR = dot (
vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { t [ 1 ] * t [ 2 ] * t [ 3 ] } ,
$ { t [ 2 ] * t [ 3 ] } , $ { t [ 3 ] } , 1 ) ) ;
2020-10-11 18:41:17 +02:00
int texC = depth3 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { h } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let m=Qi(n);return `
float $ { a } ( int row , int col , int depth , int depth2 , int depth3 ) {
2020-10-11 18:41:17 +02:00
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { o } + col * $ { i } + depth * $ { s } +
depth2 * $ { r } + depth3 + $ { m } ;
vec2 uv = uvFromFlat ( $ { d } , $ { h } , index ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function Q8(e){let t=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:s}=k.squeezeShape(t);if(r.length<t.length){let g=ku(e,r),y=["row","col","depth","depth2","depth3","depth4"];return `
$ { vu ( g ) }
float $ { a } ( int row , int col , int depth ,
2020-10-11 18:41:17 +02:00
int depth2 , int depth3 , int depth4 ) {
2021-01-12 16:01:34 +01:00
return $ { a } ( $ { Iu ( y , s ) } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }let i=t[5],o=t[4]*i,l=t[3]*o,c=t[2]*l,u=t[1]*c;if(e.shapeInfo.isUniform)return `
float $ { a } ( int row , int col , int depth ,
2020-10-11 18:41:17 +02:00
int depth2 , int depth3 , int depth4 ) {
int index = round ( dot (
vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { u } , $ { c } , $ { l } , $ { o } ) ) +
2020-10-11 18:41:17 +02:00
dot (
vec2 ( depth3 , depth4 ) ,
2021-01-12 16:01:34 +01:00
vec2 ( $ { i } , 1 ) ) ) ;
$ { wu ( e ) }
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],m=d[1];if(m===u&&p==null)return `
float $ { a } ( int row , int col , int depth ,
2020-10-11 18:41:17 +02:00
int depth2 , int depth3 , int depth4 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { c } , $ { l } , $ { o } , $ { i } ) ) +
2020-10-11 18:41:17 +02:00
float ( depth4 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { m } . 0 , $ { h } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;if(m===i&&p==null)return `
float $ { a } ( int row , int col , int depth ,
2020-10-11 18:41:17 +02:00
int depth2 , int depth3 , int depth4 ) {
float texR = dot ( vec4 ( row , col , depth , depth2 ) ,
2021-01-12 16:01:34 +01:00
vec4 ( $ { t [ 1 ] * t [ 2 ] * t [ 3 ] * t [ 4 ] } ,
$ { t [ 2 ] * t [ 3 ] * t [ 4 ] } ,
$ { t [ 3 ] * t [ 4 ] } ,
$ { t [ 4 ] } ) ) + float ( depth3 ) ;
2020-10-11 18:41:17 +02:00
int texC = depth4 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { m } . 0 , $ { h } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;let f=Qi(n);return `
float $ { a } ( int row , int col , int depth ,
2020-10-11 18:41:17 +02:00
int depth2 , int depth3 , int depth4 ) {
// Explicitly use integer operations as dot() only works on floats.
2021-01-12 16:01:34 +01:00
int index = row * $ { u } + col * $ { c } + depth * $ { l } +
depth2 * $ { o } + depth3 * $ { i } + depth4 + $ { f } ;
vec2 uv = uvFromFlat ( $ { h } , $ { m } , index ) ;
return sampleTexture ( $ { n } , uv ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function wu(e){let t=e.name,n=k.sizeFromShape(e.shapeInfo.logicalShape);return n<2? ` return $ { t } ; ` : `
for ( int i = 0 ; i < $ { n } ; i ++ ) {
2020-10-11 18:41:17 +02:00
if ( i == index ) {
2021-01-12 16:01:34 +01:00
return $ { t } [ i ] ;
2020-10-11 18:41:17 +02:00
}
}
2021-01-12 16:01:34 +01:00
` }function sK(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=uS(e.shapeInfo.logicalShape,t.logicalShape),l=mt(i),c=i-s,u,p=["x","y","z","w","u","v"];s===0?u="":i<2&&o.length>=1?u="coords = 0;":u=o.map(g=> ` coords . $ { p [ g + c ] } = 0 ; ` ).join( `
` );let d="";i<2&&s>0?d="coords":d=e.shapeInfo.logicalShape.map((g,y)=> ` coords . $ { p [ y + c ] } ` ).join(", ");let h="return outputValue;",m=k.sizeFromShape(e.shapeInfo.logicalShape)===1,f=k.sizeFromShape(t.logicalShape)===1;if(s===1&&!m&&!f)h= `
2020-10-11 18:41:17 +02:00
return vec4 ( outputValue . xy , outputValue . xy ) ;
2021-01-12 16:01:34 +01:00
` ;else if(m&&!f)i===1?h= `
2020-10-11 18:41:17 +02:00
return vec4 ( outputValue . x , outputValue . x , 0. , 0. ) ;
2021-01-12 16:01:34 +01:00
` :h= `
2020-10-11 18:41:17 +02:00
return vec4 ( outputValue . x ) ;
2021-01-12 16:01:34 +01:00
` ;else if(o.length){let g=s-2,y=s-1;o.indexOf(g)>-1&&o.indexOf(y)>-1?h="return vec4(outputValue.x);":o.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(y)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return `
vec4 $ { r } ( ) {
$ { l } coords = getOutputCoords ( ) ;
$ { u }
vec4 outputValue = get$ { a } ( $ { d } ) ;
$ { h }
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }function iK(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&k.arraysEqual(i,s))return `
float $ { r } ( ) {
return sampleTexture ( $ { n } , resultUV ) ;
}
` ;let c=mt(l),u=uS(e.shapeInfo.logicalShape,t.logicalShape),p=l-o,d,h=["x","y","z","w","u","v"];o===0?d="":l<2&&u.length>=1?d="coords = 0;":d=u.map(f=> ` coords . $ { h [ f + p ] } = 0 ; ` ).join( `
` );let m="";return l<2&&o>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=> ` coords . $ { h [ g + p ] } ` ).join(", "), `
float $ { r } ( ) {
$ { c } coords = getOutputCoords ( ) ;
$ { d }
return get$ { a } ( $ { m } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +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 ku(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Iu(e,t){return t.map(n=>e[n]).join(", ")}function vK(e,t,n,a){let r=t.userCode,s=n.map((h,m)=>{let f={logicalShape:h.shape,texShape:h.isUniform?null:h.texData.texShape,isUniform:h.isUniform,isPacked:h.isUniform?!1:h.texData.isPacked,flatOffset:null};return h.texData!=null&&h.texData.slice!=null&&h.texData.slice.flatOffset>0&&(f.flatOffset=h.texData.slice.flatOffset),{name:t.variableNames[m],shapeInfo:f}}),i=s.map(h=>h.shapeInfo),o={logicalShape:a.shape,texShape:a.texData.texShape,isUniform:!1,isPacked:a.texData.isPacked,flatOffset:null},l=j8(s,o,r,t.packedInputs),c=e.createProgram(l),u=null,p=e.getUniformLocation(c,"NAN",!1);ee().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(c,"INFINITY",!1));let d={};for(let h=0;h<t.variableNames.length;h++){let m=t.variableNames[h],f=!1;d[m]=e.getUniformLocation(c,m,f),d[ ` offset$ { m } ` ]=e.getUniformLocation(c, ` offset$ { m } ` ,f)}return{program:t,source:l,webGLProgram:c,uniformLocations:d,inShapeInfos:i,outShapeInfo:o,infLoc:u,nanLoc:p}}function dS(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,a)=>{let r=n.logicalShape,s=t[a],i=s.shape;if(!k.arraysEqual(r,i))throw Error( ` Binary was compiled with different shapes than the current args . Shapes $ { r } and $ { i } must match ` );if(n.isUniform&&s.isUniform)return;let o=n.texShape,l=s.isUniform?null:s.texData.texShape;if(!k.arraysEqual(o,l))throw Error( ` Binary was compiled with different texture shapes than the current args . Shape $ { o } and $ { l } must match ` )})}function wK(e,t,n,a,r){dS(t.inShapeInfos,n),dS([t.outShapeInfo],[a]);let s=a.texData.texture,i=a.texData.texShape;a.texData.isPacked?e.setOutputPackedMatrixTexture(s,i[0],i[1]):e.setOutputMatrixTexture(s,i[0],i[1]),e.setProgram(t.webGLProgram),ee().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,Infinity),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((o,l)=>{let c=t.program.variableNames[l],u=t.uniformLocations[c],p=t.uniformLocations[ ` offset$ { c } ` ];if(u!=null){if(o.isUniform){if(k.sizeFromShape(o.shape)<2)e.gl.uniform1f(u,o.uniformValues[0]);else{let d=o.uniformValues;d instanceof Float32Array||(d=new Float32Array(d)),e.gl.uniform1fv(u,d)}return}o.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,o.texData.slice.flatOffset),e.setInputMatrixTexture(o.texData.texture,u,l)}}),r!=null&&r(e,t.webGLProgram),e.executeProgram()}function kK(e,t,n){let a="";t.concat(n).forEach(i=>{let o=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0,l=i.isUniform?"uniform":i.texData.texShape;a+= ` $ { i . shape } _$ { l } _$ { o } ` });let r=e.userCode,s=e.constructor.name;return s+="_"+a+"_"+r,s}var{addImpl:IK,bincountImpl:hS,bincountReduceImpl:NK,ceilImpl:TK,concatImpl:SK,expImpl:CK,expm1Impl:EK,floorImpl:_K,gatherV2Impl:FK,greaterImpl:AK,lessImpl: $ K,linSpaceImpl:DK,logImpl:MK,maxImpl:RK,maximumImpl:PK,minimumImpl:OK,multiplyImpl:LK,negImpl:zK,prodImpl:BK,rangeImpl:WK,rsqrtImpl:VK,simpleAbsImpl:mS,sliceImpl:UK,stridedSliceImpl:GK,subImpl:HK,tileImpl:jK,topKImpl:qK,transposeImpl:Xv,uniqueImpl:KK}=lT;function fS(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=> ` $ { e } . $ { n } ` )}function yn(e,t){return t===1?[e]:fS(e,t)}function XK(e,t){if(e===1)return"rc";let n="";for(let a=0;a<e;a++)n+=t[a],a<e-1&&(n+=",");return n}var QK=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;let t=e.length;if(t===0)this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
setOutput ( vec4 ( getA ( ) , 0. , 0. , 0. ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;else{let n=yn("rc",t),a=mt(t),r=YK(t,e,n),s=JK(t,e[e.length-1],e[e.length-2],n),i=ZK(e,n);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { a } rc = getOutputCoords ( ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( $ { r } ) {
2020-12-15 14:15:43 +01:00
setOutput ( vec4 ( 0 ) ) ;
} else {
2021-01-12 16:01:34 +01:00
$ { s }
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
setOutput ( vec4 ( $ { i } ) ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }}};function eX(e,t){let n=[];for(let a=0;a<=1;a++)for(let r=0;r<=1;r++){let s= ` $ { a === 0 ? "r" : "rp1" } , $ { r === 0 ? "c" : "cp1" } ` ;for(let i=2;i<e;i++)s= ` $ { t [ t . length - 1 - i ] } , ` +s;n.push(s)}return n}function YK(e,t,n){if(e===1)return ` rc > $ { t [ 0 ] } ` ;let a="";for(let r=e-2;r<e;r++)a+= ` $ { n [ r ] } >= $ { t [ r ] } ` ,r<e-1&&(a+="||");return a}function JK(e,t,n,a){if(e===1)return"";let r=a.slice(-2);return `
int r = $ { r [ 0 ] } ;
int c = $ { r [ 1 ] } ;
2020-12-15 14:15:43 +01:00
int rp1 = r + 1 ;
int cp1 = c + 1 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
bool cEdge = cp1 >= $ { t } ;
bool rEdge = rp1 >= $ { n } ;
` }function ZK(e,t){let n=e.length,a=eX(n,t);return n===1? ` getA ( rc ) ,
rc + 1 >= $ { e [ 0 ] } ? 0. : getA ( rc + 1 ) ,
0 , 0 ` : ` getA ( $ { a [ 0 ] } ) ,
cEdge ? 0. : getA ( $ { a [ 1 ] } ) ,
rEdge ? 0. : getA ( $ { a [ 2 ] } ) ,
rEdge || cEdge ? 0. : getA ( $ { a [ 3 ] } ) ` }var gS=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let n="";for(let a=0;a<4;a++){let r="thisRC = rc;";a%2==1&&(r+="thisRC.z += 1;"),a>1&&(r+="thisRC.y += 1;"),n+= `
$ { r }
$ { a > 0 ? "if(thisRC.y < rows && thisRC.z < cols){" : "" }
2020-12-15 14:15:43 +01:00
int flatIndex = getFlatIndex ( thisRC ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec3 inputRC = inputCoordsFromReshapedOutCoords ( flatIndex ) ;
vec2 inputRCInnerDims = vec2 ( float ( inputRC . y ) , float ( inputRC . z ) ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
result [ $ { a } ] =
2020-12-15 14:15:43 +01:00
getChannel ( getA ( inputRC . x , inputRC . y , inputRC . z ) , inputRCInnerDims ) ;
2021-01-12 16:01:34 +01:00
$ { a > 0 ? "}" : "" }
2020-12-15 14:15:43 +01:00
` }this.userCode= `
2021-01-12 16:01:34 +01:00
$ { tX ( t ) }
$ { Kv ( e ) }
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
ivec3 thisRC ;
2021-01-12 16:01:34 +01:00
int rows = $ { e [ 1 ] } ;
int cols = $ { e [ 2 ] } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
$ { n }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function tX(e){return `
2020-12-15 14:15:43 +01:00
ivec3 inputCoordsFromReshapedOutCoords ( int index ) {
2021-01-12 16:01:34 +01:00
$ { Zi ( [ "r" , "c" , "d" ] , e ) }
2020-12-15 14:15:43 +01:00
return ivec3 ( r , c , d ) ;
}
2021-01-12 16:01:34 +01:00
` }var nX=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 a=bS(t,n),r=xS(e,a,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=yS(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[r].shift();return this.usedTextures[r].push(o),o}let i;return a===sn.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===sn.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===sn.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===sn.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===sn.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,n,a){if(this.freeTextures==null)return;let r=bS(n,a),s=xS(t,r,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=yS(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=ee().get("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],c=l.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,1),this.log()}log(){if(!this.logEnabled)return;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)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function aX(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F||t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error( ` Unknown internal format $ { t } ` )}function yS(e,t,n,a,r){let s=rX(t,a),i;if(r){let[l,c]=yu(e[0],e[1]);i=l*c}else{let[l,c]=Ip(e[0],e[1]);i=l*c}let o=aX(n,s);return i*o}function rX(e,t){switch(e){case sn.PACKED_2X2_FLOAT32:return oS(t);case sn.PACKED_2X2_FLOAT16:return lS(t);case sn.UNPACKED_FLOAT32:return rS(t);case sn.UNPACKED_FLOAT16:return sS(t);case sn.PACKED_4X1_UNSIGNED_BYTE:return iS(t);default:throw new Error( ` Unknown physical texture type $ { e } ` )}}function sX(e){return ee().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?sn.PACKED_2X2_FLOAT32:sn.UNPACKED_FLOAT32:e?sn.PACKED_2X2_FLOAT16:sn.UNPACKED_FLOAT16}function bS(e,t){if(e===ra.UPLOAD)return sn.PACKED_2X2_FLOAT32;if(e===ra.RENDER||e==null)return sX(t);if(e===ra.DOWNLOAD||e===ra.PIXELS)return sn.PACKED_4X1_UNSIGNED_BYTE;throw new Error( ` Unknown logical texture type $ { e } ` )}function xS(e,t,n){return ` $ { e [ 0 ] } _$ { e [ 1 ] } _$ { t } _$ { n } ` }var ys=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
float unaryOperation ( float x ) {
2021-01-12 16:01:34 +01:00
$ { t }
2020-10-11 18:41:17 +02:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
float x = getAAtOutCoords ( ) ;
float y = unaryOperation ( x ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
setOutput ( y ) ;
}
2021-01-12 16:01:34 +01:00
` }},Oa="if (isnan(x)) return x;",iX="return x;",vS="return abs(x);",oX="return (x >= 0.0) ? x : (exp(x) - 1.0);",lX=Oa+ `
2020-12-15 14:15:43 +01:00
return ( x < 0.0 ) ? 0.0 : x ;
2021-01-12 16:01:34 +01:00
` ,uX=Oa+ `
2020-12-15 14:15:43 +01:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2021-01-12 16:01:34 +01:00
` ,rf="return x;",cX="return x;",pX= `
2020-12-15 14:15:43 +01:00
vec4 result ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,dX= `
2020-12-15 14:15:43 +01:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,hX= `
2020-12-15 14:15:43 +01:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,Nu=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
vec4 unaryOperation ( vec4 x ) {
2021-01-12 16:01:34 +01:00
$ { t }
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
vec4 x = getAAtOutCoords ( ) ;
vec4 y = unaryOperation ( x ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
setOutput ( y ) ;
}
2021-01-12 16:01:34 +01:00
` }},mX=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=yn("rc",t),a=mt(t),r=XK(t,n),s=n.slice(-2),i=t<=1?"rc": ` vec2 ( $ { s . join ( "," ) } ) ` ;this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { a } rc = getOutputCoords ( ) ;
vec4 packedInput = getA ( $ { r } ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
setOutput ( getChannel ( packedInput , $ { i } ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},fX=Qa.whereImpl,gX=1e-7,yX=1e-4,Yv={};function bX(e){return e in Yv||(Yv[e]={}),Yv[e]}var xX=128,vX=600;function wX(){return ee().global.screen==null?1024:ee().global.screen.height*ee().global.screen.width*window.devicePixelRatio*vX/1024/1024}var IX=class extends uc{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!ee().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=ir(ee().getNumber("WEBGL_VERSION"));this.binaryCache=bX(ee().getNumber("WEBGL_VERSION")),this.gpgpu=new O8(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new nX(this.gpgpu),this.numMBBeforeWarning=wX(),this.texData=new Md(this,ns())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((ee().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||ee().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 a={};return this.texData.set(a,{shape:t,dtype:n,values:e,usage:ra.UPLOAD,refCount:1,complexParentRefCount:0}),a}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,a){if(ee().getBool("DEBUG")&&this.checkNumericalProblems(t),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:a,values:t,usage:ra.UPLOAD,refCount:1,complexParentRefCount:0})}disposeIntermediateTensorInfo(e){let t=e.dataId;if(this.texData.has(t)){let n=this.texData.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}readSync(e){let t=this.texData.get(e),{values:n,dtype:a,complexTensorInfos:r,slice:s,shape:i,isPacked:o}=t;if(s!=null){let p;o?p=new Nu(i,rf):p=new ys(i,rf);let d=this.runWebGLProgram(p,[{dataId:e,shape:i,dtype:a}],a),h=this.readSync(d.dataId);return this.disposeIntermediateTensorInfo(d),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return n;let l=this.activeTimers!=null,c;l&&(c=k.now());let u;if(a==="complex64"){let p=this.readSync(r.real.dataId),d=this.readSync(r.imag.dataId);u=_.mergeRealAndImagArrays(p,d)}else u=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=k.now()-c),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(m=>h.push(m))}let t=this.texData.get(e),{values:n,shape:a,slice:r,dtype:s,complexTensorInfos:i,isPacked:o}=t;if(r!=null){let h;o?h=new Nu(a,rf):h=new ys(a,rf);let m=this.runWebGLProgram(h,[{dataId:e,shape:a,dtype:s}],s),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(n!=null)return this.convertAndCacheOnCPU(e);if(!ee().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&ee().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(s!=="complex64"&&ee().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let h=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(h.texture,...Np(a))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(s==="complex64"){let h=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),m=h[0],f=h[1];u=_.mergeRealAndImagArrays(m,f)}else if(l==null)u=this.getValuesFromTexture(e);else{let h=k.sizeFromShape(a);u=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}c!=null&&this.disposeIntermediateTensorInfo(c);let p=this.convertAndCacheOnCPU(e,u),d=this.pendingRead.get(e);return this.pendingRead.delete(e),d.forEach(h=>h(p)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),p}bufferSync(
2020-10-11 18:41:17 +02:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2021-01-12 16:01:34 +01:00
` ,Tu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode= `
2020-10-11 18:41:17 +02:00
float binaryOperation ( float a , float b ) {
2021-01-12 16:01:34 +01:00
$ { e }
2020-10-11 18:41:17 +02:00
}
void main ( ) {
float a = getAAtOutCoords ( ) ;
float b = getBAtOutCoords ( ) ;
setOutput ( binaryOperation ( a , b ) ) ;
}
2021-01-12 16:01:34 +01:00
` }},sf= `
2020-10-11 18:41:17 +02:00
result . r = isNaN . r > 0. ? NAN : result . r ;
result . g = isNaN . g > 0. ? NAN : result . g ;
result . b = isNaN . b > 0. ? NAN : result . b ;
result . a = isNaN . a > 0. ? NAN : result . a ;
2021-01-12 16:01:34 +01:00
` ,Cp=class{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length,s="";if(a)if(r===0||k.sizeFromShape(this.outputShape)===1)s= `
2020-10-11 18:41:17 +02:00
result . y = 0. ;
result . z = 0. ;
result . w = 0. ;
2021-01-12 16:01:34 +01:00
` ;else if(s= `
$ { mt ( r ) } coords = getOutputCoords ( ) ;
` ,r===1)s+= `
2020-10-11 18:41:17 +02:00
result . y = ( coords + 1 ) >= $ { this . outputShape [ 0 ] } ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
2021-01-12 16:01:34 +01:00
` ;else{let i=yn("coords",r);s+= `
2020-10-11 18:41:17 +02:00
bool nextRowOutOfBounds =
2021-01-12 16:01:34 +01:00
( $ { i [ r - 2 ] } + 1 ) >= $ { this . outputShape [ r - 2 ] } ;
2020-10-11 18:41:17 +02:00
bool nextColOutOfBounds =
2021-01-12 16:01:34 +01:00
( $ { i [ r - 1 ] } + 1 ) >= $ { this . outputShape [ r - 1 ] } ;
2020-10-11 18:41:17 +02:00
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
2021-01-03 17:05:09 +01:00
` }this.userCode= `
2020-10-11 18:41:17 +02:00
vec4 binaryOperation ( vec4 a , vec4 b ) {
2021-01-12 16:01:34 +01:00
$ { e }
2020-10-11 18:41:17 +02:00
}
void main ( ) {
vec4 a = getAAtOutCoords ( ) ;
vec4 b = getBAtOutCoords ( ) ;
vec4 result = binaryOperation ( a , b ) ;
2021-01-12 16:01:34 +01:00
$ { s }
2020-10-11 18:41:17 +02:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function Wn(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var TX={kernelName:il,backendName:"webgl",kernelFunc:Wn};function bs(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.makeTensorInfo(a.shape,"complex64"),i=n.texData.get(s.dataId),o=Wn({inputs:{x:a},backend:n}),l=n.texData.get(o.dataId);l.complexParentRefCount++;let c=Wn({inputs:{x:r},backend:n}),u=n.texData.get(c.dataId);return u.complexParentRefCount++,i.complexTensorInfos={real:o,imag:c},s}var SX={kernelName:Ud,backendName:"webgl",kernelFunc:bs},kS="return (a < 0.) ? b * a : a;",IS= `
2020-12-15 14:15:43 +01:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2021-01-12 16:01:34 +01:00
` ;function CX(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a,i=n.makeTensorInfo([],"float32",k.createScalarValue(s,"float32")),o=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Cp(IS,r.shape,i.shape):new Tu(kS,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],r.dtype);return n.disposeIntermediateTensorInfo(i),l}var EX={kernelName:Js,backendName:"webgl",kernelFunc:CX},NS="return (a < 0.) ? b * a : a;",TS= `
2020-12-15 14:15:43 +01:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2021-01-12 16:01:34 +01:00
` ;function _X(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Cp(TS,a.shape,r.shape):new Tu(NS,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)}var FX={kernelName:ui,backendName:"webgl",kernelFunc:_X},SS="if (isnan(x)) return x;",AX= `
2020-12-15 14:15:43 +01:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2021-01-12 16:01:34 +01:00
` , $ X= `
2020-12-15 14:15:43 +01:00
result . r = isNaN . r > 0. ? NAN : result . r ;
result . g = isNaN . g > 0. ? NAN : result . g ;
result . b = isNaN . b > 0. ? NAN : result . b ;
result . a = isNaN . a > 0. ? NAN : result . a ;
2021-01-12 16:01:34 +01:00
` ;function Ye({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:a}){return({inputs:r,backend:s})=>{let{x:i}=r,o=s,l=a||i.dtype;if(o.shouldExecuteOnCPU([i])&&n!=null){let p=o.texData.get(i.dataId),d=n(p.values,l);return o.makeTensorInfo(i.shape,l,d)}let c=ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return c?u=new Nu(i.shape,t):u=new ys(i.shape,e),o.runWebGLProgram(u,[i],l)}}function on({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:a=!1,cpuKernelImpl:r,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:c}=i,u=o;if(a&&l.dtype==="complex64"){let m=u.texData.get(l.dataId),f=u.texData.get(c.dataId),[g,y]=[[m.complexTensorInfos.real,f.complexTensorInfos.real],[m.complexTensorInfos.imag,f.complexTensorInfos.imag]].map(x=>{let[v,N]=x,T={dataId:v.dataId,dtype:v.dtype,shape:l.shape},E={dataId:N.dataId,dtype:N.dtype,shape:c.shape},A=new Tu(e,l.shape,c.shape);return u.runWebGLProgram(A,[T,E],pa(v.dtype,N.dtype))}),b=bs({inputs:{real:g,imag:y},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(y),b}let p=s||pa(l.dtype,c.dtype);if(u.shouldExecuteOnCPU([l,c])&&r!=null){let m=u.texData.get(l.dataId),f=u.texData.get(c.dataId),[g,y]=r(l.shape,c.shape,m.values,f.values,p),b=u.makeTensorInfo(y,p),x=u.texData.get(b.dataId);return x.values=g,b}let d=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return d?h=new Cp(t,l.shape,c.shape,n):h=new Tu(e,l.shape,c.shape),u.runWebGLProgram(h,[l,c],p)}}function of(e,t=!1){if(e==="linear")return t?cX:iX;if(e==="relu")return t?dX:lX;if(e==="elu")return t?pX:oX;if(e==="relu6")return t?hX:uX;if(e==="prelu")return t?TS:NS;if(e==="leakyrelu")return t?IS:kS;throw new Error( ` Activation $ { e } has not been implemented for the WebGL backend . ` )}var CS=class{constructor(e,t,n,a=!1,r=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;let c=a?e[1]:e[2],u=Math.ceil(c/2),p=a?"i * 2, rc.y":"rc.y, i * 2",d=r?"rc.z, i * 2":"i * 2, rc.z",h=a?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",g="";i&&(o?f= ` vec4 activation ( vec4 a ) {
2020-12-15 14:15:43 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { i }
} ` :l?f= ` vec4 activation ( vec4 a ) {
2020-12-15 14:15:43 +01:00
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { i }
} ` :f= ` vec4 activation ( vec4 x ) {
$ { i }
} ` ,g="result = activation(result);");let y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b= ` int ( min ( float ( rc . x ) , $ { e [ 0 ] - 1 } . ) ) ` :t[0]<e[0]&&(x= ` int ( min ( float ( rc . x ) , $ { t [ 0 ] - 1 } . ) ) ` ),this.userCode= `
$ { f }
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
const float sharedDimension = $ { u } . 0 ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec4 dot2x2ARowBCol ( ivec3 rc ) {
vec4 result = vec4 ( 0 ) ;
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { u } ; i ++ ) {
int batchA = $ { b } ;
int batchB = $ { x } ;
vec4 a = getMatrixA ( batchA , $ { p } ) ;
vec4 b = getMatrixB ( batchB , $ { d } ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
2021-01-12 16:01:34 +01:00
result += ( $ { h [ 0 ] } * $ { m [ 0 ] } ) ;
result += ( $ { h [ 1 ] } * $ { m [ 1 ] } ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
return result ;
2020-10-11 18:41:17 +02:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec3 rc = getOutputCoords ( ) ;
vec4 result = dot2x2ARowBCol ( rc ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { y }
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { g }
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }},ES={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},_S=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode= `
2020-12-15 14:15:43 +01:00
float binaryOpComplex (
float areal , float aimag , float breal , float bimag ) {
2021-01-12 16:01:34 +01:00
$ { e }
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
float areal = getARealAtOutCoords ( ) ;
float aimag = getAImagAtOutCoords ( ) ;
float breal = getBRealAtOutCoords ( ) ;
float bimag = getBImagAtOutCoords ( ) ;
setOutput ( binaryOpComplex ( areal , aimag , breal , bimag ) ) ;
}
2021-01-12 16:01:34 +01:00
` }},FS="return a * b;";function AS(e){let{inputs:t,backend:n}=e,{a,b:r}=t,s=_.upcastType(a.dtype,r.dtype);if(a.dtype==="complex64"){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),c=new _S(ES.REAL,a.shape,r.shape),u=new _S(ES.IMAG,a.shape,r.shape),p=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:a.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:a.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:r.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:r.shape}],d=n.runWebGLProgram(c,p,"float32"),h=n.runWebGLProgram(u,p,"float32"),m=bs({inputs:{real:d,imag:h},backend:n});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),m}if(n.shouldExecuteOnCPU([a,r])){let o=n.texData.get(a.dataId),l=n.texData.get(r.dataId),[c,u]=LK(a.shape,r.shape,o.values,l.values,s),p=n.makeTensorInfo(u,s),d=n.texData.get(p.dataId);return d.values=c,p}let i;return ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new Cp(FS,a.shape,r.shape):i=new Tu(FS,a.shape,r.shape),n.runWebGLProgram(i,[a,r],s)}var DX={kernelName:si,backendName:"webgl",kernelFunc:AS};function MX(e,t,n){let a=[bu(e.shape),...xu(e.shape)],r={dtype:e.dtype,shape:a,dataId:e.dataId},s=[bu(t),...xu(t)],i=new gS(s,a),o=!0,l=n.runWebGLProgram(i,[r],e.dtype,null,o);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function xe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=n,o=k.sizeFromShape(r.shape),l=k.inferFromImplicitShape(s,o),c=k.sizeFromShape(l);k.assert(o===c,()=> ` The new shape ( $ { l } ) has $ { c } elements and the old shape ( $ { r . shape } ) has $ { o } elements . The new shape and old shape must have the same number of elements . ` );let u=i.texData.get(r.dataId);return u.isPacked&&!af(r.shape,l)&&!(u.texture!==null&&af(u.shape,l))?MX(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var RX={kernelName:Nl,backendName:"webgl",kernelFunc:xe}, $ S=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i=Math.floor(n/4)*4,o=n%4,l="sumValue += dot(values, ones);";if(t!=null){let u=1/t;l= ` sumValue += dot ( values * $ { k . isInt ( u ) ? u . toPrecision ( 2 ) : u } , ones ) ; ` }let c="";r%n>0&&(c= `
if ( inIdx < 0 || inIdx >= $ { r } ) {
2020-12-15 14:15:43 +01:00
return 0.0 ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
` ),this.userCode= `
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
2021-01-12 16:01:34 +01:00
$ { c }
2020-12-15 14:15:43 +01:00
return getX ( batch , inIdx ) ;
2020-10-11 18:41:17 +02:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 coords = getOutputCoords ( ) ;
2020-10-11 18:41:17 +02:00
int batch = coords [ 0 ] ;
2020-12-15 14:15:43 +01:00
int outIdx = coords [ 1 ] ;
2021-01-12 16:01:34 +01:00
int inOffset = outIdx * $ { n } ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float sumValue = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { i } ; i += 4 ) {
2020-12-15 14:15:43 +01:00
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { l }
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int inIdx = inOffset + $ { i } ;
if ( $ { o === 1 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 ( getValue ( batch , inIdx ) , 0.0 , 0.0 , 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { l }
} else if ( $ { o === 2 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) , 0.0 , 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { l }
} else if ( $ { o === 3 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) , 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { l }
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
setOutput ( sumValue ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},PX=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="max");let l= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let c=Math.floor(n/4)*4,u=n%4,p= `
if ( $ { t === "sum" } ) {
2020-12-15 14:15:43 +01:00
sumValue += dot ( values , ones ) ;
2021-01-12 16:01:34 +01:00
} else if ( $ { t === "prod" } ) {
2020-12-15 14:15:43 +01:00
vec2 tmp = vec2 ( values [ 0 ] , values [ 1 ] ) * vec2 ( values [ 2 ] , values [ 3 ] ) ;
prodValue *= tmp [ 0 ] * tmp [ 1 ] ;
} else {
2021-01-12 16:01:34 +01:00
minMaxValue = $ { o } ( values , minMaxValue ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ,d="vec4";t==="all"?(i="1.0",p= `
2020-12-15 14:15:43 +01:00
bool reducedAllValue = all ( values ) ;
float floatedReducedAllValue = float ( reducedAllValue ) ;
allValue = float ( allValue >= 1.0 && floatedReducedAllValue >= 1.0 ) ;
2021-01-12 16:01:34 +01:00
` ,d="bvec4"):t==="any"&&(i="0.0",p= `
2020-12-15 14:15:43 +01:00
bool reducedAnyValue = any ( values ) ;
float floatedReducedAnyValue = float ( reducedAnyValue ) ;
anyValue = float ( anyValue >= 1.0 || floatedReducedAnyValue >= 1.0 ) ;
2021-01-12 16:01:34 +01:00
` ,d="bvec4");let h="";r%n>0&&(h= `
if ( inIdx < 0 || inIdx >= $ { r } ) {
2020-12-15 14:15:43 +01:00
return initializationValue ;
}
` ),this.userCode= `
2021-01-12 16:01:34 +01:00
const float initializationValue = $ { i } ;
2020-12-15 14:15:43 +01:00
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float getValue ( int batch , int inIdx ) {
2021-01-12 16:01:34 +01:00
$ { h }
2020-12-15 14:15:43 +01:00
return getX ( batch , inIdx ) ;
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
2021-01-12 16:01:34 +01:00
int inOffset = outIdx * $ { n } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
vec4 minMaxValue = vec4 ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
float prodValue = 1.0 ;
float sumValue = 0.0 ;
float allValue = 1.0 ;
float anyValue = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { c } ; i += 4 ) {
2020-12-15 14:15:43 +01:00
int inIdx = inOffset + i ;
2021-01-12 16:01:34 +01:00
$ { d } values = $ { d } (
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { p }
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int inIdx = inOffset + $ { c } ;
if ( $ { u === 1 } ) {
$ { d } values = $ { d } (
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { p }
} else if ( $ { u === 2 } ) {
$ { d } values = $ { d } (
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { p }
} else if ( $ { u === 3 } ) {
$ { d } values = $ { d } (
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { p }
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
setOutput ( $ { l } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function OX(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],a=_.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}function eo(e,t,n,a){let r=OX(e.shape),s=e;for(let i=0;i<r.length;i++){let{inSize:o,windowSize:l,outSize:c}=r[i],u,p;n==="mean"?u=i===0?new $ S({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c},o):new $ S({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c}):u=new PX({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:c},n),p=s,s=a.runWebGLProgram(u,[s],t),p.dataId!==e.dataId&&a.disposeIntermediateTensorInfo(p)}return s}var zX=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.rank=n.length;let a=mt(this.rank),r=LX(t);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { a } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { r } ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function LX(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"],a=new Array(t);for(let r=0;r<e.length;r++)a[e[r]]=n[r];return a.join()}var BX=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let c=0;c<n.length;c++)n[c]=e[t[c]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error( ` Packed transpose for rank $ { this . rank } is not yet supported . ` );let a=mt(this.rank),r=fS("rc",this.rank),s=new Array(this.rank);for(let c=0;c<t.length;c++)s[t[c]]=r[c];let i= ` vec2 ( $ { s . slice ( - 2 ) . join ( ) } ) ` ,o= ` ++ $ { r [ this . rank - 1 ] } < $ { n [ this . rank - 1 ] } ` ,l= ` getChannel ( getA ( $ { s . join ( ) } ) , $ { i } ) ` ;this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { a } rc = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
result [ 0 ] = $ { l } ;
if ( $ { o } ) {
result [ 1 ] = $ { l } ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
-- $ { r [ this . rank - 1 ] } ;
if ( ++ $ { r [ this . rank - 2 ] } < $ { n [ this . rank - 2 ] } ) {
result [ 2 ] = $ { l } ;
if ( $ { o } ) {
result [ 3 ] = $ { l } ;
2020-12-15 14:15:43 +01:00
}
}
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function lf(e,t,n){let a=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new BX(e.shape,t):new zX(e.shape,t);return n.runWebGLProgram(a,[e],e.dtype)}function WX(e,t,n,a){let r=t,s=e.shape.length,i=k.parseAxisParam(r,e.shape),o=i,l=_.getAxesPermutation(o,s),c=l!=null,u=e;c&&(u=lf(e,l,a),o=_.getInnerMostAxes(o.length,s)),_.assertAxesAreInnerMostDims("sum",o,s);let[p,d]=_.computeOutAndReduceShapes(u.shape,o),h=p;n&&(h=_.expandShapeToKeepDim(p,i));let m=k.sizeFromShape(d),f=k.sizeFromShape(e.shape)/m,g=xe({inputs:{x:u},attrs:{shape:[f,m]},backend:a}),y=xh(e.dtype),b=eo(g,y,"sum",a),x=xe({inputs:{x:b},attrs:{shape:h},backend:a});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(b),c&&a.disposeIntermediateTensorInfo(u),x}function Jv(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;return WX(r,s,i,n)}var VX={kernelName:xi,backendName:"webgl",kernelFunc:Jv};function En(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{perm:s}=a,i=n,o=r.shape.length,l=new Array(o);for(let u=0;u<l.length;u++)l[u]=r.shape[s[u]];let c;if(i.shouldExecuteOnCPU([r])){let u=i.texData.get(r.dataId).values,p=Xv(u,r.shape,r.dtype,s,l);c=i.makeTensorInfo(l,r.dtype);let d=i.texData.get(c.dataId);d.values=p}else c=lf(r,s,i);return c}var UX={kernelName:Ni,backendName:"webgl",kernelFunc:En},DS=1e3;function uf({a:e,b:t,transposeA:n,transposeB:a,backend:r,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let c=e.shape.length,u=t.shape.length,p=n?e.shape[c-2]:e.shape[c-1],d=a?t.shape[u-1]:t.shape[u-2],h=n?e.shape[c-1]:e.shape[c-2],m=a?t.shape[u-2]:t.shape[u-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=k.sizeFromShape(f),b=k.sizeFromShape(g),x=y===b||y===1||b===1;k.assert(c>=2&&u>=2&&x,()=> ` Error in matMul : the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of ( $ { f } ) and ( $ { g } ) . ` );let v=(y>b?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,m]);k.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 = $ { a } must match . ` );let N=n?[y,p,h]:[y,h,p],T=a?[b,m,d]:[b,d,m],E=xe({inputs:{x:e},backend:r,attrs:{shape:N}}),A=xe({inputs:{x:t},backend:r,attrs:{shape:T}}), $ =[E,A],O=Math.max(y,b),V=n?E.shape[1]:E.shape[2],W=s!=null,H=i!=null,X=l==="leakyrelu",q=l!=null?of(l,!0):null,K=W||H||X||q!=null,J;if((h===1||m===1)&&V>DS&&K===!1){let Q=E,ie=A;n&&(Q=En({inputs:{x:E},backend:r,attrs:{perm:[0,2,1]}}), $ .push(Q)),a&&(ie=En({inputs:{x:A},backend:r,attrs:{perm:[0,2,1]}}), $ .push(ie));let re=m!==1,ae=m===1,oe=Q;re&&(oe=xe({inputs:{x:Q},backend:r,attrs:{shape:[O,V,1]}}), $ .push(oe));let he=m===1?2:1,ce=ie;ae&&(ce=xe({inputs:{x:ie},backend:r,attrs:{shape:[O,1,V]}}), $ .push(ce));let ge=AS({inputs:{a:oe,b:ce},backend:r});J=Jv({inputs:{x:ge},backend:r,attrs:{axis:he,keepDims:!0}}), $ .push(ge)}else{let Q=pa(e.dtype,t.dtype),ie=new CS(N,T,[O,h,m],n,a,W,q,H,X),re=[E,A];if(s!=null&&re.push(s),H&&re.push(i),X){let ae=r.makeTensorInfo([],"float32",k.createScalarValue(o,"float32"));re.push(ae), $ .push(ae)}J=r.runWebGLProgram(ie,re,Q)}let te=xe({inputs:{x:J},backend:r,attrs:{shape:v}}); $ .push(J);for(let Q of $ )r.disposeIntermediateTensorInfo(Q);return te}function GX(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:p}=a;return uf({a:r,b:s,transposeA:l,transposeB:c,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:p,activation:u})}var HX={kernelName:Ti,backendName:"webgl",kernelFunc:GX},MS="return abs(x);";function jX(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])&&a.dtype!=="complex64"){let s=n.texData.get(a.dataId),i=mS(s.values);return n.makeTensorInfo(a.shape,a.dtype,i)}let r;return ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Nu(a.shape,MS):r=new ys(a.shape,MS),n.runWebGLProgram(r,[a],a.dtype)}var qX={kernelName:Lo,backendName:"webgl",kernelFunc:jX},KX=Oa+ `
2020-12-15 14:15:43 +01:00
if ( abs ( x ) > 1. ) {
return NAN ;
}
return acos ( x ) ;
2021-01-12 16:01:34 +01:00
` ,XX=Ye({opSnippet:KX}),YX={kernelName:zo,backendName:"webgl",kernelFunc:XX},JX=Oa+ `
2020-12-15 14:15:43 +01:00
if ( x < 1.0 ) return NAN ;
2021-01-12 16:01:34 +01:00
return log ( x + sqrt ( x * x - 1.0 ) ) ; ` ,ZX=Ye({opSnippet:JX}),QX={kernelName:Bo,backendName:"webgl",kernelFunc:ZX},RS="return a + b;",eY=on({opSnippet:RS,packedOpSnippet:RS,supportsComplex:!0,cpuKernelImpl:IK}),tY={kernelName:qr,backendName:"webgl",kernelFunc:eY},nY=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((r,s)=> ` T$ { s } ` );let n=[];this.variableNames.forEach(r=>{n.push( ` float v$ { r } = get$ { r } AtOutCoords ( ) ; ` )});let a=this.variableNames.map(r=> ` v$ { r } ` ).join(" + ");this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { n . join ( `
2020-12-15 14:15:43 +01:00
` )}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
float result = $ { a } ;
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }},aY=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((r,s)=> ` T$ { s } ` );let n=[];this.variableNames.forEach(r=>{n.push( ` vec4 v$ { r } = get$ { r } AtOutCoords ( ) ; ` )});let a=this.variableNames.map(r=> ` v$ { r } ` ).join(" + ");this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { n . join ( `
2020-12-15 14:15:43 +01:00
` )}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
vec4 result = $ { a } ;
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function cf(e){let{inputs:t,backend:n}=e,a=t;if(a.length===1)return Wn({inputs:{x:a[0]},backend:n});if(a.length>ee().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=cf({inputs:a.slice(0,o),backend:n}),c=cf({inputs:a.slice(o),backend:n});return cf({inputs:[l,c],backend:n})}let r=a.map(o=>o.dtype).reduce((o,l)=>pa(o,l)),s=a.map(o=>o.shape),i=ee().getBool("WEBGL_PACK")?new aY(a[0].shape,s):new nY(a[0].shape,s);return n.runWebGLProgram(i,a,r)}var rY={kernelName:Rs,backendName:"webgl",kernelFunc:cf};function sY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=k.parseAxisParam(s,r.shape),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=En({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,o)),_.assertAxesAreInnerMostDims("all",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=xe({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=eo(f,f.dtype,"all",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=xe({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=xe({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var iY={kernelName:Ld,backendName:"webgl",kernelFunc:sY};function oY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=k.parseAxisParam(s,r.shape),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=En({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,o)),_.assertAxesAreInnerMostDims("any",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=xe({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=eo(f,f.dtype,"any",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=xe({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=xe({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var lY={kernelName:zd,backendName:"webgl",kernelFunc:oY},uY=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:a,batchSize:r,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,s];let i=t==="max"?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
2021-01-12 16:01:34 +01:00
int inOffset = outIdx * $ { a } ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
int bestIndex = inOffset ;
float bestValue = getA ( batch , bestIndex ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { a } ; i ++ ) {
int inIdx = $ { o } ;
2020-12-15 14:15:43 +01:00
float candidate = getA ( batch , inIdx ) ;
2021-01-12 16:01:34 +01:00
if ( candidate $ { i } bestValue ) {
2020-12-15 14:15:43 +01:00
bestValue = candidate ;
bestIndex = inIdx ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
}
setOutput ( float ( bestIndex ) ) ;
}
2021-01-12 16:01:34 +01:00
` }},cY=class{constructor(e,t,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k.assert(e.length>2,()=> ` Packed arg$ { n . charAt ( 0 ) . toUpperCase ( ) + n . slice ( 1 ) } supports only inputs with rank above 2. ` );let r=e[e.length-1],s=Math.ceil(r/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),a||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=mt(o),c=yn("coords",o),u,p;if(s===1){p=o+1;let E=mt(p);u= `
$ { E } sourceLocR = $ { E } ( $ { c . join ( ) } , 0 ) ;
++ $ { c [ o - 1 ] } ;
$ { E } sourceLocG = $ { E } ( $ { c . join ( ) } , 0 ) ;
++ $ { c [ o - 2 ] } ;
$ { E } sourceLocA = $ { E } ( $ { c . join ( ) } , 0 ) ;
-- $ { c [ o - 1 ] } ;
$ { E } sourceLocB = $ { E } ( $ { c . join ( ) } , 0 ) ;
-- $ { c [ o - 2 ] } ; ` }else p=o,u= `
$ { l } sourceLocR = coords ;
++ $ { c [ o - 1 ] } ;
$ { l } sourceLocG = coords ;
++ $ { c [ o - 2 ] } ;
$ { l } sourceLocA = coords ;
-- $ { c [ o - 1 ] } ;
$ { l } sourceLocB = coords ;
-- $ { c [ o - 2 ] } ; ` ;let d=["x","y","z","w","u","v"].slice(0,p),h="."+d[p-1],m=d.map(E=>"int "+E),f=yn("sourceLocR",p-1).concat("inIdx.r"),g=yn("sourceLocG",p-1).concat("inIdx.g"),y=yn("sourceLocB",p-1).concat("inIdx.b"),b=yn("sourceLocA",p-1).concat("inIdx.a"),x=n==="max"?"greaterThan":"lessThan",v=a?"": `
inIdx = round ( vec4 ( getBestIndicesAChannel ( $ { f . join ( ) } ) ,
getBestIndicesAChannel ( $ { g . join ( ) } ) ,
getBestIndicesAChannel ( $ { y . join ( ) } ) ,
getBestIndicesAChannel ( $ { b . join ( ) } ) ) ) ; ` ,N= ` vec4 (
getAChannel ( $ { f . join ( ) } ) ,
hasNextCol ? getAChannel ( $ { g . join ( ) } ) : 0. ,
hasNextRow ? getAChannel ( $ { y . join ( ) } ) : 0. ,
hasNextRow && hasNextCol ? getAChannel ( $ { b . join ( ) } ) : 0. ) ` ,T=a?"": `
float getBestIndicesAChannel ( $ { m . join ( ) } ) {
return getChannel ( getBestIndicesA ( $ { d . join ( ) } ) ,
vec2 ( $ { d . slice ( - 2 ) . join ( ) } ) ) ;
2020-12-15 14:15:43 +01:00
} ` ;this.userCode= `
2021-01-12 16:01:34 +01:00
float getAChannel ( $ { m . join ( ) } ) {
return getChannel ( getA ( $ { d . join ( ) } ) ,
vec2 ( $ { d . slice ( - 2 ) . join ( ) } ) ) ;
}
$ { T }
void main ( ) {
$ { l } coords = getOutputCoords ( ) ;
bool hasNextCol = $ { c [ o - 1 ] } < $ { i [ o - 1 ] - 1 } ;
bool hasNextRow = $ { c [ o - 2 ] } < $ { i [ o - 2 ] - 1 } ;
$ { u }
ivec4 srcIdx = ivec4 ( sourceLocR$ { h } , sourceLocG$ { h } ,
sourceLocB$ { h } , sourceLocA$ { h } ) * $ { t } ;
2020-12-15 14:15:43 +01:00
ivec4 inIdx = srcIdx ;
vec4 bestIndex = vec4 ( inIdx ) ;
2021-01-12 16:01:34 +01:00
vec4 bestValue = $ { N } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { t } ; i ++ ) {
2020-12-15 14:15:43 +01:00
inIdx = srcIdx ;
2021-01-12 16:01:34 +01:00
$ { v }
vec4 candidate = $ { N } ;
2020-12-15 14:15:43 +01:00
bvec4 nan = isnan ( candidate ) ;
bvec4 replace = bvec4 (
2021-01-12 16:01:34 +01:00
vec4 ( $ { x } ( candidate , bestValue ) ) * ( vec4 ( 1.0 ) - vec4 ( nan ) ) ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ++ ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
setOutput ( bestIndex ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function PS(e,t,n,a=null){let r=t.shape[0],s=t.shape[1];a!=null&&(r=a.shape[0],s=a.shape[1]);let i=_.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new uY(o,n,a==null),c=[t];a!=null&&c.push(a);let u=e.runWebGLProgram(l,c,"int32");if(u.shape[1]===1)return u;let p=PS(e,t,n,u);return e.disposeIntermediateTensorInfo(u),p}function OS(e,t,n,a=null){let r=a!=null?a.shape:t.shape,s=r[r.length-1],i=_.computeOptimalWindowSize(s),o=new cY(r,i,n,a==null),l=a==null?[t]:[t,a],c=e.runWebGLProgram(o,l,"int32");if(c.shape.length===t.shape.length){let u=OS(e,t,n,c);return e.disposeIntermediateTensorInfo(c),u}return c}function LS(e,t,n,a){let r=[n];if(_.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),r,t.shape.length),!ee().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],[i,o]=_.computeOutAndReduceShapes(t.shape,r),l=k.sizeFromShape(o),c=xe({inputs:{x:t},backend:e,attrs:{shape:[-1,l]}});s.push(c);let u=PS(e,c,a);s.push(u);let p=xe({inputs:{x:u},backend:e,attrs:{shape:i}});return s.forEach(d=>e.disposeIntermediateTensorInfo(d)),p}return OS(e,t,a)}function pY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=k.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=En({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),_.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let u=LS(n,l,i[0],"max");return c.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var dY={kernelName:Ps,backendName:"webgl",kernelFunc:pY};function hY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=k.parseAxisParam(s,r.shape),o=_.getAxesPermutation(i,r.shape.length),l=r,c=[];o!=null&&(l=En({inputs:{x:r},backend:n,attrs:{perm:o}}),c.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),_.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let u=LS(n,l,i[0],"min");return c.forEach(p=>n.disposeIntermediateTensorInfo(p)),u}var mY={kernelName:dc,backendName:"webgl",kernelFunc:hY},fY=Oa+ `
2020-12-15 14:15:43 +01:00
if ( abs ( x ) > 1. ) {
return NAN ;
}
return asin ( x ) ;
2021-01-12 16:01:34 +01:00
` ,gY=Ye({opSnippet:fY}),yY={kernelName:Wo,backendName:"webgl",kernelFunc:gY},bY=Oa+"return log(x + sqrt(x * x + 1.0));",xY=Ye({opSnippet:bY}),vY={kernelName:Vo,backendName:"webgl",kernelFunc:xY},wY=Oa+ `
2020-12-15 14:15:43 +01:00
return atan ( x ) ;
2021-01-12 16:01:34 +01:00
` ,kY=Ye({opSnippet:wY}),IY={kernelName:Uo,backendName:"webgl",kernelFunc:kY},NY=AX+ `
2020-12-15 14:15:43 +01:00
return atan ( a , b ) ;
2021-01-12 16:01:34 +01:00
` ,TY= `
2020-12-15 14:15:43 +01:00
vec4 result = atan ( a , b ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-01-12 16:01:34 +01:00
` + $ X+ `
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,SY=on({opSnippet:NY,packedOpSnippet:TY}),CY={kernelName:Ho,backendName:"webgl",kernelFunc:SY},EY=Oa+ `
2020-12-15 14:15:43 +01:00
if ( ( x < - 1.0 ) || ( x > 1.0 ) ) return NAN ;
2021-01-12 16:01:34 +01:00
return ( log ( 1.0 + x ) - log ( 1.0 - x ) ) / 2.0 ; ` ,_Y=Ye({opSnippet:EY}),FY={kernelName:Go,backendName:"webgl",kernelFunc:_Y},Ep=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,u=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let m=t==="avg",f= ` ( ( batch * $ { e . inHeight } + xR ) * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,g= ` ( xR * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,y="0.0";if(m||(y="-1.0 / 1e-20"),n){let E=">=";this.userCode= `
const ivec2 strides = ivec2 ( $ { i } , $ { o } ) ;
const ivec2 pads = ivec2 ( $ { d } , $ { h } ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d = coords [ 3 ] ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
float avgValue = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { u } ;
wR += $ { l } ) {
2020-12-15 14:15:43 +01:00
int xR = xRCorner + wR ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { p } ;
wC += $ { c } ) {
2020-12-15 14:15:43 +01:00
int xC = xCCorner + wC ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
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 ) ;
2021-01-12 16:01:34 +01:00
if ( value $ { E } currMinMaxValue ) {
2020-12-15 14:15:43 +01:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
2021-01-12 16:01:34 +01:00
minMaxPosition = $ { a ? r ? f : g : ` wR * ${ p } + wC ` } ;
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
}
}
2020-12-15 14:15:43 +01:00
setOutput ( float ( minMaxPosition ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;return}let b="max",x= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(x="avgValue / count");let v=Math.floor(s/4)*4,N=s%4,T= `
if ( $ { m } ) {
2020-12-15 14:15:43 +01:00
avgValue += dot ( values , ones ) ;
} else {
2021-01-12 16:01:34 +01:00
minMaxValue = $ { b } ( values , minMaxValue ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
` ;this.userCode= `
2021-01-12 16:01:34 +01:00
const ivec2 strides = ivec2 ( $ { i } , $ { o } ) ;
const ivec2 pads = ivec2 ( $ { d } , $ { h } ) ;
const float initializationValue = $ { y } ;
2020-12-15 14:15:43 +01:00
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float count = 0.0 ;
float getValue ( int batch , int xR , int xC , int d ) {
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xR , xC , d ) ;
}
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2020-12-15 14:15:43 +01:00
int d = coords [ 3 ] ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
2021-01-12 16:01:34 +01:00
vec4 minMaxValue = vec4 ( $ { y } ) ;
2020-12-15 14:15:43 +01:00
float avgValue = 0.0 ;
count = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { u } ;
wR += $ { l } ) {
2020-12-15 14:15:43 +01:00
int xR = xRCorner + wR ;
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { v } ; wC += 4 ) {
int xC = xCCorner + wC * $ { c } ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xR , xC + $ { c } , d ) ,
getValue ( batch , xR , xC + 2 * $ { c } , d ) ,
getValue ( batch , xR , xC + 3 * $ { c } , d )
2020-12-15 14:15:43 +01:00
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { T }
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int xC = xCCorner + $ { v } ;
if ( $ { N === 1 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { T }
} else if ( $ { N === 2 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xR , xC + $ { c } , d ) ,
2020-12-15 14:15:43 +01:00
initializationValue ,
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { T }
} else if ( $ { N === 3 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xR , xC + $ { c } , d ) ,
getValue ( batch , xR , xC + 2 * $ { c } , d ) ,
2020-12-15 14:15:43 +01:00
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { T }
2020-10-11 18:41:17 +02:00
}
}
2021-01-12 16:01:34 +01:00
setOutput ( $ { x } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},Zv=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,c=e.dilationDepth,u=e.dilationHeight,p=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let b=t==="avg",x="0.0";if(b||(x="-1.0 / 1e-20"),n){let $ =">=";this.userCode= `
2020-12-15 14:15:43 +01:00
const ivec3 strides =
2021-01-12 16:01:34 +01:00
ivec3 ( $ { i } , $ { o } , $ { l } ) ;
const ivec3 pads = ivec3 ( $ { f } , $ { g } , $ { y } ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wD = 0 ; wD < $ { d } ;
wD += $ { c } ) {
2020-12-15 14:15:43 +01:00
int xD = xDCorner + wD ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xD < 0 || xD >= $ { e . inDepth } ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { h } ;
wR += $ { u } ) {
2020-12-15 14:15:43 +01:00
int xR = xRCorner + wR ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-15 14:15:43 +01:00
continue ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { m } ;
wC += $ { p } ) {
2020-12-15 14:15:43 +01:00
int xC = xCCorner + wC ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float value = getX ( batch , xD , xR , xC , ch ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
2021-01-12 16:01:34 +01:00
if ( value $ { $ } currMinMaxValue ) {
2020-12-15 14:15:43 +01:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
2021-01-12 16:01:34 +01:00
minMaxPosition = $ { a ? r ? ` (((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 } * ${ m } +
wR * $ { m } + wC ` };
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( float ( minMaxPosition ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ;return}let v="max",N= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(N="avgValue / count");let T=Math.floor(s/4)*4,E=s%4,A= `
if ( $ { b } ) {
2020-12-15 14:15:43 +01:00
avgValue += dot ( values , ones ) ;
} else {
2021-01-12 16:01:34 +01:00
minMaxValue = $ { v } ( values , minMaxValue ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
` ;this.userCode= `
const ivec3 strides =
2021-01-12 16:01:34 +01:00
ivec3 ( $ { i } , $ { o } , $ { l } ) ;
const ivec3 pads = ivec3 ( $ { f } , $ { g } , $ { y } ) ;
const float initializationValue = $ { x } ;
2020-12-15 14:15:43 +01: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 ) {
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xD , xR , xC , ch ) ;
}
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
2020-12-15 14:15:43 +01:00
int ch = coords . u ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2021-01-12 16:01:34 +01:00
vec4 minMaxValue = vec4 ( $ { x } ) ;
2020-12-15 14:15:43 +01:00
float avgValue = 0.0 ;
count = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wD = 0 ; wD < $ { d } ;
wD += $ { c } ) {
2020-12-15 14:15:43 +01:00
int xD = xDCorner + wD ;
2021-01-12 16:01:34 +01:00
if ( xD < 0 || xD >= $ { e . inDepth } ) {
2020-12-15 14:15:43 +01:00
continue ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { h } ;
wR += $ { u } ) {
2020-12-15 14:15:43 +01:00
int xR = xRCorner + wR ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { T } ; wC += 4 ) {
int xC = xCCorner + wC * $ { p } ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2021-01-12 16:01:34 +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 )
2020-12-15 14:15:43 +01:00
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { A }
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int xC = xCCorner + $ { T } ;
if ( $ { E === 1 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { A }
} else if ( $ { E === 2 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xD , xR , xC + $ { p } , ch ) ,
2020-12-15 14:15:43 +01:00
initializationValue ,
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { A }
} else if ( $ { E === 3 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
2021-01-12 16:01:34 +01:00
getValue ( batch , xD , xR , xC + $ { p } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { p } , ch ) ,
2020-12-15 14:15:43 +01:00
initializationValue
) ;
2021-01-12 16:01:34 +01:00
$ { A }
2020-10-11 18:41:17 +02:00
}
}
2021-01-12 16:01:34 +01:00
setOutput ( $ { N } ) ;
2020-10-11 18:41:17 +02:00
}
}
2021-01-12 16:01:34 +01:00
` }};function AY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;Tp(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(_.eitherStridesOrDilationsAreOne(i,c),()=> ` Error in avgPool : Either strides or dilations must be 1. Got strides $ { i } and dilations '${c}' ` );let u=_.computePool2DInfo(r.shape,s,i,c,o,l);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return Wn({inputs:{x:r},backend:n});let p=new Ep(u,"avg",!1);return n.runWebGLProgram(p,[r],"float32")}var $ Y={kernelName:Os,backendName:"webgl",kernelFunc:AY};function DY(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:c}=a,u=[1,1,1],p=_.computePool3DInfo(r.shape,s,i,u,o,l,c),d=new Zv(p,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var MY={kernelName:hc,backendName:"webgl",kernelFunc:DY},RY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=o-1-e.padInfo.top,u=l-1-e.padInfo.left,p=1/(t*n);this.userCode= `
const ivec2 pads = ivec2 ( $ { c } , $ { u } ) ;
const float avgMultiplier = float ( $ { p } ) ;
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
2020-10-11 18:41:17 +02:00
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { o } ;
wR += $ { s } ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
int idyR = int ( dyR ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { l } ;
wC += $ { i } ) {
float dyC = float ( dyCCorner + wC ) / $ { r } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
int idyC = int ( dyC ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( b , idyR , idyC , d ) ;
dotProd += dyValue * avgMultiplier ;
2020-10-11 18:41:17 +02:00
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},PY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.effectiveFilterDepth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,h=u-1-e.padInfo.front,m=p-1-e.padInfo.top,f=d-1-e.padInfo.left,g=1/(t*n*a);this.userCode= `
const ivec3 pads = ivec3 ( $ { h } , $ { m } , $ { f } ) ;
const float avgMultiplier = float ( $ { g } ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wD = 0 ; wD < $ { u } ;
wD += $ { o } ) {
float dyD = float ( dyDCorner + wD ) / $ { r } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
2020-12-15 14:15:43 +01:00
continue ;
}
int idyD = int ( dyD ) ;
2020-12-02 22:46:41 +01:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { p } ;
wR += $ { l } ) {
float dyR = float ( dyRCorner + wR ) / $ { s } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { d } ;
wC += $ { c } ) {
float dyC = float ( dyCCorner + wC ) / $ { i } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
dotProd += dyValue * avgMultiplier ;
}
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }};function OY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:c,dimRoundingMode:u}=a,p=[1,1,1],d=_.computePool3DInfo(i.shape,o,l,p,c,u),h=new PY(d);return n.runWebGLProgram(h,[r],i.dtype)}var LY={kernelName:Wd,backendName:"webgl",kernelFunc:OY};function zY(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;Tp([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:c}=a,u=_.computePool2DInfo(i.shape,o,l,1,c),p=new RY(u);return n.runWebGLProgram(p,[r],i.dtype)}var BY={kernelName:Bd,backendName:"webgl",kernelFunc:zY};function WY(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;return uf({a:r,b:s,transposeA:i,transposeB:o,backend:n})}var VY={kernelName:Ls,backendName:"webgl",kernelFunc:WY},UY=class{constructor(e,t,n,a,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let i="0.0";a!=null&&(_.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
float x = getXAtOutCoords ( ) ;
float mean = getMeanAtOutCoords ( ) ;
float variance = getVarianceAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
float offset = $ { i } ;
float scale = $ { o } ;
float inv = scale * inversesqrt ( variance + float ( $ { s } ) ) ;
2020-12-15 14:15:43 +01:00
setOutput ( dot ( vec3 ( x , - mean , offset ) , vec3 ( inv , inv , 1 ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` }},GY=class{constructor(e,t,n,a,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";a!=null&&(_.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
vec4 offset = $ { i } ;
vec4 scale = $ { o } ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec4 x = getXAtOutCoords ( ) ;
vec4 mean = getMeanAtOutCoords ( ) ;
vec4 variance = getVarianceAtOutCoords ( ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
vec4 inv = scale * inversesqrt ( variance + vec4 ( $ { s } ) ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
setOutput ( ( x - mean ) * inv + offset ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},HY=({inputs:e,backend:t,attrs:n})=>{let{x:a,mean:r,variance:s,offset:i,scale:o}=e;k.assert(r.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let c=[a,r,s],u=null;i!=null&&(u=i.shape,c.push(i));let p=null;o!=null&&(p=o.shape,c.push(o));let d=ee().getBool("WEBGL_PACK_NORMALIZATION")?new GY(a.shape,r.shape,s.shape,u,p,l):new UY(a.shape,r.shape,s.shape,u,p,l);return t.runWebGLProgram(d,c,c[0].dtype)},jY={kernelName:Xs,backendName:"webgl",kernelFunc:HY},KY=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=mt(this.rank),n= ` uniform int start [ $ { this . rank } ] ; ` ,a=qY(this.rank),r,s=e.map((i,o)=> ` sourceLoc . $ { Qv [ o ] } = start [ $ { o } ] + coords . $ { Qv [ o ] } ; ` );r= `
$ { t } sourceLoc ;
$ { t } coords = getOutputCoords ( ) ;
$ { s . join ( `
2020-12-15 14:15:43 +01:00
` )}
` ,this.userCode= `
2021-01-12 16:01:34 +01:00
$ { n }
void main ( ) {
$ { r }
setOutput ( getSource ( $ { a } ) ) ;
}
` }getCustomSetupFunc(e){if(e.length!==this.rank)throw Error( ` The rank ( $ { this . rank } ) of the program must match the length of start ( $ { e . length } ) ` );return(t,n)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}},Qv=["x","y","z","w","u","v"];function qY(e){if(e===1)return"sourceLoc";if(e<=6)return Qv.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error( ` Slicing for rank $ { e } is not yet supported ` )}var XY=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=mt(this.rank),n=yn("coords",this.rank),a=yn("sourceLoc",this.rank),r=this.rank===1?"sourceLoc": ` vec2 ( $ { a . slice ( - 2 ) . join ( ) } ) ` ,s= ` getChannel ( getSource ( $ { a . join ( ) } ) , $ { r } ) ` ,i= `
result . x = $ { s } ;
if ( ++ $ { n [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
++ $ { a [ this . rank - 1 ] } ;
result . y = $ { s } ;
-- $ { a [ this . rank - 1 ] } ;
}
` ,o=this.rank===1?"": `
-- $ { n [ this . rank - 1 ] } ;
if ( ++ $ { n [ this . rank - 2 ] } < $ { e [ this . rank - 2 ] } ) {
++ $ { a [ this . rank - 2 ] } ;
result . z = $ { s } ;
if ( ++ $ { n [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
++ $ { a [ this . rank - 1 ] } ;
result . w = $ { s } ;
}
}
` ,l=this.rank<=4? ` sourceLoc = coords +
$ { t } ( $ { e . map ( ( c , u ) => ` start[ ${ u } ] ` ) . join ( ) } ) ; ` :e.map((c,u)=> ` $ { a [ u ] } = $ { n [ u ] } + start [ $ { u } ] ; ` ).join( `
2020-12-15 14:15:43 +01:00
` );this.userCode= `
uniform int start [ $ { this . rank } ] ;
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { t } coords = getOutputCoords ( ) ;
$ { t } sourceLoc ;
$ { l }
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
$ { i }
$ { o }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e){if(e.length!==this.rank)throw Error( ` The rank ( $ { this . rank } ) of the program must match the length of start ( $ { e . length } ) ` );return(t,n)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}};function YY(e,t,n,a){let r=a.texData.get(e.dataId),s=a.makeTensorInfo(n,e.dtype),i=a.texData.get(s.dataId);Object.assign(i,r),i.shape=n,i.dtype=e.dtype;let o=hn.computeFlatOffset(t,k.computeStrides(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};let l=a.dataRefCount.get(i.slice.origDataId)||1;return a.dataRefCount.set(i.slice.origDataId,l+1),s}function _p(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a,[o,l]=hn.parseSliceParams(r,s,i);if(hn.assertParamsValid(r,o,l),k.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let p=n.texData.get(r.dataId),d=UK(p.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,d)}let{isPacked:c}=n.texData.get(r.dataId),u=hn.isSliceContinous(r.shape,o,l);if(c||!u){let p=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new XY(l):new KY(l),d=p.getCustomSetupFunc(o);return n.runWebGLProgram(p,[r],r.dtype,d)}return n.uploadToGPU(r.dataId),YY(r,o,l,n)}var JY={kernelName:El,backendName:"webgl",kernelFunc:_p},ZY=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;k.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((b,x)=>b*x),l=_.getReshaped(r.shape,s,o),c=_.getPermuted(l.length,s.length),u=_.getReshapedPermuted(r.shape,s,o),p=_.getSliceBeginCoords(i,s.length),d=_.getSliceSize(u,i,s.length),h=[],m=xe({inputs:{x:r},backend:n,attrs:{shape:l}}),f=En({inputs:{x:m},backend:n,attrs:{perm:c}}),g=xe({inputs:{x:f},backend:n,attrs:{shape:u}}),y=_p({inputs:{x:g},backend:n,attrs:{begin:p,size:d}});return h.push(m),h.push(f),h.push(g),h.forEach(b=>n.disposeIntermediateTensorInfo(b)),y},QY={kernelName:mc,backendName:"webgl",kernelFunc:ZY};function e7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i}=a,o=n.readSync(r.dataId),l=n.readSync(s.dataId),c=hS(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,c)}var t7={kernelName:Vd,backendName:"webgl",kernelFunc:e7},n7="return float(a != b);",zS=on({opSnippet:n7,dtype:"bool"}),a7={kernelName:gl,backendName:"webgl",kernelFunc:zS};function Fp(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return Wn({inputs:{x:r.complexTensorInfos.real},backend:n})}var r7={kernelName:uh,backendName:"webgl",kernelFunc:Fp},s7="return float(int(x));";function i7(e,t){let n=new ys(e.shape,s7),a=t.runWebGLProgram(n,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function ew(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return Wn({inputs:{x:r},backend:n});let i=bt(r.shape),o=ew({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=bs({inputs:{real:o,imag:i},backend:n});return i.dispose(),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=Fp({inputs:{input:r},backend:n}),o=ew({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!k.hasEncodingLoss(r.dtype,s)){let i=Wn({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return i7(r,n);if(s==="bool"){let i=n.makeTensorInfo([],"bool",k.getTypedArrayFromDType("bool",1)),o=zS({inputs:{a:r,b:i},backend:n});return n.disposeIntermediateTensorInfo(i),o}throw new Error( ` Error in Cast : failed to cast $ { r . dtype } to $ { s } ` )}var o7={kernelName:zs,backendName:"webgl",kernelFunc:ew},BS="return ceil(x);",l7=Ye({opSnippet:BS,packedOpSnippet:BS,cpuKernelImpl:TK}),u7={kernelName:jo,backendName:"webgl",kernelFunc:l7},c7=class{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float minVal ;
uniform float maxVal ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
float value = getAAtOutCoords ( ) ;
if ( isnan ( value ) ) {
setOutput ( value ) ;
2020-10-11 18:41:17 +02:00
return ;
}
2020-12-15 14:15:43 +01:00
setOutput ( clamp ( value , minVal , maxVal ) ) ;
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e,t){return(n,a)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(a,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(a,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}},p7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float minVal ;
uniform float maxVal ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
vec4 value = getAAtOutCoords ( ) ;
if ( any ( isnan ( value ) ) ) {
setOutput ( value ) ;
2020-10-11 18:41:17 +02:00
return ;
}
2020-12-15 14:15:43 +01:00
setOutput ( clamp ( value , vec4 ( minVal ) , vec4 ( maxVal ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e,t){return(n,a)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(a,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(a,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}};function d7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o;ee().getBool("WEBGL_PACK_CLIP")?o=new p7(r.shape):o=new c7(r.shape);let l=o.getCustomSetupFunc(s,i);return n.runWebGLProgram(o,[r],r.dtype,l)}var h7={kernelName:Kr,backendName:"webgl",kernelFunc:d7},m7=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
float re = abs ( getRealAtOutCoords ( ) ) ;
float im = abs ( getImagAtOutCoords ( ) ) ;
float mx = max ( re , im ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ) )
) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function WS(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function f7(e){let{inputs:t,backend:n}=e,{x:a}=t,r=n.texData.get(a.dataId),s=new m7(a.shape),i=[WS(a,r.complexTensorInfos.real),WS(a,r.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}var g7={kernelName:fc,backendName:"webgl",kernelFunc:f7},y7=class{constructor(e){this.outputShape=[],this.outputShape=_.computeOutShape(e,1),this.variableNames=e.map((s,i)=> ` T$ { i } ` );let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let n=[ ` if ( yC < $ { t [ 0 ] } ) setOutput ( getT0 ( yR , yC ) ) ; ` ];for(let s=1;s<t.length;s++){let i=t[s-1];n.push( ` else if ( yC < $ { t [ s ] } ) setOutput ( getT$ { s } ( yR , yC - $ { i } ) ) ; ` )}let a=t.length,r=t[t.length-1];n.push( ` else setOutput ( getT$ { a } ( yR , yC - $ { r } ) ) ; ` ),this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 coords = getOutputCoords ( ) ;
int yR = coords . x ;
int yC = coords . y ;
2021-01-12 16:01:34 +01:00
$ { n . join ( `
2020-12-15 14:15:43 +01:00
` )}
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},b7=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.computeOutShape(e,t);let n=this.outputShape,a=n.length,r=mt(a),s=yn("coords",a),i=["x","y","z","w","u","v"].slice(0,a);this.variableNames=e.map((m,f)=> ` T$ { f } ` );let o=new Array(e.length-1);o[0]=e[0][t];for(let m=1;m<o.length;m++)o[m]=o[m-1]+e[m][t];let l=i[t],c=i.slice(-2),u=i.join(),p= ` if ( $ { l } < $ { o [ 0 ] } ) {
2020-12-15 14:15:43 +01:00
return getChannel (
2021-01-12 16:01:34 +01:00
getT0 ( $ { u } ) , vec2 ( $ { c . join ( ) } ) ) ;
} ` ;for(let m=1;m<o.length;m++){let f=o[m-1];p+= `
if ( $ { l } < $ { o [ m ] } && $ { l } >= $ { o [ m - 1 ] } ) {
2020-12-15 14:15:43 +01:00
return getChannel (
2021-01-12 16:01:34 +01:00
getT$ { m } ( $ { pf ( i , l , f ) } ) ,
vec2 ( $ { pf ( c , l , f ) } ) ) ;
} ` }let d=o.length,h=o[o.length-1];p+= `
2020-12-15 14:15:43 +01:00
return getChannel (
2021-01-12 16:01:34 +01:00
getT$ { d } ( $ { pf ( i , l , h ) } ) ,
vec2 ( $ { pf ( c , l , h ) } ) ) ; ` ,this.userCode= `
float getValue ( $ { i . map ( m => "int " + m ) } ) {
$ { p }
2020-10-11 18:41:17 +02:00
}
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { r } coords = getOutputCoords ( ) ;
vec4 result = vec4 ( getValue ( $ { s } ) , 0. , 0. , 0. ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { s [ a - 1 ] } = $ { s [ a - 1 ] } + 1 ;
if ( $ { s [ a - 1 ] } < $ { n [ a - 1 ] } ) {
result . g = getValue ( $ { s } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
$ { s [ a - 2 ] } = $ { s [ a - 2 ] } + 1 ;
if ( $ { s [ a - 2 ] } < $ { n [ a - 2 ] } ) {
result . a = getValue ( $ { s } ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
$ { s [ a - 1 ] } = $ { s [ a - 1 ] } - 1 ;
if ( $ { s [ a - 2 ] } < $ { n [ a - 2 ] } &&
$ { s [ a - 1 ] } < $ { n [ a - 1 ] } ) {
result . b = getValue ( $ { s } ) ;
2020-12-15 14:15:43 +01:00
}
setOutput ( result ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function pf(e,t,n){let a=e.indexOf(t);return e.map((r,s)=>s===a? ` $ { r } - $ { n } ` :r).join()}function df(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return Wn({inputs:{x:r.complexTensorInfos.imag},backend:n})}var x7={kernelName:nh,backendName:"webgl",kernelFunc:df};function Su(e,t,n){let a=e[0].dtype;if(a==="complex64"){let c=e.map(m=>Fp({inputs:{input:m},backend:n})),u=e.map(m=>df({inputs:{input:m},backend:n})),p=Su(c,t,n),d=Su(u,t,n),h=bs({inputs:{real:p,imag:d},backend:n});return c.forEach(m=>n.disposeIntermediateTensorInfo(m)),u.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),h}if(a==="string"){let{tensors2D:c,outShape:u}=VS(e,t,n),p=c.map(g=>({vals:n.readSync(g.dataId),shape:g.shape})),d=c[0].shape[0]===1,h=SK(p,u,a,d),m=_.computeOutShape(e.map(g=>g.shape),t),f=n.makeTensorInfo(m,a,h);return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),f}if(e.length>ee().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(e.length/2),u=Su(e.slice(0,c),t,n),p=Su(e.slice(c),t,n),d=Su([u,p],t,n);return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),d}if(ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let c=new b7(e.map(u=>u.shape),t);return n.runWebGLProgram(c,e,a)}let{tensors2D:r,outShape:s}=VS(e,t,n),i=new y7(r.map(c=>c.shape)),o=n.runWebGLProgram(i,r,a);r.forEach(c=>n.disposeIntermediateTensorInfo(c));let l=xe({inputs:{x:o},attrs:{shape:s},backend:n});return n.disposeIntermediateTensorInfo(o),l}function VS(e,t,n){let a=_.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>xe({inputs:{x:r},attrs:{shape:[-1,k.sizeFromShape(r.shape.slice(t))]},backend:n})),outShape:a}}function US(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=k.parseAxisParam(r,t[0].shape)[0],i=_.computeOutShape(t.map(c=>c.shape),s);if(k.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(c=>k.sizeFromShape(c.shape)>0);if(o.length===1)return Wn({inputs:{x:o[0]},backend:n});let l=o.map(c=>c.shape);return _.assertParamsConsistent(l,s),Su(o,s,n)}var v7={kernelName:qo,backendName:"webgl",kernelFunc:US},GS=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,c=e.dilationHeight,u=e.dilationWidth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4,f=e.dataFormat==="channelsLast",g=f?1:2,y=f?2:3,b=f?3:1,x="",v="";n&&(a?x= ` float activation ( float a ) {
2020-12-15 14:15:43 +01:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { n }
} ` :r?x= ` float activation ( float a ) {
2020-12-15 14:15:43 +01:00
float b = getLeakyreluAlphaAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { n }
} ` :x= `
2020-12-15 14:15:43 +01:00
float activation ( float x ) {
2021-01-12 16:01:34 +01:00
$ { n }
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ,v="result = activation(result);");let N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { x }
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
const ivec2 strides = ivec2 ( $ { o } , $ { l } ) ;
const ivec2 pads = ivec2 ( $ { s } , $ { i } ) ;
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2021-01-12 16:01:34 +01:00
int d2 = coords [ $ { b } ] ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec2 xRCCorner =
2021-01-12 16:01:34 +01:00
ivec2 ( coords [ $ { g } ] , coords [ $ { y } ] ) * strides - pads ;
2020-12-15 14:15:43 +01:00
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { p } ; wR ++ ) {
int xR = xRCorner + wR * $ { c } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { d } ; wC ++ ) {
int xC = xCCorner + wC * $ { u } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int d1 = 0 ; d1 < $ { h } ; d1 += 4 ) {
2020-12-15 14:15:43 +01:00
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 )
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( $ { f } ) {
2020-12-15 14:15:43 +01: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 ) ;
}
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( $ { m === 1 } ) {
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( $ { f } ) {
2020-12-15 14:15:43 +01:00
dotProd +=
2021-01-12 16:01:34 +01:00
getX ( batch , xR , xC , $ { h } ) *
getW ( wR , wC , $ { h } , d2 ) ;
2020-12-15 14:15:43 +01:00
} else {
dotProd +=
2021-01-12 16:01:34 +01:00
getX ( batch , $ { h } , xR , xC ) *
getW ( wR , wC , $ { h } , d2 ) ;
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
} else if ( $ { m === 2 } ) {
2020-12-15 14:15:43 +01:00
vec2 wValues = vec2 (
2021-01-12 16:01:34 +01:00
getW ( wR , wC , $ { h } , d2 ) ,
getW ( wR , wC , $ { h } + 1 , d2 )
2020-12-15 14:15:43 +01:00
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( $ { f } ) {
2020-12-15 14:15:43 +01:00
vec2 xValues = vec2 (
2021-01-12 16:01:34 +01:00
getX ( batch , xR , xC , $ { h } ) ,
getX ( batch , xR , xC , $ { h } + 1 )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec2 xValues = vec2 (
2021-01-12 16:01:34 +01:00
getX ( batch , $ { h } , xR , xC ) ,
getX ( batch , $ { h } + 1 , xR , xC )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
} else if ( $ { m === 3 } ) {
2020-12-15 14:15:43 +01:00
vec3 wValues = vec3 (
2021-01-12 16:01:34 +01:00
getW ( wR , wC , $ { h } , d2 ) ,
getW ( wR , wC , $ { h } + 1 , d2 ) ,
getW ( wR , wC , $ { h } + 2 , d2 )
2020-12-15 14:15:43 +01:00
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( $ { f } ) {
2020-12-15 14:15:43 +01:00
vec3 xValues = vec3 (
2021-01-12 16:01:34 +01:00
getX ( batch , xR , xC , $ { h } ) ,
getX ( batch , xR , xC , $ { h } + 1 ) ,
getX ( batch , xR , xC , $ { h } + 2 )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
2020-10-11 18:41:17 +02:00
} else {
2020-12-15 14:15:43 +01:00
vec3 xValues = vec3 (
2021-01-12 16:01:34 +01:00
getX ( batch , $ { h } , xR , xC ) ,
getX ( batch , $ { h } + 1 , xR , xC ) ,
getX ( batch , $ { h } + 2 , xR , xC )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
2020-10-11 18:41:17 +02:00
}
}
2020-12-15 14:15:43 +01:00
}
float result = dotProd ;
2021-01-12 16:01:34 +01:00
$ { N }
$ { v }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }},w7=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,a=e.padInfo.left,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.filterDepth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode= `
const ivec3 strides = ivec3 ( $ { r } , $ { s } , $ { i } ) ;
const ivec3 pads = ivec3 ( $ { t } , $ { n } , $ { a } ) ;
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d2 = coords . u ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec3 xFRCCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xFCorner = xFRCCorner . x ;
int xRCorner = xFRCCorner . y ;
int xCCorner = xFRCCorner . z ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ;
2021-01-12 16:01:34 +01:00
for ( int wF = 0 ; wF < $ { u } ; wF ++ ) {
int xF = xFCorner + wF * $ { o } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xF < 0 || xF >= $ { e . inDepth } ) {
2020-12-15 14:15:43 +01:00
continue ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { p } ; wR ++ ) {
int xR = xRCorner + wR * $ { l } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { d } ; wC ++ ) {
int xC = xCCorner + wC * $ { c } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int d1 = 0 ; d1 < $ { h } ; d1 += 4 ) {
2020-12-15 14:15:43 +01:00
vec4 xValues = vec4 (
getX ( batch , xF , xR , xC , d1 ) ,
getX ( batch , xF , xR , xC , d1 + 1 ) ,
getX ( batch , xF , xR , xC , d1 + 2 ) ,
getX ( batch , xF , xR , xC , d1 + 3 )
) ;
vec4 wValues = vec4 (
getW ( wF , wR , wC , d1 , d2 ) ,
getW ( wF , wR , wC , d1 + 1 , d2 ) ,
getW ( wF , wR , wC , d1 + 2 , d2 ) ,
getW ( wF , wR , wC , d1 + 3 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-01-12 16:01:34 +01:00
if ( $ { m === 1 } ) {
2020-12-15 14:15:43 +01:00
dotProd +=
2021-01-12 16:01:34 +01:00
getX ( batch , xF , xR , xC , $ { h } ) *
getW ( wF , wR , wC , $ { h } , d2 ) ;
} else if ( $ { m === 2 } ) {
2020-12-15 14:15:43 +01:00
vec2 xValues = vec2 (
2021-01-12 16:01:34 +01:00
getX ( batch , xF , xR , xC , $ { h } ) ,
getX ( batch , xF , xR , xC , $ { h } + 1 )
2020-12-15 14:15:43 +01:00
) ;
vec2 wValues = vec2 (
2021-01-12 16:01:34 +01:00
getW ( wF , wR , wC , $ { h } , d2 ) ,
getW ( wF , wR , wC , $ { h } + 1 , d2 )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
2021-01-12 16:01:34 +01:00
} else if ( $ { m === 3 } ) {
2020-12-15 14:15:43 +01:00
vec3 xValues = vec3 (
2021-01-12 16:01:34 +01:00
getX ( batch , xF , xR , xC , $ { h } ) ,
getX ( batch , xF , xR , xC , $ { h } + 1 ) ,
getX ( batch , xF , xR , xC , $ { h } + 2 )
2020-12-15 14:15:43 +01:00
) ;
vec3 wValues = vec3 (
2021-01-12 16:01:34 +01:00
getW ( wF , wR , wC , $ { h } , d2 ) ,
getW ( wF , wR , wC , $ { h } + 1 , d2 ) ,
getW ( wF , wR , wC , $ { h } + 2 , d2 )
2020-12-15 14:15:43 +01:00
) ;
dotProd += dot ( xValues , wValues ) ;
}
}
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }},k7=class{constructor(e,t,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let{filterWidth:a,inChannels:r,strideWidth:s,strideHeight:i,padInfo:o,outWidth:l,dilationWidth:c,dilationHeight:u,dataFormat:p}=n,{left:d,top:h}=o,m=r*a,f=gn(),g=p==="channelsLast",y=g?0:1,b=g?1:2,x="";for(let v=0;v<=1;v++)for(let N=0;N<=1;N++)x+= `
blockIndex = rc . y + $ { N } ;
pos = rc . x + $ { v } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( blockIndex < $ { e [ 1 ] } && pos < $ { e [ 0 ] } ) {
offsetY = int ( blockIndex / ( $ { l } ) ) * $ { i } - $ { h } ;
d0 = offsetY + $ { u } * ( pos / $ { m } ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( d0 < $ { t [ y ] } && d0 >= 0 ) {
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
offsetX = int ( mod ( float ( blockIndex ) , $ { l } . ) * $ { s } . - $ { d } . ) ;
d1 = offsetX + $ { c } * ( int ( mod ( float ( pos ) , $ { m } . ) / $ { r } . ) ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( d1 < $ { t [ b ] } && d1 >= 0 ) {
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
ch = int ( mod ( float ( pos ) , $ { r } . ) ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( $ { g } ) {
2020-10-11 18:41:17 +02:00
innerDims = vec2 ( d1 , ch ) ;
2021-01-12 16:01:34 +01:00
result [ $ { v * 2 + N } ] = getChannel (
2020-10-11 18:41:17 +02:00
getA ( d0 , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
} else {
innerDims = vec2 ( d0 , d1 ) ;
2021-01-12 16:01:34 +01:00
result [ $ { v * 2 + N } ] = getChannel (
2020-10-11 18:41:17 +02:00
getA ( ch , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
}
}
}
}
` ;this.userCode= `
void main ( ) {
ivec2 rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0 ) ;
int blockIndex , pos , offsetY , d0 , offsetX , d1 , ch ;
vec2 innerDims ;
2021-01-12 16:01:34 +01:00
$ { x }
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { f . output } = result ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function HS({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,c=a.texData.get(e.dataId),u=n.inChannels,p=l[0]*l[1]*l[2],d=n.outChannels,h=n.dataFormat==="channelsLast",m=!1,f=!1,g,y=[],b=(p===1||d===1)&&u>DS,x=l[2]%2!=0&&!!c.isPacked;if(b||!ee().getBool("WEBGL_LAZILY_UNPACK")||!ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!x){let v=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],N=xe({inputs:{x:e},backend:a,attrs:{shape:[1,v,n.inChannels]}}),T=xe({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),E=uf({a:N,b:T,transposeA:m,transposeB:f,backend:a,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=xe({inputs:{x:E},backend:a,attrs:{shape:n.outShape}}),y.push(N),y.push(T),y.push(E)}else{let v=h?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),N={dataId:e.dataId,shape:[1,v,n.inChannels],dtype:e.dtype},T=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,k.assert(af(c.shape,N.shape),()=> ` packed reshape $ { c . shape } to $ { N . shape } isn ' t free ` );let E=xe({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(E);let A=uf({a:N,b:E,backend:a,transposeA:m,transposeB:f,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}), $ =a.texData.get(A.dataId);k.assert( $ .isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=T, $ .shape=n.outShape,g=Wn({inputs:{x:A},backend:a}),g.shape=n.outShape,y.push(A)}for(let v of y)a.disposeIntermediateTensorInfo(v);return g}function jS({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:c,inChannels:u,outWidth:p,outHeight:d,dataFormat:h}=n,m=h==="channelsLast",f=l*c*u,g=d*p,y=[f,g],b=!0,x=!1,v=[],N=xe({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),T=xe({inputs:{x:t},backend:a,attrs:{shape:[1,f,k.sizeFromShape(t.shape)/f]}});v.push(N),v.push(T);let E=new k7(y,N.shape,n),A=a.runWebGLProgram(E,[N],"float32"), $ =xe({inputs:{x:A},backend:a,attrs:{shape:[1,y[0],y[1]]}});v.push(A),v.push( $ );let O=r!=null,V=s!=null,W=o==="leakyrelu",H=o?of(o,!0):null,X=new CS( $ .shape,T.shape,[1,g,n.outChannels],b,x,O,H,V,W),q=[ $ ,T];if(r&&q.push(r),V&&q.push(s),W){let Q=a.makeTensorInfo([],"float32",k.createScalarValue(i,"float32"));q.push(Q),v.push(Q)}let K=a.runWebGLProgram(X,q,"float32"),J=m?[1,d,p,n.outChannels]:[1,n.outChannels,d,p],te=xe({inputs:{x:K},backend:a,attrs:{shape:J}});v.push(K);for(let Q of v)a.disposeIntermediateTensorInfo(Q);return te}function I7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:c,dimRoundingMode:u}=a,p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,s.shape,i,c,o,u,!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=HS({x:r,filter:s,convInfo:d,backend:n});else if(ee().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=jS({x:r,filter:s,convInfo:d,backend:n});else{let f=new GS(d);h=n.runWebGLProgram(f,[r,s],"float32")}let m=xe({inputs:{x:h},backend:n,attrs:{shape:d.outShape}});return n.disposeIntermediateTensorInfo(h),m}var N7={kernelName:Bs,backendName:"webgl",kernelFunc:I7},T7=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.dataFormat==="channelsLast";this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int d2 = coords . w ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { t } - $ { a } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { n } - $ { r } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
if ( $ { s } ) {
2020-12-15 14:15:43 +01: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 ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
2020-10-11 18:41:17 +02:00
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},S7=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=s?1:2,c=s?2:3,u=s?3:1;this.userCode= `
const ivec2 pads = ivec2 ( $ { i } , $ { o } ) ;
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int batch = coords [ 0 ] ;
2021-01-12 16:01:34 +01:00
int d1 = coords [ $ { u } ] ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
ivec2 dyCorner = ivec2 ( coords [ $ { l } ] , coords [ $ { c } ] ) - pads ;
2020-12-15 14:15:43 +01:00
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
2020-10-11 18:41:17 +02:00
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2020-10-11 18:41:17 +02:00
continue ;
}
int idyR = int ( dyR ) ;
2021-01-12 16:01:34 +01:00
int wRPerm = $ { t } - 1 - wR ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { r } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-10-11 18:41:17 +02:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2021-01-12 16:01:34 +01:00
int wCPerm = $ { n } - 1 - wC ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( $ { s } ) {
2020-12-15 14:15:43 +01: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 ;
}
}
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }},C7=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.padInfo.front,s=e.padInfo.top,i=e.padInfo.left;this.userCode= `
2020-12-15 14:15:43 +01: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 ;
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yF = 0 ; yF < $ { e . outDepth } ; yF ++ ) {
int xF = wF + yF * $ { t } - $ { r } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( xF < 0 || xF >= $ { e . inDepth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { n } - $ { s } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { a } - $ { i } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
float dyValue = getDy ( b , yF , yR , yC , d2 ) ;
float xValue = getX ( b , xF , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
}
}
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }},E7=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,c=a-1-e.padInfo.left;this.userCode= `
const ivec3 pads = ivec3 ( $ { o } , $ { l } , $ { c } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . u ;
2020-10-11 18:41:17 +02:00
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
2020-12-15 14:15:43 +01:00
int dyFCorner = dyCorner . x ;
2020-10-11 18:41:17 +02:00
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
float dotProd = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int wF = 0 ; wF < $ { t } ; wF ++ ) {
float dyF = float ( dyFCorner + wF ) / $ { r } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyF < 0.0 || dyF >= $ { e . outDepth } . 0 || fract ( dyF ) > 0.0 ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
int idyF = int ( dyF ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int wFPerm = $ { t } - 1 - wF ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { n } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { s } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyR ) > 0.0 ) {
2020-10-11 18:41:17 +02:00
continue ;
}
int idyR = int ( dyR ) ;
2021-01-12 16:01:34 +01:00
int wRPerm = $ { n } - 1 - wR ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { a } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { i } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-10-11 18:41:17 +02:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2021-01-12 16:01:34 +01:00
int wCPerm = $ { a } - 1 - wC ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
2020-12-15 14:15:43 +01:00
float xValue = getDy ( batch , idyF , idyR , idyC , d2 ) ;
float wValue = getW ( wFPerm , wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
}
2020-10-11 18:41:17 +02:00
}
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }};function _7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:c,filterShape:u}=a,p=_.convertConv2DDataFormat(l),d=_.computeConv2DInfo(r.shape,u,i,1,o,c,!1,p),h=new T7(d);return n.runWebGLProgram(h,[r,s],"float32")}var F7={kernelName:Gd,backendName:"webgl",kernelFunc:_7};function A7(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:c,dimRoundingMode:u}=a,p=_.convertConv2DDataFormat(c),d=_.computeConv2DInfo(i,s.shape,o,1,l,u,!1,p),h=new S7(d);return n.runWebGLProgram(h,[r,s],"float32")}var $ 7={kernelName:Ws,backendName:"webgl",kernelFunc:A7};function D7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,c=_.computeConv3DInfo(r.shape,s.shape,i,l,o),u=new w7(c);return n.runWebGLProgram(u,[r,s],"float32")}var M7={kernelName:gc,backendName:"webgl",kernelFunc:D7};function R7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,c=_.computeConv3DInfo(r.shape,l,i,1,o),u=new C7(c);return n.runWebGLProgram(u,[r,s],"float32")}var P7={kernelName:Hd,backendName:"webgl",kernelFunc:R7};function O7(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,c=_.computeConv3DInfo(l,s.shape,o,1,i),u=new E7(c);return n.runWebGLProgram(u,[r,s],"float32")}var L7={kernelName:jd,backendName:"webgl",kernelFunc:O7},z7=SS+ `
2020-12-15 14:15:43 +01:00
return cos ( x ) ;
2021-01-12 16:01:34 +01:00
` ,B7=Ye({opSnippet:z7}),W7={kernelName:Vs,backendName:"webgl",kernelFunc:B7},V7= `
2020-12-15 14:15:43 +01:00
float e2x = exp ( - x ) ;
return ( e2x + 1.0 / e2x ) / 2.0 ;
2021-01-12 16:01:34 +01:00
` ,U7=Ye({opSnippet:V7}),G7={kernelName:Ko,backendName:"webgl",kernelFunc:U7},H7=class{constructor(e,t,n,a,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[c]=t,[u,p]=n;this.outputShape=[c,u,p,l];let d=a==="bilinear"?1:0,[h,m]=[ ` $ { i - 1 } . 0 ` , ` $ { o - 1 } . 0 ` ],[f,g,y]=u>1?[ ` $ { ( i - 1 ) / ( u - 1 ) } ` ,"(y2-y1) * height_ratio", ` y1 * $ { h } + float ( y ) * ( height _scale ) ` ]:["0.0","0.0", ` 0.5 * ( y1 + y2 ) * $ { h } ` ],[b,x,v]=p>1?[ ` $ { ( o - 1 ) / ( p - 1 ) } ` ,"(x2-x1) * width_ratio", ` x1 * $ { m } + float ( x ) * ( width _scale ) ` ]:["0.0","0.0", ` 0.5 * ( x1 + x2 ) * $ { m } ` ];this.userCode= `
const float height _ratio = float ( $ { f } ) ;
const float width _ratio = float ( $ { b } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int y = coords [ 1 ] ;
int x = coords [ 2 ] ;
int d = coords [ 3 ] ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// get box vals
float y1 = getBoxes ( b , 0 ) ;
float x1 = getBoxes ( b , 1 ) ;
float y2 = getBoxes ( b , 2 ) ;
float x2 = getBoxes ( b , 3 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// get image in batch index
int bInd = round ( getBoxInd ( b ) ) ;
2021-01-12 16:01:34 +01:00
if ( bInd < 0 || bInd >= $ { s } ) {
2020-12-15 14:15:43 +01:00
return ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
float height _scale = $ { g } ;
float width _scale = $ { x } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
float in _y = $ { y } ;
if ( in _y < 0.0 || in _y > $ { h } ) {
setOutput ( float ( $ { r } ) ) ;
2020-12-15 14:15:43 +01:00
return ;
}
2021-01-12 16:01:34 +01:00
float in _x = $ { v } ;
if ( in _x < 0.0 || in _x > $ { m } ) {
setOutput ( float ( $ { r } ) ) ;
2020-12-15 14:15:43 +01:00
return ;
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec2 sourceFracIndexCR = vec2 ( in _x , in _y ) ;
2021-01-12 16:01:34 +01:00
if ( $ { d } == 1 ) {
2020-12-15 14:15:43 +01:00
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2 ( sourceFracIndexCR ) ;
ivec2 sourceCeilCR = ivec2 ( ceil ( sourceFracIndexCR ) ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec2 fracCR = sourceFracIndexCR - vec2 ( sourceFloorCR ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
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 ) ;
2020-10-11 18:41:17 +02:00
}
}
2021-01-12 16:01:34 +01:00
` }},j7=e=>{let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:c}=a,u=new H7(r.shape,s.shape,o,l,c);return n.runWebGLProgram(u,[r,s,i],"float32")},q7={kernelName:Xo,backendName:"webgl",kernelFunc:j7},XS=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;let a=e.length,r=t?"0.0": ` getX ( $ { qS ( a , "coords" ) } ) ` ,s=e[e.length-1],i="",o="";t?(i=n? ` end != $ { s - 1 } ` :"end != 0",o=n?"end + 1":"end - 1"):(i=n? ` end + pow2 < $ { s } ` :"end >= pow2",o=n?"end + pow2":"end - pow2"),this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float index ;
2020-10-11 18:41:17 +02:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { mt ( a ) } coords = getOutputCoords ( ) ;
int end = $ { KS ( a , "coords" ) } ;
float val = $ { r } ;
2020-12-15 14:15:43 +01:00
int pow2 = int ( pow ( 2.0 , index ) ) ;
2021-01-12 16:01:34 +01:00
if ( $ { i } ) {
int idx = $ { o } ;
$ { KS ( a , "coords" ) } = idx ;
val += getX ( $ { qS ( a , "coords" ) } ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
setOutput ( val ) ;
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}};function qS(e,t){if(e===1)return ` $ { t } ` ;if(e===2)return ` $ { t } . x , $ { t } . y ` ;if(e===3)return ` $ { t } . x , $ { t } . y , $ { t } . z ` ;if(e===4)return ` $ { t } . x , $ { t } . y , $ { t } . z , $ { t } . w ` ;throw Error( ` Cumulative sum for rank $ { e } is not yet supported ` )}function KS(e,t){if(e===1)return ` $ { t } ` ;if(e===2)return ` $ { t } . y ` ;if(e===3)return ` $ { t } . z ` ;if(e===4)return ` $ { t } . w ` ;throw Error( ` Cumulative sum for rank $ { e } is not yet supported ` )}function K7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length,c=_.getAxesPermutation([s],l),u=r;c!=null&&(u=En({inputs:{x:r},backend:n,attrs:{perm:c}}));let p=_.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error( ` WebGL cumsum shader expects an inner - most axis = $ { r . shape . length - 1 } but got axis = $ { s } ` );let d=r.shape[p],h=Wn({inputs:{x:u},backend:n});for(let m=0;m<=Math.ceil(Math.log2(d))-1;m++){let f=new XS(u.shape,!1,o),g=f.getCustomSetupFunc(m),y=h;h=n.runWebGLProgram(f,[h],h.dtype,g),n.disposeIntermediateTensorInfo(y)}if(i){let m=new XS(u.shape,i,o),f=h;h=n.runWebGLProgram(m,[h],h.dtype),n.disposeIntermediateTensorInfo(f)}if(c!=null){let m=_.getUndoAxesPermutation(c),f=En({inputs:{x:h},backend:n,attrs:{perm:m}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),f}return h}var X7={kernelName:Us,backendName:"webgl",kernelFunc:K7};function Y7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=a;if(r.shape.length===1){let l=n.readSync(r.dataId),c=n.readSync(s.dataId),u=hS(l,c,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}else if(r.shape.length===2){let l=n.bufferSync(r),c=n.bufferSync(s),u=NK(l,c,i,o);return n.makeTensorInfo(u.shape,s.dtype,u.values)}throw new Error( ` Error in denseBincount : input must be at most rank 2 , but got rank$ { r . shape . length } . ` )}var J7={kernelName:qd,backendName:"webgl",kernelFunc:Y7},Z7=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int h = $ { this . getHeightCoordString ( ) } ;
int w = $ { this . getWidthCoordString ( ) } ;
int d = $ { this . getDepthCoordString ( ) } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
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 ) *
2020-12-15 14:15:43 +01:00
$ { this . getOutputDepthSize ( ) } ;
int in _d = d + offset _d ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float result = $ { this . getInputSamplingString ( ) } ;
setOutput ( result ) ;
}
2021-01-12 16:01:34 +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 Q7(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a;k.assert(s>1,()=> ` blockSize should be > 1 for depthToSpace , but was : $ { s } ` );let o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],c=i==="NHWC"?r.shape[2]:r.shape[3],u=i==="NHWC"?r.shape[3]:r.shape[1],p=l*s,d=c*s,h=u/(s*s),m=i==="NHWC"?[o,p,d,h]:[o,h,p,d],f=new Z7(m,s,i);return n.runWebGLProgram(f,[r],r.dtype)}var eJ={kernelName:Yo,backendName:"webgl",kernelFunc:Q7},YS=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.inHeight,i=e.inWidth,o=e.padInfo.top,l=e.padInfo.left,c=e.strideHeight,u=e.strideWidth,p=e.dilationHeight,d=e.dilationWidth,h=e.filterHeight,m=e.filterWidth,f=e.outChannels/e.inChannels,g="",y="";n&&(a?g= ` float activation ( float a ) {
2020-12-15 14:15:43 +01:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { n }
} ` :r?g= ` float activation ( float a ) {
2020-12-15 14:15:43 +01:00
float b = getLeakyreluAlphaAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { n }
} ` :g= `
2020-12-15 14:15:43 +01:00
float activation ( float x ) {
2021-01-12 16:01:34 +01:00
$ { n }
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` ,y="result = activation(result);");let b=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { g }
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
const ivec2 strides = ivec2 ( $ { c } , $ { u } ) ;
const ivec2 pads = ivec2 ( $ { o } , $ { l } ) ;
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int batch = coords . x ;
2020-10-11 18:41:17 +02:00
ivec2 xRCCorner = coords . yz * strides - pads ;
2020-12-15 14:15:43 +01:00
int d2 = coords . w ;
2021-01-12 16:01:34 +01:00
int d1 = d2 / $ { f } ;
int q = d2 - d1 * $ { f } ;
2020-12-15 14:15:43 +01:00
2020-10-11 18:41:17 +02:00
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2020-12-15 14:15:43 +01:00
// 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.
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { h } ; wR ++ ) {
int xR = xRCorner + wR * $ { p } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { s } ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { m } ; wC ++ ) {
int xC = xCCorner + wC * $ { d } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { i } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float xVal = getX ( batch , xR , xC , d1 ) ;
float wVal = getW ( wR , wC , d1 , q ) ;
dotProd += xVal * wVal ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float result = dotProd ;
2021-01-12 16:01:34 +01:00
$ { b }
$ { y }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }},JS=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;let s=e.inHeight,i=e.inWidth,o=e.padInfo.top,l=e.padInfo.left,c=e.strideHeight,u=e.strideWidth,p=e.dilationHeight,d=e.dilationWidth,h=e.filterHeight,m=e.filterWidth,f=m,g="int xR; int xC; int xCOffset;";for(let v=0;v<h;v++)for(let N=0;N<m;N++)g+= `
vec4 xTexelR$ { v } C$ { N * 2 } = vec4 ( 0. ) ;
vec4 wR$ { v } C$ { N } = vec4 ( 0. ) ;
vec4 xR$ { v } C$ { N } = vec4 ( 0. ) ; ` ;for(let v=0;v<h;v++)for(let N=0;N<f;N++){let T=N*2;if(g+= `
xR = xRCorner + $ { v * p } ;
xC = xCCorner + $ { T * d } ;
` ,u===1){if(T<m&&(l%2==1?g+= `
2020-12-15 14:15:43 +01:00
xCOffset = xC + 1 ;
2021-01-12 16:01:34 +01:00
if ( xR >= 0 && xR < $ { s } && xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { v } C$ { T } = getX ( batch , xR , xCOffset , d1 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2021-01-12 16:01:34 +01:00
if ( xCOffset + 1 >= $ { i } ) {
xTexelR$ { v } C$ { T } . zw = vec2 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { v } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
xCOffset = xC + 1 - 2 ;
2021-01-12 16:01:34 +01:00
if ( xR >= 0 && xR < $ { s } && xCOffset >= 0 && xCOffset < $ { i } ) {
2020-12-15 14:15:43 +01:00
vec4 previous = getX ( batch , xR , xCOffset , d1 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2021-01-12 16:01:34 +01:00
if ( xCOffset + 1 >= $ { i } ) {
2020-12-15 14:15:43 +01:00
previous . zw = vec2 ( 0. ) ;
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
xR$ { v } C$ { T } = vec4 ( previous . zw , xTexelR$ { v } C$ { T } . xy ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xR$ { v } C$ { T } = vec4 ( 0 , 0 , xTexelR$ { v } C$ { T } . xy ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` :g+= `
if ( xR >= 0 && xR < $ { s } && xC >= 0 && xC < $ { i } ) {
xTexelR$ { v } C$ { T } = getX ( batch , xR , xC , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { v } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
xR$ { v } C$ { T } = xTexelR$ { v } C$ { T } ;
` ,T+1<m)){let E=l%2==0?k.nearestLargerEven(d):d;d%2==0&&l%2==1||d%2!=0&&l%2!=1?(g+= `
xCOffset = xC + $ { l % 2 } + $ { E } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xR >= 0 && xR < $ { s } &&
xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { v } C$ { T + 2 } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ,d>1&&(g+= `
2020-12-15 14:15:43 +01:00
xCOffset -= 2 ;
2021-01-12 16:01:34 +01:00
if ( xR >= 0 && xR < $ { s } &&
xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { v } C$ { T } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { v } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ),g+= `
xR$ { v } C$ { T + 1 } = vec4 (
xTexelR$ { v } C$ { T } . zw , xTexelR$ { v } C$ { T + 2 } . xy ) ;
` ):g+= `
xCOffset = xC + $ { E } ;
if ( xR >= 0 && xR < $ { s } &&
xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { v } C$ { T + 2 } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
xR$ { v } C$ { T + 1 } = xTexelR$ { v } C$ { T + 2 } ;
` }}else T<m&&(g+= `
if ( xR >= 0 && xR < $ { s } ) {
` ,l%2==1?(g+= `
xCOffset = xC + 1 - $ { u } ;
if ( xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { v } C$ { T } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { v } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xC + 1 >= 0 && xC + 1 < $ { i } ) {
xTexelR$ { v } C$ { T + 2 } = getX ( batch , xR , xC + 1 , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { v } C$ { T + 2 } = vec4 ( 0. ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
xR$ { v } C$ { T } = vec4 (
xTexelR$ { v } C$ { T } . zw , xTexelR$ { v } C$ { T + 2 } . zw ) ;
` ,T+1<m&&(g+= `
2020-12-15 14:15:43 +01:00
vec4 final = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
xCOffset = xC + 1 + $ { u } ;
if ( xCOffset >= 0 && xCOffset < $ { i } ) {
2020-12-15 14:15:43 +01:00
final = getX ( batch , xR , xCOffset , d1 ) ;
}
2021-01-12 16:01:34 +01:00
xR$ { v } C$ { T + 1 } = vec4 ( xTexelR$ { v } C$ { T + 2 } . xy , final . xy ) ;
` )):(g+= `
if ( xC >= 0 && xC < $ { i } ) {
xTexelR$ { v } C$ { T } = getX ( batch , xR , xC , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { v } C$ { T } = vec4 ( 0. ) ;
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
xCOffset = xC + $ { u } ;
if ( xCOffset >= 0 && xCOffset < $ { i } ) {
xTexelR$ { v } C$ { T + 2 } = getX ( batch , xR , xCOffset , d1 ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
xTexelR$ { v } C$ { T + 2 } = vec4 ( 0. ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
xR$ { v } C$ { T } = vec4 (
xTexelR$ { v } C$ { T } . xy , xTexelR$ { v } C$ { T + 2 } . xy ) ;
` ,T+1<m&&(g+= `
xR$ { v } C$ { T + 1 } = vec4 (
xTexelR$ { v } C$ { T } . zw , xTexelR$ { v } C$ { T + 2 } . zw ) ;
` )),g+="}");T<m&&(g+= `
vec4 wTexelR$ { v } C$ { T } = getW ( $ { v } , $ { T } , d1 , q ) ;
wR$ { v } C$ { T } = vec4 ( wTexelR$ { v } C$ { T } . xz , wTexelR$ { v } C$ { T } . xz ) ;
` ,T+1<m&&(g+= `
vec4 wTexelR$ { v } C$ { T + 1 } = getW ( $ { v } , $ { T + 1 } , d1 , q ) ;
wR$ { v } C$ { T + 1 } =
vec4 ( wTexelR$ { v } C$ { T + 1 } . xz , wTexelR$ { v } C$ { T + 1 } . xz ) ; ` ))}for(let v=0;v<h;v++)for(let N=0;N<m;N++)g+= ` dotProd += xR$ { v } C$ { N } * wR$ { v } C$ { N } ; ` ;let y="",b="";n&&(a?y= ` vec4 activation ( vec4 a ) {
2020-12-15 14:15:43 +01:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { n }
} ` :r?y= ` vec4 activation ( vec4 a ) {
2020-12-15 14:15:43 +01:00
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
2021-01-12 16:01:34 +01:00
$ { n }
} ` :y= ` vec4 activation ( vec4 x ) {
$ { n }
} ` ,b="result = activation(result);");let x=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { y }
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
const ivec2 strides = ivec2 ( $ { c } , $ { u } ) ;
const ivec2 pads = ivec2 ( $ { o } , $ { l } ) ;
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
2020-10-11 18:41:17 +02:00
int batch = coords . x ;
2020-12-15 14:15:43 +01:00
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
int d1 = d2 ;
int q = 0 ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec4 dotProd = vec4 ( 0. ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { g }
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec4 result = dotProd ;
2021-01-12 16:01:34 +01:00
$ { x }
$ { b }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function tJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:c}=a,u=l;u==null&&(u=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(i,u),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { i } and dilations '${u}' ` );let p=_.computeConv2DInfo(r.shape,s.shape,i,u,o,c,!0),d;return ee().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?d=new JS(p):d=new YS(p),n.runWebGLProgram(d,[r,s],"float32")}var nJ={kernelName:Gs,backendName:"webgl",kernelFunc:tJ},aJ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int dm = coords . w ;
2021-01-12 16:01:34 +01:00
int d2 = d1 * $ { s } + dm ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float dotProd = 0.0 ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// TO DO: Vec4 over the batch size
2021-01-12 16:01:34 +01:00
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { t } - $ { a } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2021-01-12 16:01:34 +01:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { n } - $ { r } ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( b , yR , yC , d2 ) ;
float xValue = getX ( b , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
}
}
setOutput ( dotProd ) ;
}
2021-01-12 16:01:34 +01:00
` }},rJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode= `
const ivec2 pads = ivec2 ( $ { s } , $ { i } ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d1 = coords [ 3 ] ;
ivec2 dyCorner = coords . yz - pads ;
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float dotProd = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2020-12-15 14:15:43 +01:00
continue ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
int idyR = int ( dyR ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int wRPerm = $ { t } - 1 - wR ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { r } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int wCPerm = $ { n } - 1 - wC ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// TO DO: Vec4 over the channelMul
2021-01-12 16:01:34 +01:00
for ( int dm = 0 ; dm < $ { o } ; dm ++ ) {
int d2 = d1 * $ { o } + dm ;
2020-12-15 14:15:43 +01:00
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , dm ) ;
dotProd += xValue * wValue ;
}
}
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function sJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:c,filterShape:u}=a,p=_.computeConv2DInfo(r.shape,u,i,o,l,c,!0),d=new aJ(p);return n.runWebGLProgram(d,[r,s],"float32")}var iJ={kernelName:Kd,backendName:"webgl",kernelFunc:sJ};function oJ(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:c,inputShape:u}=a,p=_.computeConv2DInfo(u,s.shape,i,o,l,c,!0),d=new rJ(p);return n.runWebGLProgram(d,[r,s],"float32")}var lJ={kernelName:Xd,backendName:"webgl",kernelFunc:oJ},uJ=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 coords = getOutputCoords ( ) ;
float val = coords [ 0 ] == coords [ 1 ] ? getX ( coords [ 0 ] ) : 0.0 ;
setOutput ( val ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function cJ(e){let{inputs:t,backend:n}=e,{x:a}=t,r=[...a.shape,...a.shape],s=k.sizeFromShape(a.shape),i=xe({inputs:{x:a},backend:n,attrs:{shape:[s]}}),o=new uJ(s),l=n.runWebGLProgram(o,[i],i.dtype),c=xe({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var pJ={kernelName:Yd,backendName:"webgl",kernelFunc:cJ},dJ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:a,strideHeight:r,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:c}=e,{top:u,left:p}=a;this.userCode= `
const ivec2 strides = ivec2 ( $ { r } , $ { s } ) ;
const ivec2 pads = ivec2 ( $ { u } , $ { p } ) ;
2020-12-15 14:15:43 +01:00
const float neg _infinity = - 3.4 e38 ;
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int batch = coords . x ;
int d1 = coords . w ;
ivec2 outTopLeftCorner =
coords . yz * strides - pads ;
int hBeg = outTopLeftCorner . x ;
int wBeg = outTopLeftCorner . y ;
float curVal = neg _infinity ;
2021-01-12 16:01:34 +01:00
for ( int h = 0 ; h < $ { i } ; h ++ ) {
int hIn = hBeg + h * $ { l } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( hIn >= 0 && hIn < $ { t } ) {
for ( int w = 0 ; w < $ { o } ; w ++ ) {
int wIn = wBeg + w * $ { c } ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( wIn >= 0 && wIn < $ { n } ) {
2020-12-15 14:15:43 +01:00
float xVal = getX ( batch , hIn , wIn , d1 ) ;
float wVal = getW ( h , w , d1 ) ;
float val = xVal + wVal ;
if ( val > curVal ) {
curVal = val ;
}
}
}
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float result = curVal ;
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }};function hJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,c=_.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),u,p=new dJ(c);u=n.runWebGLProgram(p,[r,s],"float32");let d=xe({inputs:{x:u},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(u),d}var mJ={kernelName:yc,backendName:"webgl",kernelFunc:hJ},fJ="return (x >= 0.0) ? x : (exp(x) - 1.0);",gJ= `
2020-12-15 14:15:43 +01:00
vec4 result ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,yJ=Ye({opSnippet:fJ,packedOpSnippet:gJ}),bJ={kernelName:Jo,backendName:"webgl",kernelFunc:yJ},xJ="return (b >= 1.0) ? a : a * (b + 1.0);",vJ= `
2020-12-15 14:15:43 +01:00
vec4 bGTEZero = vec4 ( greaterThanEqual ( b , vec4 ( 0. ) ) ) ;
return ( bGTEZero * a ) + ( ( vec4 ( 1.0 ) - bGTEZero ) * ( a * ( b + vec4 ( 1.0 ) ) ) ) ;
2021-01-12 16:01:34 +01:00
` ,wJ=e=>{let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=ee().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Cp(vJ,a.shape,r.shape):new Tu(xJ,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)},kJ={kernelName:Qd,backendName:"webgl",kernelFunc:wJ},IJ= `
2020-12-15 14:15:43 +01:00
return vec4 ( equal ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,NJ="return float(a == b);",TJ=on({opSnippet:NJ,packedOpSnippet:IJ,dtype:"bool"}),SJ={kernelName:Qo,backendName:"webgl",kernelFunc:TJ},CJ= `
2020-12-15 14:15:43 +01:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2021-01-12 16:01:34 +01:00
float p = $ { _ . ERF _P } ;
float a1 = $ { _ . ERF _A1 } ;
float a2 = $ { _ . ERF _A2 } ;
float a3 = $ { _ . ERF _A3 } ;
float a4 = $ { _ . ERF _A4 } ;
float a5 = $ { _ . ERF _A5 } ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01: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 ) ) ;
2021-01-12 16:01:34 +01:00
` ,EJ=Ye({opSnippet:CJ}),_J={kernelName:Zo,backendName:"webgl",kernelFunc:EJ},ZS="return exp(x);",QS=Ye({opSnippet:ZS,packedOpSnippet:ZS,cpuKernelImpl:CK}),FJ={kernelName:js,backendName:"webgl",kernelFunc:QS};function tw(e){let{inputs:t,attrs:n,backend:a}=e,{dim:r}=n,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=r;return r<0&&(k.assert(-(i+1)<=r,()=> ` Axis must be in the interval [ $ { - ( i + 1 ) } , $ { i } ] ` ),l=i+r+1),o.splice(l,0,1),xe({inputs:{x:s},backend:a,attrs:{shape:o}})}var AJ={kernelName:el,backendName:"webgl",kernelFunc:tw},e2="return exp(x) - 1.0;", $ J=Ye({opSnippet:e2,packedOpSnippet:e2,cpuKernelImpl:EK}),DJ={kernelName:tl,backendName:"webgl",kernelFunc: $ J},t2=class{constructor(e,t,n){this.variableNames=["real","imag"];let a=t[1];this.outputShape=t;let r=n? ` 2.0 * $ { Math . PI } ` : ` - 2.0 * $ { Math . PI } ` ,s=n? ` $ { a } . 0 ` :"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error( ` FFT component must be either "real" or "imag" , got $ { e } . ` );this.userCode= `
const float exponentMultiplier = $ { r } ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float unaryOpComplex ( float real , float expR , float imag , float expI ) {
2021-01-12 16:01:34 +01:00
$ { i }
2020-12-15 14:15:43 +01:00
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float mulMatDFT ( int batch , int index ) {
2021-01-12 16:01:34 +01:00
float indexRatio = float ( index ) / float ( $ { a } ) ;
2020-12-15 14:15:43 +01:00
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float result = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { a } ; i ++ ) {
2020-12-15 14:15:43 +01: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 +=
2021-01-12 16:01:34 +01:00
unaryOpComplex ( real , expR , imag , expI ) / $ { s } ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
return result ;
2020-10-11 18:41:17 +02:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 coords = getOutputCoords ( ) ;
setOutput ( mulMatDFT ( coords [ 0 ] , coords [ 1 ] ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};function n2(e,t,n){let a=n.texData.get(e.dataId),r=k.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=r/s,o=xe({inputs:{x:e},backend:n,attrs:{shape:[i,s]}}).shape,l=new t2("real",o,t),c=new t2("imag",o,t),u=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:o},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:o}],p=n.runWebGLProgram(l,u,"float32"),d=n.runWebGLProgram(c,u,"float32"),h=bs({inputs:{real:p,imag:d},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d);let m=xe({inputs:{x:h},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(m),m}function MJ(e){let{inputs:t,backend:n}=e,{input:a}=t;return n2(a,!1,n)}var RJ={kernelName:eh,backendName:"webgl",kernelFunc:MJ},PJ=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float value ;
void main ( ) {
// Input can be obtained from uniform value.
setOutput ( value ) ;
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}};function nw(e){let{backend:t,attrs:n}=e,{shape:a,value:r}=n,{dtype:s}=n;if(s=s||k.inferDtype(r),s==="string"){let i=k.getArrayFromDType(s,k.sizeFromShape(a));return i.fill(r),t.makeTensorInfo(a,s,i)}else{let i=new PJ(a,r),o=i.getCustomSetupFunc(r);return t.runWebGLProgram(i,[],s,o)}}var OJ={kernelName:bc,backendName:"webgl",kernelFunc:nw},LJ=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int coordX = $ { t } - x ;
2020-12-15 14:15:43 +01:00
float outputValue ;
2021-01-12 16:01:34 +01:00
if ( coordX >= 0 && coordX < $ { t } ) {
2020-12-15 14:15:43 +01:00
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coordX , coords [ 3 ] ) ;
} else {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coords [ 2 ] , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2021-01-12 16:01:34 +01:00
` }},zJ={kernelName:nl,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,a=t,r=new LJ(n.shape);return a.runWebGLProgram(r,[n],n.dtype)}},a2="return floor(x);",BJ=Ye({opSnippet:a2,packedOpSnippet:a2,cpuKernelImpl:_K}),WJ={kernelName:qs,backendName:"webgl",kernelFunc:BJ},VJ= `
2020-12-15 14:15:43 +01: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-01-12 16:01:34 +01:00
` ,UJ= `
2020-12-15 14:15:43 +01: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 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if ( cond [ 0 ] ) {
result [ 0 ] = idiv ( ia [ 0 ] , ib [ 0 ] , s [ 0 ] ) ;
}
if ( cond [ 1 ] ) {
result [ 1 ] = idiv ( ia [ 1 ] , ib [ 1 ] , s [ 1 ] ) ;
}
if ( cond [ 2 ] ) {
result [ 2 ] = idiv ( ia [ 2 ] , ib [ 2 ] , s [ 2 ] ) ;
}
if ( cond [ 3 ] ) {
result [ 3 ] = idiv ( ia [ 3 ] , ib [ 3 ] , s [ 3 ] ) ;
}
return vec4 ( result ) ;
2021-01-12 16:01:34 +01:00
` ,GJ=on({opSnippet:VJ,packedOpSnippet:UJ,dtype:"int32"}),HJ={kernelName:Ks,backendName:"webgl",kernelFunc:GJ},jJ=class{constructor(e){this.variableNames=["A"];let t=gn(),[n,a]=e;this.outputShape=e,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
2021-01-12 16:01:34 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { a } . 0 , $ { n } . 0 ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
vec4 values = $ { t . texture2D } ( A , uv ) ;
2020-12-15 14:15:43 +01:00
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 ;
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
setOutput ( floor ( value * 255.0 + 0.5 ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},qJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=gn(),[n,a]=e;this.outputShape=e,this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
for ( int row = 0 ; row <= 1 ; row ++ ) {
for ( int col = 0 ; col <= 1 ; col ++ ) {
texC = coords [ 1 ] + row ;
depth = coords [ 2 ] + col ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
2021-01-12 16:01:34 +01:00
vec2 ( $ { a } . 0 , $ { n } . 0 ) ;
vec4 values = $ { t . texture2D } ( A , uv ) ;
2020-12-15 14:15:43 +01:00
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 ;
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
result [ row * 2 + col ] = floor ( value * 255.0 + 0.5 ) ;
}
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
$ { t . output } = result ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }},XJ={kernelName:mh,backendName:"webgl",kernelFunc:KJ},Cu;function KJ(e){let{inputs:t,backend:n,attrs:a}=e,{pixels:r}=t,{numChannels:s}=a,i=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,l=typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap,[c,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[u,c],d=[u,c,s];(o||i||l)&&(Cu==null&&(Cu=document.createElement("canvas").getContext("2d")),Cu.canvas.width=c,Cu.canvas.height=u,Cu.drawImage(r,0,0,c,u),r=Cu.canvas);let h=n.makeTensorInfo(p,"int32");n.texData.get(h.dataId).usage=ra.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(h.dataId),r);let m=ee().getBool("WEBGL_PACK")?new qJ(d):new jJ(d),f=n.runWebGLProgram(m,[h],"int32");return n.disposeData(h.dataId),f}function YJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dataFormat:u,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:m}=a,f=_.convertConv2DDataFormat(u),g=_.computeConv2DInfo(r.shape,s.shape,l,p,c,d,!1,f),y,b=[];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"))y=HS({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else if(ee().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)y=jS({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else{let v=i!=null,N=o!=null,T=h==="leakyrelu",E=h?of(h,!1):null,A=new GS(g,v,E,N,T), $ =[r,s];if(i&& $ .push(i),o&& $ .push(o),T){let O=n.makeTensorInfo([],"float32",k.createScalarValue(m,"float32")); $ .push(O),b.push(O)}y=n.runWebGLProgram(A, $ ,"float32")}let x=xe({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var JJ={kernelName:Si,backendName:"webgl",kernelFunc:YJ};function ZJ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:p,activation:d,leakyreluAlpha:h}=a,m=[],f=u;f==null&&(f=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(l,f),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { l } and dilations '${f}' ` );let g=_.computeConv2DInfo(r.shape,s.shape,l,f,c,p,!0),y=ee().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=d?of(d,y):null,x=[r,s],v=i!=null,N=o!=null,T=d==="leakyrelu";if(v&&x.push(i),N&&x.push(o),T){let $ =n.makeTensorInfo([],"float32",k.createScalarValue(h,"float32"));x.push( $ ),m.push( $ )}let E;y?E=new JS(g,v,b,N,T):E=new YS(g,v,b,N,T);let A=n.runWebGLProgram(E,x,"float32");return m.forEach( $ =>n.disposeIntermediateTensorInfo( $ )),A}var QJ={kernelName:Ci,backendName:"webgl",kernelFunc:ZJ},eZ=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let a=mt(t.length),r=mt(n.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode= `
$ { a } strides = $ { a } ( $ { this . strides } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { r } coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
int flattenIndex = 0 ;
for ( int j = 0 ; j < $ { this . sliceDim } ; j ++ ) {
int index = round ( getIndices ( coords [ 0 ] , j ) ) ;
2021-01-12 16:01:34 +01:00
flattenIndex += index * $ { s } ;
2020-12-15 14:15:43 +01:00
}
setOutput ( getX ( flattenIndex , coords [ 1 ] ) ) ;
}
2021-01-12 16:01:34 +01:00
` }};function tZ(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=r.shape,i=s[s.length-1],[o,l,c,u]=_.prepareAndValidate(a,r),p=xe({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),d=xe({inputs:{x:a},backend:n,attrs:{shape:[k.sizeFromShape(a.shape)/c,c]}}),h=new eZ(i,u,[l,c]),m=n.runWebGLProgram(h,[d,p],d.dtype),f=xe({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),f}var nZ={kernelName:rl,backendName:"webgl",kernelFunc:tZ},rZ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=mt(this.rank),a=aZ(e,2);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { n } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { a } ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function aZ(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let r=0;r<e.length;r++)r===2?a.push("int(getIndices(resRC.x, resRC.z))"):a.push( ` $ { n [ r ] } ` );return a.join()}function sZ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a,l=k.parseAxisParam(i,r.shape)[0],c=_.segment_util.collectGatherOpShapeInfo(r,s,l,o),u=k.sizeFromShape(s.shape),p=[],d=xe({inputs:{x:r},backend:n,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),h=xe({inputs:{x:s},backend:n,attrs:{shape:[c.batchSize,u/c.batchSize]}});p.push(d),p.push(h);let m=[c.batchSize,c.outerSize,u/c.batchSize,c.sliceSize];if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.bufferSync(h),x=n.bufferSync(d),v=FK(x,b,m);return p.forEach(N=>n.disposeIntermediateTensorInfo(N)),n.makeTensorInfo(c.outputShape,v.dtype,v.values)}let f=new rZ(d.shape,m),g=n.runWebGLProgram(f,[d,h],d.dtype);p.push(g);let y=xe({inputs:{x:g},backend:n,attrs:{shape:c.outputShape}});return p.forEach(b=>n.disposeIntermediateTensorInfo(b)),y}var iZ={kernelName:al,backendName:"webgl",kernelFunc:sZ},oZ="return float(a > b);",lZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( greaterThan ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,uZ=on({opSnippet:oZ,packedOpSnippet:lZ,cpuKernelImpl:AK,dtype:"bool"}),cZ={kernelName:sl,backendName:"webgl",kernelFunc:uZ},pZ="return float(a >= b);",dZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( greaterThanEqual ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,hZ=on({opSnippet:pZ,packedOpSnippet:dZ,dtype:"bool"}),mZ={kernelName:Ys,backendName:"webgl",kernelFunc:hZ};function fZ(e){let{inputs:t,backend:n}=e,{input:a}=t;return n2(a,!0,n)}var gZ={kernelName:th,backendName:"webgl",kernelFunc:fZ},yZ="return float(!isnan(x) && !isinf(x));",bZ=Ye({opSnippet:yZ,dtype:"bool"}),xZ={kernelName:ol,backendName:"webgl",kernelFunc:bZ},vZ="return float(isinf(x));",wZ=Ye({opSnippet:vZ,dtype:"bool"}),kZ={kernelName:ll,backendName:"webgl",kernelFunc:wZ},IZ="return float(isnan(x));",NZ=Ye({opSnippet:IZ,dtype:"bool"}),TZ={kernelName:ul,backendName:"webgl",kernelFunc:NZ},SZ="return float(a < b);",CZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( lessThan ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` ,EZ=on({opSnippet:SZ,packedOpSnippet:CZ,cpuKernelImpl: $ K,dtype:"bool"}),_Z={kernelName:cl,backendName:"webgl",kernelFunc:EZ},FZ="return float(a <= b);",AZ= `
2020-12-15 14:15:43 +01:00
return vec4 ( lessThanEqual ( a , b ) ) ;
2021-01-12 16:01:34 +01:00
` , $ Z=on({opSnippet:FZ,packedOpSnippet:AZ,dtype:"bool"}),DZ={kernelName:pl,backendName:"webgl",kernelFunc: $ Z};function MZ(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=DK(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var RZ={kernelName:ah,backendName:"webgl",kernelFunc:MZ},PZ= ` if ( x < 0.0 ) return NAN ;
return log ( x ) ; ` ,OZ= `
2020-12-15 14:15:43 +01:00
vec4 result = log ( x ) ;
vec4 isNaN = vec4 ( lessThan ( x , vec4 ( 0.0 ) ) ) ;
result . r = isNaN . r == 1.0 ? NAN : result . r ;
result . g = isNaN . g == 1.0 ? NAN : result . g ;
result . b = isNaN . b == 1.0 ? NAN : result . b ;
result . a = isNaN . a == 1.0 ? NAN : result . a ;
return result ;
2021-01-12 16:01:34 +01:00
` ,LZ=Ye({opSnippet:PZ,packedOpSnippet:OZ,cpuKernelImpl:MK}),zZ={kernelName:Zs,backendName:"webgl",kernelFunc:LZ},BZ="return log(1.0 + x);",WZ=Ye({opSnippet:BZ}),VZ={kernelName:dl,backendName:"webgl",kernelFunc:WZ},UZ="return float(a >= 1.0 && b >= 1.0);",GZ= `
2020-12-15 14:15:43 +01:00
return vec4 (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) *
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ) ;
2021-01-12 16:01:34 +01:00
` ,HZ=on({opSnippet:UZ,packedOpSnippet:GZ,dtype:"bool"}),jZ={kernelName:hl,backendName:"webgl",kernelFunc:HZ},qZ="return float(!(x >= 1.0));",KZ=Ye({opSnippet:qZ}),XZ={kernelName:xc,backendName:"webgl",kernelFunc:KZ},YZ="return float(a >= 1.0 || b >= 1.0);",JZ= `
2020-12-15 14:15:43 +01:00
return min (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) +
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ,
vec4 ( 1.0 ) ) ;
2021-01-12 16:01:34 +01:00
` ,ZZ=on({opSnippet:YZ,packedOpSnippet:JZ,dtype:"bool"}),QZ={kernelName:vc,backendName:"webgl",kernelFunc:ZZ},e9=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l= ` float ( $ { n } ) + float ( $ { a } ) * sum ` ;r===.5?o= ` inversesqrt ( $ { l } ) ` :r===1?o= ` 1.0 / ( $ { l } ) ` :o= ` exp ( log ( $ { l } ) * float ( - $ { r } ) ) ; ` ,this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-12-15 14:15:43 +01:00
int d = coords [ 3 ] ;
float x = getX ( b , r , c , d ) ;
float sum = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int j = - $ { s } ; j <= $ { s } ; j ++ ) {
2020-12-15 14:15:43 +01:00
int idx = d + j ;
2021-01-12 16:01:34 +01:00
if ( idx >= 0 && idx <= $ { i } ) {
2020-12-15 14:15:43 +01:00
float z = getX ( b , r , c , idx ) ;
sum += z * z ;
}
}
2021-01-12 16:01:34 +01:00
float val = x * $ { o } ;
2020-12-15 14:15:43 +01:00
setOutput ( val ) ;
}
2021-01-12 16:01:34 +01:00
` }},t9=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=t,i=e[3]-1;this.outputShape=e;let o,l= ` float ( $ { n } ) + float ( $ { a } ) * sum ` ;r===.5?o= ` inversesqrt ( $ { l } ) ` :r===1?o= ` 1.0 / ( $ { l } ) ` :o= ` exp ( log ( $ { l } ) * float ( - $ { r } ) ) ; ` ,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords . x ;
int r = coords . y ;
int c = coords . z ;
int d = coords . w ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
bool hasNextCol = d < $ { this . outputShape [ 3 ] } ;
bool hasNextRow = c < $ { this . outputShape [ 2 ] } ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
vec4 sum = vec4 ( 0. ) ;
vec4 xFragAtOutputCoords = getX ( b , r , c , d ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
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
) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
int firstChannel = d - $ { s } ;
2020-12-15 14:15:43 +01: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 ) ) ;
}
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec2 depth = ivec2 ( d , d + 1 ) ;
2021-01-12 16:01:34 +01:00
for ( int j = - $ { s } ; j <= $ { s } ; j ++ ) {
2020-12-15 14:15:43 +01:00
ivec2 idx = depth + j ;
bvec2 aboveLowerBound = greaterThanEqual ( idx , ivec2 ( 0 ) ) ;
2021-01-12 16:01:34 +01:00
bvec2 belowUpperBound = lessThanEqual ( idx , ivec2 ( $ { i } ) ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
bool depthInRange = aboveLowerBound . x && belowUpperBound . x ;
bool depthPlusOneInRange = aboveLowerBound . y && belowUpperBound . y ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
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 ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
vec4 result = xAtOutputCoords * $ { o } ;
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }},n9=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,c=ee().getBool("WEBGL_PACK_NORMALIZATION")?new t9(r.shape,s,i,o,l):new e9(r.shape,s,i,o,l);return n.runWebGLProgram(c,[r],r.dtype)},a9={kernelName:wc,backendName:"webgl",kernelFunc:n9},r9=class{constructor(e,t,n,a,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=a,this.beta=r,this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float result = 0.0 ;
for ( int d = 0 ; d < $ { this . depth } ; ++ d ) {
2021-01-12 16:01:34 +01:00
int depthBegin = int ( max ( 0.0 , float ( d - $ { t } ) ) ) ;
2020-12-15 14:15:43 +01:00
int depthEnd = int ( min ( float ( $ { this . depth } ) ,
2021-01-12 16:01:34 +01:00
float ( d + $ { t } + 1 ) ) ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
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 ) {
2020-10-11 18:41:17 +02:00
continue ;
}
2020-12-15 14:15:43 +01:00
else if ( k >= depthBegin && k < depthEnd ) {
norm += getInputImage ( b , r , c , k ) * getInputImage ( b , r , c , k ) ;
}
else {
break ;
}
}
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
norm = float ( $ { a } ) * norm + float ( $ { n } ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
2021-01-12 16:01:34 +01:00
float dyi = - 2.0 * float ( $ { a } )
* float ( $ { r } )
2020-12-15 14:15:43 +01:00
* getInputImage ( b , r , c , k ) * getOutputImage ( b , r , c , d )
/ n o r m ;
if ( k == d ) {
2021-01-12 16:01:34 +01:00
dyi += pow ( norm , - 1.0 * $ { r } ) ;
2020-12-15 14:15:43 +01:00
}
if ( k == coords [ 3 ] ) {
dyi *= getDy ( b , r , c , d ) ;
result += dyi ;
}
}
else {
break ;
2020-10-11 18:41:17 +02:00
}
}
}
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }},s9=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:c,beta:u}=a,p=new r9(r.shape,o,l,c,u);return n.runWebGLProgram(p,[r,s,i],r.dtype)},i9={kernelName:rh,backendName:"webgl",kernelFunc:s9};function o9(e,t,n,a){let r=k.sizeFromShape(t),s=k.sizeFromShape(e.shape)/r,i=xe({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=eo(i,e.dtype,"max",a),l=xe({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function r2(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=r.shape.length,l=k.parseAxisParam(s,r.shape),c=l,u=_.getAxesPermutation(c,o),p=u!=null,d=n.shouldExecuteOnCPU([r]),h=r;if(p){if(d){let b=n.texData.get(h.dataId).values,x=new Array(o);for(let T=0;T<x.length;T++)x[T]=r.shape[u[T]];let v=Xv(b,r.shape,r.dtype,u,x);h=n.makeTensorInfo(x,r.dtype);let N=n.texData.get(h.dataId);N.values=v}else h=lf(r,u,n);c=_.getInnerMostAxes(c.length,o)}_.assertAxesAreInnerMostDims("max",c,o);let[m,f]=_.computeOutAndReduceShapes(h.shape,c),g=m;i&&(g=_.expandShapeToKeepDim(m,l));let y;if(d){let b=n.texData.get(h.dataId).values,x=RK(b,k.sizeFromShape(f),g,r.dtype);y=n.makeTensorInfo(g,r.dtype);let v=n.texData.get(y.dataId);v.values=x}else y=o9(h,f,g,n);return p&&n.disposeIntermediateTensorInfo(h),y}var l9={kernelName:Qs,backendName:"webgl",kernelFunc:r2},u9=wS+ `
2020-12-15 14:15:43 +01:00
return max ( a , b ) ;
2021-01-12 16:01:34 +01:00
` ,c9= `
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( max ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-01-12 16:01:34 +01:00
` +sf+ `
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,p9=on({opSnippet:u9,packedOpSnippet:c9,cpuKernelImpl:PK}),d9={kernelName:ei,backendName:"webgl",kernelFunc:p9};function h9(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;Tp(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,c=1;k.assert(_.eitherStridesOrDilationsAreOne(i,c),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { i } and dilations '${c}' ` );let u=_.computePool2DInfo(r.shape,s,i,c,o,l);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return Wn({inputs:{x:r},backend:n});let p=new Ep(u,"max",!1);return n.runWebGLProgram(p,[r],r.dtype)}var m9={kernelName:ti,backendName:"webgl",kernelFunc:h9};function f9(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:c}=a,u=[1,1,1],p=_.computePool3DInfo(r.shape,s,i,u,o,c,l),d=new Zv(p,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var g9={kernelName:kc,backendName:"webgl",kernelFunc:f9},y9=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,a=e.dilationHeight,r=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=s-1-e.padInfo.left,l=r*s-1;this.userCode= `
const ivec2 pads = ivec2 ( $ { i } , $ { o } ) ;
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
2020-12-15 14:15:43 +01:00
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// 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 ;
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { r } ;
wR += $ { a } ) {
float dyR = float ( dyRCorner + wR ) / $ { t } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2020-12-15 14:15:43 +01:00
continue ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
int idyR = int ( dyR ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { s } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { n } . 0 ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
int idyC = int ( dyC ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( b , idyR , idyC , d ) ;
2021-01-12 16:01:34 +01:00
int maxPosValue = $ { l } - int ( getMaxPos ( b , idyR , idyC , d ) ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Get the current value, check it against the value from the
// position matrix.
2021-01-12 16:01:34 +01:00
int curPosValue = wR * $ { s } + wC ;
2020-12-15 14:15:43 +01:00
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
dotProd += dyValue * mask ;
}
}
setOutput ( dotProd ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }},b9=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=o-1-e.padInfo.front,p=l-1-e.padInfo.top,d=c-1-e.padInfo.left,h=o*l*c-1;this.userCode= `
const ivec3 pads = ivec3 ( $ { u } , $ { p } , $ { d } ) ;
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// 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 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wD = 0 ; wD < $ { o } ;
wD += $ { r } ) {
float dyD = float ( dyDCorner + wD ) / $ { t } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
2020-12-15 14:15:43 +01:00
continue ;
}
int idyD = int ( dyD ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wR = 0 ; wR < $ { l } ;
wR += $ { s } ) {
float dyR = float ( dyRCorner + wR ) / $ { n } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int wC = 0 ; wC < $ { c } ;
wC += $ { i } ) {
float dyC = float ( dyCCorner + wC ) / $ { a } . 0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2020-12-15 14:15:43 +01:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
2021-01-12 16:01:34 +01:00
int maxPosValue = $ { h } -
2020-12-15 14:15:43 +01:00
int ( getMaxPos ( batch , idyD , idyR , idyC , ch ) ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
2021-01-12 16:01:34 +01:00
wD * $ { l } * $ { c } +
wR * $ { c } + wC ;
2020-12-15 14:15:43 +01:00
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
dotProd += dyValue * mask ;
}
}
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
setOutput ( dotProd ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function x9(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:c,dimRoundingMode:u}=a,p=[1,1,1],d=_.computePool3DInfo(i.shape,o,l,p,c,u),h=new Zv(d,"max",!0),m=n.runWebGLProgram(h,[i],i.dtype),f=new b9(d),g=n.runWebGLProgram(f,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),g}var v9={kernelName:ih,backendName:"webgl",kernelFunc:x9};function w9(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;Tp([s,i],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:p}=a,d=_.computePool2DInfo(o.shape,l,c,1,u,p),h=!0,m=new Ep(d,"max",h),f=n.runWebGLProgram(m,[o],o.dtype),g=new y9(d),y=n.runWebGLProgram(g,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),y}var k9={kernelName:sh,backendName:"webgl",kernelFunc:w9};function I9(e,t,n,a){let r=new Ep(n,"max",!1),s=a.runWebGLProgram(r,[e],"float32");r=new Ep(n,"max",!0,!0,t);let i=a.runWebGLProgram(r,[e],"float32");return[s,i]}var N9={kernelName:oh,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;k.assert(a.shape.length===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { a . shape . length } . ` );let c=[1,1];k.assert(_.eitherStridesOrDilationsAreOne(s,c),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { s } and dilations '${c}' ` );let u=_.computePool2DInfo(a.shape,r,s,c,i),[p,d]=I9(a,o,u,l);return[p,d]}};function T9(e,t,n,a){let r=k.sizeFromShape(t),s=k.sizeFromShape(e.shape)/r,i=xe({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=eo(i,"float32","mean",a),l=xe({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var S9={kernelName:ni,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{keepDims:r,axis:s}=t,i=n,o=a.shape.length,l=k.parseAxisParam(s,a.shape),c=l,u=_.getAxesPermutation(c,o),p=u!=null,d=i.shouldExecuteOnCPU([a]),h=[],m=a;if(p){if(d){let x=i.texData.get(m.dataId).values,v=new Array(o);for(let E=0;E<v.length;E++)v[E]=a.shape[u[E]];let N=Xv(x,a.shape,a.dtype,u,v);m=i.makeTensorInfo(v,a.dtype);let T=i.texData.get(m.dataId);T.values=N}else m=lf(a,u,i);h.push(m),c=_.getInnerMostAxes(c.length,o)}_.assertAxesAreInnerMostDims("sum",c,o);let[f,g]=_.computeOutAndReduceShapes(m.shape,c),y=f;r&&(y=_.expandShapeToKeepDim(f,l));let b=T9(m,g,y,i);for(let x of h)i.disposeIntermediateTensorInfo(x);return b}};function C9(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=k.parseAxisParam(s,r.shape),c=l,u=_.getAxesPermutation(c,o),p=r;u!=null&&(p=En({inputs:{x:r},backend:n,attrs:{perm:u}}),c=_.getInnerMostAxes(c.length,r.shape.length)),_.assertAxesAreInnerMostDims("min",c,o);let[d,h]=_.computeOutAndReduceShapes(p.shape,c),m=k.sizeFromShape(h),f=xe({inputs:{x:p},backend:n,attrs:{shape:[-1,m]}}),g=eo(f,f.dtype,"min",n),y;if(i){let b=_.expandShapeToKeepDim(d,l);y=xe({inputs:{x:g},backend:n,attrs:{shape:b}})}else y=xe({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(p),y}var E9={kernelName:ai,backendName:"webgl",kernelFunc:C9},_9=wS+ `
2020-12-15 14:15:43 +01:00
return min ( a , b ) ;
2021-01-12 16:01:34 +01:00
` ,F9= `
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( min ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-01-12 16:01:34 +01:00
` +sf+ `
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,A9=on({opSnippet:_9,packedOpSnippet:F9,cpuKernelImpl:OK}), $ 9={kernelName:ri,backendName:"webgl",kernelFunc:A9},D9=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((c,u)=>c[0]+e[u]+c[1]);let a=e.length,r=mt(a),s=t.map(c=>c[0]).join(","),i=t.map((c,u)=>c[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a),l=n==="reflect"?0:1;if(a===1){this.userCode= `
int start = $ { s } ;
int end = $ { i } ;
2020-12-15 14:15:43 +01:00
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start ) {
2021-01-12 16:01:34 +01:00
outC = start * 2 - outC - $ { l } ;
2020-12-15 14:15:43 +01:00
} else if ( outC >= end ) {
2021-01-12 16:01:34 +01:00
outC = ( end - 1 ) * 2 - outC + $ { l } ;
2020-12-15 14:15:43 +01:00
}
setOutput ( getX ( outC - start ) ) ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
` ;return}this.userCode= `
2021-01-12 16:01:34 +01:00
$ { r } start = $ { r } ( $ { s } ) ;
$ { r } end = $ { r } ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
2020-12-02 22:46:41 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { r } outC = getOutputCoords ( ) ;
for ( int i = 0 ; i < $ { a } ; i ++ ) {
2020-12-15 14:15:43 +01:00
if ( outC [ i ] < start [ i ] ) {
2021-01-12 16:01:34 +01:00
outC [ i ] = start [ i ] * 2 - outC [ i ] - $ { l } ;
2020-12-15 14:15:43 +01:00
} else if ( outC [ i ] >= end [ i ] ) {
2021-01-12 16:01:34 +01:00
outC [ i ] = ( end [ i ] - 1 ) * 2 - outC [ i ] + $ { l } ;
2020-12-15 14:15:43 +01:00
}
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
$ { r } coords = outC - start ;
setOutput ( getX ( $ { o } ) ) ;
2020-12-02 22:46:41 +01:00
}
2021-01-12 16:01:34 +01:00
` }},M9=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,m)=>h[0]+e[m]+h[1]);let a=e.length,r=mt(a),s=t.map(h=>h[0]).join(","),i=t.map((h,m)=>h[0]+e[m]).join(","),o=yn("rc",a),l=yn("source",a),c= ` $ { o [ a - 1 ] } < $ { this . outputShape [ a - 1 ] } ` ,u=a===1?"source": ` vec2 ( $ { l . slice ( - 2 ) . join ( ) } ) ` ,p=n==="reflect"?0:1,d="";if(a===1){let h= `
$ { r } source = rc ;
2020-12-15 14:15:43 +01:00
if ( source < start ) {
2021-01-12 16:01:34 +01:00
source = start * 2 - source - $ { p } ;
2020-12-15 14:15:43 +01:00
} else if ( source >= end ) {
2021-01-12 16:01:34 +01:00
source = ( end - 1 ) * 2 - source + $ { p } ;
2020-12-15 14:15:43 +01:00
}
source -= start ;
2021-01-12 16:01:34 +01:00
` ;d= `
$ { r } rc = outputLoc ;
$ { h }
result [ 0 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { u } ) ;
$ { o [ a - 1 ] } += 1 ;
if ( $ { c } ) {
$ { h }
result [ 1 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { u } ) ;
}
` }else{let h= `
$ { r } source = rc ;
$ { r } lt = $ { r } ( lessThan ( source , start ) ) ;
$ { r } gte = $ { r } ( greaterThanEqual ( source , end ) ) ;
$ { r } orig = 1 - ( lt + gte ) ;
2020-12-15 14:15:43 +01:00
source = orig * source +
2021-01-12 16:01:34 +01:00
lt * ( start * 2 - source - $ { p } ) +
gte * ( ( end - 1 ) * 2 - source + $ { p } ) ;
2020-12-15 14:15:43 +01:00
source -= start ;
2021-01-12 16:01:34 +01:00
` ;d= `
$ { r } rc = outputLoc ;
$ { h }
result [ 0 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { u } ) ;
$ { o [ a - 1 ] } += 1 ;
if ( $ { c } ) {
$ { h }
result [ 1 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { u } ) ;
2020-12-15 14:15:43 +01:00
}
rc = outputLoc ;
2021-01-12 16:01:34 +01:00
$ { o [ a - 2 ] } += 1 ;
if ( $ { o [ a - 2 ] } < $ { this . outputShape [ a - 2 ] } ) {
$ { h }
result [ 2 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { u } ) ;
$ { o [ a - 1 ] } += 1 ;
if ( $ { c } ) {
$ { h }
result [ 3 ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { u } ) ;
2020-12-15 14:15:43 +01:00
}
}
` }this.userCode= `
2021-01-12 16:01:34 +01:00
const $ { r } start = $ { r } ( $ { s } ) ;
const $ { r } end = $ { r } ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
2020-10-11 18:41:17 +02:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { r } outputLoc = getOutputCoords ( ) ;
2020-10-11 18:41:17 +02:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
$ { d }
2020-10-11 18:41:17 +02:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }},R9=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{paddings:r,mode:s}=n,i=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new M9(a.shape,r,s):new D9(a.shape,r,s);return t.runWebGLProgram(i,[a],a.dtype)},P9={kernelName:Ic,backendName:"webgl",kernelFunc:R9},O9= ` if ( b == 0.0 ) return NAN ;
return mod ( a , b ) ; ` ,L9= `
2020-12-15 14:15:43 +01:00
vec4 result = mod ( a , b ) ;
vec4 isNaN = vec4 ( equal ( b , vec4 ( 0.0 ) ) ) ;
2021-01-12 16:01:34 +01:00
` +sf+ `
2020-12-15 14:15:43 +01:00
return result ;
2021-01-12 16:01:34 +01:00
` ,z9=on({opSnippet:O9,packedOpSnippet:L9}),B9={kernelName:ml,backendName:"webgl",kernelFunc:z9},W9=class{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode= `
2020-12-15 14:15:43 +01:00
uniform float seed ;
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float r = random ( seed ) ;
float cdf = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { t - 1 } ; i ++ ) {
2020-12-15 14:15:43 +01:00
cdf += getProbs ( batch , i ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
if ( r < cdf ) {
setOutput ( float ( i ) ) ;
return ;
}
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// If no other event happened, last event happened.
2021-01-12 16:01:34 +01:00
setOutput ( float ( $ { t - 1 } ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }getCustomSetupFunc(e){return(t,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}},V9= `
2020-12-15 14:15:43 +01:00
if ( a == b ) {
return 1.0 ;
} ;
2021-01-12 16:01:34 +01:00
return a / b ; ` ,U9= `
2020-12-15 14:15:43 +01: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. ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
if ( a . y == b . y ) {
result . y = 1. ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
if ( a . z == b . z ) {
result . z = 1. ;
}
if ( a . w == b . w ) {
result . w = 1. ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
2020-10-11 18:41:17 +02:00
return result ;
2021-01-12 16:01:34 +01:00
` ,s2=on({opSnippet:V9,packedOpSnippet:U9,checkOutOfBounds:!0}),G9={kernelName:Hs,backendName:"webgl",kernelFunc:s2},i2="return a - b;",o2=on({opSnippet:i2,packedOpSnippet:i2,supportsComplex:!0,cpuKernelImpl:HK}),H9={kernelName:ki,backendName:"webgl",kernelFunc:o2};function l2(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=k.parseAxisParam([s],r.shape),o=r2({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=_.expandShapeToKeepDim(o.shape,i),c=xe({inputs:{x:o},backend:n,attrs:{shape:l}}),u=o2({inputs:{a:r,b:c},backend:n}),p=QS({inputs:{x:u},backend:n}),d=Jv({inputs:{x:p},backend:n,attrs:{axis:i,keepDims:!1}}),h=xe({inputs:{x:d},backend:n,attrs:{shape:l}}),m=s2({inputs:{a:p,b:h},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),m}var j9={kernelName:vi,backendName:"webgl",kernelFunc:l2};function q9(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?r:l2({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),c=l.shape[0],u=l.shape[1],p=new W9(c,u,s),d=p.getCustomSetupFunc(i),h=n.runWebGLProgram(p,[l],"int32",d);return o||n.disposeIntermediateTensorInfo(l),h}var K9={kernelName:lh,backendName:"webgl",kernelFunc:q9},u2="return -x;";function X9(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){let s=n.texData.get(a.dataId),[i,o]=zK(s.values,a.shape,a.dtype);return n.makeTensorInfo(o,a.dtype,i)}let r;return ee().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Nu(a.shape,u2):r=new ys(a.shape,u2),n.runWebGLProgram(r,[a],a.dtype)}var Y9={kernelName:fl,backendName:"webgl",kernelFunc:X9},J9=Qa.nonMaxSuppressionV3Impl;function Z9(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a,c=n.readSync(r.dataId),u=n.readSync(s.dataId),{selectedIndices:p}=J9(c,u,i,o,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var Q9={kernelName:yl,backendName:"webgl",kernelFunc:Z9},eQ=Qa.nonMaxSuppressionV4Impl;function tQ(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:c}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),{selectedIndices:d,validOutputs:h}=eQ(u,p,i,o,l,c);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var nQ={kernelName:bl,backendName:"webgl",kernelFunc:tQ},aQ=Qa.nonMaxSuppressionV5Impl;function rQ(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:c}=a,u=n.readSync(r.dataId),p=n.readSync(s.dataId),d=i,h=o,m=l,f=c,{selectedIndices:g,selectedScores:y}=aQ(u,p,d,h,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var sQ={kernelName:xl,backendName:"webgl",kernelFunc:rQ},iQ=class{constructor(e,t,n,a){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int index = round ( getIndices ( coords . x ) ) ;
2021-01-12 16:01:34 +01:00
setOutput ( mix ( float ( $ { a } ) , float ( $ { n } ) ,
2020-12-15 14:15:43 +01:00
float ( index == coords . y ) ) ) ;
}
2021-01-12 16:01:34 +01:00
` }},oQ=e=>{let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a,l=k.sizeFromShape(r.shape),c=new iQ(l,s,i,o),u=xe({inputs:{x:r},backend:n,attrs:{shape:[l]}}),p=n.runWebGLProgram(c,[u],r.dtype);n.disposeIntermediateTensorInfo(u);let d=[...r.shape,s],h=xe({inputs:{x:p},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(p),h},lQ={kernelName:ii,backendName:"webgl",kernelFunc:oQ};function hf(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="complex64"){let r=Fp({inputs:{input:a},backend:n}),s=hf({inputs:{x:r},backend:n}),i=df({inputs:{input:a},backend:n}),o=hf({inputs:{x:i},backend:n}),l=bs({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return nw({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:n})}var uQ={kernelName:Ol,backendName:"webgl",kernelFunc:hf};function c2(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(a.dtype==="complex64"){let r=Fp({inputs:{input:a},backend:n}),s=c2({inputs:{x:r},backend:n}),i=df({inputs:{input:a},backend:n}),o=hf({inputs:{x:i},backend:n}),l=bs({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return nw({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:n})}var cQ={kernelName:vl,backendName:"webgl",kernelFunc:c2};function pQ(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return tw({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{k.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=tw({inputs:{input:u},backend:n,attrs:{dim:r}});return o.push(p),p}),c=US({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var dQ={kernelName:wl,backendName:"webgl",kernelFunc:pQ},hQ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);let a=e.length,r=mt(a),s=t.map(l=>l[0]).join(","),i=t.map((l,c)=>l[0]+e[c]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a);if(a===1){this.userCode= `
int start = $ { s } ;
int end = $ { i } ;
2020-12-15 14:15:43 +01:00
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start || outC >= end ) {
2021-01-12 16:01:34 +01:00
setOutput ( float ( $ { n } ) ) ;
2020-12-15 14:15:43 +01:00
} else {
setOutput ( getX ( outC - start ) ) ;
}
}
` ;return}this.userCode= `
2021-01-12 16:01:34 +01:00
$ { r } start = $ { r } ( $ { s } ) ;
$ { r } end = $ { r } ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { r } outC = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
if ( any ( lessThan ( outC , start ) ) || any ( greaterThanEqual ( outC , end ) ) ) {
2021-01-12 16:01:34 +01:00
setOutput ( float ( $ { n } ) ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
$ { r } coords = outC - start ;
setOutput ( getX ( $ { o } ) ) ;
2020-12-15 14:15:43 +01:00
}
}
2021-01-12 16:01:34 +01:00
` }},mQ=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);let a=e.length,r=mt(a),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=yn("rc",a),l=yn("source",a),c= ` $ { o [ a - 1 ] } < $ { this . outputShape [ a - 1 ] } ` ,u=a===1?"source": ` vec2 ( $ { l . slice ( - 2 ) . join ( ) } ) ` ,p=[ ` $ { r } rc = outputLoc ; ` , ` $ { o [ a - 1 ] } += 1 ;
if ( $ { c } ) {
` ,a===1?"": ` }
2020-12-15 14:15:43 +01:00
rc = outputLoc ;
2021-01-12 16:01:34 +01:00
$ { o [ a - 2 ] } += 1 ;
if ( $ { o [ a - 2 ] } < $ { this . outputShape [ a - 2 ] } ) { ` ,a===1?"": ` $ { o [ a - 1 ] } += 1 ;
if ( $ { c } ) { ` ],d=a===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let m=0,f=a===1?2:4;m<f;m++)h+= `
$ { p [ m ] }
if ( $ { d } ) {
result [ $ { m } ] = float ( $ { n } ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
$ { r } source = rc - start ;
result [ $ { m } ] = getChannel ( getX ( $ { l . join ( ) } ) , $ { u } ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ;h+=a===1?"} ":"}}",this.userCode= `
const $ { r } start = $ { r } ( $ { s } ) ;
const $ { r } end = $ { r } ( $ { i } ) ;
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { r } outputLoc = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
$ { h }
2020-12-15 14:15:43 +01:00
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` }},p2=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a,o=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new mQ(r.shape,s,i):new hQ(r.shape,s,i);return n.runWebGLProgram(o,[r],r.dtype)},fQ={kernelName:oi,backendName:"webgl",kernelFunc:p2},gQ= `
2020-12-15 14:15:43 +01:00
if ( a < 0.0 && floor ( b ) < b ) {
2020-10-11 18:41:17 +02:00
return NAN ;
}
2020-12-15 14:15:43 +01:00
if ( b == 0.0 ) {
return 1.0 ;
2020-10-11 18:41:17 +02:00
}
2020-12-15 14:15:43 +01:00
return ( round ( mod ( b , 2.0 ) ) != 1 ) ?
pow ( abs ( a ) , b ) : sign ( a ) * pow ( abs ( a ) , b ) ;
2021-01-12 16:01:34 +01:00
` ,yQ= `
2020-12-15 14:15:43 +01: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 ) ;
// 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
2020-12-15 14:15:43 +01:00
vec4 isNaN = vec4 ( lessThan ( a , vec4 ( 0.0 ) ) ) * vec4 ( lessThan ( floor ( b ) , b ) ) ;
2021-01-12 16:01:34 +01:00
` +sf+ `
2020-10-11 18:41:17 +02:00
return result ;
2021-01-12 16:01:34 +01:00
` ,bQ=on({opSnippet:gQ,packedOpSnippet:yQ}),xQ={kernelName:li,backendName:"webgl",kernelFunc:bQ};function vQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=[],c=k.parseAxisParam(s,r.shape),u=c,p=_.getAxesPermutation(u,o),d=r;p!=null&&(d=En({inputs:{x:r},backend:n,attrs:{perm:p}}),u=_.getInnerMostAxes(u.length,o),l.push(d)),_.assertAxesAreInnerMostDims("prod",u,o);let h;if(n.shouldExecuteOnCPU([d])){let m=n.texData.get(d.dataId).values,{outVals:f,outShape:g,outDtype:y}=BK(d.shape,d.dtype,m,u);h=n.makeTensorInfo(g,y,f)}else{let[m,f]=_.computeOutAndReduceShapes(d.shape,u),g=k.sizeFromShape(f),y=xe({inputs:{x:d},backend:n,attrs:{shape:[-1,g]}}),b=xh(r.dtype),x=eo(y,b,"prod",n);h=xe({inputs:{x},backend:n,attrs:{shape:m}}),l.push(y),l.push(x)}if(i){l.push(h);let m=_.expandShapeToKeepDim(h.shape,c);h=xe({inputs:{x:h},backend:n,attrs:{shape:m}})}return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),h}var wQ={kernelName:kl,backendName:"webgl",kernelFunc:vQ},d2=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=WK(a,r,s,i);return t.makeTensorInfo([o.length],i,o)},kQ={kernelName:Nc,backendName:"webgl",kernelFunc:d2},IQ="return 1.0 / x;",NQ=Ye({opSnippet:IQ}),TQ={kernelName:Il,backendName:"webgl",kernelFunc:NQ},SQ=Oa+ `
2020-12-15 14:15:43 +01:00
return ( x < 0.0 ) ? 0.0 : x ;
2021-01-12 16:01:34 +01:00
` ,CQ= `
2020-10-11 18:41:17 +02:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2021-01-12 16:01:34 +01:00
` ,EQ=Ye({opSnippet:SQ,packedOpSnippet:CQ}),_Q={kernelName:ci,backendName:"webgl",kernelFunc:EQ},FQ=Oa+ `
2020-12-15 14:15:43 +01:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2021-01-12 16:01:34 +01:00
` ,AQ= `
2020-10-11 18:41:17 +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 ;
2021-01-12 16:01:34 +01:00
` , $ Q=Ye({opSnippet:FQ,packedOpSnippet:AQ}),DQ={kernelName:di,backendName:"webgl",kernelFunc: $ Q},MQ=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let c=[a&&t>1?i-1:i,a&&n>1?o-1:o],u=[a&&t>1?t-1:t,a&&n>1?n-1:n],p;r?p="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2020-12-15 14:15:43 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
2021-01-12 16:01:34 +01:00
$ { c [ 0 ] / u [ 0 ] } ,
$ { c [ 1 ] / u [ 1 ] } ) ;
const vec2 inputShapeRC = vec2 ( $ { i } . 0 , $ { o } . 0 ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Fractional source index.
2021-01-12 16:01:34 +01:00
vec2 sourceFracIndexRC = $ { p } ;
2020-12-15 14:15:43 +01:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2 ( max ( sourceFracIndexRC , vec2 ( 0.0 ) ) ) ;
ivec2 sourceCeilRC = ivec2 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
float topLeft = getA ( b , sourceFloorRC . x , sourceFloorRC . y , d ) ;
float bottomLeft = getA ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ;
float topRight = getA ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ;
float bottomRight = getA ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ;
vec2 fracRC = sourceFracIndexRC - vec2 ( sourceFloorRC ) ;
float top = topLeft + ( topRight - topLeft ) * fracRC . y ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracRC . y ;
float newValue = top + ( bottom - top ) * fracRC . x ;
setOutput ( newValue ) ;
}
2021-01-12 16:01:34 +01:00
` }},RQ=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let c=[a&&t>1?i-1:i,a&&n>1?o-1:o],u=[a&&t>1?t-1:t,a&&n>1?n-1:n],p;r?p="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2020-12-15 14:15:43 +01:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
2021-01-12 16:01:34 +01:00
$ { c [ 0 ] / u [ 0 ] } ,
$ { c [ 1 ] / u [ 1 ] } ,
$ { c [ 1 ] / u [ 1 ] } ) ;
const vec3 inputShapeRC = vec3 ( $ { i } . 0 , $ { o } . 0 ,
$ { o } . 0 ) ;
2020-12-15 14:15:43 +01:00
float getAValue ( int b , int r , int c , int d ) {
return getChannel ( getA ( b , r , c , d ) , vec2 ( c , d ) ) ;
2020-10-11 18:41:17 +02:00
}
void main ( ) {
2020-12-15 14:15:43 +01:00
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-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
// Fractional source index.
2021-01-12 16:01:34 +01:00
vec3 sourceFracIndexRC = $ { p } ;
2020-12-15 14:15:43 +01:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3 ( max ( sourceFracIndexRC , vec3 ( 0.0 ) ) ) ;
ivec3 sourceCeilRC = ivec3 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
// Should we calculate next column and row elements in 2x2 packed cell.
2021-01-12 16:01:34 +01:00
bool hasNextCol = d < $ { l - 1 } ;
bool hasNextRow = coords . z < $ { n - 1 } ;
2020-12-15 14:15:43 +01: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 ) ;
vec4 bottomLeft = vec4 (
getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d + 1 ) : 0.0 ) ;
vec4 topRight = vec4 (
getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
vec4 bottomRight = vec4 (
getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
vec3 fracRC = sourceFracIndexRC - vec3 ( sourceFloorRC ) ;
vec4 top = mix ( topLeft , topRight , fracRC . yyzz ) ;
vec4 bottom = mix ( bottomLeft , bottomRight , fracRC . yyzz ) ;
vec4 newValue = mix ( top , bottom , fracRC . x ) ;
setOutput ( newValue ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function PQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,u=ee().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new RQ(r.shape,l,c,s,i):new MQ(r.shape,l,c,s,i);return n.runWebGLProgram(u,[r],"float32")}var OQ={kernelName:pi,backendName:"webgl",kernelFunc:PQ},LQ=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],c=o[0]/l[0],u=o[1]/l[1],p=1/c,d=1/u,h=Math.ceil(p)*2+2,m=Math.ceil(d)*2+2;this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
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
2020-12-15 14:15:43 +01:00
float accumulator = 0.0 ;
2021-01-12 16:01:34 +01:00
const float heightScale = float ( $ { c } ) ;
const float widthScale = float ( $ { u } ) ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
const float invHeightScale = float ( $ { p } ) ;
const float invWidthScale = float ( $ { d } ) ;
2020-12-15 14:15:43 +01:00
2021-01-12 16:01:34 +01:00
const int winHeight = int ( $ { h } ) ;
const int winWidth = int ( $ { m } ) ;
2020-12-15 14:15:43 +01:00
// Compute bounds for where in dy we will look
float startRLerp = floor ( float ( r ) * invHeightScale ) ;
int startDyR = int ( startRLerp - float ( winHeight / 2 ) ) ;
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( startCLerp - float ( winWidth / 2 ) ) ;
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
// Guard against the window exceeding the bounds of dy
2021-01-12 16:01:34 +01:00
if ( dyR < 0 || dyR >= $ { s } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
// Guard against the window exceeding the bounds of dy
2021-01-12 16:01:34 +01:00
if ( dyC < 0 || dyC >= $ { i } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
float dxR = float ( dyR ) * heightScale ;
int topDxRIndex = int ( floor ( dxR ) ) ;
2021-01-12 16:01:34 +01:00
int bottomDxRIndex = int ( min ( ceil ( dxR ) , $ { a - 1 } . 0 ) ) ;
2020-12-15 14:15:43 +01:00
float dxRLerp = dxR - float ( topDxRIndex ) ;
float inverseDxRLerp = 1.0 - dxRLerp ;
float dxC = float ( dyC ) * widthScale ;
int leftDxCIndex = int ( floor ( dxC ) ) ;
2021-01-12 16:01:34 +01:00
int rightDxCIndex = int ( min ( ceil ( dxC ) , $ { r - 1 } . 0 ) ) ;
2020-12-15 14:15:43 +01:00
float dxCLerp = dxC - float ( leftDxCIndex ) ;
float inverseDxCLerp = 1.0 - dxCLerp ;
if ( r == topDxRIndex && c == leftDxCIndex ) {
// topLeft
accumulator +=
getDy ( b , dyR , dyC , d ) * inverseDxRLerp * inverseDxCLerp ;
}
if ( r == topDxRIndex && c == rightDxCIndex ) {
// topRight
accumulator += getDy ( b , dyR , dyC , d ) * inverseDxRLerp * dxCLerp ;
}
if ( r == bottomDxRIndex && c == leftDxCIndex ) {
// bottomLeft
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * inverseDxCLerp ;
}
if ( r == bottomDxRIndex && c == rightDxCIndex ) {
// bottomRight
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * dxCLerp ;
}
}
}
// End loop over dy
setOutput ( accumulator ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function zQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new LQ(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var BQ={kernelName:ph,backendName:"webgl",kernelFunc:zQ},WQ=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let c=[a&&t>1?i-1:i,a&&n>1?o-1:o],u=[a&&t>1?t-1:t,a&&n>1?n-1:n],p=a?"0.5":"0.0",d;r?d="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2020-12-15 14:15:43 +01:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
2021-01-12 16:01:34 +01:00
$ { c [ 0 ] / u [ 0 ] } ,
$ { c [ 1 ] / u [ 1 ] } ) ;
const vec2 inputShapeRC = vec2 ( $ { i } . 0 , $ { o } . 0 ) ;
2020-12-15 14:15:43 +01:00
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
// Fractional source index.
2021-01-12 16:01:34 +01:00
vec2 sourceFracIndexRC = $ { d } ;
2020-12-15 14:15:43 +01:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2 (
2021-01-12 16:01:34 +01:00
min ( inputShapeRC - 1.0 , floor ( sourceFracIndexRC + $ { p } ) ) ) ;
2020-12-15 14:15:43 +01:00
float newValue = getA ( b , sourceNearestRC . x , sourceNearestRC . y , d ) ;
setOutput ( newValue ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function VQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,c]=o,u=new WQ(r.shape,l,c,s,i);return n.runWebGLProgram(u,[r],r.dtype)}var UQ={kernelName:Tc,backendName:"webgl",kernelFunc:VQ},GQ=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],c=o[0]/l[0],u=o[1]/l[1],p=1/c,d=1/u,h=Math.ceil(p)*2+2,m=Math.ceil(d)*2+2;this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
2020-12-15 14:15:43 +01:00
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
2020-12-15 14:15:43 +01:00
float accumulator = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
const float heightScale = float ( $ { c } ) ;
const float widthScale = float ( $ { u } ) ;
2020-10-11 18:41:17 +02:00
2021-01-12 16:01:34 +01:00
const float invHeightScale = float ( $ { p } ) ;
const float invWidthScale = float ( $ { d } ) ;
2020-10-29 05:16:50 +01:00
2021-01-12 16:01:34 +01:00
const int winHeight = int ( $ { h } ) ;
const int winWidth = int ( $ { m } ) ;
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01: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-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( floor ( startCLerp - float ( winWidth / 2 ) ) ) ;
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
// Guard against the window exceeding the bounds of dy
2021-01-12 16:01:34 +01:00
if ( dyR < 0 || dyR >= $ { s } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
// Guard against the window exceeding the bounds of dy
2021-01-12 16:01:34 +01:00
if ( dyC < 0 || dyC >= $ { i } ) {
2020-12-15 14:15:43 +01:00
continue ;
}
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
float sourceFracRow =
2021-01-12 16:01:34 +01:00
float ( $ { o [ 0 ] } ) *
( float ( dyR ) / float ( $ { l [ 0 ] } ) ) ;
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
float sourceFracCol =
2021-01-12 16:01:34 +01:00
float ( $ { o [ 1 ] } ) *
( float ( dyC ) / float ( $ { l [ 1 ] } ) ) ;
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
int sourceNearestRow = int ( min (
2021-01-12 16:01:34 +01:00
float ( int ( $ { a } ) - 1 ) ,
$ { n } ? float ( round ( sourceFracRow ) ) :
2020-12-15 14:15:43 +01:00
float ( floor ( sourceFracRow ) ) ) ) ;
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
int sourceNearestCol = int ( min (
2021-01-12 16:01:34 +01:00
float ( int ( $ { r } ) - 1 ) ,
$ { n } ? float ( round ( sourceFracCol ) ) :
2020-12-15 14:15:43 +01:00
float ( floor ( sourceFracCol ) ) ) ) ;
if ( r == sourceNearestRow && c == sourceNearestCol ) {
accumulator += getDy ( b , dyR , dyC , d ) ;
}
}
2020-10-29 05:16:50 +01:00
}
2020-12-15 14:15:43 +01:00
// End loop over dy
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01:00
setOutput ( accumulator ) ;
2020-10-29 05:16:50 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function HQ(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new GQ(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var jQ={kernelName:ch,backendName:"webgl",kernelFunc:HQ},qQ=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= `
2020-12-15 14:15:43 +01:00
void main ( ) {
int coord = getOutputCoords ( ) ;
2021-01-12 16:01:34 +01:00
setOutput ( getX ( $ { e [ 0 ] } - coord - 1 ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` ;return}let a=i=>t.indexOf(i)!==-1&&e[i]!==1? ` $ { e [ i ] } - coords [ $ { i } ] - 1 ` : ` coords [ $ { i } ] ` ,r=e.map((i,o)=>a(o)).join(","),s=mt(n);this.userCode= `
2020-10-29 05:16:50 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { r } ) ) ;
2020-10-29 05:16:50 +01:00
}
2021-01-12 16:01:34 +01:00
` }},KQ=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 a=yn("rc",n),r= ` $ { a [ n - 1 ] } + 1 < $ { this . outputShape [ n - 1 ] } ` ,s= ` $ { a [ n - 2 ] } + 1 < $ { this . outputShape [ n - 2 ] } ` ,i=mt(n);n===1?this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
int rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
result . r = getChannel ( getX ( $ { e [ 0 ] } - rc - 1 ) ,
$ { e [ 0 ] } - rc - 1 ) ;
if ( $ { r } ) {
result . g = getChannel ( getX ( $ { e [ 0 ] } - ( rc + 1 ) - 1 ) ,
$ { e [ 0 ] } - ( rc + 1 ) - 1 ) ;
2020-12-15 14:15:43 +01:00
}
setOutput ( result ) ;
}
` :this.userCode= `
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { i } rc = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
vec4 result = vec4 ( 0. ) ;
2021-01-12 16:01:34 +01:00
result . r = $ { o ( a . slice ( ) ) } ;
if ( $ { r } ) {
result . g = $ { l ( a . slice ( ) ) } ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
if ( $ { s } ) {
result . b = $ { c ( a . slice ( ) ) } ;
if ( $ { r } ) {
result . a = $ { u ( a . slice ( ) ) } ;
2020-12-15 14:15:43 +01:00
}
}
setOutput ( result ) ;
}
2021-01-12 16:01:34 +01:00
` ;function o(h){return p(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",p(h)}function c(h){return h[n-2]="("+h[n-2]+" + 1)",p(h)}function u(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",p(h)}function p(h){let m=e.map((y,b)=>d(b,h)),f=m.join(","),g=m.slice(-2).join(",");return ` getChannel ( getX ( $ { f } ) , vec2 ( $ { g } ) ) ` }function d(h,m){return t.indexOf(h)!==-1&&e[h]!==1? ` $ { e [ h ] } - $ { m [ h ] } - 1 ` : ` $ { m [ h ] } ` }}};function XQ(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=r.shape.length,o=k.parseAxisParam(s,r.shape);if(i===0)return Wn({inputs:{x:r},backend:n});let l=ee().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new KQ(r.shape,o):new qQ(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}var YQ={kernelName:hi,backendName:"webgl",kernelFunc:XQ},JQ=class{constructor(e,t,n,a){this.variableNames=["Image"],this.outputShape=[];let r=e[1],s=e[2],i=Math.sin(t).toFixed(3),o=Math.cos(t).toFixed(3);this.outputShape=e;let[l,c]=_.getImageCenter(a,r,s),u=l.toFixed(3),p=c.toFixed(3),d="";typeof n=="number"?d= ` float outputValue = $ { n . toFixed ( 2 ) } ; ` :d= `
vec3 fill = vec3 ( $ { n . join ( "," ) } ) ;
2020-12-15 14:15:43 +01:00
float outputValue = fill [ coords [ 3 ] ] ; ` ,this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
2020-12-15 14:15:43 +01:00
int y = coords [ 1 ] ;
2021-01-12 16:01:34 +01:00
float coordXFloat = ( float ( x ) - $ { u } ) * $ { o } - ( float ( y ) - $ { p } ) * $ { i } ;
float coordYFloat = ( float ( x ) - $ { u } ) * $ { i } + ( float ( y ) - $ { p } ) * $ { o } ;
int coordX = int ( round ( coordXFloat + $ { u } ) ) ;
int coordY = int ( round ( coordYFloat + $ { p } ) ) ;
$ { d }
if ( coordX >= 0 && coordX < $ { s } && coordY >= 0 && coordY < $ { r } ) {
2020-12-15 14:15:43 +01:00
outputValue = getImage ( coords [ 0 ] , coordY , coordX , coords [ 3 ] ) ;
2020-10-11 18:41:17 +02:00
}
setOutput ( outputValue ) ;
}
2021-01-12 16:01:34 +01:00
` }},ZQ={kernelName:zl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=new JQ(a.shape,r,s,i);return o.runWebGLProgram(l,[a],a.dtype)}},QQ= `
2020-12-15 14:15:43 +01: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-01-12 16:01:34 +01:00
` ,eee=Ye({opSnippet:QQ}),tee={kernelName:mi,backendName:"webgl",kernelFunc:eee},nee="return inversesqrt(x);",aee=Ye({opSnippet:nee,cpuKernelImpl:VK}),ree={kernelName:fi,backendName:"webgl",kernelFunc:aee},h2=class{constructor(e,t,n,a,r,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=mt(r.length),l=mt(s.length),c="";n===1?c="i":n===2&&(c="i, j");let u= ` getIndices ( $ { c } ) ` ,p="";a===1?p="i":a===2&&(p="i, coords[1]");let d= ` getUpdates ( $ { p } ) ` ,h=t>1?"strides[j]":"strides";this.userCode= `
$ { o } strides = $ { o } ( $ { r } ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { l } coords = getOutputCoords ( ) ;
2020-12-15 14:15:43 +01:00
float sum = 0.0 ;
bool found = false ;
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { e } ; i ++ ) {
2020-12-15 14:15:43 +01:00
int flattenedIndex = 0 ;
2021-01-12 16:01:34 +01:00
for ( int j = 0 ; j < $ { t } ; j ++ ) {
int index = round ( $ { u } ) ;
flattenedIndex += index * $ { h } ;
2020-12-15 14:15:43 +01:00
}
if ( flattenedIndex == coords [ 0 ] ) {
2021-01-12 16:01:34 +01:00
sum += $ { d } ;
2020-12-15 14:15:43 +01:00
found = true ;
}
}
setOutput ( mix ( getDefaultValue ( ) , sum , float ( found ) ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function see(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:c,strides:u,outputSize:p}=_.calculateShapes(s,r,i),d=[p/c,c];if(p===0)return n.makeTensorInfo(i,r.dtype);let h=xe({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),m=xe({inputs:{x:s},backend:n,attrs:{shape:[l,c]}}),f=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new h2(l,o,h.shape.length,m.shape.length,u,d),y=n.runWebGLProgram(g,[m,h,f],m.dtype),b=xe({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(f),b}var iee={kernelName:Tl,backendName:"webgl",kernelFunc:see},oee=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let a,r;if(n>4)throw Error( ` Where for rank $ { n } is not yet supported ` );if(n===1)r="resRC",a="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let c=0;c<t.length;c++)l.push( ` $ { i [ c ] } ` ),c<e&&o.push( ` $ { i [ c ] } ` );a=o.join(),r=l.join()}let s=mt(n);this.userCode= `
2020-10-11 18:41:17 +02:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } resRC = getOutputCoords ( ) ;
float cVal = getC ( $ { a } ) ;
2020-12-15 14:15:43 +01:00
if ( cVal >= 1.0 ) {
2021-01-12 16:01:34 +01:00
setOutput ( getA ( $ { r } ) ) ;
2020-12-15 14:15:43 +01:00
} else {
2021-01-12 16:01:34 +01:00
setOutput ( getB ( $ { r } ) ) ;
2020-12-15 14:15:43 +01:00
}
}
2021-01-12 16:01:34 +01:00
` }};function lee(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=new oee(a.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[a,r,s],pa(r.dtype,s.dtype))}var uee={kernelName:Sl,backendName:"webgl",kernelFunc:lee},cee= `
2020-12-15 14:15:43 +01:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2021-01-12 16:01:34 +01:00
float scaleAlpha = $ { _ . SELU _SCALEALPHA } ;
float scale = $ { _ . SELU _SCALE } ;
2020-12-15 14:15:43 +01:00
return ( x >= 0.0 ) ? scale * x : scaleAlpha * ( exp ( x ) - 1.0 ) ;
2021-01-12 16:01:34 +01:00
` ,pee=Ye({opSnippet:cee}),dee={kernelName:Cl,backendName:"webgl",kernelFunc:pee},hee="return 1.0 / (1.0 + exp(-1.0 * x));",mee=Ye({opSnippet:hee}),fee={kernelName:yi,backendName:"webgl",kernelFunc:mee},gee= `
2020-12-15 14:15:43 +01:00
if ( isnan ( x ) ) { return 0.0 ; }
return sign ( x ) ;
2021-01-12 16:01:34 +01:00
` ,yee=Ye({opSnippet:gee}),bee={kernelName:Fl,backendName:"webgl",kernelFunc:yee},xee=SS+ `
2020-12-15 14:15:43 +01:00
return sin ( x ) ;
2021-01-12 16:01:34 +01:00
` ,vee=Ye({opSnippet:xee}),wee={kernelName:gi,backendName:"webgl",kernelFunc:vee},kee= `
2020-12-15 14:15:43 +01:00
float e2x = exp ( x ) ;
return ( e2x - 1.0 / e2x ) / 2.0 ;
2021-01-12 16:01:34 +01:00
` ,Iee=Ye({opSnippet:kee}),Nee={kernelName:_l,backendName:"webgl",kernelFunc:Iee},Tee= `
2020-12-15 14:15:43 +01:00
float epsilon = 1.1920928955078125 e - 7 ;
float threshold = log ( epsilon ) + 2.0 ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
bool too _large = x > - threshold ;
bool too _small = x < threshold ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
float result ;
float exp _x = exp ( x ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
if ( too _large ) {
result = x ;
}
else if ( too _small ) {
result = exp _x ;
}
else {
result = log ( exp _x + 1.0 ) ;
}
return result ;
2021-01-12 16:01:34 +01:00
` ,See=Ye({opSnippet:Tee}),Cee={kernelName:Al,backendName:"webgl",kernelFunc:See},Eee=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;k.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((y,b)=>y*b),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<r.shape.length;++y)l.push([0,0]);let c=[],u=p2({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=_.getReshaped(u.shape,s,o,!1),d=_.getPermuted(p.length,s.length,!1),h=_.getReshapedPermuted(u.shape,s,o,!1),m=xe({inputs:{x:u},backend:n,attrs:{shape:p}}),f=En({inputs:{x:m},backend:n,attrs:{perm:d}}),g=xe({inputs:{x:f},backend:n,attrs:{shape:h}});return c.push(u),c.push(m),c.push(f),c.forEach(y=>n.disposeIntermediateTensorInfo(y)),g},_ee={kernelName:Sc,backendName:"webgl",kernelFunc:Eee};function Fee(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:c,strides:u,outputSize:p}=_.calculateShapes(s,r,o),d=!1,h=new h2(c,l,r.shape.length,s.shape.length,u,[p,1],d),m=n.runWebGLProgram(h,[s,r,i],s.dtype),f=xe({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),f}var Aee={kernelName:dh,backendName:"webgl",kernelFunc:Fee};function $ ee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=k.parseAxisParam(i,r.shape)[0],l=_.prepareSplitSize(r,s,o),c=r.shape.length,u=new Array(c).fill(0),p=r.shape.slice();return l.map(d=>{let h=[...p];h[o]=d;let m=_p({inputs:{x:r},backend:n,attrs:{begin:u,size:h}});return u[o]+=d,m})}var Dee={kernelName: $ l,backendName:"webgl",kernelFunc: $ ee},Mee="return sqrt(x);",Ree=Ye({opSnippet:Mee}),Pee={kernelName:bi,backendName:"webgl",kernelFunc:Ree},Oee="return x * x;",Lee=Ye({opSnippet:Oee}),zee={kernelName:Cc,backendName:"webgl",kernelFunc:Lee},m2="return (a - b) * (a - b);",Bee=on({opSnippet:m2,packedOpSnippet:m2}),Wee={kernelName:wi,backendName:"webgl",kernelFunc:Bee};function Vee({inputs:e,attrs:t,backend:n}){let{x:a}=e,r=Oa+ `
return x > 0.0 ? 1.0 : float ( $ { t . alpha } ) ;
` ,s=new ys(a.shape,r);return n.runWebGLProgram(s,[a],a.dtype)}var Uee={kernelName:Ll,backendName:"webgl",kernelFunc:Vee},Gee=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let a=n.length,r=mt(n.length),s=mt(n.length),i="";if(a===1)i="coords * strides + begin";else{let o=0;i=n.map((l,c)=>(o++,n.length===1? ` coords * strides [ $ { c } ] + begin [ $ { c } ] ` : ` coords [ $ { o - 1 } ] * strides [ $ { c } ] + begin [ $ { c } ] ` )).join(",")}this.userCode= `
$ { r } begin = $ { r } ( $ { e } ) ;
$ { r } strides = $ { r } ( $ { t } ) ;
2020-10-11 18:41:17 +02:00
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { s } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { i } ) ) ;
2020-12-15 14:15:43 +01:00
}
2021-01-12 16:01:34 +01:00
` }};function Hee(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:d}=a,{nonStrided:h, $ begin:m, $ strides:f,size:g,newShape:y,outShape:b}=hn.sliceInfo(r.shape,s,i,o,l,c,u,p,d),x=xe({inputs:{x:r},backend:n,attrs:{shape:y}}),v;if(h){let T=_p({inputs:{x},backend:n,attrs:{begin:m,size:g}});v=xe({inputs:{x:T},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(T)}else if(b.some(T=>T===0))v=n.makeTensorInfo(b,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let T=n.texData.get(x.dataId).values,E=Le(x.shape,x.dtype,T),A=GK(b,E,f,m);v=n.makeTensorInfo(b,x.dtype,A.values)}else{let T=new Gee(m,f,b);v=n.runWebGLProgram(T,[x],x.dtype)}let N=xe({inputs:{x:v},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(v),N}var jee={kernelName:Dl,backendName:"webgl",kernelFunc:Hee},qee="return tan(x);",Kee=Ye({opSnippet:qee}),Xee={kernelName:Ml,backendName:"webgl",kernelFunc:Kee},Yee= `
2020-12-15 14:15:43 +01:00
float e2x = exp ( - 2.0 * abs ( x ) ) ;
return sign ( x ) * ( 1.0 - e2x ) / ( 1.0 + e2x ) ;
2021-01-12 16:01:34 +01:00
` ,Jee=Ye({opSnippet:Yee}),Zee={kernelName:Ii,backendName:"webgl",kernelFunc:Jee},ete=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[s]*t[s];this.outputShape=n,this.rank=n.length;let a=mt(this.rank),r=Qee(e);this.userCode= `
2020-12-15 14:15:43 +01:00
void main ( ) {
2021-01-12 16:01:34 +01:00
$ { a } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { r } ) ) ;
2020-10-11 18:41:17 +02:00
}
2021-01-12 16:01:34 +01:00
` }};function Qee(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"],a=[];for(let r=0;r<e.length;r++)a.push( ` imod ( $ { n [ r ] } , $ { e [ r ] } ) ` );return a.join()}function f2(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;if(r.dtype==="string"){let o=n.readSync(r.dataId).map(u=>k.decodeString(u)),l=Le(r.shape,r.dtype,o),c=jK(l,s);return n.makeTensorInfo(c.shape,c.dtype,c.values)}let i=new ete(r.shape,s);return n.runWebGLProgram(i,[r],r.dtype)}var tte={kernelName:Xr,backendName:"webgl",kernelFunc:f2};function nte(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a,o=n.readSync(r.dataId),[l,c]=qK(o,r.shape,r.dtype,s,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(c.shape,c.dtype,c.values)]}var ate={kernelName:Rl,backendName:"webgl",kernelFunc:nte};function rte(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;Tp(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=a.readSync(s.dataId),{outputValues:o,outputShape:l,indices:c}=KK(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([c.length],"int32",c)]}var ste={kernelName:hh,backendName:"webgl",kernelFunc:rte};function ite(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r,o=i.shape.length,l=r.shape[s],c=new Array(o-1),u=0;for(let f=0;f<o;f++)f!==s&&(c[u++]=i.shape[f]);let p=[],d=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){d[s]=f;let g=_p({inputs:{x:i},backend:n,attrs:{begin:d,size:h}}),y=xe({inputs:{x:g},backend:n,attrs:{shape:c}});m[f]=y,p.push(g)}return p.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var ote={kernelName:Pl,backendName:"webgl",kernelFunc:ite},lte=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,a=e.batchSize,r=e.inSize,s=e.numSegments,i=s*Math.ceil(r/n);this.outputShape=[a,i];let o="0.0",l="sumValue",c=Math.floor(n/4)*4,u=n%4,p= `
2020-12-15 14:15:43 +01:00
sumValue += dot ( values , segFilter ) ;
2021-01-12 16:01:34 +01:00
` ,d="";r%n>0&&(d= `
if ( inIdx < 0 || inIdx >= $ { r } ) {
2020-12-15 14:15:43 +01:00
return initializationValue ;
}
2021-01-12 16:01:34 +01:00
` );let h="";r%n>0&&(h= `
if ( inIdx < 0 || inIdx >= $ { r } ) {
2020-12-15 14:15:43 +01:00
return - 1.0 ;
2020-10-29 05:16:50 +01:00
}
` ),this.userCode= `
2021-01-12 16:01:34 +01:00
const float initializationValue = $ { o } ;
2020-10-29 05:16:50 +01:00
float getValue ( int batch , int inIdx ) {
2021-01-12 16:01:34 +01:00
$ { d }
2020-10-29 05:16:50 +01:00
return getX ( batch , inIdx ) ;
}
2020-12-15 14:15:43 +01:00
float getSegmentIdAtIndex ( int inIdx ) {
2021-01-12 16:01:34 +01:00
$ { h }
2020-12-15 14:15:43 +01:00
return getSegmentIds ( inIdx ) ;
}
2020-10-29 05:16:50 +01:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
2020-12-15 14:15:43 +01:00
int inOffset = int ( floor ( float ( outIdx ) / float (
2021-01-12 16:01:34 +01:00
$ { s } ) ) * float ( $ { n } ) ) ;
int currentSeg = int ( mod ( float ( outIdx ) , float ( $ { s } ) ) ) ;
2020-10-29 05:16:50 +01:00
float sumValue = 0.0 ;
2021-01-12 16:01:34 +01:00
for ( int i = 0 ; i < $ { c } ; i += 4 ) {
2020-10-29 05:16:50 +01:00
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2020-12-15 14:15:43 +01: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-01-12 16:01:34 +01:00
$ { p }
2020-10-29 05:16:50 +01:00
}
2021-01-12 16:01:34 +01:00
int inIdx = inOffset + $ { c } ;
if ( $ { u === 1 } ) {
2020-12-15 14:15:43 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
int inIdxSeg = int ( getSegmentIdAtIndex ( inIdx ) ) ;
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
0 ,
0 ,
0
) ;
2020-10-29 05:16:50 +01:00
2021-01-12 16:01:34 +01:00
$ { p }
} else if ( $ { u === 2 } ) {
2020-10-29 05:16:50 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
0 ,
0
) ;
2020-10-29 05:16:50 +01:00
2021-01-12 16:01:34 +01:00
$ { p }
} else if ( $ { u === 3 } ) {
2020-10-29 05:16:50 +01:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
2020-12-15 14:15:43 +01:00
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2020-10-29 05:16:50 +01:00
2020-12-15 14:15:43 +01: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
2021-01-12 16:01:34 +01:00
$ { p }
2020-10-29 05:16:50 +01:00
}
2021-01-12 16:01:34 +01:00
setOutput ( $ { l } ) ;
2020-10-29 05:16:50 +01:00
}
2021-01-12 16:14:33 +01:00
` }};function ute(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a,o=r.shape.length,l=[],c=0,u=_.getAxesPermutation([c],o),p=r;u!=null&&(p=En({inputs:{x:r},backend:n,attrs:{perm:u}}),l.push(p),c=_.getInnerMostAxes(1,o)[0]);let d=_.segment_util.computeOutShape(p.shape,c,i),h=k.sizeFromShape([p.shape[c]]),m=xe({inputs:{x:p},backend:n,attrs:{shape:[-1,h]}});l.push(m);let f=xh(r.dtype),g=(v,N,T,E,A)=>{let $ =v.shape[0],O=v.shape[1],V=_.segment_util.segOpComputeOptimalWindowSize(O,A),W={windowSize:V,inSize:O,batchSize: $ ,numSegments:A},H=new lte(W,N),X=n.compileAndRun(H,[v,T],E);if(l.push(X),X.shape[1]===A)return X;let q=d2({backend:n,attrs:{start:0,stop:A,step:1,dtype:"float32"}}),K=f2({inputs:{x:q},backend:n,attrs:{reps:[O/V]}});return l.push(q),l.push(K),g(X,N,K,E,A)},y=g(m,"unsortedSegmentSum",s,f,i),b=xe({inputs:{x:y},backend:n,attrs:{shape:d}}),x=b;if(u!=null){l.push(b);let v=_.getUndoAxesPermutation(u);x=En({inputs:{x},backend:n,attrs:{perm:v}})}return l.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var cte={kernelName:Ec,backendName:"webgl",kernelFunc:ute},pte=[a9,i9,HX,qX,YX,QX,tY,rY,iY,lY,dY,mY,yY,vY,CY,IY,FY,MY, $ Y,LY,BY,VY,jY,QY,t7,o7,u7,h7,g7,SX,v7,F7, $ 7,N7,P7,L7,M7,W7,G7,q7,X7,J7,eJ,iJ,lJ,nJ,pJ,mJ,bJ,kJ,SJ,_J,FJ,AJ,DJ,RJ,OJ,zJ,WJ,HJ,XJ,JJ,QJ,nZ,iZ,cZ,mZ,TX,gZ,x7,xZ,kZ,TZ,EX,_Z,DZ,RZ,VZ,zZ,jZ,XZ,QZ,l9,g9,m9,v9,k9,N9,d9,S9,E9, $ 9,P9,B9,K9,DX,Y9,Q9,nQ,sQ,a7,lQ,cQ,dQ,fQ,xQ,FX,wQ,kQ,r7,G9,TQ,DQ,_Q,RX,OQ,BQ,UQ,jQ,YQ,ZQ,tee,ree,iee,uee,dee,fee,bee,wee,Nee,JY,j9,Cee,_ee,Aee,Dee,Pee,zee,Wee,Uee,jee,H9,VX,Xee,Zee,tte,ate,UX,ste,ote,cte,uQ];for(let e of pte)Fc(e);var dte="2.8.3",hte={"tfjs-core":rk,"tfjs-backend-cpu":UG,"tfjs-backend-webgl":NX,"tfjs-data":HN,"tfjs-layers":Dm,"tfjs-converter":zN,tfjs:dte},Vn;(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"})(Vn||(Vn={}));var Ap;(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"})(Ap||(Ap={}));var g2;function mte(e){g2=e.wasm.cwrap(Ti,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function fte(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:p}=a,d=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(s.dataId).id,m=0;if(i!=null){let A=n.dataIdMap.get(i.dataId);if(A.shape.length!==1)throw new Error( ` _FusedMatMul only supports rank - 1 bias but got rank $ { A . shape . length } . ` );m=A.id}let f=o==null?0:n.dataIdMap.get(o.dataId).id,g=Ap[u];if(g==null)throw new Error( ` $ { u } activation not yet supported for FusedConv2D in the wasm backend . ` );let y=l?r.shape[2]:r.shape[1],b=c?s.shape[1]:s.shape[2],x=r.shape[0],v=n.makeOutput([x,y,b],r.dtype),N=n.dataIdMap.get(v.dataId).id,T=new Uint8Array(new Int32Array(r.shape).buffer),E=new Uint8Array(new Int32Array(s.shape).buffer);return g2(d,T,r.shape.length,h,E,s.shape.length,l,c,g,m,f,p||0,N),v}var gte={kernelName:Ti,backendName:"wasm",setupFunc:mte,kernelFunc:fte};function Un(e){let t;function n(r){t=r.wasm.cwrap(e,null,["number","number"])}function a(r){let{backend:s,inputs:{x:i}}=r,o=s.dataIdMap.get(i.dataId).id,l=s.makeOutput(i.shape,i.dtype),c=s.dataIdMap.get(l.dataId).id;return k.sizeFromShape(l.shape)===0||t(o,c),l}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var yte=Un(Lo);function bn(e,t,n){let a;function r(i){a=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:c,b:u}=l,p=o.dataIdMap.get(c.dataId).id,d=o.dataIdMap.get(u.dataId).id,h=n!=null?n:c.dtype,m=_.assertAndGetBroadcastShape(c.shape,u.shape),f=o.makeOutput(m,h);if(k.sizeFromShape(m)===0)return f;let g=new Uint8Array(new Int32Array(c.shape).buffer),y=new Uint8Array(new Int32Array(u.shape).buffer),b=o.dataIdMap.get(f.dataI
2020-10-11 18:41:17 +02:00
/ * *
* @ license
* Copyright 2017 Google LLC . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT - style
* license that can be found in the LICENSE file or at
* https : //opensource.org/licenses/MIT.
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2018 Google LLC . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
*
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2018 Google LLC . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT - style
* license that can be found in the LICENSE file or at
* https : //opensource.org/licenses/MIT.
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2019 Google LLC . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
*
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2019 Google LLC . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2020 Google Inc . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT - style
* license that can be found in the LICENSE file or at
* https : //opensource.org/licenses/MIT.
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2020 Google LLC . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ license
* Copyright 2020 Google LLC . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the License ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an AS IS BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2021-01-10 16:35:51 +01:00
/ * *
* @ license
* Copyright 2021 Google LLC . All Rights Reserved .
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2020-10-11 18:41:17 +02:00
/** @license See the LICENSE file. */
//# sourceMappingURL=face-api.js.map