2021-09-08 19:51:28 +02:00
/ *
2020-12-02 22:46:41 +01:00
Face - API
homepage : < https : //github.com/vladmandic/face-api>
author : < https : //github.com/vladmandic>'
2021-09-08 19:51:28 +02:00
* /
2020-12-02 22:46:41 +01:00
2021-12-09 20:22:22 +01:00
var faceapi = ( ( ) => { var c0 = Object . defineProperty ; var dD = e => c0 ( e , "__esModule" , { value : ! 0 } ) ; var pD = ( e => typeof require != "undefined" ? require : typeof Proxy != "undefined" ? new Proxy ( e , { get : ( t , n ) => ( typeof require != "undefined" ? require : t ) [ n ] } ) : e ) ( function ( e ) { if ( typeof require != "undefined" ) return require . apply ( this , arguments ) ; throw new Error ( 'Dynamic require of "' + e + '" is not supported' ) } ) ; var Up = ( e , t ) => { dD ( e ) ; for ( var n in t ) c0 ( e , n , { get : t [ n ] , enumerable : ! 0 } ) } ; var Wue = { } ; Up ( Wue , { AgeGenderNet : ( ) => Jm , BoundingBox : ( ) => Wu , Box : ( ) => ut , ComposableTask : ( ) => Rr , ComputeAllFaceDescriptorsTask : ( ) => Aa , ComputeFaceDescriptorsTaskBase : ( ) => og , ComputeSingleFaceDescriptorTask : ( ) => Da , DetectAllFaceLandmarksTask : ( ) => cg , DetectAllFacesTask : ( ) => fp , DetectFaceLandmarksTaskBase : ( ) => ig , DetectFacesTaskBase : ( ) => lg , DetectSingleFaceLandmarksTask : ( ) => ug , DetectSingleFaceTask : ( ) => dg , Dimensions : ( ) => Nn , FACE _EXPRESSION _LABELS : ( ) => R1 , FaceDetection : ( ) => xt , FaceDetectionNet : ( ) => rA , FaceExpressionNet : ( ) => Ym , FaceExpressions : ( ) => Ea , FaceLandmark68Net : ( ) => Yu , FaceLandmark68TinyNet : ( ) => Qm , FaceLandmarkNet : ( ) => HE , FaceLandmarks : ( ) => yr , FaceLandmarks5 : ( ) => AE , FaceLandmarks68 : ( ) => Uu , FaceMatch : ( ) => np , FaceMatcher : ( ) => hg , FaceRecognitionNet : ( ) => Zu , Gender : ( ) => Ms , LabeledBox : ( ) => rp , LabeledFaceDescriptors : ( ) => Rs , NetInput : ( ) => Ps , NeuralNetwork : ( ) => ln , ObjectDetection : ( ) => Na , Point : ( ) => Pe , PredictedBox : ( ) => DE , Rect : ( ) => Vu , SsdMobilenetv1 : ( ) => Di , SsdMobilenetv1Options : ( ) => $r , TinyFaceDetector : ( ) => nl , TinyFaceDetectorOptions : ( ) => ag , TinyYolov2 : ( ) => el , TinyYolov2Options : ( ) => ms , allFaces : ( ) => Lue , allFacesSsdMobilenetv1 : ( ) => yA , allFacesTinyYolov2 : ( ) => Mue , awaitMediaLoaded : ( ) => _1 , bufferToImage : ( ) => E1 , computeFaceDescriptor : ( ) => Iue , createCanvas : ( ) => Ni , createCanvasFromMedia : ( ) => ip , createFaceDetectionNet : ( ) => gue , createFaceRecognitionNet : ( ) => aue , createSsdMobilenetv1 : ( ) => nA , createTinyFaceDetector : ( ) => Bue , createTinyYolov2 : ( ) => vue , detectAllFaces : ( ) => pg , detectFaceLandmarks : ( ) => gA , detectFaceLandmarksTiny : ( ) => kue , detectLandmarks : ( ) => Pue , detectSingleFace : ( ) => Oue , draw : ( ) => L1 , env : ( ) => tt , euclideanDistance : ( ) => K1 , extendWithAge : ( ) => ng , extendWithFaceDescriptor : ( ) => tg , extendWithFaceDetection : ( ) => Si , extendWithFaceExpressions : ( ) => Zm , extendWithFaceLandmarks : ( ) => Xu , extendWithGender : ( ) => rg , extractFaceTensors : ( ) => Hu , extractFaces : ( ) => Gu , fetchImage : ( ) => jce , fetchJson : ( ) => F1 , fetchNetWeights : ( ) => qce , fetchOrThrow : ( ) => Os , fetchVideo : ( ) => Kce , getContext2dOrThrow : ( ) => Un , getMediaDimensions : ( ) => Ci , imageTensorToCanvas : ( ) => A1 , imageToSquare : ( ) => D1 , inverseSigmoid : ( ) => Bce , iou : ( ) => y1 , isMediaElement : ( ) => Wm , isMediaLoaded : ( ) => op , isWithAge : ( ) => oue , isWithFaceDetection : ( ) => hs , isWithFaceExpressions : ( ) => P1 , isWithFaceLandmarks : ( ) => Ei , isWithGender : ( ) => iue , loadAgeGenderModel : ( ) => Fue , loadFaceDetectionModel : ( ) => $ue , loadFaceExpressionModel : ( ) => Due , loadFaceLandmarkModel : ( ) => _ue , loadFaceLandmarkTinyModel : ( ) => Eue , loadFaceRecognitionModel : ( ) => Aue , loadSsdMobilenetv1Model : ( ) => bA , loadTinyFaceDetectorModel : ( ) => Cue , loadTinyYolov2Model : ( ) => Nue , loadWeightMap : ( ) => $1 , locateFaces : ( ) => Rue , matchDimensions : ( ) => Xce , minBbox : ( ) => v1 , nets : ( ) => nt , nonMaxSuppression : ( ) => x1 , normalize : ( ) => Xr , padToSquare : ( ) => w1 , predictAgeAndGender : ( ) => Tue , recognizeFaceExpressions : ( ) => Sue , resizeResults : ( ) => vA , resolveInput : ( ) => Ti , shuffleArray : ( ) => Lce , sigmoid : ( ) => tp , ssdMobilenetv1 : ( ) => mA , tf : ( ) => h1 , tinyFaceDetector : ( ) => xue , tinyYolov2 : ( ) => wue , toNetInput : ( ) => bt , utils : ( ) => b1 , validateConfig : ( ) => G1 , version : ( ) => zue } ) ; var h1 = { } ; Up ( h1 , { Abs : ( ) => Yi , Acos : ( ) => Zi , Acosh : ( ) => Ji , AdadeltaOptimizer : ( ) => wf , AdagradOptimizer : ( ) => kf , AdamOptimizer : ( ) => If , AdamaxOptimizer : ( ) => Sf , Add : ( ) => Zs , AddN : ( ) => Ba , All : ( ) => Qi , Any : ( ) => ec , ArgMax : ( ) => za , ArgMin : ( ) => Sl , Asin : ( ) => tc , Asinh : ( ) => nc , Atan : ( ) => rc , Atan2 : ( ) => ac , Atanh : ( ) => sc , AvgPool : ( ) => Wa , AvgPool3D : ( ) => Tl , AvgPool3DGrad : ( ) => Jp , AvgPoolGrad : ( ) => Zp , BackendWasm : ( ) => NE , BatchMatMul : ( ) => Va , BatchToSpaceND : ( ) => oc , Bincount : ( ) => Qp , BroadcastArgs : ( ) => eh , BroadcastTo : ( ) => N0 , Callback : ( ) => bT , CallbackList : ( ) => uS , Cast : ( ) => Ua , Ceil : ( ) => Ga , ClipByValue : ( ) => Js , Complex : ( ) => th , ComplexAbs : ( ) => Cl , Concat : ( ) => ic , Conv2D : ( ) => Ha , Conv2DBackpropFilter : ( ) => nh , Conv2DBackpropInput : ( ) => ja , Conv3D : ( ) => Nl , Conv3DBackpropFilterV2 : ( ) => rh , Conv3DBackpropInputV2 : ( ) =>
2021-12-06 12:34:50 +01:00
` )),c.join( `
2021-12-09 20:22:22 +01:00
` )}function _F(e,t,n,r){let s=yt(t),a=r[r.length-1],o=new Array(a).fill(0),i=t.length,c=n==="complex64"?Kl(e):e;if(i>1)for(let l=0;l<s/a;l++){let u=l*a;for(let d=0;d<a;d++)o[d]=Math.max(o[d],ql(c[u+d],0,n).length)}return o}function ql(e,t,n){let r;return Array.isArray(e)?r= ` $ { parseFloat ( e [ 0 ] . toFixed ( Qb ) ) } + $ { parseFloat ( e [ 1 ] . toFixed ( Qb ) ) } j ` :Xs(e)?r= ` '${e}' ` :n==="bool"?r=P0(e):r=parseFloat(e.toFixed(Qb)).toString(),Il(r,t)}function P0(e){return e===0?"false":"true"}function Oh(e,t,n,r,s,a=!0){let o=n==="complex64"?2:1,i=t[0],c=t.length;if(c===0){if(n==="complex64"){let m=Kl(e);return[ql(m[0],0,n)]}return n==="bool"?[P0(e[0])]:[e[0].toString()]}if(c===1){if(i>R0){let g=jl*o,b=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-jl)*o,i*o));return n==="complex64"&&(b=Kl(b),y=Kl(y)),["["+b.map((v,x)=>ql(v,s[x],n)).join(", ")+", ..., "+y.map((v,x)=>ql(v,s[i-jl+x],n)).join(", ")+"]"]}let m=n==="complex64"?Kl(e):Array.from(e);return["["+m.map((g,b)=>ql(g,s[b],n)).join(", ")+"]"]}let l=t.slice(1),u=r.slice(1),d=r[0]*o,p=[];if(i>R0){for(let m=0;m<jl;m++){let g=m*d,b=g+d;p.push(...Oh(e.slice(g,b),l,n,u,s,!1))}p.push("...");for(let m=i-jl;m<i;m++){let g=m*d,b=g+d;p.push(...Oh(e.slice(g,b),l,n,u,s,m===i-1))}}else for(let m=0;m<i;m++){let g=m*d,b=g+d;p.push(...Oh(e.slice(g,b),l,n,u,s,m===i-1))}let h=c===2?",":"";p[0]="["+p[0]+h;for(let m=1;m<p.length-1;m++)p[m]=" "+p[m]+h;let f= ` ,
2021-12-06 12:34:50 +01:00
` ;for(let m=2;m<c;m++)f+= `
2021-12-09 20:22:22 +01:00
` ;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function Kl(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Ut=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=yt(e),n!=null){let r=n.length;P(r===this.size,()=> ` Length of values '${r}' does not match the size inferred by the shape '${this.size}' . ` )}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||b0(t,this.size),this.strides=Ki(e)}set(e,...t){t.length===0&&(t=[0]),P(t.length===this.rank,()=> ` The number of provided coordinates ( $ { t . length } ) must match the rank ( $ { this . rank } ) ` );let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let r of e){if(r<0||r>=this.shape[t]){let s= ` Requested out of range element at $ { e } . Buffer shape = $ { this . shape } ` ;throw new Error(s)}t++}let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Zr().makeTensor(this.values,this.shape,this.dtype)}},Zr=null,Qc=null,EF=null;function AF(e){Zr=e}function DF(e){Qc=e}function FF(e){EF=e}var Ee=class{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=yt(e),this.strides=Ki(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Qc.buffer(this.shape,this.dtype,e)}bufferSync(){return Qc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Xi(this.shape,e,this.dtype==="complex64")}arraySync(){return Xi(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Zr().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>Ph(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=Zr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ph(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 Zr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Zr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Qc.print(this,e)}clone(){return this.throwIfDisposed(),Qc.clone(this)}toString(e=!1){let t=this.dataSync();return NF(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Qc.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Zr().makeVariable(this,e,t,n)}};Object.defineProperty(Ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function ee(){return Xb("Tensor",()=>Ee)}ee();var ra=class extends Ee{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error( ` dtype of the new value ( $ { e . dtype } ) and previous value ( $ { this . dtype } ) must match ` );if(!Ks(e.shape,this.shape))throw new Error( ` shape of the new value ( $ { e . shape } ) and previous value ( $ { this . shape } ) must match ` );Zr().disposeTensor(this),this.dataId=e.dataId,Zr().incRef(this,null)}dispose(){Zr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(ra,Symbol.hasInstance,{value:e=>e instanceof Ee&&e.as
Manifest JSON has weights with names : $ { i . join ( ", " ) } . ` )}let c=s.reduce((h,f,m)=>(f&&h.push(m),h),[]),l=[];c.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;l.push(m)})});let u=await e(l),d={},p=0;return c.forEach(h=>{let f=t[h].paths.length,m=0;for(let x=0;x<f;x++)m+=u[p+x].byteLength;let g=new ArrayBuffer(m),b=new Uint8Array(g),y=0;for(let x=0;x<f;x++){let w=new Uint8Array(u[p+x]);b.set(w,y),y+=w.byteLength}a[h].forEach(x=>{let w=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),T=G0(w,[x.manifestEntry]);for(let C in T)d[C]=T[C]}),p+=f}),d}}var E $ ="application/octet-stream",A $ ="application/json",gy=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?(P(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of ` fetch ` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=Q().platform.fetch,P(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&P(e.length===2,()=> ` URL paths for http must have a length of 2 , ( actual length is $ { e . length } ) . ` ),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=q0(e,n);t.body.append("model.json",new Blob([JSON.stringify(r)],{type:A $ }),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:E $ }),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Jl(e),responses:[s]};throw new Error( ` BrowserHTTPRequest . save ( ) failed due to HTTP response status $ { s . status } . ` )}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error( ` Request to $ { this . path } failed with status code $ { e . status } . Please verify this URL points to the model JSON of the model to load . ` );let t;try{t=await e.json()}catch(s){let a= ` Failed to parse model JSON of response from $ { this . path } . ` ;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,r=t.weightsManifest;if(n==null&&r==null)throw new Error( ` The JSON from HTTP path $ { this . path } contains neither model topology or manifest for weights . ` );return dy(t,s=>this.loadWeights(s))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=D $ (t),s=this.weightPathPrefix||n,a=[];for(let l of e)a.push(...l.weights);let o=[],i=[];for(let l of e)for(let u of l.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(s+u+r);this.weightUrlConverter&&o.push(...await Promise.all(i));let c=await sk(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,ly(c)]}};gy.URL_SCHEME_REGEX=/^https?: \/ \/ /;function D $ (e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}function by(e){return e.match(gy.URL_SCHEME_REGEX)!=null}var ok=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>by(r)):n=by(e),n)return yy(e,t)}return null};Ft.registerSaveRouter(ok);Ft.registerLoadRouter(ok);function yy(e,t){return new gy(e,t)}function F $ (e,t){return yy(e,t)}var vy=class{
2021-09-11 17:11:38 +02:00
Actual : $ { s } .
2021-12-06 12:34:50 +01:00
Expected : $ { a } . ` );for(let o=0;o<a.length;++o){let i=s[o],c=a[o];if(!n(i,c))throw new Error( ` Arrays differ : actual [ $ { o } ] = $ { i } , expected [ $ { o } ] = $ { c } .
2021-09-11 17:11:38 +02:00
Actual : $ { s } .
2021-12-09 20:22:22 +01:00
Expected : $ { a } . ` )}}function aR(e,t){e().then(()=>t.fail(),()=>t())}function oR(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Xs(e)||Xs(e[0])||Xs(t)||Xs(t[0])?Cy(e,n,(r,s)=>r==s):Cy(e,t,(r,s)=>Ny(r,s,0))}function iR(e,t,n){if(n==null&&(n=Ty()),!Ny(e,t,n))throw new Error( ` Numbers differ : actual === $ { e } , expected === $ { t } ` )}function Ny(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function cR(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error( ` Value out of range : $ { e [ r ] } low : $ { t } , high : $ { n } ` )}function uR(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function Tk(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?Tk(n):e[t]=Hl(n)}return e}var lR="3.12.0";function dR(){Q().set("PROD",!0)}function pR(){Q().set("DEBUG",!0)}function hR(){Q().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function _y(e){Q().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}FF(_y);function fR(){z.disposeVariables()}function ks(){return z}function Wh(){return z.memory()}function mR(e){return z.profile(e)}function M(e,t){return z.tidy(e,t)}function Fe(e){ay(e).forEach(n=>n.dispose())}function Zt(e){return z.keep(e)}function gR(e){return z.time(e)}function bR(e){return z.setBackend(e)}function yR(){return z.ready()}function vR(){return z.backendName}function xR(e){z.removeBackend(e)}function wR(e){return z.findBackend(e)}function kR(e){return z.findBackendFactory(e)}function Vh(e,t,n=1){return z.registerBackend(e,t,n)}function Ck(){return z.backend}function IR(e,t){Q().setPlatform(e,t)}function SR(e,t){let n=A(e,"a","add"),r=A(t,"b","add");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(Zs,s)}var Y=W({add_:SR});function TR(e,t){let n=A(e,"a","floorDiv"),r=A(t,"b","floorDiv");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(to,s)}var Uh=W({floorDiv_:TR});function CR(e,t){let n=A(e,"a","div"),r=A(t,"b","div");if([n,r]=_t(n,r),n.dtype==="int32"&&r.dtype==="int32")return Uh(n,r);let s={a:n,b:r},a={};return z.runKernel(Za,s,a)}var me=W({div_:CR});function NR(e,t){let n=A(e,"a","mul"),r=A(t,"b","mul");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(mo,s)}var V=W({mul_:NR});function _R(e){let t=A(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return z.runKernel(Cl,n)}else{let n={x:t};return z.runKernel(Yi,n)}}var Bt=W({abs_:_R});function ER(e){let n={x:A(e,"x","acos")};return z.runKernel(Zi,n)}var Ey=W({acos_:ER});function AR(e){let n={x:A(e,"x","acosh")};return z.runKernel(Ji,n)}var Ay=W({acosh_:AR});function DR(e){P(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),P(e.length>=1,()=> ` Must pass at least one tensor to tf . addN ( ) , but got $ { e . length } ` );let t=e.map((s,a)=>A(s, ` tensors$ { a } ` ,"addN")),n=t[0];t.forEach(s=>{if(s.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(s=>{if(!Ks(s.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=t;return z.runKernel(Ba,r)}var Nk=W({addN_:DR});function FR(e,t=null,n=!1){let s={x:A(e,"x","all","bool")},a={axis:t,keepDims:n};return z.runKernel(Qi,s,a)}var Gh=W({all_:FR});function $ R(e,t=null,n=!1){let s={x:A(e,"x","any","bool")},a={axis:t,keepDims:n};return z.runKernel(ec,s,a)}var Ql=W({any_: $ R});function RR(e,t=0){let r={x:A(e,"x","argMax")},s={axis:t};return z.runKernel(za,r,s)}var qo=W({argMax_:RR});function PR(e,t=0){let r={x:A(e,"x","argMin")},s={axis:t};return z.runKernel(Sl,r,s)}var Dy=W({argMin_:PR});function OR(e){let n={x:A(e,"x","asin")};return z.runKernel(tc,n)}var Fy=W({asin_:OR});function MR(e){let n={x:A(e,"x","asinh")};return z.runKernel(nc,n)}var $ y=W({asinh_:MR});function LR(e){let n={x:A(e,"x","atan")};return z.runKernel(rc,n)}var Ry=W({atan_:LR});function BR(e,t){let n=A(e,"a","atan2"),r=A(t,"b","atan2");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(ac,s)}var Py=W({atan2_:BR});function zR(e){let n={x:A
with dtype $ { a . dtype } . ` )}),n.length===1)return ws(n[0]);let r=n,s={axis:t};return z.runKernel(ic,r,s)}var et=W({concat_:YR});function ZR(e){let n={x:A(e,"x","sigmoid","float32")};return z.runKernel(No,n)}var dr=W({sigmoid_:ZR});function JR(e,t,n){let r=A(e,"x","slice","string_or_numeric");if(r.rank===0)throw new Error("Slicing scalar is not possible");let s={x:r},a={begin:t,size:n};return z.runKernel(Bc,s,a)}var ze=W({slice_:JR});function QR(e){let n={x:A(e,"x","tanh","float32")};return z.runKernel(Ro,n)}var Xo=W({tanh_:QR});function eP(e,t,n,r,s,a){let o=A(e,"forgetBias","basicLSTMCell"),i=A(t,"lstmKernel","basicLSTMCell"),c=A(n,"lstmBias","basicLSTMCell"),l=A(r,"data","basicLSTMCell"),u=A(s,"c","basicLSTMCell"),d=A(a,"h","basicLSTMCell"),p=et([l,d],1),h=De(p,i),f=Y(h,c),m=f.shape[0],g=f.shape[1]/4,b=[m,g],y=ze(f,[0,0],b),v=ze(f,[0,g],b),x=ze(f,[0,g*2],b),w=ze(f,[0,g*3],b),T=Y(V(dr(y),Xo(v)),V(u,dr(Y(o,x)))),C=V(Xo(T),dr(w));return[T,C]}var tP=W({basicLSTMCell_:eP});function nP(e,t,n){let r=A(e,"x","batchToSpaceND"),s=t.reduce((i,c)=>i*c);P(r.rank>=1+t.length,()=> ` input rank is $ { r . rank } but should be > than blockShape . length $ { t . length } ` ),P(n.length===t.length,()=> ` crops . length is $ { n . length } but should be equal to blockShape . length $ { t . length } ` ),P(r.shape[0]%s==0,()=> ` input tensor batch is $ { r . shape [ 0 ] } but is not divisible by the product of the elements of blockShape $ { t . join ( " * " ) } === $ { s } ` );let a={x:r},o={blockShape:t,crops:n};return z.runKernel(oc,a,o)}var td=W({batchToSpaceND_:nP});function rP(e){let t;return e.rank===0||e.rank===1?t=U(e,[1,1,1,e.size]):e.rank===2?t=U(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function sP(e,t,n,r,s,a){a==null&&(a=.001);let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;r!=null&&(u=A(r,"offset","batchNorm")),P(i.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),P(l==null||i.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:rP(o),scale:l,offset:u,mean:i,variance:c},h={varianceEpsilon:a},f=z.runKernel(no,p,h);return U(f,o.shape)}var Is=W({batchNorm_:sP});function aP(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;return r!=null&&(u=A(r,"offset","batchNorm")),P(o.rank===2,()=> ` Error in batchNorm2D : x must be rank 2 but got rank $ { o . rank } . ` ),P(i.rank===2||i.rank===1,()=> ` Error in batchNorm2D : mean must be rank 2 or rank 1 but got rank $ { i . rank } . ` ),P(c.rank===2||c.rank===1,()=> ` Error in batchNorm2D : variance must be rank 2 or rank 1 but got rank $ { c . rank } . ` ),l!=null&&P(l.rank===2||l.rank===1,()=> ` Error in batchNorm2D : scale must be rank 2 or rank 1 but got rank $ { l . rank } . ` ),u!=null&&P(u.rank===2||u.rank===1,()=> ` Error in batchNorm2D : offset must be rank 2 or rank 1 but got rank $ { u . rank } . ` ),Is(o,i,c,u,l,a)}var Dk=W({batchNorm2d_:aP});function oP(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;return r!=null&&(u=A(r,"offset","batchNorm")),P(o.rank===3,()=> ` Error in batchNorm3D : x must be rank 3 but got rank $ { o . rank } . ` ),P(i.rank===3||i.rank===1,()=> ` Error in batchNorm3D : mean must be rank 3 or rank 1 but got rank $ { i . rank } . ` ),P(c.rank===3||c.rank===1,()=> ` Error in batchNorm3D : variance must be rank 3 or rank 1 but got rank $ { c . rank } . ` ),l!=null&&P(l.rank===3||l.rank===1,()=> ` Error in batchNorm3D : scale must be rank 3 or rank 1 but got rank $ { l . rank } . ` ),u!=null&&P(u.rank===3||u.rank===1,()=> ` Error in batchNorm3D : offset must be rank 3 or rank 1 but got rank $ { u . rank } . ` ),Is(o,i,c,u,l,a)}var Fk=W({batchNorm3d_:oP});function iP(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"))
2021-09-11 17:11:38 +02:00
$ { s } and $ { t } for depthToSpace with input shape
2021-12-09 20:22:22 +01:00
$ { r . shape } ` ),P(a*t>=0,()=> ` Negative dimension size caused by overflow when multiplying
2021-09-11 17:11:38 +02:00
$ { a } and $ { t } for depthToSpace with input shape
2021-12-09 20:22:22 +01:00
$ { r . shape } ` ),P(o%(t*t)==0,()=> ` Dimension size must be evenly divisible by $ { t * t } but is $ { o } for depthToSpace with input shape $ { r . shape } ` );let i={x:r},c={blockSize:t,dataFormat:n};return z.runKernel(uc,i,c)}var Gy=W({depthToSpace_:_P});function EP(e,t,n,r,s="NHWC",a=[1,1],o){let i=A(e,"x","depthwiseConv2d","float32"),c=A(t,"filter","depthwiseConv2d","float32"),l=i,u=!1;i.rank===3&&(u=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),P(l.rank===4,()=> ` Error in depthwiseConv2d : input must be rank 4 , but got rank $ { l . rank } . ` ),P(c.rank===4,()=> ` Error in depthwiseConv2d : filter must be rank 4 , but got rank $ { c . rank } . ` ),P(l.shape[3]===c.shape[2],()=> ` Error in depthwiseConv2d : number of input channels ( $ { l . shape [ 3 ] } ) must match the inChannels dimension in filter $ { c . shape [ 2 ] } . ` ),vn("depthwiseConv2d",r,o);let d={x:l,filter:c},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},h=z.runKernel(Ya,d,p);return u?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var ua=W({depthwiseConv2d_:EP});function AP(e){let n={x:A(e,"x","diag")};return z.runKernel(ch,n)}var DP=W({diag_:AP});function FP(e,t,n,r,s=[1,1],a="NHWC"){let o=A(e,"x","dilation2d"),i=A(t,"filter","dilation2d");P(o.rank===3||o.rank===4,()=> ` Error in dilation2d : input must be rank 3 or 4 , but got rank $ { o . rank } . ` ),P(i.rank===3,()=> ` Error in dilation2d : filter must be rank 3 , but got rank $ { i . rank } . ` ),P(a==="NHWC",()=> ` Error in dilation2d : Only NHWC is currently supported , but got dataFormat of $ { a } ` );let c=o,l=!1;o.rank===3&&(c=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=!0);let u={x:c,filter:i},d={strides:n,pad:r,dilations:s},p=z.runKernel(_l,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Hy=W({dilation2d_:FP});function $ P(e,t){let n=A(e,"a","equal","string_or_numeric"),r=A(t,"b","equal","string_or_numeric");[n,r]=_t(n,r),pt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(dc,s)}var Xn=W({equal_: $ P});function RP(e,t,n){let r=A(t,"a","where"),s=A(n,"b","where"),a=A(e,"condition","where","bool"),o=pt(pt(a.shape,r.shape),s.shape),i=ou(a,o),c=ou(r,o),l=ou(s,o),u={condition:i,t:c,e:l};return z.runKernel(Mc,u)}var hn=W({where_:RP});function PP(e){let n={x:A(e,"x","zerosLike")};return z.runKernel(Yc,n)}var Ge=W({zerosLike_:PP});function OP(e,t){let n=A(e,"a","div"),r=A(t,"b","div");[n,r]=_t(n,r);let s=me(n,r),a=Ge(s),o=Xn(r,a);return hn(o,a,s)}var jy=W({divNoNan_:OP});function MP(e,t){let n=A(e,"t1","dot"),r=A(t,"t2","dot");P((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),()=> ` Error in dot : inputs must all be rank 1 or 2 , but got ranks $ { n . rank } and $ { r . rank } . ` );let s=n.rank===1?n.size:n.shape[1],a=r.rank===1?r.size:r.shape[0];if(P(s===a,()=> ` Error in dot : inner dimensions of inputs must match , but got $ { s } and $ { a } . ` ),n.rank===1&&r.rank===1){let o=U(n,[1,-1]),i=U(r,[-1,1]),c=De(o,i);return U(c,[])}else if(n.rank===1&&r.rank===2){let o=U(n,[1,-1]),i=U(r,[r.shape[0],r.shape[1]]),c=De(o,i);return U(c,[c.size])}else if(n.rank===2&&r.rank===1){let o=U(r,[-1,1]),i=De(n,o);return U(i,[i.size])}else{let o=U(r,[r.shape[0],r.shape[1]]);return De(n,o)}}var Vk=W({dot_:MP});function LP(e,...t){let n=t.map((s,a)=>A(s, ` tensors$ { a } ` ,"einsum")),r={equation:e};return z.runKernel(dh,n,r)}var Uk=W({einsum_:LP});function BP(e){let n={x:A(e,"x","elu","float32")};return z.runKernel(Ja,n)}var iu=W({elu_:BP});function zP(e){let t=A(e,"x","erf");P(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be ` int32 ` or ` float32 ` ."),t.dtype==="int32"&&(t=ce(t,"float32"));let n={x:t};return z.runKernel(lc,n)}var qy=W({erf_:zP});function WP(e){let n={x:A(e,"x","exp")};return z.runKernel(Qa,n)}var fn=W({exp_:WP});function VP(e,t=0){let n=A(e,"x","expandDims","string_or_numeric");P(t<=n.rank,()=>"Axis must be <= rank of the tensor");let r={input:n},s={dim:t};return z.runKernel(pc,r,s)}var mn=W({expandDims_:VP});function UP(e){let n={x:A(e,"x","expm1")};return z.runKernel(hc,n)}var Ky=W({expm1_:UP});function GP(e,t){let n=A(e,"x","tile","string_or_numeric");P(n.rank===t.length,()=> ` Error in transpose : rank of input $ { n . rank } must match length of reps $ { t } . ` );let r={x:n},s={reps:
rank $ { a . rank } . ` ),P(qi(t),()=> ` Error in localResponseNormalization : depthRadius must be an integer but got depthRadius $ { t } . ` );let o=a,i=!1;a.rank===3&&(i=!0,o=U(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let c={x:o},l={depthRadius:t,bias:n,alpha:r,beta:s},u=z.runKernel(Fl,c,l);return i?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var Zy=W({localResponseNormalization_:rO});function sO(e){let n={x:A(e,"x","log","float32")};return z.runKernel(oo,n)}var Yn=W({log_:sO});function aO(e){let n={x:A(e,"x","log1p")};return z.runKernel(Ic,n)}var sd=W({log1p_:aO});function oO(e){return P(Ys(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let r=A(t,"x","tf.grad","string_or_numeric"),s=n!=null?A(n,"dy","tf.grad"):null;return z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(r),[r],s);return s!=null&&bn(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Jh(o),o[0]})}}function iO(e){return P(Ys(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{P(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of ` Tensor ` s or ` TensorLike ` s");let r=Zl(t,"args","tf.grads","string_or_numeric"),s=n!=null?A(n,"dy","tf.grads"):null;return z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(...r),r,s);return s!=null&&bn(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Jh(o),o})}}function cO(e){return P(Ys(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{P(t instanceof Ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),P(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:r,value:s}=z.gradients(()=>e(t),[t],n);return Jh(r),{grad:r[0],value:s}}}function uO(e){return P(Ys(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{P(Array.isArray(t)&&t.every(s=>s instanceof Ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),P(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let r=z.gradients(()=>e(...t),t,n);return n!=null&&bn(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Jh(r.grads),r}}function qk(e,t){P(Ys(e),()=>"The f passed in variableGrads(f) must be a function"),P(t==null||Array.isArray(t)&&t.every(l=>l instanceof ra),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let l in z.registeredVariables)t.push(z.registeredVariables[l])}let r=n?t.filter(l=>!l.trainable):null,s=t.length;t=t.filter(l=>l.trainable),P(t.length>0,()=> ` variableGrads ( ) expects at least one of the input variables to be trainable , but none of the $ { s } variables is trainable . ` );let a=!0,{value:o,grads:i}=z.gradients(e,t,null,a);P(i.some(l=>l!=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()."),P(o.rank===0,()=> ` The f passed in variableGrads ( f ) must return a scalar , but it returned a rank - $ { o . rank } tensor ` );let c={};return t.forEach((l,u)=>{i[u]!=null&&(c[l.name]=i[u])}),r!=null&&r.forEach(l=>c[l.name]=null),{value:o,grads:c}}function es(e){return z.customGrad(e)}function Jh(e){if(e.filter(n=>n==null).length>0)throw new Error( ` Cannot compute gradient of y = f ( x ) with respect to x . Make sure that
the f you passed encloses all operations that lead from x to y . ` )}function lO(e){let n={x:A(e,"x","neg")};return z.runKernel(Cc,n)}var It=W({neg_:lO});function dO(e){let n={x:A(e,"x","softplus")};return z.runKernel(Vc,n)}var Zo=W({softplus_:dO});function pO(e){let t=A(e,"x","logSigmoid");return es(r=>({value:It(Zo(It(r))),gradFunc:o=>V(o,dr(It(r)))}))(t)}var Kk=W({logSigmoid_:pO});function hO(e,t=null,n=!1){let s={x:A(e,"x","max")},a={reductionIndices:t,keepDims:n};return z.runKernel(io,s,a)}var Tr=W({max_:hO});function fO(e,t){let n=A(e,"a","sub"),r=A(t,"b","sub");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(Fo,s)}var fe=W({sub_:fO});function mO(e,t=null,n=!1){let r=A(e,"x","sum");r.dtype==="bool"&&(r=ce(r,"int32"));let s={x:r},a={axis:t,keepDims:n};return z.runKernel(Eo,s,a)}var xe=W({sum_:mO});function gO(e,t=-1){let n=A(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 es((s,a)=>{let o=!0,i=Tr(s,t,!0),c=fe(s,i),l=fe(ce(c,"float32"),Yn(xe(fn(c),t,o)));return a([l]),{value:l,gradFunc:(d,p)=>{let[h]=p,f=!0,m=fn(h);return fe(d,V(xe(d,t,f),m))}}})(n)}var Qh=W({logSoftmax_:gO});function Jy(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Xk(e,t,n){let r=e.length+t.length,s=[],a=0,o=0;for(let i=0;i<r;i++)n.indexOf(i)===-1?s.push(e[a++]):s.push(t[o++]);return s}function Yk(e,t){let n=[],r=e.length;for(let a=0;a<r;a++)t.indexOf(a)===-1&&n.push(e[a]);let s=t.map(a=>e[a]);return[n,s]}function Jo(e,t){let n=t.map(r=>1);return Xk(e,n,t)}function bO(e,t,n){P(Jy(t,n),()=> ` $ { e } supports only inner - most axes for now . Got axes $ { t } and rank - $ { n } input . ` )}function Zk(e,t){if(Jy(e,t))return null;let n=[];for(let r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);return e.forEach(r=>n.push(r)),n}function Qy(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function yO(e,t){let n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function vO(e,t=null,n=!1){let r=A(e,"x","logSumExp"),s=Ir(t,r.shape),a=Tr(r,s,!0),o=fe(r,a),i=fn(o),c=xe(i,s),l=Yn(c),u=Y(U(a,l.shape),l);if(n){let d=Jo(u.shape,s);return U(u,d)}return u}var ev=W({logSumExp_:vO});function xO(e,t){let n=A(e,"a","logicalAnd","bool"),r=A(t,"b","logicalAnd","bool");pt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(Sc,s)}var Cr=W({logicalAnd_:xO});function wO(e){let n={x:A(e,"x","logicalNot","bool")};return z.runKernel(Al,n)}var ad=W({logicalNot_:wO});function kO(e,t){let n=A(e,"a","logicalOr","bool"),r=A(t,"b","logicalOr","bool");pt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(Dl,s)}var ef=W({logicalOr_:kO});function IO(e,t){let n=A(e,"a","logicalXor","bool"),r=A(t,"b","logicalXor","bool");return pt(n.shape,r.shape),Cr(ef(e,t),ad(Cr(e,t)))}var Jk=W({logicalXor_:IO});function SO(e,t,n,r,s){let a=A(e,"x","maxPool"),o=1,i=a,c=!1;a.rank===3&&(c=!0,i=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),P(i.rank===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { i . rank } . ` ),P(Qr(n,o),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { n } and dilations '${o}' ` ),vn("maxPool",r,s);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s},d=z.runKernel(uo,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Pt=W({maxPool_:SO});function TO(e,t=[1,1,1],n,r,s,a="NDHWC"){let o=A(e,"x","maxPool3d"),i=o,c=!1;o.rank===4&&(c=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),P(i.rank===5,()=> ` Error in maxPool3d : x must be rank 5 but got rank $ { i . rank } . ` ),P(a==="NDHWC",()=> ` Error in maxPool3d : Only NDHWC is currently supported , but got dataFormat of $ { a } ` ),vn("maxPool3d",r,s);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},d=z.runKernel( $ l,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var tv=W({maxPool3d_:TO});function CO(e,t,n,r,s=!1){let o={x:A(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},c=z.runKernel(xh,o,i);return{result:c[0],indexes:c[1]}}var Qk=W({maxPoolWithArgmax_:CO});f
$ { s . shape } ` );if(a.rank!==1)throw new Error( ` Values should be Tensor1D but received shape $ { a . shape } ` );if(o.rank!==1)throw new Error( ` Dense shape should be Tensor1D but received shape $ { o . shape } ` );if(i.rank!==0)throw new Error( ` Default value should be a scalar but received shape $ { i . shape } ` );let c={indices:s,values:a,denseShape:o,defaultValue:i},l=z.runKernel(Ol,c);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}var LL=W({sparseFillEmptyRows_:ML});function BL(e,t,n){let r=A(e,"inputIndices","sparseReshape","int32"),s=A(t,"inputShape","sparseReshape","int32"),a=A(n,"newShape","sparseReshape","int32");if(r.rank!==2)throw new Error( ` Input indices should be Tensor2D but received shape
$ { r . shape } ` );if(s.rank!==1)throw new Error( ` Input shape should be Tensor1D but received shape $ { s . shape } ` );if(a.rank!==1)throw new Error( ` New shape should be Tensor1D but received shape $ { a . shape } ` );let o={inputIndices:r,inputShape:s,newShape:a},i=z.runKernel(Hc,o);return{outputIndices:i[0],outputShape:i[1]}}var zL=W({sparseReshape_:BL});function WL(e,t,n){let r=A(e,"data","sparseSegmentMean"),s=A(t,"indices","sparseSegmentMean","int32"),a=A(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error( ` Indices should be Tensor1D but received shape
2021-09-11 17:11:38 +02:00
$ { s . shape } ` );if(a.rank!==1)throw new Error( ` Segment ids should be Tensor1D but received shape
2021-12-09 20:22:22 +01:00
$ { a . shape } ` );let o={data:r,indices:s,segmentIds:a};return z.runKernel(Ml,o)}var VL=W({sparseSegmentMean_:WL});function UL(e,t,n){let r=A(e,"data","sparseSegmentSum"),s=A(t,"indices","sparseSegmentSum","int32"),a=A(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error( ` Indices should be Tensor1D but received shape
2021-09-11 17:11:38 +02:00
$ { s . shape } ` );if(a.rank!==1)throw new Error( ` Segment ids should be Tensor1D but received shape
2021-12-09 20:22:22 +01:00
$ { a . shape } ` );let o={data:r,indices:s,segmentIds:a};return z.runKernel(Ll,o)}var GL=W({sparseSegmentSum_:UL});function HL(e,t,n,r,s,a,o,i){let c=A(e,"data","stringNGrams","string");if(c.dtype!=="string")throw new Error("Data must be of datatype string");if(c.shape.length!==1)throw new Error( ` Data must be a vector , saw : $ { c . shape } ` );let l=A(t,"dataSplits","stringNGrams");if(l.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:c,dataSplits:l},p=z.runKernel(Ch,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var jL=W({stringNGrams_:HL});function qL(e,t,n=!0){let r=A(e,"input","stringSplit","string"),s=A(t,"delimiter","stringSplit","string");if(r.rank!==1)throw new Error( ` Input should be Tensor1D but received shape $ { r . shape } ` );if(s.rank!==0)throw new Error( ` Delimiter should be a scalar but received shape $ { s . shape } ` );let a={skipEmpty:n},o={input:r,delimiter:s},i=z.runKernel(Nh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var KL=W({stringSplit_:qL});function XL(e,t){let n=A(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let s={input:n};return z.runKernel(_h,s,r)}var YL=W({stringToHashBucketFast_:XL}),ZL={fft:dd,ifft:hu,rfft:pd,irfft:df},JL={hammingWindow:_M,hannWindow:hI,frame:fI,stft:FM},er={flipLeftRight:OM,grayscaleToRGB:LM,resizeNearestNeighbor:xI,resizeBilinear:vI,rotateWithOffset:zM,cropAndResize:RM,nonMaxSuppression:VM,nonMaxSuppressionAsync:YM,nonMaxSuppressionWithScore:JM,nonMaxSuppressionWithScoreAsync:eL,nonMaxSuppressionPadded:nL,nonMaxSuppressionPaddedAsync:sL,threshold:uL,transform:dL},kI={bandPart:hL,gramSchmidt:mL,qr:bL},QL={absoluteDifference:xL,computeWeightedLoss:Ts,cosineDistance:kL,hingeLoss:SL,huberLoss:CL,logLoss:_L,meanSquaredError:AL,sigmoidCrossEntropy: $ L,softmaxCrossEntropy:OL},hd={sparseFillEmptyRows:LL,sparseReshape:zL,sparseSegmentMean:VL,sparseSegmentSum:GL},xf={stringNGrams:jL,stringSplit:KL,stringToHashBucketFast:YL},Cs=class extends kk{minimize(e,t=!1,n){let{value:r,grads:s}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:s[o.name]}));this.applyGradients(a)}else this.applyGradients(s);return Fe(s),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return qk(e,t)}dispose(){this.iterations_!=null&&Fe(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ie(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error( ` setWeights ( ) is not implemented for this optimizer class $ { this . getClassName ( ) } ` )}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty(Cs,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var wf=class extends Cs{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=z.registeredVariables[n],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName: ` $ { n } / accum _grad ` ,variable:M(()=>Ge(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName: ` $ { n } / accum _var ` ,variable:M(()=>Ge(s).variable(a))});let o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;M(()=>{let l=Y(V(i,this.rho),V(ct(o),1-this.rho)),u=V(me(an(Y(c,this.epsilon)),an(Y(i,this.epsilon))),o),d=Y(V(c,this.rho),V(ct(u),1-this.rho));i.assign(l),c.assign(d);let p=Y(V(u,-this.learningRate),s);s.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpda
indices . shape [ 0 ] = $ { e } ` }function $ B(e,t){return ` indices ( $ { e } , 0 ) is invalid : $ { t } < 0 ` }function RB(e,t,n){return ` indices ( $ { e } , 0 ) is invalid : $ { t } >= $ { n } ` }function PB(e,t){return ` only one output dimension may be - 1 , not both $ { e } and $ { t } ` }function OB(e,t){return ` size $ { e } must be non - negative , not $ { t } ` }function MB(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function LB(e,t){let n=yt(e),r=yt(t);return ` Input to reshape is a SparseTensor with $ { n }
dense values , but the requested shape requires a multiple of $ { r } . inputShape = $ { e } outputShape = $ { t } ` }function BB(e,t){let n=yt(e),r=yt(t);return ` Input to reshape is a tensor with $ { n } dense values , but the requested shape has $ { r } . inputShape = $ { e } outputShape = $ { t } ` }function zB(){return"segment ids must be >= 0"}function WB(){return"segment ids are not increasing"}function VB(e,t){return ` Segment id $ { e } out of range [ 0 , $ { t } ) , possibly because segmentIds input is not sorted . ` }function UB(e,t,n){return ` Bad : indices [ $ { e } ] == $ { t } out of range [ 0 , $ { n } ) ` }var _I={};Ae(_I,{collectGatherOpShapeInfo:()=>jB,computeOutShape:()=>HB,segOpComputeOptimalWindowSize:()=>GB});function GB(e,t){let n=!1,r;for(e<=yv?(r=e,n=!0):r=Xp(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=Xp(e,r+1);return r}function HB(e,t,n){let r=[],s=e.length;for(let a=0;a<s;a++)a!==t?r.push(e[a]):r.push(n);return r}function jB(e,t,n,r){let s=t.shape.length,a=e.shape.length;if(r!==0&&(r<-s||r>s))throw new Error( ` Expect batchDims in the range of [ - $ { s } , $ { s } ] , but got $ { r } ` );if(r<0&&(r+=s),r>a)throw new Error( ` batchDims ( $ { r } ) must be less than rank ( x ) (
$ { a } ) . ` );if(n<r)throw new Error( ` batchDims ( $ { r } ) must be less than or equal to axis ( $ { n } ) . ` );for(let d=0;d<r;++d)if(e.shape[d]!==t.shape[d])throw new Error( ` x . shape [ $ { d } ] : $ { e . shape [ d ] } should be equal to indices . shape [ $ { d } ] : $ { t . shape [ d ] } . ` );let o=e.shape[n],i=[],c=1,l=1,u=1;for(let d=0;d<r;++d)i.push(e.shape[d]),c*=e.shape[d];for(let d=r;d<n;d++)i.push(e.shape[d]),l*=e.shape[d];for(let d=r;d<s;d++)i.push(t.shape[d]);for(let d=n+1;d<a;d++)i.push(e.shape[d]),u*=e.shape[d];return{batchSize:c,sliceSize:u,outerSize:l,dimSize:o,outputShape:i}}function qB(e){try{return e.map(t=>Ph(t))}catch(t){throw new Error( ` Failed to decode encoded string bytes into utf - 8 , error : $ { t } ` )}}function KB(e){return e.map(t=>Hl(t))}var rs={};Ae(rs,{nonMaxSuppressionV3Impl:()=>mI,nonMaxSuppressionV4Impl:()=>gI,nonMaxSuppressionV5Impl:()=>bI,whereImpl:()=>aI});var EI={kernelName:Yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,fu(ce(n,"float32"),-1))}}},XB={kernelName:Zi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=ct(ce(n,"float32")),s=an(fe(Ie(1),r));return It(me(e,s))}}}},YB={kernelName:Ji,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=an(fe(ct(ce(n,"float32")),1));return me(e,r)}}}},ZB={kernelName:Zs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=pt(n.shape,r.shape);return{a:()=>{let i=e,c=Lt(n.shape,s);return c.length>0&&(i=xe(i,c)),U(i,n.shape)},b:()=>{let i=e,c=Lt(r.shape,s);return c.length>0&&(i=xe(i,c)),U(i,r.shape)}}}},JB={kernelName:Ba,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((r,s)=>{n[s]=()=>e.clone()}),n}},QB={kernelName:za,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},ez={kernelName:Sl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},tz={kernelName:tc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>me(e,an(fe(Ie(1),ct(ce(n,"float32")))))}}},nz={kernelName:nc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=an(Y(Ie(1),ct(ce(n,"float32"))));return me(e,r)}}}},rz={kernelName:ac,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=pt(n.shape,r.shape);return{a:()=>{let i=Y(ct(n),ct(r)),c=V(e,me(r,i)),l=Lt(n.shape,s);return l.length>0&&(c=xe(c,l)),U(c,n.shape)},b:()=>{let i=Y(ct(n),ct(r)),c=It(V(e,me(n,i))),l=Lt(r.shape,s);return l.length>0&&(c=xe(c,l)),U(c,r.shape)}}}},sz={kernelName:rc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>me(e,Y(ct(ce(n,"float32")),1))}}},az={kernelName:sc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>me(e,fe(Ie(1),ct(ce(n,"float32"))))}}};function oz(e,t,n,r,s,a){let o=A(e,"dy","avgPool3dGrad"),i=A(t,"input","avgPool3dGrad"),c=o,l=i,u=!1;i.rank===4&&(u=!0,c=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),l=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(c.rank===5,()=> ` Error in avgPool3dGrad : dy must be rank 5 but got rank $ { c . rank } . ` ),P(l.rank===5,()=> ` Error in avgPool3dGrad : input must be rank 5 but got rank $ { l . rank } . ` ),vn("avgPool3dGrad",s,a);let d={dy:c,input:l},p={filterSize:n,strides:r,pad:s,dimRoundingMode:a},h=z.runKernel(Jp,d,p);return u?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var iz=W({avgPool3dGrad_:oz}),cz={kernelName:Tl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>iz(e,r,s,a,o,i)}}};function uz(e,t,n,r,s){let a=A(e,"dy","avgPoolGrad"),o=A(t,"input","avgPoolGrad");P(o.rank===a.rank,()=> ` Rank of input ( $ { o . rank } ) does not match rank of dy ( $ { a . rank } ) ` );let i=o,c=a,l=!1;o.rank===3&&(l=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),P(c.rank===4,()=> ` Error in avgPoolGrad : dy must be rank 4 but got rank $ { c . rank } . ` ),P(i.rank===4,()=> ` Error in avgPoolGrad : input must be rank 4 but got rank $ { i . rank } . ` );let u={dy:c,input:i},d={filterSize:n,strides:r,pad:s},p=z.runKernel(Zp,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var lz=W({avgPoolGrad_:uz}),dz={kernelName:Wa,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o}=n;return{x:()=>lz(e,r,s,a,o)}}},pz={kernelName:Va,i
2021-09-11 17:11:38 +02:00
1. The $ { r } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2. The custom $ { r } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );return o}else{let a=e;if(a.className==null||a.config==null)throw new H( ` $ { r } : Improper config format : $ { JSON . stringify ( a ) } .
2021-12-09 20:22:22 +01:00
'className' and 'config' must set . ` );let o=a.className,i,c;if(o in n?[i,c]=n[o]:o in Nr?[i,c]=Nr.className:o in t&&([i,c]=t[o]),i==null)throw new H( ` Unknown $ { r } : $ { o } . This may be due to one of the following reasons :
2021-09-11 17:11:38 +02:00
1. The $ { r } is defined in Python , in which case it needs to be ported to TensorFlow . js or your JavaScript code .
2021-12-09 20:22:22 +01:00
2. The custom $ { r } is defined in JavaScript , but is not registered properly with tf . serialization . registerClass ( ) . ` );if(c!=null){let l={};for(let h of Object.keys(Nr))l[h]=Nr[h];for(let h of Object.keys(n))l[h]=n[h];let u=a.config;u.customObjects=l;let d=Object.assign({},Nr);for(let h of Object.keys(n))Nr[h]=n[h];kv(a.config);let p=c(i,a.config,n,s);return Nr=Object.assign({},d),p}else{let l=Object.assign({},Nr);for(let d of Object.keys(n))Nr[d]=n[d];let u=new i(a.config);return Nr=Object.assign({},l),u}}}function Y4(e,t){return e<t?-1:e>t?1:0}function Nf(e,t){return-1*Y4(e,t)}function fa(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function Z4(e){if(e==null)throw new H( ` Invalid value in obj : $ { JSON . stringify ( e ) } ` );for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function si(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new H( ` $ { n } is not a valid $ { t } . Valid values are $ { e } or null / undefined . ` )}function Iv(e,t,n=0,r=1/0){return ss(n>=0),ss(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(s=>typeof s===t)}function Qt(e,t){Array.isArray(e)?(k.assert(e.length>0,()=> ` $ { t } is unexpectedly an empty array . ` ),e.forEach((n,r)=>Qt(n, ` element $ { r + 1 } of $ { t } ` ))):k.assert(Number.isInteger(e)&&e>0,()=> ` Expected $ { t } to be a positive integer , but got $ { zI ( e ) } . ` )}function zI(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>zI(t)).join(",")+"]":typeof e=="string"? ` "${e}" ` : ` $ { e } ` }function J4(e,t,n){let r=n!=null?n():k.now(),s;return(...o)=>{let i=n!=null?n():k.now();return i-r<t||(r=i,s=e(...o)),s}}function WI(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Sv(e,t){return M(()=>an(xe(V(e,e),t,!0)))}var gd=class extends ie.Serializable{getConfig(){return{}}},Tv=class extends gd{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 M(()=>{let t=Sv(e,this.axis),n=Jt(t,0,this.maxValue);return V(e,me(n,Y(Ht(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};Tv.className="MaxNorm";ie.registerClass(Tv);var Cv=class extends gd{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return M(()=>me(e,Y(Ht(),Sv(e,this.axis))))}getConfig(){return{axis:this.axis}}};Cv.className="UnitNorm";ie.registerClass(Cv);var Nv=class extends gd{apply(e){return qe(e)}};Nv.className="NonNeg";ie.registerClass(Nv);var _v=class extends gd{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 M(()=>{let t=Sv(e,this.axis),n=Y(V(this.rate,Jt(t,this.minValue,this.maxValue)),V(1-this.rate,t));return V(e,me(n,Y(Ht(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};_v.className="MinMaxNorm";ie.registerClass(_v);var VI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function jt(e){return wv(e)}function UI(e,t={}){return md(e,ie.SerializationMap.getMap().classNameMap,t,"constraint")}function qt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in VI?VI[e]:e,config:{}};return UI(n)}else return e instanceof gd?e:UI(e)}function Q4(e){return new Tv(e)}function eW(e){return new Cv(e)}function tW(){return new Nv}function nW(e){return new _v(e)}var GI={};Ae(GI,{constant:()=>TW,glorotNormal:()=>FW,glorotUniform:()=>DW,heNormal:()=> $ W,heUniform:()=>RW,identity:()=>EW,leCunNormal:()=>PW,leCunUniform:()=>OW,ones:()=>SW,orthogonal:()=>MW,randomNormal:()=>NW,randomUniform:()=>CW,truncatedNormal:()=>_W,varianceScaling:()=>AW,zeros:()=>IW});var rW=["channelsFirst","channelsLast"],sW=["nearest","bilinear"],aW=["valid","same","causal"],oW=["max","avg"],iW=["sum","mul","concat","ave"],gu=new Map;function Mt(e){si(rW,"DataFo
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),Dr(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,Zt(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error( ` TensorArray $ { this . name } : could not write multiple tensors , because the index size : $ { e . length } is not the same as tensors size : $ { t . length } . ` );e.forEach((n,r)=>this.write(n,t[r]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but gather requested dtype $ { t } ` );if(e)e=e.slice(0,this.size());else{e=[];for(let r=0;r<this.size();r++)e.push(r)}if(e.length===0)return Kn([],[0].concat(this.elementShape));let n=this.readMany(e);return Dr(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Ot(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 Kn([],[0].concat(this.elementShape));let t=[];for(let r=0;r<this.size();r++)t.push(r);let n=this.readMany(t);return Dr(this.elementShape,n[0].shape, ` TensorArray shape mismatch : tensor array shape ( $ { this . elementShape } ) vs first tensor shape ( $ { n [ 0 ] . shape } ) ` ),et(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,ht(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error( ` TensorArray dtype is $ { this . dtype } but tensor has dtype $ { t . dtype } ` );let n=0,r=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error( ` Expected sum of lengths to be equal to
2021-09-11 17:11:38 +02:00
tensor . shape [ 0 ] , but sum of lengths is
2021-12-09 20:22:22 +01:00
$ { n } , and tensor 's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray' s size is not equal to the size of lengths ( $ { this . maxSize } vs . $ { e . length } ) , and the TensorArray is not marked as dynamically resizeable ` );let s=n===0?0:t.size/n,a=[];M(()=>{t=U(t,[1,n,s]);for(let i=0;i<e.length;++i){let c=i===0?0:r[i-1],l=[0,c,0],u=[1,e[i],s];a[i]=U(ze(t,l,u),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},Rd=class{constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(s=>{if(n!==s.dtype)throw new Error( ` Invalid data types ; op elements $ { n } , but list elements $ { s . dtype } ` );Dr(t,s.shape,"TensorList shape mismatch: "),Zt(s)}),this.idTensor=Ie(0),this.maxNumElements=r,Zt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Rd([...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 . ` );Dr(e,this.elementShape,"TensorList shape mismatch: ");let r= $ d(this.elementShape,this.tensors,e);return M(()=>{let s=this.tensors.map(a=>U(a,r));return Ot(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t } , but list elements $ { this . elementDtype } ` );if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n= $ d(this.elementShape,this.tensors,e),r=this.tensors.pop();return Dr(r.shape,e,"TensorList shape mismatch: "),U(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { e . dtype } , but list elements $ { this . elementDtype } ` );if(Dr(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Zt(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 . ` );Dr(this.tensors[e].shape,t,"TensorList shape mismatch: ");let r= $ d(this.elementShape,this.tensors,t);return U(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error( ` Invalid data types ; op elements $ { t . dtype } , but list elements $ { this . elementDtype } ` );if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error( ` Trying to set element $ { e } in a list with max $ { this . maxNumElements } elements . ` );Dr(this.elementShape,t.shape,"TensorList shape mismatch: "),Zt(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 } ` );Dr(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let r= $ d(this.elementShape,this.tensors,n);return e.length===0?Kn([],[0].concat(r)):M(()=>{let s=e.map(a=>U(this.tensors[a],r));return Ot(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error( ` TensorList dtype is $ { this . elementDtype } but concat requested dtype $ { e } ` );Dr(this.elementShape,t,"TensorList shape mismatch: ");let n= $ d(this.elementShape,this.tensors,t);return this.size()===0?Kn([],[0].concat(n)):M(()=>{let r=this.tensors.map(s=>U(s,n));return et(r,0)})}};function iH(e,t,n){let r=e.dtype;if(e.shape.length<1)throw new Error( ` Tensor m
2021-09-11 17:11:38 +02:00
tensor . shape [ 0 ] , but sum of lengths is
2021-12-09 20:22:22 +01:00
$ { r } , and tensor ' s shape is : $ { e . shape } ` );let a=e.shape.slice(1),o=yw(a,n),i=r===0?0:e.size/r,c=M(()=>{let u=[];e=U(e,[1,r,i]);for(let d=0;d<t.length;++d){let p=d===0?0:s[d-1],h=[0,p,0],f=[1,t[d],i];u[d]=U(ze(e,h,f),o)}return e.dispose(),u}),l=new Rd([],n,e.dtype,t.length);for(let u=0;u<c.length;u++)l.setItem(u,c[u]);return l}var dH=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let r=I("thenBranch",e,t,n),s=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let r=I("body",e,t,n),s=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(u=>u.id),c=await o[0].data();o.forEach(u=>{!u.kept&&i.indexOf(u.id)===-1&&u.dispose()});let l=a;for(;c[0];){let u=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);let d=l.map(h=>h.id);u.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[s].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);c=await p[0].data(),p.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return l}case"LoopCond":{let r=I("pred",e,t,n);return[As(r)]}case"Switch":{let r=I("pred",e,t,n),s=I("data",e,t,n);return s.kept||(s=As(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{let r=e.inputNames.find(s=>kn(s,t,n)!==void 0);if(r){let s=kn(r,t,n);return[As(s)]}return}case"Enter":{let r=I("frameName",e,t,n),s=I("tensor",e,t,n);return n.enterFrame(r),[As(s)]}case"Exit":{let r=I("tensor",e,t,n);return n.exitFrame(),[As(r)]}case"NextIteration":{let r=I("tensor",e,t,n);return n.nextIteration(),[As(r)]}case"TensorArrayV3":{let r=I("size",e,t,n),s=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),c=I("identicalElementShapes",e,t,n),l=I("name",e,t,n),u=new oH(l,s,r,a,c,o,i);return n.addTensorArray(u),[u.idTensor,Ie(1)]}case"TensorArrayWriteV3":{let r=I("tensorArrayId",e,t,n),s=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(s,a),[o.idTensor]}case"TensorArrayReadV3":{let r=I("tensorArrayId",e,t,n),s=I("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{let r=I("tensorArrayId",e,t,n),s=I("indices",e,t,n),a=I("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{let r=I("tensorArrayId",e,t,n),s=I("indices",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(s,a),[o.idTensor]}case"TensorArrayConcatV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=I("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{let r=I("tensorArrayId",e,t,n),s=I("tensor",e,t,n),a=I("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(a,s),[o.idTensor]}case"TensorArraySizeV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return[Ie(s.size(),"int32")]}case"TensorArrayCloseV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{let r=I("tensorListId",e,t,n),s=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(s,a),[o.idTensor]}case"TensorListGetItem":{let r=I("tensorListId",e,t,n),s=I("index",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let r=I("indices",e,t,n),s=I("tensor",e,t,n),a=I("elementShape",e,t,n),o=I("numElements",e,t,n),i=uH(s,r,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let r=I("elementShape",e,t,n),s=I("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=I(a,e,t,n),i=cH(r,s,o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{let r=I("tensorListId",e,t,n),s=I("indices",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensor
$ { e } ` );let r;return this.size===1/0||this.size==null?r=this.size:t?r=Math.ceil(this.size/e):r=Math.floor(this.size/e),nr(async()=>(await n.iterator()).columnMajorBatch(e,t,l6),r)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,nr(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,nr(async()=>(await t.iterator()).filter(r=>M(()=>e(r))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return nr(async()=>(await t.iterator()).map(n=>M(()=>e(n))),this.size)}mapAsync(e){let t=this;return nr(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 nr(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,nr(async()=>{let r=kw(async()=>({value:await t.iterator(),done:!1}));return KH(r.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,nr(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError(" ` Dataset . shuffle ( ) ` requires bufferSize to be specified."):new RangeError( ` \ ` Dataset.shuffle() \` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \` tf.Tensor \` s), consider setting bufferSize to the dataset size ( ${ this . size } elements) ` ) ; let r = this , s = zH . alea ( t || k . now ( ) . toString ( ) ) ; return nr ( async ( ) => { let a = s . int32 ( ) ; return n && ( a += s . int32 ( ) ) , ( await r . iterator ( ) ) . shuffle ( e , a . toString ( ) ) } , this . size ) } take ( e ) { let t = this , n ; return this . size != null && this . size > e ? n = e : this . size != null && this . size <= e ? n = this . size : n = null , nr ( async ( ) => ( await t . iterator ( ) ) . take ( e ) , n ) } async toArray ( ) { if ( this . size === 1 / 0 ) throw new Error ( "Can not convert infinite data stream to array." ) ; return ( await this . iterator ( ) ) . toArray ( ) } async toArrayForTest ( ) { if ( this . size === 1 / 0 ) throw new Error ( "Can not convert infinite data stream to array." ) ; return ( await this . iterator ( ) ) . toArrayForTest ( ) } } ; Su . MAX _BUFFER _SIZE = 1e4 ; function nr ( e , t = null ) { return new class extends Su { constructor ( ) { super ( ... arguments ) ; this . size = t } async iterator ( ) { return e ( ) } } } function c6 ( e ) { return nr ( async ( ) => rC ( e ) , e . length ) } function u6 ( e ) { if ( ! Iu ( 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 nr ( async ( ) => { let n = await tC ( e , r => { if ( r instanceof Su ) return { value : r . iterator ( ) , recurse : ! 1 } ; if ( Iu ( r ) ) return { value : null , recurse : ! 0 } ; throw new Error ( "Leaves of the structure passed to zip() must be Datasets, not primitives." ) } ) ; return XH ( n , wa . SHORTEST ) } , t ) } function l6 ( e ) { if ( e === null ) return null ; let t = e [ 0 ] ; return GH ( t ) ? { value : d6 ( e ) , recurse : ! 1 } : { value : null , recurse : ! 0 } } function d6 ( e ) { if ( e . length === 0 ) throw new Error ( "Can't make a batch of zero elements." ) ; return e [ 0 ] instanceof Ee ? Ot ( e ) : Kn ( e ) } var iC = class extends Su { constructor ( e ) { super ( ) ; this . input = e } async iterator ( ) { return ( await this . input . iterator ( ) ) . decodeUTF8 ( ) . split ( `
` ).map(r=>(r.endsWith(" \r ")&&(r=r.slice(0,-1)),r))}},cm='"',Pd=Symbol("out"),cC=Symbol("field"),um=Symbol("quote"),Sw=Symbol("quoteafterquote"),uC=Symbol("quoteinquote"),lC=class extends Su{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 iC(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((r,s)=>(r[s]=r[s]+1||1,r),{}),n=Object.keys(t).filter(r=>t[r]>1);if(k.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let r of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(r)===-1)throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],o=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!o)){let i=t[s],c=null;if(i==="")if(o&&o.default!==void 0)c=o.default;else{if(o&&(o.required||o.isLabel))throw new Error( ` Required column $ { a } is empty in this line : $ { e } ` );c=void 0}else{let l=Number(i);if(isNaN(l))o&&o.dtype==="bool"?c=this.getBoolean(i):c=i;else if(!o||!o.dtype)c=l;else switch(o.dtype){case"float32":c=l;break;case"int32":c=Math.floor(l);break;case"bool":c=this.getBoolean(i);break;default:c=l}}o&&o.isLabel?r[a]=c:n[a]=c}}return Object.keys(r).length===0?n:{xs:n,ys:r}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],r=0,s=e.length,a=Pd;for(let o=0;o<s;o++)switch(a){case Pd:switch(e.charAt(o)){case cm:r=o+1,a=um;break;case this.delimiter:if(r=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=Pd;break;default:a=cC,r=o;break}break;case cC:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o)),a=Pd,r=o+1;break;default:}break;case um:switch(e.charAt(o)){case cm:a=Sw;break;default:}break;case Sw:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o-1)),a=Pd,r=o+1;break;case cm:a=um;break;default:a=uC;break}break;case uC:switch(e.charAt(o)){case cm:a=um;break;default:}break;default:}if(a===Sw?n.push(e.substring(r,s-1)):n.push(e.substring(r)),t&&n.length!==this.fullColumnNames.length)throw new Error( ` Invalid row in csv file . Should have $ { this . fullColumnNames . length } elements in a row , but got $ { n } ` );return n}},dC=class extends en{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error( ` Invalid fftSi
2021-09-11 17:11:38 +02:00
=== === === === === === === === === =
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-12-09 20:22:22 +01:00
=== === === === === === === === === = ` ));let r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&k.isString(n[0])){let s=n.map(a=>k.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return _.mergeRealAndImagArrays(r,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(r=>k.decodeString(r))}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return Be(e.shape,e.dtype,n)}makeOutput(e,t,n){let r=this.write(e,t,n);return ks().makeTensorFromDataId(r,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=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 T6(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Tw.nextDataId=0;var vC={};Ae(vC,{addImpl:()=>wC,bincountImpl:()=>Nw,bincountReduceImpl:()=>kC,ceilImpl:()=>IC,concatImpl:()=>_w,equalImpl:()=>SC,expImpl:()=>CC,expm1Impl:()=>_C,floorImpl:()=>EC,gatherNdImpl:()=>AC,gatherV2Impl:()=>DC,greaterEqualImpl:()=> $ C,greaterImpl:()=>FC,lessEqualImpl:()=>PC,lessImpl:()=>RC,linSpaceImpl:()=>OC,logImpl:()=>MC,maxImpl:()=>LC,maximumImpl:()=>BC,minimumImpl:()=>zC,multiplyImpl:()=>Ew,negImpl:()=>WC,notEqualImpl:()=>VC,prodImpl:()=>UC,rangeImpl:()=>Dw,rsqrtImpl:()=>GC,sigmoidImpl:()=>h5,simpleAbsImpl:()=>xC,sliceImpl:()=>pm,sparseFillEmptyRowsImpl:()=>jC,sparseReshapeImpl:()=>qC,sparseSegmentReductionImpl:()=>Fw,sqrtImpl:()=>g5,squaredDifferenceImpl:()=>KC,stridedSliceImpl:()=>XC,stringNGramsImpl:()=>YC,stringSplitImpl:()=>ZC,stringToHashBucketFastImpl:()=>JC,subImpl:()=>QC,tileImpl:()=>e2,topKImpl:()=>n2,transposeImpl:()=>Aw,uniqueImpl:()=>r2});function xC(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var C6=e=>{let{x:t}=e.inputs,n=e.backend;ke(t,"abs");let r=new Float32Array(k.sizeFromShape(t.shape)),s=n.data.get(t.dataId).values;return r=xC(s),n.makeOutput(r,t.shape,t.dtype)},N6={kernelName:Yi,backendName:"cpu",kernelFunc:C6};function Wt(e){return(t,n,r,s,a)=>{let o=_.assertAndGetBroadcastShape(t,n),i=o.length,c=k.computeStrides(o),l=k.sizeFromShape(o),u=k.getTypedArrayFromDType(a,l),d=t.length,p=n.length,h=k.computeStrides(t),f=k.computeStrides(n),m=_.getBroadcastDims(t,o),g=_.getBroadcastDims(n,o);if(m.length+g.length===0)for(let b=0;b<u.length;++b)u[b]=e(r[b%r.length],s[b%s.length]);else for(let b=0;b<u.length;++b){let y=k.indexToLoc(b,i,c),v=y.slice(-d);m.forEach(C=>v[C]=0);let x=k.locToIndex(v,d,h),w=y.slice(-p);g.forEach(C=>w[C]=0);let T=k.locToIndex(w,p,f);u[b]=e(r[x],s[T])}return[u,o]}}function rr(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,i=n.makeTensorInfo(r.shape,"complex64"),c=n.data.get(i.dataId);return c.complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",a),imag:n.makeTensorInfo(s.shape,"float32",o)},i}var _6={kernelName:th,backendName:"cpu",kernelFunc:rr};function lm(e,t,n="float32"){if(n==="complex64"){let s=lm(e,t,"float32"),a=lm(e,t,"float32")
2021-09-11 17:11:38 +02:00
$ { a . shape } ` );if(r.shape.length!==2)throw new Error( ` Indices must be a matrix , saw :
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Values must be a vector , saw :
$ { s . shape } ` );if(o.shape.length!==0)throw new Error( ` Default value must be a scalar , saw :
2021-12-09 20:22:22 +01:00
$ { o . shape } ` );let i=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,u=n.data.get(o.dataId).values[0],[d,p,h,f,m]=jC(i,r.shape,r.dtype,c,s.dtype,l,u);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var MK={kernelName:Ol,backendName:"cpu",kernelFunc:OK};function LK(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error( ` Input indices should be a matrix but received shape
2021-09-11 17:11:38 +02:00
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape
2021-12-09 20:22:22 +01:00
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Target shape should be a vector but received shape $ { a . shape } ` );let o=Array.from(n.data.get(s.dataId).values),i=n.data.get(r.dataId).values,c=Array.from(n.data.get(a.dataId).values),[l,u,d]=qC(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(u,r.dtype,l),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var BK={kernelName:Hc,backendName:"cpu",kernelFunc:LK};function zK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
2021-12-09 20:22:22 +01:00
$ { a . shape } ` );if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[l,u]=Fw(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(u,r.dtype,l)}var WK={kernelName:Ml,backendName:"cpu",kernelFunc:zK};function VK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
2021-12-09 20:22:22 +01:00
$ { a . shape } ` );if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[l,u]=Fw(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(u,r.dtype,l)}var UK={kernelName:Ll,backendName:"cpu",kernelFunc:VK};function GK(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:p}=_.calculateShapes(a,s,i),h=!1,f=n.bufferSync(s),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],b=x2(f,m,i,p,u,l,c,d,g,h);return n.makeTensorInfo(i,b.dtype,b.values)}var HK={kernelName:Th,backendName:"cpu",kernelFunc:GK};function jK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=k.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=new Array(s.shape.length).fill(0),u=s.shape.slice();return c.map(d=>{let p=[...u];p[i]=d;let h=pi({inputs:{x:s},backend:n,attrs:{begin:l,size:p}});return l[i]+=d,h})}var qK={kernelName:Gc,backendName:"cpu",kernelFunc:jK},KK={kernelName:Bl,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,r=t;ke(n,"square");let s=r.data.get(n.dataId).values,a=new Float32Array(s.length);for(let i=0;i<s.length;++i){let c=s[i];a[i]=c*c}return{dataId:r.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},XK=ot(ea,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),YK={kernelName:ea,backendName:"cpu",kernelFunc:XK};function ZK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r;ke(s,"stridedSlice");let{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=Gt.sliceInfo(s.shape,a,o,i,c,l,u,d,p),w;if(m)w=Nt({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||b){k.assert(s.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { s . shape . length } ` );let T=Gt.computeOutShape(y,v,x),C=pi({inputs:{x:s},backend:n,attrs:{begin:y,size:T}});w=Nt({inputs:{x:C},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(C)}else{let T=n.bufferSync(s),C=XC(h,T,x,y);w=n.makeTensorInfo(f,C.dtype,C.values)}return w}var JK={kernelName:jc,backendName:"cpu",kernelFunc:ZK};function QK(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:l}=r,{data:u,dataSplits:d}=t,p=n.data.get(u.dataId).values,h=n.data.get(d.dataId).values,[f,m]=YC(p,h,s,a,o,i,c,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var eX={kernelName:Ch,backendName:"cpu",kernelFunc:QK};function tX(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error( ` Input must be a vector , got shape : $ { a . shape } ` );if(o.shape.length!==0)throw new Error( ` Delimiter must be a scalar , got shape : $ { o . shape } ` );let i=n.data.get(a.dataId).values,c=n.data.get(o.dataId).values[0],[l,u,d]=ZC(i,c,s),p=u.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var nX={kernelName:Nh,backendName:"cpu",kernelFunc:tX};function rX(e){let{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");let o=n.data.get(a.dataId).values,i=JC(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var sX={kernelName:_h,backendName:"cpu",kernelFunc:rX},aX=ot( $ o,e=>Math.tan(e)),oX={kernelName: $ o,backendName:"cpu",kernelFunc:aX},iX=ot(Ro,e=>Math.tanh(e)),cX={kernelName:Ro,backendName:"cpu",kernelFunc:iX};function uX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;ke(s,"tile");let o=e2(n.bufferSync(s),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var lX={kernelName:Qs,backendName:"cpu",kernelFunc:uX};function dX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r;ke(s,"topk
` ),a=s.length.toString().length+2,o=s.map((d,p)=>k.rightPad((p+1).toString(),a)+d),i=0;for(let d=0;d<o.length;d++)i=Math.max(o[d].length,i);let c=o.slice(0,r-1),l=o.slice(r-1,r),u=o.slice(r);console.log(c.join( `
2021-09-11 17:11:38 +02:00
` )),console.log(t.split( `
2021-12-09 20:22:22 +01:00
` )[0]),console.log( ` % c $ { k . rightPad ( l [ 0 ] , i ) } ` ,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join( `
` ))}function E2(e){return Ds(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function A2(e,t){if(be(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 gm(e,t){if(be(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function D2(e,t){let n=Ds(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return be(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),be(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function F2(e,t){let n=Ds(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return be(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),be(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function MX(){return Q().getNumber("WEBGL_VERSION")===2?1:4}function $ 2(e){return Ds(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function R2(e,t){let n=Q().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let r= ` [ $ { e } x$ { t } ] ` ;throw new Error("Requested texture size "+r+" is invalid.")}if(e>n||t>n){let r= ` [ $ { e } x$ { t } ] ` ,s= ` [ $ { n } x$ { n } ] ` ;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+s+".")}}function P2(e){return Ds(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Vw(e,t,n,r,s,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(be(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),be(e,()=>e.vertexAttribPointer(i,s,e.FLOAT,!1,a,o)),be(e,()=>e.enableVertexAttribArray(i)),!0)}function O2(e,t,n){W2(e,n),be(e,()=>e.activeTexture(e.TEXTURE0+n)),be(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function LX(e,t){W2(e,t),be(e,()=>e.activeTexture(e.TEXTURE0+t)),be(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function M2(e,t,n){return Ds(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function L2(e,t,n){return e.getUniformLocation(t,n)}function B2(e,t,n,r){be(e,()=>O2(e,t,r)),be(e,()=>e.uniform1i(n,r))}function BX(e){be(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),be(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),be(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function bm(e,t,n){be(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),be(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Uw(e,t){be(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),be(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Ud(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+z2(e,t))}function z2(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 Ds(e,t,n){let r=be(e,()=>t());if(r==null)throw new Error(n);return r}function W2(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n){let s= ` [ gl . TEXTURE0 , gl . TEXTURE$ { n } ] ` ;throw new Error( ` textureUnit must be in $ { s } . ` )}}function fi(e,t=2){return k.sizeFromShape(e.slice(0,e.length-t))}function mi(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 ym(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[fi(e),...mi(e)]),t}function V2(e,t=!1){let n=Q().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((s,a)=>a>=e.length-2?k.nearestLargerEven(e[a]):e[a]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=k.squeezeShape(e).newShape);let r=k.sizeFromShape(e);if(e.length<=1&&r<=n)return[1,r];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]
2021-09-11 17:11:38 +02:00
bool isnan _custom ( float val ) {
return ( val > 0.0 || val < 0.0 ) ? false : val != 0.0 ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan _custom ( val . x ) ,
isnan _custom ( val . y ) , isnan _custom ( val . z ) , isnan _custom ( val . w ) ) ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
# define isnan ( value ) isnan _custom ( value )
2021-12-06 12:34:50 +01:00
` ,c="",l= `
2021-09-11 17:11:38 +02:00
# define round ( value ) newRound ( value )
int newRound ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
ivec4 newRound ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
` ):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",o="",i= `
# define isnan ( value ) isnan _custom ( value )
bool isnan _custom ( float val ) {
return ( val > 0. || val < 1. || val == 0. ) ? false : true ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan _custom ( vec4 val ) {
return bvec4 ( isnan ( val . x ) , isnan ( val . y ) , isnan ( val . z ) , isnan ( val . w ) ) ;
2021-06-04 14:54:48 +02:00
}
2021-12-06 12:34:50 +01:00
` ,c= `
2021-09-11 17:11:38 +02:00
uniform float INFINITY ;
bool isinf ( float val ) {
return abs ( val ) == INFINITY ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isinf ( vec4 val ) {
return equal ( abs ( val ) , vec4 ( INFINITY ) ) ;
2021-06-04 14:54:48 +02:00
}
2021-10-22 15:06:43 +02:00
` ,l= `
2021-09-11 17:11:38 +02:00
int round ( float value ) {
return int ( floor ( value + 0.5 ) ) ;
}
ivec4 round ( vec4 value ) {
return ivec4 ( floor ( value + vec4 ( 0.5 ) ) ) ;
}
2021-12-09 20:22:22 +01:00
` ),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:c,defineRound:l}}function gi(e,t,n="index"){let r=k.computeStrides(t);return r.map((s,a)=>{let o= ` int $ { e [ a ] } = $ { n } / $ { s } ` ,i=a===r.length-1? ` int $ { e [ a + 1 ] } = $ { n } - $ { e [ a ] } * $ { s } ` : ` index -= $ { e [ a ] } * $ { s } ` ;return ` $ { o } ; $ { i } ; ` }).join("")}function km(e,t,n="index"){let r=k.computeStrides(t);return r.map((s,a)=>{let o= ` int $ { e [ a ] } = $ { n } / outShapeStrides [ $ { a } ] ` ,i=a===r.length-1? ` int $ { e [ a + 1 ] } = $ { n } - $ { e [ a ] } * outShapeStrides [ $ { a } ] ` : ` index -= $ { e [ a ] } * outShapeStrides [ $ { a } ] ` ;return ` $ { o } ; $ { i } ; ` }).join("")}function UX(e,t){let n=e.length,r=e.map(a=> ` $ { t } [ $ { a } ] ` ),s=new Array(n-1);s[n-2]=r[n-1];for(let a=n-3;a>=0;--a)s[a]= ` ( $ { s [ a + 1 ] } * $ { r [ a + 1 ] } ) ` ;return s}function GX(e,t,n="index"){let r=e.map((a,o)=>o),s=UX(r,t);return s.map((a,o)=>{let i= ` int $ { e [ o ] } = $ { n } / $ { s [ o ] } ` ,c=o===s.length-1? ` int $ { e [ o + 1 ] } = $ { n } - $ { e [ o ] } * $ { s [ o ] } ` : ` index -= $ { e [ o ] } * $ { s [ o ] } ` ;return ` $ { i } ; $ { c } ; ` }).join("")}function jw(e){let t=k.computeStrides(e).map(n=>n.toString());return `
2021-09-11 17:11:38 +02:00
int getFlatIndex ( ivec3 coords ) {
return coords . x * $ { t [ 0 ] } + coords . y * $ { t [ 1 ] } + coords . z ;
}
2021-12-09 20:22:22 +01:00
` }function qw(){return `
2021-09-11 17:11:38 +02:00
int getFlatIndex ( ivec3 coords ) {
return coords . x * outShapeStrides [ 0 ] + coords . y * outShapeStrides [ 1 ] + coords . z ;
}
2021-12-09 20:22:22 +01:00
` }var X2= `
2021-09-11 17:11:38 +02:00
const float FLOAT _MAX = 1.70141184 e38 ;
const float FLOAT _MIN = 1.17549435 e - 38 ;
lowp vec4 encode _float ( highp float v ) {
if ( isnan ( v ) ) {
return vec4 ( 255 , 255 , 255 , 255 ) ;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
highp float av = abs ( v ) ;
if ( av < FLOAT _MIN ) {
return vec4 ( 0.0 , 0.0 , 0.0 , 0.0 ) ;
} else if ( v > FLOAT _MAX ) {
return vec4 ( 0.0 , 0.0 , 128.0 , 127.0 ) / 255.0 ;
} else if ( v < - FLOAT _MAX ) {
return vec4 ( 0.0 , 0.0 , 128.0 , 255.0 ) / 255.0 ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
highp vec4 c = vec4 ( 0 , 0 , 0 , 0 ) ;
highp float e = floor ( log2 ( av ) ) ;
highp float m = exp2 ( fract ( log2 ( av ) ) ) - 1.0 ;
c [ 2 ] = floor ( 128.0 * m ) ;
m -= c [ 2 ] / 128.0 ;
c [ 1 ] = floor ( 32768.0 * m ) ;
m -= c [ 1 ] / 32768.0 ;
c [ 0 ] = floor ( 8388608.0 * m ) ;
highp float ebias = e + 127.0 ;
c [ 3 ] = floor ( ebias / 2.0 ) ;
ebias -= c [ 3 ] * 2.0 ;
c [ 2 ] += floor ( ebias ) * 128.0 ;
c [ 3 ] += 128.0 * step ( 0.0 , - v ) ;
return c / 255.0 ;
}
2021-12-09 20:22:22 +01:00
` ,{getBroadcastDims:Y2}=_;function HX(e,t,n){let r=[];if(e.forEach(h=>{let f=k.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?r.push( ` uniform float $ { h . name } $ { f > 1 ? ` [ ${ f } ] ` : "" } ; ` ):(r.push( ` uniform sampler2D $ { h . name } ; ` ),r.push( ` uniform int offset$ { h . name } ; ` )),n.enableShapeUniforms){let{uniformShape:m}=Kw(n.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(m.length){case 1:r.push( ` uniform int $ { h . name } Shape ; ` );break;case 2:r.push( ` uniform ivec2 $ { h . name } Shape ; ` );break;case 3:r.push( ` uniform ivec3 $ { h . name } Shape ; ` );break;case 4:r.push( ` uniform ivec4 $ { h . name } Shape ; ` );break;default:break}r.push( ` uniform ivec2 $ { h . name } TexShape ; ` )}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;");break;default:break}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(h=>{r.push( ` uniform $ { h . type } $ { h . name } $ { h . arrayIndex ? ` [ ${ h . arrayIndex } ] ` : "" } ; ` )});let s=r.join( `
` ),a=e.map(h=>jX(h,t,n.packedInputs,n.enableShapeUniforms)).join( `
` ),o=t.texShape,i=In(),c=XX(i),l,u,d=JX(i);return t.isPacked?(l=qX(t.logicalShape,o,n.enableShapeUniforms),u=ZX(i)):(l=KX(t.logicalShape,o,n.enableShapeUniforms),u=YX(i)),n.packedInputs&&(d+=n7),[d,c,u,s,l,a,n.userCode].join( `
` )}function Au(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return f7(e,t);case 1:return g7(e,t);case 2:return y7(e,t);case 3:return x7(e,t);case 4:return k7(e,t);case 5:return I7(e);case 6:return S7(e);default:throw new Error( ` $ { n . length } - D input sampling is not yet supported ` )}}function Z2(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return h7(e);case 1:return m7(e,t);case 2:return b7(e,t);case 3:return v7(e,t);default:return w7(e,t)}}function jX(e,t,n=!1,r){let s="";n?s+=Z2(e,r):s+=Au(e,r);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?s+=T7(e,t):s+=C7(e,t)),s}function qX(e,t,n){switch(e.length){case 0:return J2();case 1:return r7(e,t,n);case 2:return d7(e,t,n);case 3:return a7(e,t,n);default:return i7(e,t,n)}}function KX(e,t,n){switch(e.length){case 0:return J2();case 1:return s7(e,t,n);case 2:return p7(e,t,n);case 3:return o7(e,t,n);case 4:return c7(e,t,n);case 5:return u7(e,t);case 6:return l7(e,t);default:throw new Error( ` $ { e . length } - D output sampling is not yet supported ` )}}function XX(e){return `
2021-09-11 17:11:38 +02:00
float sampleTexture ( sampler2D textureSampler , vec2 uv ) {
return $ { e . texture2D } ( textureSampler , uv ) . r ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function YX(e){return `
2021-09-11 17:11:38 +02:00
void setOutput ( float val ) {
$ { e . output } = vec4 ( val , 0 , 0 , 0 ) ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function ZX(e){return `
2021-09-11 17:11:38 +02:00
void setOutput ( vec4 val ) {
$ { e . output } = val ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function JX(e){return ` $ { e . version }
2021-09-11 17:11:38 +02:00
precision highp float ;
precision highp int ;
precision highp sampler2D ;
$ { e . varyingFs } vec2 resultUV ;
$ { e . defineOutput }
const vec2 halfCR = vec2 ( 0.5 , 0.5 ) ;
struct ivec5
{
int x ;
int y ;
int z ;
int w ;
int u ;
} ;
struct ivec6
{
int x ;
int y ;
int z ;
int w ;
int u ;
int v ;
} ;
uniform float NAN ;
$ { e . defineSpecialNaN }
$ { e . defineSpecialInf }
$ { e . defineRound }
int imod ( int x , int y ) {
return x - y * ( x / y ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
int idiv ( int a , int b , float sign ) {
int res = a / b ;
int mod = imod ( a , b ) ;
if ( sign < 0. && mod != 0 ) {
res -= 1 ;
}
return res ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
# define HASHSCALE1 443.8975
float random ( float seed ) {
vec2 p = resultUV * seed ;
vec3 p3 = fract ( vec3 ( p . xyx ) * HASHSCALE1 ) ;
p3 += dot ( p3 , p3 . yzx + 19.19 ) ;
return fract ( ( p3 . x + p3 . y ) * p3 . z ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
2021-12-09 20:22:22 +01:00
$ { QX }
$ { e7 }
$ { t7 }
` }var QX= `
2021-09-11 17:11:38 +02:00
vec2 uvFromFlat ( int texNumR , int texNumC , int index ) {
int texR = index / texNumC ;
int texC = index - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
vec2 packedUVfrom1D ( int texNumR , int texNumC , int index ) {
int texelIndex = index / 2 ;
int texR = texelIndex / texNumC ;
int texC = texelIndex - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2021-12-09 20:22:22 +01:00
` ,e7= `
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom2D ( int texelsInLogicalRow , int texNumR ,
int texNumC , int row , int col ) {
int texelIndex = ( row / 2 ) * texelsInLogicalRow + ( col / 2 ) ;
int texR = texelIndex / texNumC ;
int texC = texelIndex - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2021-12-09 20:22:22 +01:00
` ,t7= `
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom3D ( int texNumR , int texNumC ,
int texelsInBatch , int texelsInLogicalRow , int b ,
int row , int col ) {
int index = b * texelsInBatch + ( row / 2 ) * texelsInLogicalRow + ( col / 2 ) ;
int texR = index / texNumC ;
int texC = index - texR * texNumC ;
return ( vec2 ( texC , texR ) + halfCR ) / vec2 ( texNumC , texNumR ) ;
}
2021-12-09 20:22:22 +01:00
` ,n7= `
2021-09-11 17:11:38 +02:00
float getChannel ( vec4 frag , vec2 innerDims ) {
vec2 modCoord = mod ( innerDims , 2. ) ;
return modCoord . x == 0. ?
( modCoord . y == 0. ? frag . r : frag . g ) :
( modCoord . y == 0. ? frag . b : frag . a ) ;
}
float getChannel ( vec4 frag , int dim ) {
float modCoord = mod ( float ( dim ) , 2. ) ;
return modCoord == 0. ? frag . r : frag . g ;
}
2021-12-09 20:22:22 +01:00
` ;function J2(){return `
2021-09-11 17:11:38 +02:00
int getOutputCoords ( ) {
return 0 ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function r7(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return r[0]===1?n? `
2021-09-11 17:11:38 +02:00
int getOutputCoords ( ) {
return 2 * int ( resultUV . x * ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
}
` : `
int getOutputCoords ( ) {
return 2 * int ( resultUV . x * $ { r [ 1 ] } . 0 ) ;
}
` :r[1]===1?n? `
int getOutputCoords ( ) {
return 2 * int ( resultUV . y * ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) ) ;
}
` : `
int getOutputCoords ( ) {
return 2 * int ( resultUV . y * $ { r [ 0 ] } . 0 ) ;
}
` :n? `
int getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
return 2 * ( resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
return 2 * ( resTexRC . x * $ { r [ 1 ] } + resTexRC . y ) ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function s7(e,t,n){return t[0]===1?n? `
2021-09-11 17:11:38 +02:00
int getOutputCoords ( ) {
return int ( resultUV . x * float ( outTexShape [ 1 ] ) ) ;
}
` : `
int getOutputCoords ( ) {
return int ( resultUV . x * $ { t [ 1 ] } . 0 ) ;
}
` :t[1]===1?n? `
int getOutputCoords ( ) {
return int ( resultUV . y * float ( outTexShape [ 0 ] ) ) ;
}
` : `
int getOutputCoords ( ) {
return int ( resultUV . y * $ { t [ 0 ] } . 0 ) ;
}
` :n? `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
return resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
int getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
return resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function a7(e,t,n){if(n)return `
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
int texelsInLogicalRow = int ( ceil ( float ( outShape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatch = texelsInLogicalRow * int ( ceil ( float ( outShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
int index = resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ;
int b = index / texelsInBatch ;
index -= b * texelsInBatch ;
int r = 2 * ( index / texelsInLogicalRow ) ;
int c = imod ( index , texelsInLogicalRow ) * 2 ;
return ivec3 ( b , r , c ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
` ;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return `
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
int index = resTexRC . x * $ { r [ 1 ] } + resTexRC . y ;
int b = index / $ { a } ;
index -= b * $ { a } ;
int r = 2 * ( index / $ { s } ) ;
int c = imod ( index , $ { s } ) * 2 ;
return ivec3 ( b , r , c ) ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function o7(e,t,n){if(n)return `
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
2021-12-09 20:22:22 +01:00
$ { km ( [ "r" , "c" , "d" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
}
2021-12-06 12:34:50 +01:00
` ;let r=gi(["r","c","d"],e);return `
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { r }
return ivec3 ( r , c , d ) ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function i7(e,t,n){if(n)return `
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
int index = resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ;
int texelsInLogicalRow = int ( ceil ( float ( outShape [ 3 ] ) / 2.0 ) ) ;
int texelsInBatch = texelsInLogicalRow * int ( ceil ( float ( outShape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatchN = texelsInBatch * outShape [ 1 ] ;
int b2 = index / texelsInBatchN ;
index -= b2 * texelsInBatchN ;
int b = index / texelsInBatch ;
index -= b * texelsInBatch ;
int r = 2 * ( index / texelsInLogicalRow ) ;
int c = imod ( index , texelsInLogicalRow ) * 2 ;
return ivec4 ( b2 , b , r , c ) ;
2021-05-18 14:11:17 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2),o=a,i="",c="b, r, c";for(let l=2;l<e.length-1;l++)o*=e[e.length-l-1],i= `
2021-10-22 15:06:43 +02:00
int b$ { l } = index / $ { o } ;
index -= b$ { l } * $ { o } ;
2021-12-06 12:34:50 +01:00
` +i,c= ` b$ { l } , ` +c;return `
2021-09-11 17:11:38 +02:00
ivec$ { e . length } getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
int index = resTexRC . x * $ { r [ 1 ] } + resTexRC . y ;
$ { i }
int b = index / $ { a } ;
index -= b * $ { a } ;
int r = 2 * ( index / $ { s } ) ;
int c = imod ( index , $ { s } ) * 2 ;
2021-12-06 12:34:50 +01:00
return ivec$ { e . length } ( $ { c } ) ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function c7(e,t,n){if(n)return `
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
2021-12-09 20:22:22 +01:00
$ { km ( [ "r" , "c" , "d" , "d2" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec4 ( r , c , d , d2 ) ;
2021-05-18 14:11:17 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let r=gi(["r","c","d","d2"],e);return `
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { r }
return ivec4 ( r , c , d , d2 ) ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function u7(e,t){let n=gi(["r","c","d","d2","d3"],e);return `
2021-09-11 17:11:38 +02:00
ivec5 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( $ { t [ 0 ] } ,
$ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { n }
ivec5 outShape = ivec5 ( r , c , d , d2 , d3 ) ;
return outShape ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function l7(e,t){let n=gi(["r","c","d","d2","d3","d4"],e);return `
2021-09-11 17:11:38 +02:00
ivec6 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
$ { n }
ivec6 result = ivec6 ( r , c , d , d2 , d3 , d4 ) ;
return result ;
2021-05-18 14:11:17 +02:00
}
2021-12-09 20:22:22 +01:00
` }function d7(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(k.arraysEqual(e,t))return n? `
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
return 2 * ivec2 ( resultUV . yx * vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
}
` : `
ivec2 getOutputCoords ( ) {
return 2 * ivec2 ( resultUV . yx * vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
}
` ;let s=Math.ceil(e[1]/2);return n? `
ivec2 getOutputCoords ( ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( outTexShape [ 0 ] ) / 2.0 ) , ceil ( float ( outTexShape [ 1 ] ) / 2.0 ) ) ;
int texelsInLogicalRow = int ( ceil ( float ( outShape [ 1 ] ) / 2.0 ) ) ;
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( packedTexShape [ 0 ] , packedTexShape [ 1 ] ) ) ;
int index = resTexRC . x * packedTexShape [ 1 ] + resTexRC . y ;
int r = 2 * ( index / texelsInLogicalRow ) ;
int c = imod ( index , texelsInLogicalRow ) * 2 ;
return ivec2 ( r , c ) ;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { r [ 0 ] } , $ { r [ 1 ] } ) ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int index = resTexRC . x * $ { r [ 1 ] } + resTexRC . y ;
int r = 2 * ( index / $ { s } ) ;
int c = imod ( index , $ { s } ) * 2 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return ivec2 ( r , c ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }function p7(e,t,n){return k.arraysEqual(e,t)?n? `
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords ( ) {
return ivec2 ( resultUV . yx * vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
return ivec2 ( resultUV . yx * vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` :e[1]===1?n? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
return ivec2 ( index , 0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
return ivec2 ( index , 0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` :e[0]===1?n? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
return ivec2 ( 0 , index ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
return ivec2 ( 0 , index ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` :n? `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( outTexShape [ 0 ] , outTexShape [ 1 ] ) ) ;
int index = resTexRC . x * outTexShape [ 1 ] + resTexRC . y ;
int r = index / outShape [ 1 ] ;
int c = index - r * outShape [ 1 ] ;
return ivec2 ( r , c ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
ivec2 getOutputCoords ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx *
vec2 ( $ { t [ 0 ] } , $ { t [ 1 ] } ) ) ;
int index = resTexRC . x * $ { t [ 1 ] } + resTexRC . y ;
int r = index / $ { e [ 1 ] } ;
int c = index - r * $ { e [ 1 ] } ;
return ivec2 ( r , c ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }function bi(e){return ` offset$ { e } ` }function h7(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=In();return `
2021-09-11 17:11:38 +02:00
vec4 $ { n } ( ) {
return $ { r . texture2D } ( $ { t } , halfCR ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }function f7(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return ` float $ { r } ( ) { return $ { n } ; } ` ;let[s,a]=e.shapeInfo.texShape;if(s===1&&a===1)return `
2021-09-11 17:11:38 +02:00
float $ { r } ( ) {
return sampleTexture ( $ { n } , halfCR ) ;
}
2021-12-06 12:34:50 +01:00
` ;let o=bi(n);if(t)return `
2021-09-11 17:11:38 +02:00
float $ { r } ( ) {
vec2 uv = uvFromFlat ( $ { n } TexShape [ 0 ] , $ { n } TexShape [ 1 ] , $ { o } ) ;
return sampleTexture ( $ { n } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let[i,c]=e.shapeInfo.texShape;return `
2021-09-11 17:11:38 +02:00
float $ { r } ( ) {
2021-12-06 12:34:50 +01:00
vec2 uv = uvFromFlat ( $ { i } , $ { c } , $ { o } ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { n } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }function m7(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=In();if(t)return `
2021-09-11 17:11:38 +02:00
vec4 $ { r } ( int index ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { n } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { n } TexShape [ 1 ] ) / 2.0 ) ) ;
vec2 uv = packedUVfrom1D (
packedTexShape [ 0 ] , packedTexShape [ 1 ] , index ) ;
return $ { a . texture2D } ( $ { n } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` ;let o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return `
vec4 $ { r } ( int index ) {
vec2 uv = packedUVfrom1D (
$ { o [ 0 ] } , $ { o [ 1 ] } , index ) ;
return $ { a . texture2D } ( $ { n } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }function g7(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return `
2021-09-11 17:11:38 +02:00
float $ { r } ( int index ) {
2021-12-09 20:22:22 +01:00
$ { Du ( e ) }
2021-09-11 17:11:38 +02:00
}
` ;let s=e.shapeInfo.texShape,a=s[0],o=s[1];if(o===1&&a===1)return `
float $ { r } ( int index ) {
return sampleTexture ( $ { n } , halfCR ) ;
}
2021-12-06 12:34:50 +01:00
` ;let i=bi(n);return o===1?t? `
2021-09-11 17:11:38 +02:00
float $ { r } ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + $ { i } ) + 0.5 ) / float ( $ { n } TexShape [ 0 ] ) ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` : `
float $ { r } ( int index ) {
vec2 uv = vec2 ( 0.5 , ( float ( index + $ { i } ) + 0.5 ) / $ { a } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` :a===1?t? `
float $ { r } ( int index ) {
vec2 uv = vec2 ( ( float ( index + $ { i } ) + 0.5 ) / float ( $ { n } TexShape [ 1 ] ) , 0.5 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` : `
float $ { r } ( int index ) {
vec2 uv = vec2 ( ( float ( index + $ { i } ) + 0.5 ) / $ { o } . 0 , 0.5 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` :t? `
float $ { r } ( int index ) {
vec2 uv = uvFromFlat ( $ { n } TexShape [ 0 ] , $ { n } TexShape [ 1 ] , index + $ { i } ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` : `
float $ { r } ( int index ) {
vec2 uv = uvFromFlat ( $ { a } , $ { o } , index + $ { i } ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }function b7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=a[0],i=a[1],c=In();if(a!=null&&k.arraysEqual(n,a))return t? `
2021-09-11 17:11:38 +02:00
vec4 $ { s } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
2021-12-06 12:34:50 +01:00
return $ { c . texture2D } ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` : `
vec4 $ { s } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { i } . 0 , $ { o } . 0 ) ;
2021-12-06 12:34:50 +01:00
return $ { c . texture2D } ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
` ;if(t)return `
vec4 $ { s } ( int row , int col ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { r } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { r } TexShape [ 1 ] ) / 2.0 ) ) ;
int valuesPerRow = int ( ceil ( float ( $ { r } Shape [ 1 ] ) / 2.0 ) ) ;
vec2 uv = packedUVfrom2D ( valuesPerRow , packedTexShape [ 0 ] , packedTexShape [ 1 ] , row , col ) ;
2021-12-06 12:34:50 +01:00
return $ { c . texture2D } ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let l=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],u=Math.ceil(n[1]/2);return `
2021-09-11 17:11:38 +02:00
vec4 $ { s } ( int row , int col ) {
2021-12-06 12:34:50 +01:00
vec2 uv = packedUVfrom2D ( $ { u } , $ { l [ 0 ] } , $ { l [ 1 ] } , row , col ) ;
return $ { c . texture2D } ( $ { r } , uv ) ;
2021-09-11 17:11:38 +02:00
}
2021-12-09 20:22:22 +01:00
` }function y7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(a!=null&&k.arraysEqual(n,a)){if(t)return `
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` ;let p=a[0],h=a[1];return `
float $ { s } ( int row , int col ) {
vec2 uv = ( vec2 ( col , row ) + halfCR ) / vec2 ( $ { h } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }let{newShape:o,keptDims:i}=k.squeezeShape(n),c=o;if(c.length<n.length){let p=Fu(e,c),h=["row","col"];return `
$ { Au ( p , t ) }
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col ) {
2021-12-09 20:22:22 +01:00
return $ { s } ( $ { $u ( h , i ) } ) ;
2021-09-11 17:11:38 +02:00
}
` }if(e.shapeInfo.isUniform)return `
float $ { s } ( int row , int col ) {
int index = round ( dot ( vec2 ( row , col ) , vec2 ( $ { n [ 1 ] } , 1 ) ) ) ;
2021-12-09 20:22:22 +01:00
$ { Du ( e ) }
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let l=a[0],u=a[1],d=bi(r);return u===1?t? `
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { d } ) , vec3 ( $ { r } Shape [ 1 ] , 1 , 1 ) ) ;
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / float ( $ { r } TexShape [ 0 ] ) ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` : `
float $ { s } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { d } ) , vec3 ( $ { n [ 1 ] } , 1 , 1 ) ) ;
2021-10-22 15:06:43 +02:00
vec2 uv = vec2 ( 0.5 , ( index + 0.5 ) / $ { l } . 0 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { r } , uv ) ;
}
2021-10-22 15:06:43 +02:00
` :l===1?t? `
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { d } ) , vec3 ( $ { r } Shape [ 1 ] , 1 , 1 ) ) ;
vec2 uv = vec2 ( ( index + 0.5 ) / float ( $ { r } TexShape [ 1 ] ) , 0.5 ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` : `
float $ { s } ( int row , int col ) {
float index = dot ( vec3 ( row , col , $ { d } ) , vec3 ( $ { n [ 1 ] } , 1 , 1 ) ) ;
2021-12-06 12:34:50 +01:00
vec2 uv = vec2 ( ( index + 0.5 ) / $ { u } . 0 , 0.5 ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { r } , uv ) ;
}
` :t? `
float $ { s } ( int row , int col ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { r } Shape [ 1 ] + col + $ { d } ;
vec2 uv = uvFromFlat ( $ { r } TexShape [ 0 ] , $ { r } TexShape [ 1 ] , index ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` : `
float $ { s } ( int row , int col ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { n [ 1 ] } + col + $ { d } ;
2021-12-06 12:34:50 +01:00
vec2 uv = uvFromFlat ( $ { l } , $ { u } , index ) ;
2021-09-11 17:11:38 +02:00
return sampleTexture ( $ { r } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }function v7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(n[0]===1){let p=n.slice(1),h=[1,2],f=Fu(e,p),m=["b","row","col"];return `
$ { Z2 ( f , t ) }
2021-09-11 17:11:38 +02:00
vec4 $ { s } ( int b , int row , int col ) {
2021-12-09 20:22:22 +01:00
return $ { s } ( $ { $u ( m , h ) } ) ;
2021-09-11 17:11:38 +02:00
}
2021-12-09 20:22:22 +01:00
` }let i=In();if(t)return `
2021-09-11 17:11:38 +02:00
vec4 $ { s } ( int b , int row , int col ) {
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { r } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { r } TexShape [ 1 ] ) / 2.0 ) ) ;
int valuesPerRow = int ( ceil ( float ( $ { r } Shape [ 2 ] ) / 2.0 ) ) ;
int texelsInBatch = valuesPerRow * int ( ceil ( float ( $ { r } Shape [ 1 ] ) / 2.0 ) ) ;
vec2 uv = packedUVfrom3D (
packedTexShape [ 0 ] , packedTexShape [ 1 ] , texelsInBatch , valuesPerRow , b , row , col ) ;
return $ { i . texture2D } ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let c=o[0],l=o[1],u=Math.ceil(n[2]/2),d=u*Math.ceil(n[1]/2);return `
2021-09-11 17:11:38 +02:00
vec4 $ { s } ( int b , int row , int col ) {
vec2 uv = packedUVfrom3D (
2021-12-06 12:34:50 +01:00
$ { c } , $ { l } , $ { d } , $ { u } , b , row , col ) ;
2021-09-11 17:11:38 +02:00
return $ { i . texture2D } ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }function x7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],o=n[2],{newShape:i,keptDims:c}=k.squeezeShape(n),l=i;if(l.length<n.length){let m=Fu(e,l),g=["row","col","depth"];return `
$ { Au ( m , t ) }
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col , int depth ) {
2021-12-09 20:22:22 +01:00
return $ { s } ( $ { $u ( g , c ) } ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` }if(e.shapeInfo.isUniform)return `
float $ { s } ( int row , int col , int depth ) {
int index = round ( dot ( vec3 ( row , col , depth ) ,
vec3 ( $ { a } , $ { o } , 1 ) ) ) ;
2021-12-09 20:22:22 +01:00
$ { Du ( e ) }
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let u=e.shapeInfo.texShape,d=u[0],p=u[1],h=e.shapeInfo.flatOffset;if(p===a&&h==null)return t? `
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col , int depth ) {
int stride1 = $ { r } Shape [ 2 ] ;
float texR = float ( row ) ;
float texC = dot ( vec2 ( col , depth ) , vec2 ( stride1 , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` : `
float $ { s } ( int row , int col , int depth ) {
float texR = float ( row ) ;
float texC = dot ( vec2 ( col , depth ) , vec2 ( $ { o } , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { p } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` ;if(p===o&&h==null)return t? `
float $ { s } ( int row , int col , int depth ) {
float texR = dot ( vec2 ( row , col ) , vec2 ( $ { r } Shape [ 1 ] , 1 ) ) ;
float texC = float ( depth ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` : `
float $ { s } ( int row , int col , int depth ) {
float texR = dot ( vec2 ( row , col ) , vec2 ( $ { n [ 1 ] } , 1 ) ) ;
float texC = float ( depth ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { p } . 0 , $ { d } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let f=bi(r);return t? `
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col , int depth ) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = $ { r } Shape [ 1 ] * $ { r } Shape [ 2 ] ;
int stride1 = $ { r } Shape [ 2 ] ;
int index = row * $ { a } + col * $ { o } + depth + $ { f } ;
vec2 uv = uvFromFlat ( $ { r } TexShape [ 0 ] , $ { r } TexShape [ 1 ] , index ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` : `
float $ { s } ( int row , int col , int depth ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { a } + col * $ { o } + depth + $ { f } ;
vec2 uv = uvFromFlat ( $ { d } , $ { p } , index ) ;
return sampleTexture ( $ { r } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }function w7(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=In();if(t)return `
2021-09-11 17:11:38 +02:00
vec4 $ { r } ( int b2 , int b , int row , int col ) {
int valuesPerRow = int ( ceil ( float ( $ { n } Shape [ 3 ] ) / 2.0 ) ) ;
int texelsInBatch = valuesPerRow * int ( ceil ( float ( $ { n } Shape [ 2 ] ) / 2.0 ) ) ;
int index = b * texelsInBatch + ( row / 2 ) * valuesPerRow + ( col / 2 ) ;
texelsInBatch *= $ { n } Shape [ 1 ] ;
index = b2 * texelsInBatch + index ;
ivec2 packedTexShape = ivec2 ( ceil ( float ( $ { n } TexShape [ 0 ] ) / 2.0 ) , ceil ( float ( $ { n } TexShape [ 1 ] ) / 2.0 ) ) ;
int texR = index / packedTexShape [ 1 ] ;
int texC = index - texR * packedTexShape [ 1 ] ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( packedTexShape [ 1 ] , packedTexShape [ 0 ] ) ; return $ { s . texture2D } ( $ { n } , uv ) ;
}
2021-12-06 12:34:50 +01:00
` ;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=c[0],u=c[1],d=Math.ceil(a[o-1]/2),p=d*Math.ceil(a[o-2]/2),h="int b, int row, int col",f= ` b * $ { p } + ( row / 2 ) * $ { d } + ( col / 2 ) ` ;for(let m=2;m<o-1;m++)h= ` int b$ { m } , ` +h,p*=a[o-m-1],f= ` b$ { m } * $ { p } + ` +f;return `
2021-09-11 17:11:38 +02:00
vec4 $ { r } ( $ { h } ) {
int index = $ { f } ;
2021-12-06 12:34:50 +01:00
int texR = index / $ { u } ;
int texC = index - texR * $ { u } ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { u } , $ { l } ) ;
2021-09-11 17:11:38 +02:00
return $ { s . texture2D } ( $ { n } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }function k7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:c,keptDims:l}=k.squeezeShape(n);if(c.length<n.length){let y=Fu(e,c),v=["row","col","depth","depth2"];return `
$ { Au ( y , t ) }
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col , int depth , int depth2 ) {
2021-12-09 20:22:22 +01:00
return $ { s } ( $ { $u ( v , l ) } ) ;
2021-09-11 17:11:38 +02:00
}
` }if(e.shapeInfo.isUniform)return `
float $ { s } ( int row , int col , int depth , int depth2 ) {
int index = round ( dot ( vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { i } , $ { o } , $ { a } , 1 ) ) ) ;
2021-12-09 20:22:22 +01:00
$ { Du ( e ) }
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1],f= ` int stride2 = $ { r } Shape [ 3 ] ; ` ,m= ` int stride1 = $ { r } Shape [ 2 ] * stride2 ; ` ,g= ` int stride0 = $ { r } Shape [ 1 ] * stride1 ; ` ;if(h===i&&u==null)return t? `
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col , int depth , int depth2 ) {
$ { f }
$ { m }
float texR = float ( row ) ;
float texC =
dot ( vec3 ( col , depth , depth2 ) ,
vec3 ( stride1 , stride2 , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` : `
float $ { s } ( int row , int col , int depth , int depth2 ) {
float texR = float ( row ) ;
float texC =
dot ( vec3 ( col , depth , depth2 ) ,
vec3 ( $ { o } , $ { a } , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { h } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
}
2021-12-06 12:34:50 +01:00
` ;if(h===a&&u==null)return t? `
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col , int depth , int depth2 ) {
float texR = dot ( vec3 ( row , col , depth ) ,
vec3 ( $ { r } Shape [ 1 ] * $ { r } Shape [ 2 ] , $ { r } Shape [ 2 ] , 1 ) ) ;
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { r } TexShape [ 1 ] , $ { r } TexShape [ 0 ] ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` : `
float $ { s } ( int row , int col , int depth , int depth2 ) {
float texR = dot ( vec3 ( row , col , depth ) ,
vec3 ( $ { n [ 1 ] * n [ 2 ] } , $ { n [ 2 ] } , 1 ) ) ;
float texC = float ( depth2 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { h } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { r } , uv ) ;
}
2021-12-06 12:34:50 +01:00
` ;let b=bi(r);return t? `
2021-09-11 17:11:38 +02:00
float $ { s } ( int row , int col , int depth , int depth2 ) {
// Explicitly use integer operations as dot() only works on floats.
$ { f }
$ { m }
$ { g }
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2 ;
vec2 uv = uvFromFlat ( $ { r } TexShape [ 0 ] , $ { r } TexShape [ 1 ] , index + $ { b } ) ;
return sampleTexture ( $ { r } , uv ) ;
}
` : `
float $ { s } ( int row , int col , int depth , int depth2 ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { i } + col * $ { o } +
depth * $ { a } + depth2 ;
vec2 uv = uvFromFlat ( $ { p } , $ { h } , index + $ { b } ) ;
return sampleTexture ( $ { r } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }function I7(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,o=t[2]*a,i=t[1]*o,{newShape:c,keptDims:l}=k.squeezeShape(t);if(c.length<t.length){let m=Fu(e,c),g=["row","col","depth","depth2","depth3"];return `
$ { Au ( m ) }
2021-09-11 17:11:38 +02:00
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
2021-12-09 20:22:22 +01:00
return $ { r } ( $ { $u ( g , l ) } ) ;
2021-09-11 17:11:38 +02:00
}
` }if(e.shapeInfo.isUniform)return `
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
float index = dot (
vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { i } , $ { o } , $ { a } , $ { s } ) ) +
depth3 ;
2021-12-09 20:22:22 +01:00
$ { Du ( e ) }
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&u==null)return `
2021-09-11 17:11:38 +02:00
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
vec4 ( $ { o } , $ { a } , $ { s } , 1 ) ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { h } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2021-12-06 12:34:50 +01:00
` ;if(h===s&&u==null)return `
2021-09-11 17:11:38 +02:00
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
float texR = dot (
vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { t [ 1 ] * t [ 2 ] * t [ 3 ] } ,
$ { t [ 2 ] * t [ 3 ] } , $ { t [ 3 ] } , 1 ) ) ;
int texC = depth3 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { h } . 0 , $ { p } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2021-12-06 12:34:50 +01:00
` ;let f=bi(n);return `
2021-09-11 17:11:38 +02:00
float $ { r } ( int row , int col , int depth , int depth2 , int depth3 ) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * $ { i } + col * $ { o } + depth * $ { a } +
depth2 * $ { s } + depth3 + $ { f } ;
vec2 uv = uvFromFlat ( $ { p } , $ { h } , index ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }function S7(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=k.squeezeShape(t);if(s.length<t.length){let g=Fu(e,s),b=["row","col","depth","depth2","depth3","depth4"];return `
$ { Au ( g ) }
2021-09-11 17:11:38 +02:00
float $ { r } ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
2021-12-09 20:22:22 +01:00
return $ { r } ( $ { $u ( b , a ) } ) ;
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
` }let o=t[5],i=t[4]*o,c=t[3]*i,l=t[2]*c,u=t[1]*l;if(e.shapeInfo.isUniform)return `
2021-09-11 17:11:38 +02:00
float $ { r } ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
int index = round ( dot (
vec4 ( row , col , depth , depth2 ) ,
2021-12-06 12:34:50 +01:00
vec4 ( $ { u } , $ { l } , $ { c } , $ { i } ) ) +
2021-09-11 17:11:38 +02:00
dot (
vec2 ( depth3 , depth4 ) ,
vec2 ( $ { o } , 1 ) ) ) ;
2021-12-09 20:22:22 +01:00
$ { Du ( e ) }
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
` ;let d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===u&&d==null)return `
2021-09-11 17:11:38 +02:00
float $ { r } ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
int texR = row ;
float texC = dot ( vec4 ( col , depth , depth2 , depth3 ) ,
2021-12-06 12:34:50 +01:00
vec4 ( $ { l } , $ { c } , $ { i } , $ { o } ) ) +
2021-09-11 17:11:38 +02:00
float ( depth4 ) ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { f } . 0 , $ { h } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
` ;if(f===o&&d==null)return `
float $ { r } ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
float texR = dot ( vec4 ( row , col , depth , depth2 ) ,
vec4 ( $ { t [ 1 ] * t [ 2 ] * t [ 3 ] * t [ 4 ] } ,
$ { t [ 2 ] * t [ 3 ] * t [ 4 ] } ,
$ { t [ 3 ] * t [ 4 ] } ,
$ { t [ 4 ] } ) ) + float ( depth3 ) ;
int texC = depth4 ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { f } . 0 , $ { h } . 0 ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2021-12-06 12:34:50 +01:00
` ;let m=bi(n);return `
2021-09-11 17:11:38 +02:00
float $ { r } ( int row , int col , int depth ,
int depth2 , int depth3 , int depth4 ) {
// Explicitly use integer operations as dot() only works on floats.
2021-12-06 12:34:50 +01:00
int index = row * $ { u } + col * $ { l } + depth * $ { c } +
2021-09-11 17:11:38 +02:00
depth2 * $ { i } + depth3 * $ { o } + depth4 + $ { m } ;
vec2 uv = uvFromFlat ( $ { h } , $ { f } , index ) ;
return sampleTexture ( $ { n } , uv ) ;
}
2021-12-09 20:22:22 +01:00
` }function Du(e){let t=e.name,n=k.sizeFromShape(e.shapeInfo.logicalShape);return n<2? ` return $ { t } ; ` : `
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < $ { n } ; i ++ ) {
if ( i == index ) {
return $ { t } [ i ] ;
}
}
2021-12-09 20:22:22 +01:00
` }function T7(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=Y2(e.shapeInfo.logicalShape,t.logicalShape),c=mt(o),l=o-a,u,d=["x","y","z","w","u","v"];a===0?u="":o<2&&i.length>=1?u="coords = 0;":u=i.map(y=> ` coords . $ { d [ y + l ] } = 0 ; ` ).join( `
` );let p="";o<2&&a>0?p="coords":p=e.shapeInfo.logicalShape.map((y,v)=> ` coords . $ { d [ v + l ] } ` ).join(", ");let h="return outputValue;",m=k.sizeFromShape(e.shapeInfo.logicalShape)===1,b=k.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!b)h= `
2021-09-11 17:11:38 +02:00
return vec4 ( outputValue . xy , outputValue . xy ) ;
` ;else if(m&&!b)o===1?h= `
return vec4 ( outputValue . x , outputValue . x , 0. , 0. ) ;
` :h= `
return vec4 ( outputValue . x ) ;
2021-12-09 20:22:22 +01:00
` ;else if(i.length){let y=a-2,v=a-1;i.indexOf(y)>-1&&i.indexOf(v)>-1?h="return vec4(outputValue.x);":i.indexOf(y)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(v)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return `
2021-09-11 17:11:38 +02:00
vec4 $ { s } ( ) {
2021-12-06 12:34:50 +01:00
$ { c } coords = getOutputCoords ( ) ;
$ { u }
2021-09-11 17:11:38 +02:00
vec4 outputValue = get$ { r } ( $ { p } ) ;
$ { h }
}
2021-12-09 20:22:22 +01:00
` }function C7(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===c&&e.shapeInfo.flatOffset==null&&k.arraysEqual(o,a))return `
2021-09-11 17:11:38 +02:00
float $ { s } ( ) {
return sampleTexture ( $ { n } , resultUV ) ;
}
2021-12-09 20:22:22 +01:00
` ;let l=mt(c),u=Y2(e.shapeInfo.logicalShape,t.logicalShape),d=c-i,p,h=["x","y","z","w","u","v"];i===0?p="":c<2&&u.length>=1?p="coords = 0;":p=u.map(m=> ` coords . $ { h [ m + d ] } = 0 ; ` ).join( `
2021-12-06 12:34:50 +01:00
` );let f="";return c<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=> ` coords . $ { h [ g + d ] } ` ).join(", "), `
2021-09-11 17:11:38 +02:00
float $ { s } ( ) {
2021-10-22 15:06:43 +02:00
$ { l } coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
$ { p }
return get$ { r } ( $ { f } ) ;
}
2021-12-09 20:22:22 +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 Kw(e,t,n){let{newShape:r,keptDims:s}=k.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):r,c=!e&&a>1&&!k.arraysEqual(t,n)&&r.length<a||o;return{useSqueezeShape:c,uniformShape:c?i:t,keptDims:s}}function Fu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function $ u(e,t){return t.map(n=>e[n]).join(", ")}function N7(e,t,n,r){let s=n.map((x,w)=>{let T={logicalShape:x.shape,texShape:x.isUniform?null:x.texData.texShape,isUniform:x.isUniform,isPacked:x.isUniform?!1:x.texData.isPacked,flatOffset:null};return x.texData!=null&&x.texData.slice!=null&&x.texData.slice.flatOffset>0&&(T.flatOffset=x.texData.slice.flatOffset),{name:t.variableNames[w],shapeInfo:T}}),a=s.map(x=>x.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=HX(s,o,t),c=_2(e.gl,i),l=e.createProgram(c),u=null,d=e.getUniformLocation(l,"NAN",!1);Q().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(l,"INFINITY",!1));let p=!1,h={},f={},m={};for(let x=0;x<t.variableNames.length;x++){let w=t.variableNames[x];h[w]=e.getUniformLocation(l,w,p),h[ ` offset$ { w } ` ]=e.getUniformLocation(l, ` offset$ { w } ` ,p),t.enableShapeUniforms&&(f[ ` $ { w } Shape ` ]=e.getUniformLocation(l, ` $ { w } Shape ` ,p),m[ ` $ { w } TexShape ` ]=e.getUniformLocation(l, ` $ { w } TexShape ` ,p))}let g,b,y;t.enableShapeUniforms&&(g=e.getUniformLocation(l,"outShape",p),y=e.getUniformLocation(l,"outShapeStrides",p),b=e.getUniformLocation(l,"outTexShape",p));let v=[];return t.customUniforms&&t.customUniforms.forEach((x,w)=>{v[w]=e.getUniformLocation(l,x.name,p)}),{program:t,fragmentShader:c,source:i,webGLProgram:l,uniformLocations:h,customUniformLocations:v,inShapeInfos:a,outShapeInfo:o,infLoc:u,nanLoc:d,inShapesLocations:f,inTexShapesLocations:m,outShapeLocation:g,outShapeStridesLocation:y,outTexShapeLocation:b}}function Q2(e,t){if(e.length!==t.length)throw Error( ` Binary was compiled with $ { e . length } inputs , but was executed with $ { t . length } inputs ` );e.forEach((n,r)=>{let s=n.logicalShape,a=t[r],o=a.shape;if(!k.arraysEqual(s,o))throw Error( ` Binary was compiled with different shapes than the current args . Shapes $ { s } and $ { o } must match ` );if(n.isUniform&&a.isUniform)return;let i=n.texShape,c=a.isUniform?null:a.texData.texShape;if(!k.arraysEqual(i,c))throw Error( ` Binary was compiled with different texture shapes than the current args . Shape $ { i } and $ { c } must match ` )})}function _7(e,t,n,r,s){t.program.enableShapeUniforms||(Q2(t.inShapeInfos,n),Q2([t.outShapeInfo],[r]));let a=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a,o[0],o[1]):e.setOutputMatrixTexture(a,o[0],o[1]),e.setProgram(t.webGLProgram),Q().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((c,l)=>{let u=t.program.variableNames[l],d=t.uniformLocations[u],p=t.uniformLocations[ ` offset$ { u } ` ],h=t.inShapesLocations[ ` $ { u } Shape ` ],f=t.inTexShapesLocations[ ` $ { u } TexShape ` ];if(h){let{uniformShape:m}=Kw(t.program.packedInputs,c.shape,c.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,c.texData.texShape[0],c.texData.texShape[1]),d!=null){if(c.isUniform){if(k.sizeFromShape(c.shape)<2)e.gl.uniform1f(d,c.uniformValues[0]);else{let m=c.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(d,m)}return}c.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,c.texData.slice.flatOffset),e.setInputMatrixTexture(c.texData.texture,d,l)}});let i=t.outShapeLocation;if(i)switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2021-12-09 20:22:22 +01:00
$ { this . enableShapeUniforms ? km ( [ "r" , "c" , "d" ] , e ) : gi ( [ "r" , "c" , "d" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( texShape [ 0 ] , texShape [ 1 ] ) ) ;
int index = 4 * ( resTexRC . x * texShape [ 1 ] + resTexRC . y ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < 4 ; i ++ ) {
int flatIndex = index + i ;
ivec3 rc = outCoordsFromFlatIndex ( flatIndex ) ;
result [ i ] = getA ( rc . x , rc . y , rc . z ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { t . output } = result ;
}
2021-12-09 20:22:22 +01:00
` }},D7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=zd.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=In();this.outputShape=e,this.enableShapeUniforms=Wn(this.outputShape.length),this.userCode= `
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex ( int index ) {
2021-12-09 20:22:22 +01:00
$ { this . enableShapeUniforms ? km ( [ "r" , "c" , "d" ] , e ) : gi ( [ "r" , "c" , "d" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 resTexRC = ivec2 ( resultUV . yx * vec2 ( texShape [ 0 ] , texShape [ 1 ] ) ) ;
int index = 4 * ( resTexRC . x * texShape [ 1 ] + resTexRC . y ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < 4 ; i ++ ) {
int flatIndex = index + i ;
ivec3 rc = outCoordsFromFlatIndex ( flatIndex ) ;
result [ i ] = getChannel ( getA ( rc . x , rc . y , rc . z ) , vec2 ( rc . y , rc . z ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
$ { t . output } = result ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},F7=class{constructor(e){this.variableNames=["A"],this.outTexUsage=mr.DOWNLOAD;let t=In();this.outputShape=e,this.userCode= `
$ { X2 }
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
float x = getAAtOutCoords ( ) ;
$ { t . output } = encode _float ( x ) ;
}
2021-12-09 20:22:22 +01:00
` }}, $ 7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=mr.DOWNLOAD;let t=In();this.outputShape=e,this.userCode= `
$ { X2 }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
float x = getChannel ( getAAtOutCoords ( ) , vec2 ( coords . y , coords . z ) ) ;
$ { t . output } = encode _float ( x ) ;
}
2021-12-09 20:22:22 +01:00
` }},R7=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=In();this.outputShape=e,this.enableShapeUniforms=Wn(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode= `
$ { this . enableShapeUniforms ? qw ( ) : jw ( e ) }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int flatIndex = getFlatIndex ( coords ) ;
int offset = imod ( flatIndex , 4 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int r = flatIndex / texShape [ 1 ] ;
int c = imod ( flatIndex , texShape [ 1 ] ) ;
vec2 uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( texShape [ 1 ] , texShape [ 0 ] ) ;
vec4 values = $ { n . texture2D } ( A , uv ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
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-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { n . output } = vec4 ( $ { r } , 0. , 0. , 0. ) ;
}
2021-12-09 20:22:22 +01:00
` }},P7=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=In();this.outputShape=e,this.enableShapeUniforms=Wn(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let o=0;o<=1;o++){let i=a*2+o;r+= `
2021-09-11 17:11:38 +02:00
localCoords = coords ;
if ( localCoords [ 2 ] + $ { o } < $ { this . enableShapeUniforms ? "outShape[2]" : ` ${ e [ 2 ] } ` } ) {
localCoords [ 2 ] += $ { o } ;
if ( localCoords [ 1 ] + $ { a } < $ { this . enableShapeUniforms ? "outShape[1]" : ` ${ e [ 1 ] } ` } ) {
localCoords [ 1 ] += $ { a } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = getFlatIndex ( localCoords ) ;
offset = imod ( flatIndex , 4 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = idiv ( flatIndex , 4 , 1. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int r = flatIndex / texShape [ 1 ] ;
int c = imod ( flatIndex , texShape [ 1 ] ) ;
vec2 uv = ( vec2 ( c , r ) + halfCR ) / vec2 ( texShape [ 1 ] , texShape [ 0 ] ) ;
values = $ { n . texture2D } ( A , uv ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( offset == 0 ) {
result [ $ { i } ] = values [ 0 ] ;
} else if ( offset == 1 ) {
result [ $ { i } ] = values [ 1 ] ;
} else if ( offset == 2 ) {
result [ $ { i } ] = values [ 2 ] ;
} else {
result [ $ { i } ] = values [ 3 ] ;
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
` }this.userCode= `
2021-12-09 20:22:22 +01:00
$ { this . enableShapeUniforms ? qw ( ) : jw ( e ) }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
int flatIndex , r , c , offset ;
ivec3 localCoords ;
vec2 uv ;
vec4 values ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { r }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { n . output } = $ { s } ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},eN={};Ae(eN,{bindVertexProgramAttributeStreams:()=>uN,createBufferFromOutputTexture:()=>pN,createFloat16MatrixTexture:()=>aN,createFloat16PackedMatrixTexture:()=>cN,createFloat32MatrixTexture:()=>sN,createIndexBuffer:()=>rN,createPackedMatrixTexture:()=>iN,createUnsignedBytesMatrixTexture:()=>oN,createVertexBuffer:()=>nN,createVertexShader:()=>tN,downloadByteEncodedFloatMatrixFromOutputTexture:()=>fN,downloadFloat32MatrixFromBuffer:()=>hN,downloadMatrixFromPackedOutputTexture:()=>gN,downloadPackedMatrixFromBuffer:()=>mN,getInternalFormatForFloat16MatrixTexture:()=>Yw,getInternalFormatForFloat16PackedMatrixTexture:()=>Qw,getInternalFormatForFloat32MatrixTexture:()=>Xw,getInternalFormatForPackedMatrixTexture:()=>Jw,getInternalFormatForUnsignedBytesMatrixTexture:()=>Zw,uploadDenseMatrixToTexture:()=>lN,uploadPixelDataToTexture:()=>dN});function tN(e){let t=In(),n= ` $ { t . version }
2021-09-11 17:11:38 +02:00
precision highp float ;
$ { t . attribute } vec3 clipSpacePos ;
$ { t . attribute } vec2 uv ;
$ { t . varyingVs } vec2 resultUV ;
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
gl _Position = vec4 ( clipSpacePos , 1 ) ;
resultUV = uv ;
2021-12-09 20:22:22 +01:00
} ` ;return N2(e,n)}function nN(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 D2(e,t)}function rN(e){let t=new Uint16Array([0,1,2,2,1,3]);return F2(e,t)}function Hd(e,t,n,r,s,a){R2(t,n);let o= $ 2(e),i=e.TEXTURE_2D;return be(e,()=>e.bindTexture(i,o)),be(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),be(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),be(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),be(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),Q().getNumber("WEBGL_VERSION")===1?be(e,()=>e.texImage2D(i,0,r,t,n,0,s,a,null)):be(e,()=>e.texStorage2D(i,1,r,t,n)),be(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function Xw(e){return e.internalFormatFloat}function sN(e,t,n,r){let[s,a]=Wd(t,n);return Hd(e,s,a,Xw(r),r.textureFormatFloat,e.FLOAT)}function Yw(e){return e.internalFormatHalfFloat}function aN(e,t,n,r){let[s,a]=Wd(t,n);return Hd(e,s,a,Yw(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function Zw(e){return e.downloadTextureFormat}function oN(e,t,n,r){let[s,a]=Wd(t,n);return Hd(e,s,a,Zw(r),e.RGBA,e.UNSIGNED_BYTE)}function Jw(e){return e.internalFormatPackedFloat}function iN(e,t,n,r){let[s,a]=_u(t,n);return Hd(e,s,a,Jw(r),e.RGBA,e.FLOAT)}function Qw(e){return e.internalFormatPackedHalfFloat}function cN(e,t,n,r){let[s,a]=_u(t,n);return Hd(e,s,a,Qw(r),e.RGBA,r.textureTypeHalfFloat)}function uN(e,t,n){let r=0,s=3*4,a=3*4+2*4;return be(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Vw(e,t,"clipSpacePos",n,3,a,r)&&Vw(e,t,"uv",n,2,a,s)}function lN(e,t,n,r,s,a){be(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,i,c;s instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,c=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,c=a.internalFormatPackedFloat),o.set(s),Q().getNumber("WEBGL_VERSION")===2?be(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o)):be(e,()=>e.texImage2D(e.TEXTURE_2D,0,c,n,r,0,e.RGBA,i,o)),be(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function dN(e,t,n){be(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Q().getNumber("WEBGL_VERSION")===2?(be(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)),e.flush()):be(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Q().getNumber("WEBGL_VERSION")===2?(be(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)),e.flush()):be(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),be(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function pN(e,t,n,r){let s=e.createBuffer();be(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));let i=4*4*t*n;return be(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),be(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),be(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function hN(e,t,n){let r=e,s=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,s),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),s}function fN(e,t,n,r){let[s,a]=Wd(t,n),o=4,i=new Uint8Array(AX(t*n,o));return be(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function mN(e,t,n,r,s,a,o,i){let c=e,l=new Float32Array(DX(a,o));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,l),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),l}function gN(e,t,n){let r=new Float32Array(t*n*4);return be(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}var bN=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=Q().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,S2(t,e)):this.gl=ds(t);let n="WEBGL_color_buffer_float",r="EXT_color_buffer_half_float";if(Q().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Vd(this.gl,s),gr(this.gl,a))this.textureHalfFloatExtension=Vd(this.gl,a);else if(Q().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.colorB
2021-09-11 17:11:38 +02:00
void main ( ) {
setOutput ( vec4 ( getA ( ) , 0. , 0. , 0. ) ) ;
}
2021-12-09 20:22:22 +01:00
` ;else{let t=Sn("rc",this.rank),n=mt(this.rank),r=this.getOutOfBoundsCondition(t),s=this.getSetup(t),a=this.getOutput(t);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
2021-12-09 20:22:22 +01:00
$ { n } rc = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-12-09 20:22:22 +01:00
if ( $ { r } ) {
2021-09-11 17:11:38 +02:00
setOutput ( vec4 ( 0 ) ) ;
} else {
2021-12-09 20:22:22 +01:00
$ { s }
2021-04-01 19:39:54 +02:00
2021-12-09 20:22:22 +01:00
setOutput ( vec4 ( $ { a } ) ) ;
2021-04-01 19:39:54 +02:00
}
}
2021-12-09 20:22:22 +01:00
` }}getSourceCoordsArr(e){let t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let s= ` $ { n === 0 ? "r" : "rp1" } , $ { r === 0 ? "c" : "cp1" } ` ;for(let a=2;a<this.rank;a++)s= ` $ { e [ e . length - 1 - a ] } , ` +s;t.push(s)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return ` rc > $ { this . enableShapeUniforms ? "outShape" : this . outputShape [ 0 ] } ` ;let t="";for(let n=this.rank-2;n<this.rank;n++)t+= ` $ { e [ n ] } >= $ { this . enableShapeUniforms ? ` outShape[ ${ n } ] ` : this . outputShape [ n ] } ` ,n<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),n=this.enableShapeUniforms? ` outShape [ $ { this . rank } - 1 ] ` :this.outputShape[this.rank-1],r=this.enableShapeUniforms? ` outShape [ $ { this . rank } - 2 ] ` :this.outputShape[this.rank-2];return `
int r = $ { t [ 0 ] } ;
int c = $ { t [ 1 ] } ;
int rp1 = r + 1 ;
int cp1 = c + 1 ;
bool cEdge = cp1 >= $ { n } ;
bool rEdge = rp1 >= $ { r } ;
` }getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1? ` getA ( rc ) ,
rc + 1 >= $ { this . enableShapeUniforms ? "outShape" : this . outputShape [ 0 ] } ? 0. : getA ( rc + 1 ) ,
0 , 0 ` : ` getA ( $ { t [ 0 ] } ) ,
cEdge ? 0. : getA ( $ { t [ 1 ] } ) ,
rEdge ? 0. : getA ( $ { t [ 2 ] } ) ,
rEdge || cEdge ? 0. : getA ( $ { t [ 3 ] } ) ` }},kN=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Wn(this.outputShape.length);let n="";for(let r=0;r<4;r++){let s="thisRC = rc;";r%2==1&&(s+="thisRC.z += 1;"),r>1&&(s+="thisRC.y += 1;"),n+= `
2021-09-11 17:11:38 +02:00
$ { s }
$ { r > 0 ? "if(thisRC.y < rows && thisRC.z < cols){" : "" }
int flatIndex = getFlatIndex ( thisRC ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 inputRC = inputCoordsFromReshapedOutCoords ( flatIndex ) ;
vec2 inputRCInnerDims = vec2 ( float ( inputRC . y ) , float ( inputRC . z ) ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result [ $ { r } ] =
getChannel ( getA ( inputRC . x , inputRC . y , inputRC . z ) , inputRCInnerDims ) ;
$ { r > 0 ? "}" : "" }
` }this.userCode= `
2021-12-09 20:22:22 +01:00
$ { I9 ( t , this . enableShapeUniforms ) }
$ { this . enableShapeUniforms ? qw ( ) : jw ( e ) }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 thisRC ;
int rows = $ { this . enableShapeUniforms ? "outShape[1]" : e [ 1 ] } ;
int cols = $ { this . enableShapeUniforms ? "outShape[2]" : e [ 2 ] } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { n }
2021-04-01 19:39:54 +02:00
setOutput ( result ) ;
}
2021-12-09 20:22:22 +01:00
` }};function I9(e,t){return `
2021-09-11 17:11:38 +02:00
ivec3 inputCoordsFromReshapedOutCoords ( int index ) {
2021-12-09 20:22:22 +01:00
$ { t ? GX ( [ "r" , "c" , "d" ] , "inputShape" ) : gi ( [ "r" , "c" , "d" ] , e ) }
2021-09-11 17:11:38 +02:00
return ivec3 ( r , c , d ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }var S9=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){let r=SN(t,n),s=TN(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=IN(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let i=this.freeTextures[s].shift();return this.usedTextures[s].push(i),i}let o;return r===on.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===on.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===on.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===on.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===on.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(e,t,n,r){if(this.freeTextures==null)return;let s=SN(n,r),a=TN(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);let o=IN(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=Q().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let c=this.usedTextures[a],l=c.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c.splice(l,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 T9(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error( ` Unknown internal format $ { t } ` )}function IN(e,t,n,r,s){let a=C9(t,r),o;if(s){let[c,l]=_u(e[0],e[1]);o=c*l}else{let[c,l]=Wd(e[0],e[1]);o=c*l}let i=T9(n,a);return o*i}function C9(e,t){switch(e){case on.PACKED_2X2_FLOAT32:return Jw(t);case on.PACKED_2X2_FLOAT16:return Qw(t);case on.UNPACKED_FLOAT32:return Xw(t);case on.UNPACKED_FLOAT16:return Yw(t);case on.PACKED_4X1_UNSIGNED_BYTE:return Zw(t);default:throw new Error( ` Unknown physical texture type $ { e } ` )}}function N9(e){return Q().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?on.PACKED_2X2_FLOAT32:on.UNPACKED_FLOAT32:e?on.PACKED_2X2_FLOAT16:on.UNPACKED_FLOAT16}function SN(e,t){if(e===mr.UPLOAD)return on.PACKED_2X2_FLOAT32;if(e===mr.RENDER||e==null)return N9(t);if(e===mr.DOWNLOAD||e===mr.PIXELS)return on.PACKED_4X1_UNSIGNED_BYTE;throw new Error( ` Unknown logical texture type $ { e } ` )}function TN(e,t,n){return ` $ { e [ 0 ] } _$ { e [ 1 ] } _$ { t } _$ { n } ` }var Sa=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Wn(this.outputShape.length),this.userCode= `
2021-09-11 17:11:38 +02:00
float unaryOperation ( float x ) {
$ { t }
2021-04-15 22:59:35 +02:00
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
float x = getAAtOutCoords ( ) ;
float y = unaryOperation ( x ) ;
2021-04-15 22:59:35 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( y ) ;
}
2021-12-09 20:22:22 +01:00
` }},qr="if (isnan(x)) return x;",_9="return x;",CN="return abs(x);",E9="return (x >= 0.0) ? x : (exp(x) - 1.0);",A9=qr+ `
2021-09-11 17:11:38 +02:00
return ( x < 0.0 ) ? 0.0 : x ;
2021-12-09 20:22:22 +01:00
` ,D9=qr+ `
2021-09-11 17:11:38 +02:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2021-12-09 20:22:22 +01:00
` ,Im="return x;",F9="return 1.0 / (1.0 + exp(-1.0 * x));", $ 9="return x;",R9= `
2021-09-11 17:11:38 +02:00
vec4 result ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result . r = ( x . r >= 0.0 ) ? x . r : ( exp ( x . r ) - 1.0 ) ;
result . g = ( x . g >= 0.0 ) ? x . g : ( exp ( x . g ) - 1.0 ) ;
result . b = ( x . b >= 0.0 ) ? x . b : ( exp ( x . b ) - 1.0 ) ;
result . a = ( x . a >= 0.0 ) ? x . a : ( exp ( x . a ) - 1.0 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,P9= `
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,O9= `
2021-09-11 17:11:38 +02:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,M9="return 1.0 / (1.0 + exp(-1.0 * x));",Ru=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Wn(this.outputShape.length),this.userCode= `
2021-09-11 17:11:38 +02:00
vec4 unaryOperation ( vec4 x ) {
$ { t }
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main ( ) {
vec4 x = getAAtOutCoords ( ) ;
vec4 y = unaryOperation ( x ) ;
setOutput ( y ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},L9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=Wn(this.outputShape.length);let t=e.length,n=Sn("rc",t),r=mt(t),s=w9(t,n),a=n.slice(-2),o=t<=1?"rc": ` vec2 ( $ { a . join ( "," ) } ) ` ;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { r } rc = getOutputCoords ( ) ;
vec4 packedInput = getA ( $ { s } ) ;
setOutput ( getChannel ( packedInput , $ { o } ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},B9=rs.whereImpl,z9=1e-7,W9=1e-4,Sm={};function V9(e){return e in Sm||(Sm[e]={}),Sm[e]}var U9=Q().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),G9=600;function H9(){return Q().global.screen==null?1024:Q().global.screen.height*Q().global.screen.width*window.devicePixelRatio*G9/1024/1024}var Tm=class extends wl{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.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Q().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=ds(Q().getNumber("WEBGL_VERSION"));this.binaryCache=V9(Q().getNumber("WEBGL_VERSION")),this.gpgpu=new bN(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 S9(this.gpgpu),this.numMBBeforeWarning=H9(),this.texData=new jp(this,ks())}nextDataId(){return Tm.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((Q().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Q().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:mr.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,r,s){if(Q().getBool("DEBUG")&&this.checkNumericalProblems(t),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:mr.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:s,slice:a,shape:o,isPacked:i}=t;if(a!=null){let d;i?d=new Ru(o,Im):d=new Sa(o,Im);let p=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:r}],r),h=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return n;let c=this.activeTimers!=null,l;c&&(l=k.now());let u;if(r==="complex64"){let d=this.readSync(s.real.dataId),p=this.readSync(s.imag.dataId);u=_.mergeRealAndImagArrays(d,p)}else u=this.getValuesFromTexture(e);return c&&(this.downloadWaitMs+=k.now()-l),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(s!=null){let h;i?h=new Ru(r,Im):h=new Sa(r,Im);let f=this.runWebGLProgram(h,[{dataId:e,shape:r,dtype:a}],a),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(n!=null)return this.convertAndCacheOnCPU(e);if(Q().getBool("DEBUG")&&!Q().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&Q().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c=null,l;if(a!=="complex64"&&Q().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);let h=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(h.texture,...mm(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];u=_.mergeRealAndImagArrays(f,m)}else if(c==null)u=this.getValuesFromTexture(e);else{let h=k.sizeFromShape(r);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,h)}if(l!=null&&this.disposeIntermediateTensorInfo(l),c!=null){let h=this.gpgpu.gl;be(h,()=>h.deleteBuffer(c))}let d=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(h=>h(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.dis
2021-09-11 17:11:38 +02:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2021-12-09 20:22:22 +01:00
` ,Pu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=Wn(this.outputShape.length),this.userCode= `
2021-09-11 17:11:38 +02:00
float binaryOperation ( float a , float b ) {
$ { e }
2021-04-01 19:39:54 +02:00
}
void main ( ) {
2021-09-11 17:11:38 +02:00
float a = getAAtOutCoords ( ) ;
float b = getBAtOutCoords ( ) ;
setOutput ( binaryOperation ( a , b ) ) ;
}
2021-12-09 20:22:22 +01:00
` }},Cm= `
2021-09-11 17:11:38 +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-12-09 20:22:22 +01:00
` ,jd=class{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length;this.enableShapeUniforms=Wn(s);let a="";if(r)if(s===0||k.sizeFromShape(this.outputShape)===1)a= `
2021-09-11 17:11:38 +02:00
result . y = 0. ;
result . z = 0. ;
result . w = 0. ;
` ;else if(a= `
2021-12-09 20:22:22 +01:00
$ { mt ( s ) } coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
` ,s===1)this.enableShapeUniforms?a+= `
result . y = ( coords + 1 ) >= outShape ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
` :a+= `
result . y = ( coords + 1 ) >= $ { this . outputShape [ 0 ] } ? 0. : result . y ;
result . z = 0. ;
result . w = 0. ;
2021-12-09 20:22:22 +01:00
` ;else{let i=Sn("coords",s);this.enableShapeUniforms?a+= `
2021-09-11 17:11:38 +02:00
bool nextRowOutOfBounds =
( $ { i [ s - 2 ] } + 1 ) >= outShape [ $ { s } - 2 ] ;
bool nextColOutOfBounds =
( $ { i [ s - 1 ] } + 1 ) >= outShape [ $ { s } - 1 ] ;
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
` :a+= `
bool nextRowOutOfBounds =
( $ { i [ s - 2 ] } + 1 ) >= $ { this . outputShape [ s - 2 ] } ;
bool nextColOutOfBounds =
( $ { i [ s - 1 ] } + 1 ) >= $ { this . outputShape [ s - 1 ] } ;
result . y = nextColOutOfBounds ? 0. : result . y ;
result . z = nextRowOutOfBounds ? 0. : result . z ;
result . w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result . w ;
` }this.userCode= `
vec4 binaryOperation ( vec4 a , vec4 b ) {
$ { e }
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
vec4 a = getAAtOutCoords ( ) ;
vec4 b = getBAtOutCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = binaryOperation ( a , b ) ;
$ { a }
2021-04-01 19:39:54 +02:00
setOutput ( result ) ;
}
2021-12-09 20:22:22 +01:00
` }};function sr(e){let{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var X9={kernelName:so,backendName:"webgl",kernelFunc:sr};function Ta(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(a.dataId),i=sr({inputs:{x:r},backend:n}),c=sr({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:c},a}var Y9={kernelName:th,backendName:"webgl",kernelFunc:Ta},EN="return (a < 0.) ? b * a : a;",AN= `
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2021-12-09 20:22:22 +01:00
` ;function Z9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=n.makeTensorInfo([],"float32",k.createScalarValue(a,"float32")),i=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jd(AN,s.shape,o.shape):new Pu(EN,s.shape,o.shape),c=n.runWebGLProgram(i,[s,o],"float32");return n.disposeIntermediateTensorInfo(o),c}var J9={kernelName:ao,backendName:"webgl",kernelFunc:Z9},DN="return (a < 0.) ? b * a : a;",FN= `
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4 ( lessThan ( a , vec4 ( 0. ) ) ) ;
return ( aLessThanZero * ( b * a ) ) + ( ( vec4 ( 1.0 ) - aLessThanZero ) * a ) ;
2021-12-09 20:22:22 +01:00
` ;function Q9(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jd(FN,r.shape,s.shape):new Pu(DN,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}var eY={kernelName:vo,backendName:"webgl",kernelFunc:Q9}, $ N="if (isnan(x)) return x;",tY= `
2021-09-11 17:11:38 +02:00
if ( isnan ( a ) ) return a ;
if ( isnan ( b ) ) return b ;
2021-12-09 20:22:22 +01:00
` ,nY= `
2021-09-11 17:11:38 +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-12-09 20:22:22 +01:00
` ;function Xe({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{let{x:o}=s,i=a,c=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let d=i.texData.get(o.dataId),p=n(d.values,c);return i.makeTensorInfo(o.shape,c,p)}let l=Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return l?u=new Ru(o.shape,t):u=new Sa(o.shape,e),i.runWebGLProgram(u,[o],c)}}function cn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:o,backend:i})=>{let{a:c,b:l}=o,u=i;if(r&&c.dtype==="complex64"){let f=u.texData.get(c.dataId),m=u.texData.get(l.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(v=>{let[x,w]=v,T={dataId:x.dataId,dtype:x.dtype,shape:c.shape},C={dataId:w.dataId,dtype:w.dtype,shape:l.shape},D=new Pu(e,c.shape,l.shape);return u.runWebGLProgram(D,[T,C],Sr(x.dtype,w.dtype))}),y=Ta({inputs:{real:g,imag:b},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(b),y}let d=a||Sr(c.dtype,l.dtype);if((c.dtype==="string"||l.dtype==="string"||u.shouldExecuteOnCPU([c,l]))&&s!=null){let f=u.texData.get(c.dataId).values,m=u.texData.get(l.dataId).values,g=c.dtype==="string"?_.fromUint8ToStringArray(f):f,b=c.dtype==="string"?_.fromUint8ToStringArray(m):m,[y,v]=s(c.shape,l.shape,g,b,d),x=u.makeTensorInfo(v,d),w=u.texData.get(x.dataId);return w.values=y,x}let p=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new jd(t,c.shape,l.shape,n):h=new Pu(e,c.shape,l.shape),u.runWebGLProgram(h,[c,l],d)}}function Nm(e,t=!1){if(e==="linear")return t? $ 9:_9;if(e==="relu")return t?P9:A9;if(e==="elu")return t?R9:E9;if(e==="relu6")return t?O9:D9;if(e==="prelu")return t?FN:DN;if(e==="leakyrelu")return t?AN:EN;if(e==="sigmoid")return t?M9:F9;throw new Error( ` Activation $ { e } has not been implemented for the WebGL backend . ` )}var RN=class{constructor(e,t,n,r=!1,s=!1,a=!1,o=null,i=!1,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=Wn(this.outputShape.length);let l=r?e[1]:e[2],u=Math.ceil(l/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=s?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m= ` vec4 activation ( vec4 a ) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { o }
2021-12-06 12:34:50 +01:00
} ` :c?m= ` vec4 activation ( vec4 a ) {
2021-09-11 17:11:38 +02:00
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { o }
} ` :m= ` vec4 activation ( vec4 x ) {
$ { o }
2021-12-09 20:22:22 +01:00
} ` ,g="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let y="rc.x",v="rc.x";e[0]<t[0]?y= ` int ( min ( float ( rc . x ) , $ { e [ 0 ] - 1 } . ) ) ` :t[0]<e[0]&&(v= ` int ( min ( float ( rc . x ) , $ { t [ 0 ] - 1 } . ) ) ` ),this.userCode= `
2021-09-11 17:11:38 +02:00
$ { m }
// Don't use uniform for sharedDimensionPacked for performance.
2021-12-06 12:34:50 +01:00
const float sharedDimension = $ { u } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 dot2x2ARowBCol ( ivec3 rc ) {
vec4 result = vec4 ( 0 ) ;
2021-12-06 12:34:50 +01:00
for ( int i = 0 ; i < $ { u } ; i ++ ) {
2021-12-09 20:22:22 +01:00
int batchA = $ { y } ;
int batchB = $ { v } ;
2021-09-11 17:11:38 +02:00
vec4 a = getMatrixA ( batchA , $ { d } ) ;
vec4 b = getMatrixB ( batchB , $ { p } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += ( $ { h [ 0 ] } * $ { f [ 0 ] } ) ;
result += ( $ { h [ 1 ] } * $ { f [ 1 ] } ) ;
}
return result ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 rc = getOutputCoords ( ) ;
vec4 result = dot2x2ARowBCol ( rc ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { b }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { g }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
}
2021-12-09 20:22:22 +01:00
` }},PN={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},ON=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode= `
2021-09-11 17:11:38 +02:00
float binaryOpComplex (
float areal , float aimag , float breal , float bimag ) {
$ { e }
}
void main ( ) {
float areal = getARealAtOutCoords ( ) ;
float aimag = getAImagAtOutCoords ( ) ;
float breal = getBRealAtOutCoords ( ) ;
float bimag = getBImagAtOutCoords ( ) ;
setOutput ( binaryOpComplex ( areal , aimag , breal , bimag ) ) ;
}
2021-12-09 20:22:22 +01:00
` }},MN="return a * b;";function t1(e){let{inputs:t,backend:n}=e,{a:r,b:s}=t,a=_.upcastType(r.dtype,s.dtype);if(r.dtype==="complex64"){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),l=new ON(PN.REAL,r.shape,s.shape),u=new ON(PN.IMAG,r.shape,s.shape),d=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:r.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape}],p=n.runWebGLProgram(l,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=Ta({inputs:{real:p,imag:h},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}if(n.shouldExecuteOnCPU([r,s])){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),[l,u]=n9(r.shape,s.shape,i.values,c.values,a),d=n.makeTensorInfo(u,a),p=n.texData.get(d.dataId);return p.values=l,d}let o;return Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?o=new jd(MN,r.shape,s.shape):o=new Pu(MN,r.shape,s.shape),n.runWebGLProgram(o,[r,s],a)}var rY={kernelName:mo,backendName:"webgl",kernelFunc:t1};function sY(e,t,n){let r=[fi(e.shape),...mi(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[fi(t),...mi(t)],o=new kN(a,r),i=!0,c=[r],l=n.runWebGLProgram(o,[s],e.dtype,c,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function ge(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=n,i=k.sizeFromShape(s.shape),c=k.inferFromImplicitShape(a,i),l=k.sizeFromShape(c);k.assert(i===l,()=> ` The new shape ( $ { c } ) has $ { l } elements and the old shape ( $ { s . shape } ) has $ { i } elements . The new shape and old shape must have the same number of elements . ` );let u=o.texData.get(s.dataId);return u.isPacked&&!Gd(s.shape,c)&&!(u.texture!==null&&Gd(u.shape,c))?sY(s,c,o):(o.incRef(s.dataId),{dataId:s.dataId,shape:c,dtype:s.dtype})}var aY={kernelName:Pc,backendName:"webgl",kernelFunc:ge},LN=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o=Math.floor(n/4)*4,i=n%4,c="sumValue += dot(values, ones);";if(t!=null){let u=1/t;c= ` sumValue += dot ( values * $ { k . isInt ( u ) ? u . toPrecision ( 2 ) : u } , ones ) ; ` }let l="";s%n>0&&(l= `
2021-09-11 17:11:38 +02:00
if ( inIdx < 0 || inIdx >= $ { s } ) {
return 0.0 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` ),this.userCode= `
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
2021-10-22 15:06:43 +02:00
$ { l }
2021-09-11 17:11:38 +02:00
return getX ( batch , inIdx ) ;
2021-04-01 19:39:54 +02:00
}
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
int batch = coords [ 0 ] ;
2021-09-11 17:11:38 +02:00
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * $ { n } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < $ { o } ; i += 4 ) {
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
$ { c }
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + $ { o } ;
if ( $ { i === 1 } ) {
vec4 values = vec4 ( getValue ( batch , inIdx ) , 0.0 , 0.0 , 0.0 ) ;
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
$ { c }
2021-09-11 17:11:38 +02:00
} else if ( $ { i === 2 } ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) , 0.0 , 0.0 ) ;
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
$ { c }
2021-09-11 17:11:38 +02:00
} else if ( $ { i === 3 } ) {
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) , 0.0 ) ;
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
$ { c }
2021-09-11 17:11:38 +02:00
}
setOutput ( sumValue ) ;
}
2021-12-09 20:22:22 +01:00
` }},oY=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let c= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="sum"?c="sumValue":t==="prod"?c="prodValue":t==="all"?c="allValue":t==="any"&&(c="anyValue");let l=Math.floor(n/4)*4,u=n%4,d= `
2021-09-11 17:11:38 +02:00
if ( $ { t === "sum" } ) {
sumValue += dot ( values , ones ) ;
} else if ( $ { t === "prod" } ) {
vec2 tmp = vec2 ( values [ 0 ] , values [ 1 ] ) * vec2 ( values [ 2 ] , values [ 3 ] ) ;
prodValue *= tmp [ 0 ] * tmp [ 1 ] ;
} else {
minMaxValue = $ { i } ( values , minMaxValue ) ;
if ( $ { t === "min" } || $ { t === "max" } ) {
minMaxValue = $ { i } ( values , minMaxValue ) ;
bvec4 isNaN = isnan ( values ) ;
if ( isNaN . r || isNaN . g || isNaN . b || isNaN . a ) {
minMaxValue = vec4 ( NAN ) ;
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
` ,p="vec4";t==="all"?(o="1.0",d= `
bool reducedAllValue = all ( values ) ;
float floatedReducedAllValue = float ( reducedAllValue ) ;
allValue = float ( allValue >= 1.0 && floatedReducedAllValue >= 1.0 ) ;
` ,p="bvec4"):t==="any"&&(o="0.0",d= `
bool reducedAnyValue = any ( values ) ;
float floatedReducedAnyValue = float ( reducedAnyValue ) ;
anyValue = float ( anyValue >= 1.0 || floatedReducedAnyValue >= 1.0 ) ;
` ,p="bvec4");let h="";s%n>0&&(h= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
return initializationValue ;
}
` ),this.userCode= `
const float initializationValue = $ { o } ;
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float getValue ( int batch , int inIdx ) {
$ { h }
return getX ( batch , inIdx ) ;
2021-04-01 19:39:54 +02:00
}
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * $ { n } ;
vec4 minMaxValue = vec4 ( $ { o } ) ;
float prodValue = 1.0 ;
float sumValue = 0.0 ;
float allValue = 1.0 ;
float anyValue = 0.0 ;
2021-10-22 15:06:43 +02:00
for ( int i = 0 ; i < $ { l } ; i += 4 ) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i ;
$ { p } values = $ { p } (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { d }
}
2021-04-01 19:39:54 +02:00
2021-10-22 15:06:43 +02:00
int inIdx = inOffset + $ { l } ;
2021-12-06 12:34:50 +01:00
if ( $ { u === 1 } ) {
2021-09-11 17:11:38 +02:00
$ { p } values = $ { p } (
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { d }
2021-12-06 12:34:50 +01:00
} else if ( $ { u === 2 } ) {
2021-09-11 17:11:38 +02:00
$ { p } values = $ { p } (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { d }
2021-12-06 12:34:50 +01:00
} else if ( $ { u === 3 } ) {
2021-09-11 17:11:38 +02:00
$ { p } values = $ { p } (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { d }
}
2021-12-06 12:34:50 +01:00
setOutput ( $ { c } ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function iY(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],r=_.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}function yi(e,t,n,r){let s=iY(e.shape),a=e;for(let o=0;o<s.length;o++){let{inSize:i,windowSize:c,outSize:l}=s[o],u,d;n==="mean"?u=o===0?new LN({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l},i):new LN({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l}):u=new oY({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l},n),d=a,a=r.runWebGLProgram(u,[a],t),d.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(d)}return a}var cY=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];this.outputShape=n,this.rank=n.length;let r=mt(this.rank),s=uY(t);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { r } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { s } ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function uY(e){let t=e.length;if(t>6)throw Error( ` Transpose for rank $ { t } is not yet supported ` );let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let s=0;s<e.length;s++)r[e[s]]=n[s];return r.join()}var lY=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let l=0;l<n.length;l++)n[l]=e[t[l]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error( ` Packed transpose for rank $ { this . rank } is not yet supported . ` );let r=mt(this.rank),s=wN("rc",this.rank),a=new Array(this.rank);for(let l=0;l<t.length;l++)a[t[l]]=s[l];let o= ` vec2 ( $ { a . slice ( - 2 ) . join ( ) } ) ` ,i= ` ++ $ { s [ this . rank - 1 ] } < $ { n [ this . rank - 1 ] } ` ,c= ` getChannel ( getA ( $ { a . join ( ) } ) , $ { o } ) ` ;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { r } rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
2021-12-06 12:34:50 +01:00
result [ 0 ] = $ { c } ;
2021-09-11 17:11:38 +02:00
if ( $ { i } ) {
2021-12-06 12:34:50 +01:00
result [ 1 ] = $ { c } ;
2021-04-15 22:59:35 +02:00
}
2021-09-11 17:11:38 +02:00
-- $ { s [ this . rank - 1 ] } ;
if ( ++ $ { s [ this . rank - 2 ] } < $ { n [ this . rank - 2 ] } ) {
2021-12-06 12:34:50 +01:00
result [ 2 ] = $ { c } ;
2021-09-11 17:11:38 +02:00
if ( $ { i } ) {
2021-12-06 12:34:50 +01:00
result [ 3 ] = $ { c } ;
2021-04-15 22:59:35 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2021-04-15 22:59:35 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function _m(e,t,n){let r=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new lY(e.shape,t):new cY(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function dY(e,t,n,r){let s=t,a=e.shape.length,o=k.parseAxisParam(s,e.shape),i=o,c=_.getAxesPermutation(i,a),l=c!=null,u=e;l&&(u=_m(e,c,r),i=_.getInnerMostAxes(i.length,a)),_.assertAxesAreInnerMostDims("sum",i,a);let[d,p]=_.computeOutAndReduceShapes(u.shape,i),h=d;n&&(h=_.expandShapeToKeepDim(d,o));let f=k.sizeFromShape(p),g=k.sizeFromShape(e.shape)/f,b=ge({inputs:{x:u},attrs:{shape:[g,f]},backend:r}),y=Mh(e.dtype),v=yi(b,y,"sum",r),x=ge({inputs:{x:v},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(v),l&&r.disposeIntermediateTensorInfo(u),x}function Em(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return dY(s,a,o,n)}var pY={kernelName:Eo,backendName:"webgl",kernelFunc:Em};function Tn(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,o=n,i=s.shape.length,c=new Array(i);for(let u=0;u<c.length;u++)c[u]=s.shape[a[u]];let l;if(o.shouldExecuteOnCPU([s])){let d=o.texData.get(s.dataId).values,p=e1(d,s.shape,s.dtype,a,c);l=o.makeTensorInfo(c,s.dtype);let h=o.texData.get(l.dataId);h.values=p}else l=_m(s,a,o);return l}var hY={kernelName:Po,backendName:"webgl",kernelFunc:Tn},BN=1e3;function Am({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:c=null}){let l=e.shape.length,u=t.shape.length,d=n?e.shape[l-2]:e.shape[l-1],p=r?t.shape[u-1]:t.shape[u-2],h=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=k.sizeFromShape(m),y=k.sizeFromShape(g),x=su.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);k.assert(d===p,()=> ` Error in matMul : inner shapes ( $ { d } ) and ( $ { p } ) of Tensors with shapes $ { e . shape } and $ { t . shape } and transposeA = $ { n } and transposeB = $ { r } must match . ` );let w=n?[b,d,h]:[b,h,d],T=r?[y,f,p]:[y,p,f],C=ge({inputs:{x:e},backend:s,attrs:{shape:w}}),D=ge({inputs:{x:t},backend:s,attrs:{shape:T}}),F=[C,D],O=Math.max(b,y), $ =n?C.shape[1]:C.shape[2],R=a!=null,N=o!=null,L=c==="leakyrelu",G=c!=null?Nm(c,!0):null,j=R||N||L||G!=null,K;if((h===1||f===1)&& $ >BN&&j===!1){let Z=C,te=D;n&&(Z=Tn({inputs:{x:C},backend:s,attrs:{perm:[0,2,1]}}),F.push(Z)),r&&(te=Tn({inputs:{x:D},backend:s,attrs:{perm:[0,2,1]}}),F.push(te));let se=f!==1,oe=f===1,re=Z;se&&(re=ge({inputs:{x:Z},backend:s,attrs:{shape:[O, $ ,1]}}),F.push(re));let ue=f===1?2:1,ne=te;oe&&(ne=ge({inputs:{x:te},backend:s,attrs:{shape:[O,1, $ ]}}),F.push(ne));let he=t1({inputs:{a:re,b:ne},backend:s});K=Em({inputs:{x:he},backend:s,attrs:{axis:ue,keepDims:!0}}),F.push(he)}else{let Z=Sr(e.dtype,t.dtype),te=new RN(w,T,[O,h,f],n,r,R,G,N,L),se=[C,D];if(a!=null&&se.push(a),N&&se.push(o),L){let oe=s.makeTensorInfo([],"float32",k.createScalarValue(i,"float32"));se.push(oe),F.push(oe)}K=s.runWebGLProgram(te,se,Z)}let q=ge({inputs:{x:K},backend:s,attrs:{shape:x}});F.push(K);for(let Z of F)s.disposeIntermediateTensorInfo(Z);return q}function fY(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=r;return Am({a:s,b:a,transposeA:c,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var mY={kernelName:Oo,backendName:"webgl",kernelFunc:fY},zN="return abs(x);";function gY(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&r.dtype!=="complex64"){let a=n.texData.get(r.dataId),o=vN(a.values);return n.makeTensorInfo(r.shape,r.dtype,o)}let s;return Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Ru(r.shape,zN):s=new Sa(r.shape,zN),n.runWebGLProgram(s,[r],r.dtype)}var bY={kernelName:Yi,backendName:"webgl",kernelFunc:gY},yY=qr+ `
2021-09-11 17:11:38 +02:00
if ( abs ( x ) > 1. ) {
return NAN ;
2021-04-15 22:59:35 +02:00
}
2021-09-11 17:11:38 +02:00
return acos ( x ) ;
2021-12-09 20:22:22 +01:00
` ,vY=Xe({opSnippet:yY}),xY={kernelName:Zi,backendName:"webgl",kernelFunc:vY},wY=qr+ `
2021-09-11 17:11:38 +02:00
if ( x < 1.0 ) return NAN ;
2021-12-09 20:22:22 +01:00
return log ( x + sqrt ( x * x - 1.0 ) ) ; ` ,kY=Xe({opSnippet:wY}),IY={kernelName:Ji,backendName:"webgl",kernelFunc:kY},WN="return a + b;",SY=cn({opSnippet:WN,packedOpSnippet:WN,supportsComplex:!0,cpuKernelImpl:M7}),TY={kernelName:Zs,backendName:"webgl",kernelFunc:SY},CY=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=> ` T$ { a } ` );let n=[];this.variableNames.forEach(s=>{n.push( ` float v$ { s } = get$ { s } AtOutCoords ( ) ; ` )});let r=this.variableNames.map(s=> ` v$ { s } ` ).join(" + ");this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { n . join ( `
` )}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result = $ { r } ;
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},NY=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=> ` T$ { a } ` );let n=[];this.variableNames.forEach(s=>{n.push( ` vec4 v$ { s } = get$ { s } AtOutCoords ( ) ; ` )});let r=this.variableNames.map(s=> ` v$ { s } ` ).join(" + ");this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { n . join ( `
` )}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = $ { r } ;
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function Dm(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return sr({inputs:{x:r[0]},backend:n});if(r.length>Q().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),l=Dm({inputs:r.slice(0,c),backend:n}),u=Dm({inputs:r.slice(c),backend:n});return Dm({inputs:[l,u],backend:n})}let s=r.map(c=>c.dtype).reduce((c,l)=>Sr(c,l)),a=r.map(c=>c.shape),i=Q().getBool("WEBGL_PACK")?new NY(r[0].shape,a):new CY(r[0].shape,a);return n.runWebGLProgram(i,r,s)}var _Y={kernelName:Ba,backendName:"webgl",kernelFunc:Dm};function EY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=k.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=Tn({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,i)),_.assertAxesAreInnerMostDims("all",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=k.sizeFromShape(h),m=ge({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=yi(m,m.dtype,"all",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=ge({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ge({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var AY={kernelName:Qi,backendName:"webgl",kernelFunc:EY};function DY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=k.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=Tn({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,i)),_.assertAxesAreInnerMostDims("any",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=k.sizeFromShape(h),m=ge({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=yi(m,m.dtype,"any",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=ge({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ge({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var FY={kernelName:ec,backendName:"webgl",kernelFunc:DY}, $ Y=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let o=t==="max"?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = outIdx * $ { r } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int bestIndex = inOffset ;
float bestValue = getA ( batch , bestIndex ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < $ { r } ; i ++ ) {
int inIdx = $ { i } ;
float candidate = getA ( batch , inIdx ) ;
if ( candidate $ { o } bestValue ) {
bestValue = candidate ;
bestIndex = inIdx ;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( float ( bestIndex ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},RY=class{constructor(e,t,n,r){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 s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,c=mt(i),l=Sn("coords",i),u,d;if(a===1){d=i+1;let C=mt(d);u= `
$ { C } sourceLocR = $ { C } ( $ { l . join ( ) } , 0 ) ;
2021-10-22 15:06:43 +02:00
++ $ { l [ i - 1 ] } ;
2021-12-09 20:22:22 +01:00
$ { C } sourceLocG = $ { C } ( $ { l . join ( ) } , 0 ) ;
2021-10-22 15:06:43 +02:00
++ $ { l [ i - 2 ] } ;
2021-12-09 20:22:22 +01:00
$ { C } sourceLocA = $ { C } ( $ { l . join ( ) } , 0 ) ;
2021-10-22 15:06:43 +02:00
-- $ { l [ i - 1 ] } ;
2021-12-09 20:22:22 +01:00
$ { C } sourceLocB = $ { C } ( $ { l . join ( ) } , 0 ) ;
2021-12-06 12:34:50 +01:00
-- $ { l [ i - 2 ] } ; ` }else d=i,u= `
$ { c } sourceLocR = coords ;
2021-10-22 15:06:43 +02:00
++ $ { l [ i - 1 ] } ;
2021-12-06 12:34:50 +01:00
$ { c } sourceLocG = coords ;
2021-10-22 15:06:43 +02:00
++ $ { l [ i - 2 ] } ;
2021-12-06 12:34:50 +01:00
$ { c } sourceLocA = coords ;
2021-10-22 15:06:43 +02:00
-- $ { l [ i - 1 ] } ;
2021-12-06 12:34:50 +01:00
$ { c } sourceLocB = coords ;
2021-12-09 20:22:22 +01:00
-- $ { l [ i - 2 ] } ; ` ;let p=["x","y","z","w","u","v"].slice(0,d),h="."+p[d-1],f=p.map(C=>"int "+C),m=Sn("sourceLocR",d-1).concat("inIdx.r"),g=Sn("sourceLocG",d-1).concat("inIdx.g"),b=Sn("sourceLocB",d-1).concat("inIdx.b"),y=Sn("sourceLocA",d-1).concat("inIdx.a"),v=n==="max"?"greaterThan":"lessThan",x=r?"": `
2021-09-11 17:11:38 +02:00
inIdx = round ( vec4 ( getBestIndicesAChannel ( $ { m . join ( ) } ) ,
getBestIndicesAChannel ( $ { g . join ( ) } ) ,
getBestIndicesAChannel ( $ { b . join ( ) } ) ,
2021-12-09 20:22:22 +01:00
getBestIndicesAChannel ( $ { y . join ( ) } ) ) ) ; ` ,w= ` vec4 (
2021-09-11 17:11:38 +02:00
getAChannel ( $ { m . join ( ) } ) ,
hasNextCol ? getAChannel ( $ { g . join ( ) } ) : 0. ,
hasNextRow ? getAChannel ( $ { b . join ( ) } ) : 0. ,
2021-12-09 20:22:22 +01:00
hasNextRow && hasNextCol ? getAChannel ( $ { y . join ( ) } ) : 0. ) ` ,T=r?"": `
2021-09-11 17:11:38 +02:00
float getBestIndicesAChannel ( $ { f . join ( ) } ) {
return getChannel ( getBestIndicesA ( $ { p . join ( ) } ) ,
vec2 ( $ { p . slice ( - 2 ) . join ( ) } ) ) ;
} ` ;this.userCode= `
float getAChannel ( $ { f . join ( ) } ) {
return getChannel ( getA ( $ { p . join ( ) } ) ,
vec2 ( $ { p . slice ( - 2 ) . join ( ) } ) ) ;
}
2021-12-09 20:22:22 +01:00
$ { T }
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-12-06 12:34:50 +01:00
$ { c } coords = getOutputCoords ( ) ;
2021-10-22 15:06:43 +02:00
bool hasNextCol = $ { l [ i - 1 ] } < $ { o [ i - 1 ] - 1 } ;
bool hasNextRow = $ { l [ i - 2 ] } < $ { o [ i - 2 ] - 1 } ;
2021-12-06 12:34:50 +01:00
$ { u }
2021-09-11 17:11:38 +02:00
ivec4 srcIdx = ivec4 ( sourceLocR$ { h } , sourceLocG$ { h } ,
sourceLocB$ { h } , sourceLocA$ { h } ) * $ { t } ;
ivec4 inIdx = srcIdx ;
vec4 bestIndex = vec4 ( inIdx ) ;
2021-12-09 20:22:22 +01:00
vec4 bestValue = $ { w } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int i = 0 ; i < $ { t } ; i ++ ) {
inIdx = srcIdx ;
$ { x }
2021-12-09 20:22:22 +01:00
vec4 candidate = $ { w } ;
2021-09-11 17:11:38 +02:00
bvec4 nan = isnan ( candidate ) ;
bvec4 replace = bvec4 (
2021-12-09 20:22:22 +01:00
vec4 ( $ { v } ( candidate , bestValue ) ) * ( vec4 ( 1.0 ) - vec4 ( nan ) ) ) ;
2021-09-11 17:11:38 +02:00
bestValue = vec4 ( replace . x ? candidate . x : bestValue . x ,
replace . y ? candidate . y : bestValue . y ,
replace . z ? candidate . z : bestValue . z ,
replace . w ? candidate . w : bestValue . w ) ;
bestIndex = mix ( bestIndex , vec4 ( inIdx ) , vec4 ( replace ) ) ;
srcIdx ++ ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( bestIndex ) ;
}
2021-12-09 20:22:22 +01:00
` }};function VN(e,t,n,r=null){let s=t.shape[0],a=t.shape[1];r!=null&&(s=r.shape[0],a=r.shape[1]);let o=_.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:s,outSize:Math.ceil(a/o)},c=new $ Y(i,n,r==null),l=[t];r!=null&&l.push(r);let u=e.runWebGLProgram(c,l,"int32");if(u.shape[1]===1)return u;let d=VN(e,t,n,u);return e.disposeIntermediateTensorInfo(u),d}function UN(e,t,n,r=null){let s=r!=null?r.shape:t.shape,a=s[s.length-1],o=_.computeOptimalWindowSize(a),i=new RY(s,o,n,r==null),c=r==null?[t]:[t,r],l=e.runWebGLProgram(i,c,"int32");if(l.shape.length===t.shape.length){let u=UN(e,t,n,l);return e.disposeIntermediateTensorInfo(l),u}return l}function GN(e,t,n,r){let s=[n];if(_.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!Q().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let a=[],o=e.texData.get(t.dataId),i=o!==null&&o.isPacked,c=t;i&&(c=e.unpackTensor(t),a.push(c));let[l,u]=_.computeOutAndReduceShapes(c.shape,s),d=k.sizeFromShape(u),p=ge({inputs:{x:c},backend:e,attrs:{shape:[-1,d]}});a.push(p);let h=VN(e,p,r);a.push(h);let f=ge({inputs:{x:h},backend:e,attrs:{shape:l}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return UN(e,t,r)}function PY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=k.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=Tn({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMax",[o[0]],c.shape.length);let u=GN(n,c,o[0],"max");return l.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var OY={kernelName:za,backendName:"webgl",kernelFunc:PY};function MY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=k.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=Tn({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);let u=GN(n,c,o[0],"min");return l.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var LY={kernelName:Sl,backendName:"webgl",kernelFunc:MY},BY=qr+ `
2021-09-11 17:11:38 +02:00
if ( abs ( x ) > 1. ) {
2021-04-01 19:39:54 +02:00
return NAN ;
}
2021-09-11 17:11:38 +02:00
return asin ( x ) ;
2021-12-09 20:22:22 +01:00
` ,zY=Xe({opSnippet:BY}),WY={kernelName:tc,backendName:"webgl",kernelFunc:zY},VY=qr+"return log(x + sqrt(x * x + 1.0));",UY=Xe({opSnippet:VY}),GY={kernelName:nc,backendName:"webgl",kernelFunc:UY},HY=qr+ `
2021-09-11 17:11:38 +02:00
return atan ( x ) ;
2021-12-09 20:22:22 +01:00
` ,jY=Xe({opSnippet:HY}),qY={kernelName:rc,backendName:"webgl",kernelFunc:jY},KY=tY+ `
2021-09-11 17:11:38 +02:00
return atan ( a , b ) ;
2021-12-09 20:22:22 +01:00
` ,XY= `
2021-09-11 17:11:38 +02:00
vec4 result = atan ( a , b ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-12-09 20:22:22 +01:00
` +nY+ `
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,YY=cn({opSnippet:KY,packedOpSnippet:XY}),ZY={kernelName:ac,backendName:"webgl",kernelFunc:YY},JY=qr+ `
2021-09-11 17:11:38 +02:00
if ( ( x < - 1.0 ) || ( x > 1.0 ) ) return NAN ;
2021-12-09 20:22:22 +01:00
return ( log ( 1.0 + x ) - log ( 1.0 - x ) ) / 2.0 ; ` ,QY=Xe({opSnippet:JY}),eZ={kernelName:sc,backendName:"webgl",kernelFunc:QY},qd=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m= ` ( ( batch * $ { e . inHeight } + xR ) * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,g= ` ( xR * $ { e . inWidth } + xC ) * $ { e . inChannels } + d ` ,b="0.0";if(f||(b="-1.0 / 1e-20"),n){let C=">=";this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec2 strides = ivec2 ( $ { o } , $ { i } ) ;
const ivec2 pads = ivec2 ( $ { p } , $ { h } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int d = coords [ 3 ] ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
float avgValue = 0.0 ;
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
for ( int wR = 0 ; wR < $ { u } ;
wR += $ { c } ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { d } ;
2021-10-22 15:06:43 +02:00
wC += $ { l } ) {
2021-09-11 17:11:38 +02:00
int xC = xCCorner + wC ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float value = getX ( batch , xR , xC , d ) ;
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
2021-12-09 20:22:22 +01:00
if ( value $ { C } currMinMaxValue ) {
2021-09-11 17:11:38 +02:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
minMaxPosition = $ { r ? s ? m : g : ` wR * ${ d } + wC ` } ;
}
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( float ( minMaxPosition ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` ;return}let y="max",v= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(v="avgValue / count");let x=Math.floor(a/4)*4,w=a%4,T= `
2021-09-11 17:11:38 +02:00
if ( $ { f } ) {
avgValue += dot ( values , ones ) ;
2021-04-01 19:39:54 +02:00
} else {
2021-12-09 20:22:22 +01:00
minMaxValue = $ { y } ( values , minMaxValue ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` ;this.userCode= `
const ivec2 strides = ivec2 ( $ { o } , $ { i } ) ;
const ivec2 pads = ivec2 ( $ { p } , $ { h } ) ;
const float initializationValue = $ { b } ;
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float count = 0.0 ;
float getValue ( int batch , int xR , int xC , int d ) {
if ( xC < 0 || xC >= $ { e . inWidth } ) {
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xR , xC , d ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
int batch = coords [ 0 ] ;
2021-04-01 19:39:54 +02:00
int d = coords [ 3 ] ;
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner = coords . yz * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4 ( $ { b } ) ;
float avgValue = 0.0 ;
count = 0.0 ;
2021-12-06 12:34:50 +01:00
for ( int wR = 0 ; wR < $ { u } ;
wR += $ { c } ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
for ( int wC = 0 ; wC < $ { x } ; wC += 4 ) {
2021-10-22 15:06:43 +02:00
int xC = xCCorner + wC * $ { l } ;
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-10-22 15:06:43 +02:00
getValue ( batch , xR , xC + $ { l } , d ) ,
getValue ( batch , xR , xC + 2 * $ { l } , d ) ,
getValue ( batch , xR , xC + 3 * $ { l } , d )
2021-09-11 17:11:38 +02:00
) ;
2021-12-09 20:22:22 +01:00
$ { T }
2021-09-11 17:11:38 +02:00
}
int xC = xCCorner + $ { x } ;
2021-12-09 20:22:22 +01:00
if ( $ { w === 1 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2021-12-09 20:22:22 +01:00
$ { T }
} else if ( $ { w === 2 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-10-22 15:06:43 +02:00
getValue ( batch , xR , xC + $ { l } , d ) ,
2021-09-11 17:11:38 +02:00
initializationValue ,
initializationValue
) ;
2021-12-09 20:22:22 +01:00
$ { T }
} else if ( $ { w === 3 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xR , xC , d ) ,
2021-10-22 15:06:43 +02:00
getValue ( batch , xR , xC + $ { l } , d ) ,
getValue ( batch , xR , xC + 2 * $ { l } , d ) ,
2021-09-11 17:11:38 +02:00
initializationValue
) ;
2021-12-09 20:22:22 +01:00
$ { T }
2021-04-01 19:39:54 +02:00
}
}
2021-12-09 20:22:22 +01:00
setOutput ( $ { v } ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},n1=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,c=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",v="0.0";if(y||(v="-1.0 / 1e-20"),n){let F=">=";this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec3 strides =
2021-12-06 12:34:50 +01:00
ivec3 ( $ { o } , $ { i } , $ { c } ) ;
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3 ( $ { m } , $ { g } , $ { b } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0 ;
float minMaxValueFound = 0.0 ;
int minMaxPosition = 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wD = 0 ; wD < $ { p } ;
2021-10-22 15:06:43 +02:00
wD += $ { l } ) {
2021-09-11 17:11:38 +02:00
int xD = xDCorner + wD ;
if ( xD < 0 || xD >= $ { e . inDepth } ) {
continue ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for ( int wR = 0 ; wR < $ { h } ;
2021-12-06 12:34:50 +01:00
wR += $ { u } ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { f } ;
wC += $ { d } ) {
int xC = xCCorner + wC ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float value = getX ( batch , xD , xR , xC , ch ) ;
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix (
value , minMaxValue , minMaxValueFound ) ;
2021-10-28 19:58:21 +02:00
if ( value $ { F } currMinMaxValue ) {
2021-09-11 17:11:38 +02:00
minMaxValue = value ;
minMaxValueFound = 1.0 ;
minMaxPosition = $ { r ? s ? ` (((batch * ${ e . inDepth } + xD) * ${ e . inHeight } + xR) * ${ e . inWidth } + xC) * ${ e . inChannels } + ch ` : ` ((xD * ${ e . inHeight } + xR) * ${ e . inWidth } + xC) * ${ e . inChannels } + ch ` : ` wD * ${ h } * ${ f } +
wR * $ { f } + wC ` };
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput ( float ( minMaxPosition ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` ;return}let x="max",w= ` $ { t } ( $ { t } ( $ { t } ( minMaxValue [ 0 ] , minMaxValue [ 1 ] ) , minMaxValue [ 2 ] ) , minMaxValue [ 3 ] ) ` ;t==="avg"&&(w="avgValue / count");let T=Math.floor(a/4)*4,C=a%4,D= `
if ( $ { y } ) {
2021-09-11 17:11:38 +02:00
avgValue += dot ( values , ones ) ;
} else {
minMaxValue = $ { x } ( values , minMaxValue ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
` ;this.userCode= `
const ivec3 strides =
2021-12-06 12:34:50 +01:00
ivec3 ( $ { o } , $ { i } , $ { c } ) ;
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3 ( $ { m } , $ { g } , $ { b } ) ;
2021-12-09 20:22:22 +01:00
const float initializationValue = $ { v } ;
2021-09-11 17:11:38 +02:00
const vec4 ones = vec4 ( 1.0 , 1.0 , 1.0 , 1.0 ) ;
float count = 0.0 ;
float getValue ( int batch , int xD , int xR , int xC , int ch ) {
if ( xC < 0 || xC >= $ { e . inWidth } ) {
return initializationValue ;
}
count += 1.0 ;
return getX ( batch , xD , xR , xC , ch ) ;
}
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xDCorner = xCorner . x ;
int xRCorner = xCorner . y ;
int xCCorner = xCorner . z ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2021-12-09 20:22:22 +01:00
vec4 minMaxValue = vec4 ( $ { v } ) ;
2021-09-11 17:11:38 +02:00
float avgValue = 0.0 ;
count = 0.0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wD = 0 ; wD < $ { p } ;
2021-10-22 15:06:43 +02:00
wD += $ { l } ) {
2021-09-11 17:11:38 +02:00
int xD = xDCorner + wD ;
if ( xD < 0 || xD >= $ { e . inDepth } ) {
continue ;
}
for ( int wR = 0 ; wR < $ { h } ;
2021-12-06 12:34:50 +01:00
wR += $ { u } ) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2021-09-11 17:11:38 +02:00
2021-12-09 20:22:22 +01:00
for ( int wC = 0 ; wC < $ { T } ; wC += 4 ) {
2021-09-11 17:11:38 +02:00
int xC = xCCorner + wC * $ { d } ;
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + $ { d } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { d } , ch ) ,
getValue ( batch , xD , xR , xC + 3 * $ { d } , ch )
) ;
2021-12-06 12:34:50 +01:00
$ { D }
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
int xC = xCCorner + $ { T } ;
if ( $ { C === 1 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2021-12-06 12:34:50 +01:00
$ { D }
2021-12-09 20:22:22 +01:00
} else if ( $ { C === 2 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + $ { d } , ch ) ,
initializationValue ,
initializationValue
) ;
2021-12-06 12:34:50 +01:00
$ { D }
2021-12-09 20:22:22 +01:00
} else if ( $ { C === 3 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , xD , xR , xC , ch ) ,
getValue ( batch , xD , xR , xC + $ { d } , ch ) ,
getValue ( batch , xD , xR , xC + 2 * $ { d } , ch ) ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
$ { D }
2021-04-01 19:39:54 +02:00
}
}
2021-12-09 20:22:22 +01:00
setOutput ( $ { w } ) ;
2021-04-01 19:39:54 +02:00
}
}
2021-12-09 20:22:22 +01:00
` }};function tZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Eu(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;k.assert(_.eitherStridesOrDilationsAreOne(o,l),()=> ` Error in avgPool : Either strides or dilations must be 1. Got strides $ { o } and dilations '${l}' ` );let u=_.computePool2DInfo(s.shape,a,o,l,i,c);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return sr({inputs:{x:s},backend:n});let d=new qd(u,"avg",!1);return n.runWebGLProgram(d,[s],"float32")}var nZ={kernelName:Wa,backendName:"webgl",kernelFunc:tZ};function rZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:l}=r,u=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,u,i,c,l),p=new n1(d,"avg",!1);return n.runWebGLProgram(p,[s],"float32")}var sZ={kernelName:Tl,backendName:"webgl",kernelFunc:rZ},aZ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,c=e.effectiveFilterWidth,l=i-1-e.padInfo.top,u=c-1-e.padInfo.left,d=1/(t*n);this.userCode= `
2021-12-06 12:34:50 +01:00
const ivec2 pads = ivec2 ( $ { l } , $ { u } ) ;
2021-09-11 17:11:38 +02:00
const float avgMultiplier = float ( $ { d } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-09-11 17:11:38 +02:00
for ( int wR = 0 ; wR < $ { i } ;
wR += $ { a } ) {
float dyR = float ( dyRCorner + wR ) / $ { r } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2021-04-01 19:39:54 +02:00
continue ;
}
int idyR = int ( dyR ) ;
2021-12-06 12:34:50 +01:00
for ( int wC = 0 ; wC < $ { c } ;
2021-09-11 17:11:38 +02:00
wC += $ { o } ) {
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2021-04-01 19:39:54 +02:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( b , idyR , idyC , d ) ;
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier ;
2021-04-01 19:39:54 +02:00
}
}
setOutput ( dotProd ) ;
}
2021-12-09 20:22:22 +01:00
` }},oZ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=u-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3 ( $ { h } , $ { f } , $ { m } ) ;
const float avgMultiplier = float ( $ { g } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
2021-09-11 17:11:38 +02:00
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
2021-04-01 19:39:54 +02:00
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-12-06 12:34:50 +01:00
for ( int wD = 0 ; wD < $ { u } ;
2021-09-11 17:11:38 +02:00
wD += $ { i } ) {
float dyD = float ( dyDCorner + wD ) / $ { s } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
2021-04-01 19:39:54 +02:00
continue ;
}
int idyD = int ( dyD ) ;
2021-09-11 17:11:38 +02:00
for ( int wR = 0 ; wR < $ { d } ;
2021-12-06 12:34:50 +01:00
wR += $ { c } ) {
2021-09-11 17:11:38 +02:00
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
2021-04-01 19:39:54 +02:00
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { p } ;
2021-10-22 15:06:43 +02:00
wC += $ { l } ) {
2021-09-11 17:11:38 +02:00
float dyC = float ( dyCCorner + wC ) / $ { o } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
2021-04-01 19:39:54 +02:00
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier ;
2021-04-01 19:39:54 +02:00
}
}
}
setOutput ( dotProd ) ;
}
2021-12-09 20:22:22 +01:00
` }};function iZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:l,dimRoundingMode:u}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,l,u),h=new oZ(p);return n.runWebGLProgram(h,[s],o.dtype)}var cZ={kernelName:Jp,backendName:"webgl",kernelFunc:iZ};function uZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Eu([s,a],"avgPoolGrad");let{filterSize:i,strides:c,pad:l}=r,u=_.computePool2DInfo(o.shape,i,c,1,l),d=new aZ(u);return n.runWebGLProgram(d,[s],o.dtype)}var lZ={kernelName:Zp,backendName:"webgl",kernelFunc:uZ};function dZ(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return Am({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var pZ={kernelName:Va,backendName:"webgl",kernelFunc:dZ},hZ=class{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let o="0.0";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";s!=null&&(_.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
float x = getXAtOutCoords ( ) ;
float mean = getMeanAtOutCoords ( ) ;
float variance = getVarianceAtOutCoords ( ) ;
float offset = $ { o } ;
float scale = $ { i } ;
float inv = scale * inversesqrt ( variance + float ( $ { a } ) ) ;
setOutput ( dot ( vec3 ( x , - mean , offset ) , vec3 ( inv , inv , 1 ) ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},fZ=class{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";s!=null&&(_.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
vec4 offset = $ { o } ;
vec4 scale = $ { i } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 x = getXAtOutCoords ( ) ;
vec4 mean = getMeanAtOutCoords ( ) ;
vec4 variance = getVarianceAtOutCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 inv = scale * inversesqrt ( variance + vec4 ( $ { a } ) ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( ( x - mean ) * inv + offset ) ;
}
2021-12-09 20:22:22 +01:00
` }},mZ=({inputs:e,backend:t,attrs:n})=>{let{x:r,mean:s,variance:a,offset:o,scale:i}=e;k.assert(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k.assert(o==null||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k.assert(i==null||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:c}=n;c==null&&(c=.001);let l=[r,s,a],u=null;o!=null&&(u=o.shape,l.push(o));let d=null;i!=null&&(d=i.shape,l.push(i));let p=Q().getBool("WEBGL_PACK_NORMALIZATION")?new fZ(r.shape,s.shape,a.shape,u,d,c):new hZ(r.shape,s.shape,a.shape,u,d,c);return t.runWebGLProgram(p,l,l[0].dtype)},gZ={kernelName:no,backendName:"webgl",kernelFunc:mZ},bZ=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=mt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=yZ(this.rank),r,s=e.map((a,o)=> ` sourceLoc . $ { r1 [ o ] } = start [ $ { o } ] + coords . $ { r1 [ o ] } ; ` );r= `
2021-09-11 17:11:38 +02:00
$ { t } sourceLoc ;
$ { t } coords = getOutputCoords ( ) ;
$ { s . join ( `
` )}
` ,this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
$ { r }
setOutput ( getSource ( $ { n } ) ) ;
}
2021-12-09 20:22:22 +01:00
` }},r1=["x","y","z","w","u","v"];function yZ(e){if(e===1)return"sourceLoc";if(e<=6)return r1.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error( ` Slicing for rank $ { e } is not yet supported ` )}var vZ=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=mt(this.rank),n=Sn("coords",this.rank),r=Sn("sourceLoc",this.rank),s=this.rank===1?"sourceLoc": ` vec2 ( $ { r . slice ( - 2 ) . join ( ) } ) ` ,a= ` getChannel ( getSource ( $ { r . join ( ) } ) , $ { s } ) ` ,o= `
2021-09-11 17:11:38 +02:00
result . x = $ { a } ;
if ( ++ $ { n [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
++ $ { r [ this . rank - 1 ] } ;
result . y = $ { a } ;
-- $ { r [ this . rank - 1 ] } ;
}
` ,i=this.rank===1?"": `
-- $ { n [ this . rank - 1 ] } ;
if ( ++ $ { n [ this . rank - 2 ] } < $ { e [ this . rank - 2 ] } ) {
++ $ { r [ this . rank - 2 ] } ;
result . z = $ { a } ;
if ( ++ $ { n [ this . rank - 1 ] } < $ { e [ this . rank - 1 ] } ) {
++ $ { r [ this . rank - 1 ] } ;
result . w = $ { a } ;
}
}
2021-12-06 12:34:50 +01:00
` ,c=this.rank<=4? ` sourceLoc = coords +
$ { t } ( $ { e . map ( ( l , u ) => ` start[ ${ u } ] ` ) . join ( ) } ) ; ` :e.map((l,u)=> ` $ { r [ u ] } = $ { n [ u ] } + start [ $ { u } ] ; ` ).join( `
2021-09-11 17:11:38 +02:00
` );this.userCode= `
void main ( ) {
$ { t } coords = getOutputCoords ( ) ;
$ { t } sourceLoc ;
2021-12-06 12:34:50 +01:00
$ { c }
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0. ) ;
$ { o }
$ { i }
setOutput ( result ) ;
}
2021-12-09 20:22:22 +01:00
` }};function xZ(e,t,n,r){let s=r.texData.get(e.dataId),a=r.makeTensorInfo(n,e.dtype),o=r.texData.get(a.dataId);Object.assign(o,s),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=Gt.computeFlatOffset(t,k.computeStrides(e.shape));s.slice&&(i+=s.slice.flatOffset),o.slice={flatOffset:i,origDataId:s.slice&&s.slice.origDataId||e.dataId};let c=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,c+1),a}function Ou(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,c]=Gt.parseSliceParams(s,a,o);if(Gt.assertParamsValid(s,i,c),k.sizeFromShape(c)===0)return n.makeTensorInfo(c,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||s.dtype==="string"){let d=n.texData.get(s.dataId),p=u9(d.values,i,c,s.shape,s.dtype);return n.makeTensorInfo(c,s.dtype,p)}let{isPacked:l}=n.texData.get(s.dataId),u=Gt.isSliceContinous(s.shape,i,c);if(l||!u){let d=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new vZ(c):new bZ(c),p=[i];return n.runWebGLProgram(d,[s],s.dtype,p)}return n.uploadToGPU(s.dataId),xZ(s,i,c,n)}var wZ={kernelName:Bc,backendName:"webgl",kernelFunc:Ou},kZ=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;k.assert(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,v)=>y*v),c=_.getReshaped(s.shape,a,i),l=_.getPermuted(c.length,a.length),u=_.getReshapedPermuted(s.shape,a,i),d=_.getSliceBeginCoords(o,a.length),p=_.getSliceSize(u,o,a.length),h=[],f=ge({inputs:{x:s},backend:n,attrs:{shape:c}}),m=Tn({inputs:{x:f},backend:n,attrs:{perm:l}}),g=ge({inputs:{x:m},backend:n,attrs:{shape:u}}),b=Ou({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach(y=>n.disposeIntermediateTensorInfo(y)),b},IZ={kernelName:oc,backendName:"webgl",kernelFunc:kZ};function SZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.readSync(s.dataId),c=n.readSync(a.dataId),l=yN(i,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,l)}var TZ={kernelName:Qp,backendName:"webgl",kernelFunc:SZ};function CZ(e){let{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),o=n.readSync(s.dataId),i=_.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var NZ={kernelName:eh,backendName:"webgl",kernelFunc:CZ},_Z="return float(a != b);",HN=cn({opSnippet:_Z,cpuKernelImpl:s9,dtype:"bool"}),EZ={kernelName:Nc,backendName:"webgl",kernelFunc:HN};function Kd(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return sr({inputs:{x:s.complexTensorInfos.real},backend:n})}var AZ={kernelName:kh,backendName:"webgl",kernelFunc:Kd},DZ="return float(int(x));";function FZ(e,t){let n=new Sa(e.shape,DZ),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function s1(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return sr({inputs:{x:s},backend:n});let o=St(s.shape),i=s1({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),c=Ta({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),c}if(s.dtype==="complex64"){let o=Kd({inputs:{input:s},backend:n}),i=s1({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!k.hasEncodingLoss(s.dtype,a)){let o=sr({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return FZ(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",k.getTypedArrayFromDType("bool",1)),c=HN({inputs:{a:s,b:o},backend:n});return n.disposeIntermediateTensorInfo(o),c}throw new Error( ` Error in Cast : failed to cast $ { s . dtype } to $ { a } ` )}var $ Z={kernelName:Ua,backendName:"webgl",kernelFunc:s1},jN="return ceil(x);",RZ=Xe({opSnippet:jN,packedOpSnippet:jN,cpuKernelImpl:B7}),PZ={kernelName:Ga,backendName:"webgl",kernelFunc:RZ},OZ=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode= `
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
float value = getAAtOutCoords ( ) ;
if ( isnan ( value ) ) {
setOutput ( value ) ;
return ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( clamp ( value , minVal , maxVal ) ) ;
}
2021-12-09 20:22:22 +01:00
` }},MZ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
vec4 value = getAAtOutCoords ( ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( any ( isnan ( value ) ) ) {
setOutput ( value ) ;
return ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( clamp ( value , vec4 ( minVal ) , vec4 ( maxVal ) ) ) ;
}
2021-12-09 20:22:22 +01:00
` }};function LZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i;Q().getBool("WEBGL_PACK_CLIP")?i=new MZ(s.shape):i=new OZ(s.shape);let c=[[a],[o]];return n.runWebGLProgram(i,[s],s.dtype,c)}var BZ={kernelName:Js,backendName:"webgl",kernelFunc:LZ},zZ=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
float re = abs ( getRealAtOutCoords ( ) ) ;
float im = abs ( getImagAtOutCoords ( ) ) ;
float mx = max ( re , im ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput (
mx == 0.0 ? 0.0 : mx * length ( vec2 ( 1 , min ( re , im ) / mx ) )
) ;
}
2021-12-09 20:22:22 +01:00
` }};function qN(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function WZ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new zZ(r.shape),o=[qN(r,s.complexTensorInfos.real),qN(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var VZ={kernelName:Cl,backendName:"webgl",kernelFunc:WZ},UZ=class{constructor(e){this.outputShape=[],this.outputShape=_.computeOutShape(e,1),this.variableNames=e.map((a,o)=> ` T$ { o } ` );let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[ ` if ( yC < $ { t [ 0 ] } ) setOutput ( getT0 ( yR , yC ) ) ; ` ];for(let a=1;a<t.length;a++){let o=t[a-1];n.push( ` else if ( yC < $ { t [ a ] } ) setOutput ( getT$ { a } ( yR , yC - $ { o } ) ) ; ` )}let r=t.length,s=t[t.length-1];n.push( ` else setOutput ( getT$ { r } ( yR , yC - $ { s } ) ) ; ` ),this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int yR = coords . x ;
int yC = coords . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { n . join ( `
` )}
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},GZ=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.computeOutShape(e,t);let n=this.outputShape,r=n.length,s=mt(r),a=Sn("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((f,m)=> ` T$ { m } ` );let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let c=o[t],l=o.slice(-2),u=o.join(),d= ` if ( $ { c } < $ { i [ 0 ] } ) {
2021-09-11 17:11:38 +02:00
return getChannel (
2021-12-06 12:34:50 +01:00
getT0 ( $ { u } ) , vec2 ( $ { l . join ( ) } ) ) ;
2021-09-11 17:11:38 +02:00
} ` ;for(let f=1;f<i.length;f++){let m=i[f-1];d+= `
2021-12-06 12:34:50 +01:00
if ( $ { c } < $ { i [ f ] } && $ { c } >= $ { i [ f - 1 ] } ) {
2021-09-11 17:11:38 +02:00
return getChannel (
2021-12-09 20:22:22 +01:00
getT$ { f } ( $ { Fm ( o , c , m ) } ) ,
vec2 ( $ { Fm ( l , c , m ) } ) ) ;
2021-09-11 17:11:38 +02:00
} ` }let p=i.length,h=i[i.length-1];d+= `
return getChannel (
2021-12-09 20:22:22 +01:00
getT$ { p } ( $ { Fm ( o , c , h ) } ) ,
vec2 ( $ { Fm ( l , c , h ) } ) ) ; ` ,this.userCode= `
2021-09-11 17:11:38 +02:00
float getValue ( $ { o . map ( f => "int " + f ) } ) {
$ { d }
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { s } coords = getOutputCoords ( ) ;
vec4 result = vec4 ( getValue ( $ { a } ) , 0. , 0. , 0. ) ;
$ { a [ r - 1 ] } = $ { a [ r - 1 ] } + 1 ;
if ( $ { a [ r - 1 ] } < $ { n [ r - 1 ] } ) {
result . g = getValue ( $ { a } ) ;
}
$ { a [ r - 2 ] } = $ { a [ r - 2 ] } + 1 ;
if ( $ { a [ r - 2 ] } < $ { n [ r - 2 ] } ) {
result . a = getValue ( $ { a } ) ;
}
$ { a [ r - 1 ] } = $ { a [ r - 1 ] } - 1 ;
if ( $ { a [ r - 2 ] } < $ { n [ r - 2 ] } &&
$ { a [ r - 1 ] } < $ { n [ r - 1 ] } ) {
result . b = getValue ( $ { a } ) ;
}
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function Fm(e,t,n){let r=e.indexOf(t);return e.map((a,o)=>o===r? ` $ { a } - $ { n } ` :a).join()}function $ m(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return sr({inputs:{x:s.complexTensorInfos.imag},backend:n})}var HZ={kernelName:mh,backendName:"webgl",kernelFunc: $ m};function Mu(e,t,n){let r=e[0].dtype;if(r==="complex64"){let u=e.map(m=>Kd({inputs:{input:m},backend:n})),d=e.map(m=> $ m({inputs:{input:m},backend:n})),p=Mu(u,t,n),h=Mu(d,t,n),f=Ta({inputs:{real:p,imag:h},backend:n});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),d.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}let s=n.shouldExecuteOnCPU(e);if(r==="string"&&(s=!0),s){let u=e.map(b=>{let y=k.sizeFromShape(b.shape.slice(t));return ge({inputs:{x:b},backend:n,attrs:{shape:[-1,y]}})}),d=u.map(b=>({vals:n.readSync(b.dataId),shape:b.shape})),p=_.computeOutShape(u.map(b=>b.shape),1),h=u[0].shape[0]===1,f=z7(d,p,r,h),m=_.computeOutShape(e.map(b=>b.shape),t),g=n.makeTensorInfo(m,r,f);return u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g}if(e.length>Q().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(e.length/2),d=Mu(e.slice(0,u),t,n),p=Mu(e.slice(u),t,n),h=Mu([d,p],t,n);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),h}if(Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let u=new GZ(e.map(d=>d.shape),t);return n.runWebGLProgram(u,e,r)}let{tensors2D:a,outShape:o}=jZ(e,t,n),i=new UZ(a.map(u=>u.shape)),c=n.runWebGLProgram(i,a,r);a.forEach(u=>n.disposeIntermediateTensorInfo(u));let l=ge({inputs:{x:c},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(c),l}function jZ(e,t,n){let r=_.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>ge({inputs:{x:a},attrs:{shape:[-1,k.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:r}}function KN(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=k.parseAxisParam(s,t[0].shape)[0],o=_.computeOutShape(t.map(l=>l.shape),a);if(k.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(l=>k.sizeFromShape(l.shape)>0);if(i.length===1)return sr({inputs:{x:i[0]},backend:n});let c=i.map(l=>l.shape);return _.assertParamsConsistent(c,a),Mu(i,a,n)}var qZ={kernelName:ic,backendName:"webgl",kernelFunc:KN},XN=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,c=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,b=m?2:3,y=m?3:1,v="",x="";n&&(r?v= ` float activation ( float a ) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
2021-12-09 20:22:22 +01:00
} ` :s?v= ` float activation ( float a ) {
2021-09-11 17:11:38 +02:00
float b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
2021-12-09 20:22:22 +01:00
} ` :v= `
2021-09-11 17:11:38 +02:00
float activation ( float x ) {
$ { n }
}
2021-12-09 20:22:22 +01:00
` ,x="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { v }
2021-09-11 17:11:38 +02:00
2021-12-06 12:34:50 +01:00
const ivec2 strides = ivec2 ( $ { i } , $ { c } ) ;
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2 ( $ { a } , $ { o } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
int batch = coords [ 0 ] ;
2021-12-09 20:22:22 +01:00
int d2 = coords [ $ { y } ] ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner =
ivec2 ( coords [ $ { g } ] , coords [ $ { b } ] ) * strides - pads ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < $ { d } ; wR ++ ) {
2021-10-22 15:06:43 +02:00
int xR = xRCorner + wR * $ { l } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { p } ; wC ++ ) {
2021-12-06 12:34:50 +01:00
int xC = xCCorner + wC * $ { u } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int d1 = 0 ; d1 < $ { h } ; d1 += 4 ) {
vec4 wValues = vec4 (
getW ( wR , wC , d1 , d2 ) ,
getW ( wR , wC , d1 + 1 , d2 ) ,
getW ( wR , wC , d1 + 2 , d2 ) ,
getW ( wR , wC , d1 + 3 , d2 )
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { m } ) {
vec4 xValues = vec4 (
getX ( batch , xR , xC , d1 ) ,
getX ( batch , xR , xC , d1 + 1 ) ,
getX ( batch , xR , xC , d1 + 2 ) ,
getX ( batch , xR , xC , d1 + 3 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec4 xValues = vec4 (
getX ( batch , d1 , xR , xC ) ,
getX ( batch , d1 + 1 , xR , xC ) ,
getX ( batch , d1 + 2 , xR , xC ) ,
getX ( batch , d1 + 3 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { f === 1 } ) {
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { m } ) {
dotProd +=
getX ( batch , xR , xC , $ { h } ) *
getW ( wR , wC , $ { h } , d2 ) ;
} else {
dotProd +=
getX ( batch , $ { h } , xR , xC ) *
getW ( wR , wC , $ { h } , d2 ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
} else if ( $ { f === 2 } ) {
vec2 wValues = vec2 (
getW ( wR , wC , $ { h } , d2 ) ,
getW ( wR , wC , $ { h } + 1 , d2 )
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { m } ) {
vec2 xValues = vec2 (
getX ( batch , xR , xC , $ { h } ) ,
getX ( batch , xR , xC , $ { h } + 1 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec2 xValues = vec2 (
getX ( batch , $ { h } , xR , xC ) ,
getX ( batch , $ { h } + 1 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
} else if ( $ { f === 3 } ) {
vec3 wValues = vec3 (
getW ( wR , wC , $ { h } , d2 ) ,
getW ( wR , wC , $ { h } + 1 , d2 ) ,
getW ( wR , wC , $ { h } + 2 , d2 )
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { m } ) {
vec3 xValues = vec3 (
getX ( batch , xR , xC , $ { h } ) ,
getX ( batch , xR , xC , $ { h } + 1 ) ,
getX ( batch , xR , xC , $ { h } + 2 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else {
vec3 xValues = vec3 (
getX ( batch , $ { h } , xR , xC ) ,
getX ( batch , $ { h } + 1 , xR , xC ) ,
getX ( batch , $ { h } + 2 , xR , xC )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd ;
2021-12-09 20:22:22 +01:00
$ { w }
2021-09-11 17:11:38 +02:00
$ { x }
setOutput ( result ) ;
}
2021-12-09 20:22:22 +01:00
` }},KZ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec3 strides = ivec3 ( $ { s } , $ { a } , $ { o } ) ;
const ivec3 pads = ivec3 ( $ { t } , $ { n } , $ { r } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d2 = coords . u ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xFRCCorner = ivec3 ( coords . y , coords . z , coords . w ) * strides - pads ;
int xFCorner = xFRCCorner . x ;
int xRCorner = xFRCCorner . y ;
int xCCorner = xFRCCorner . z ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0 ;
2021-12-06 12:34:50 +01:00
for ( int wF = 0 ; wF < $ { u } ; wF ++ ) {
2021-09-11 17:11:38 +02:00
int xF = xFCorner + wF * $ { i } ;
if ( xF < 0 || xF >= $ { e . inDepth } ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2021-09-11 17:11:38 +02:00
for ( int wR = 0 ; wR < $ { d } ; wR ++ ) {
2021-12-06 12:34:50 +01:00
int xR = xRCorner + wR * $ { c } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { p } ; wC ++ ) {
2021-10-22 15:06:43 +02:00
int xC = xCCorner + wC * $ { l } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int d1 = 0 ; d1 < $ { h } ; d1 += 4 ) {
vec4 xValues = vec4 (
getX ( batch , xF , xR , xC , d1 ) ,
getX ( batch , xF , xR , xC , d1 + 1 ) ,
getX ( batch , xF , xR , xC , d1 + 2 ) ,
getX ( batch , xF , xR , xC , d1 + 3 )
) ;
vec4 wValues = vec4 (
getW ( wF , wR , wC , d1 , d2 ) ,
getW ( wF , wR , wC , d1 + 1 , d2 ) ,
getW ( wF , wR , wC , d1 + 2 , d2 ) ,
getW ( wF , wR , wC , d1 + 3 , d2 )
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dot ( xValues , wValues ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { f === 1 } ) {
dotProd +=
getX ( batch , xF , xR , xC , $ { h } ) *
getW ( wF , wR , wC , $ { h } , d2 ) ;
} else if ( $ { f === 2 } ) {
vec2 xValues = vec2 (
getX ( batch , xF , xR , xC , $ { h } ) ,
getX ( batch , xF , xR , xC , $ { h } + 1 )
) ;
vec2 wValues = vec2 (
getW ( wF , wR , wC , $ { h } , d2 ) ,
getW ( wF , wR , wC , $ { h } + 1 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
} else if ( $ { f === 3 } ) {
vec3 xValues = vec3 (
getX ( batch , xF , xR , xC , $ { h } ) ,
getX ( batch , xF , xR , xC , $ { h } + 1 ) ,
getX ( batch , xF , xR , xC , $ { h } + 2 )
) ;
vec3 wValues = vec3 (
getW ( wF , wR , wC , $ { h } , d2 ) ,
getW ( wF , wR , wC , $ { h } + 1 , d2 ) ,
getW ( wF , wR , wC , $ { h } + 2 , d2 )
) ;
dotProd += dot ( xValues , wValues ) ;
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},XZ=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=Wn(this.outputShape.length);let{dataFormat:n}=t,r=In(),s=n==="channelsLast",a=s?0:1,o=s?1:2,i=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {": ` if ( blockIndex < $ { e [ 1 ] } && pos < $ { e [ 0 ] } ) { ` ,c="";for(let l=0;l<=1;l++)for(let u=0;u<=1;u++)c+= `
2021-12-06 12:34:50 +01:00
blockIndex = rc . y + $ { u } ;
2021-10-22 15:06:43 +02:00
pos = rc . x + $ { l } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { i }
offsetY = int ( blockIndex / outWidth ) * stride [ 0 ] - pad [ 0 ] ;
d0 = offsetY + dilation [ 0 ] * ( pos / itemsPerBlockRow ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( d0 < inputShape [ $ { a } ] && d0 >= 0 ) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod ( blockIndex , outWidth ) * stride [ 1 ] - pad [ 1 ] ;
d1 = offsetX + dilation [ 1 ] * ( imod ( pos , itemsPerBlockRow ) /
inChannels ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( d1 < inputShape [ $ { o } ] && d1 >= 0 ) {
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
ch = imod ( pos , inChannels ) ;
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { s } ) {
innerDims = vec2 ( d1 , ch ) ;
2021-12-06 12:34:50 +01:00
result [ $ { l * 2 + u } ] = getChannel (
2021-09-11 17:11:38 +02:00
getA ( d0 , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
} else {
innerDims = vec2 ( d0 , d1 ) ;
2021-12-06 12:34:50 +01:00
result [ $ { l * 2 + u } ] = getChannel (
2021-09-11 17:11:38 +02:00
getA ( ch , int ( innerDims . x ) ,
int ( innerDims . y ) ) , innerDims ) ;
}
}
}
}
` ;this.userCode= `
2021-04-30 18:01:04 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec2 rc = getOutputCoords ( ) ;
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( 0 ) ;
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
int blockIndex , pos , offsetY , d0 , offsetX , d1 , ch ;
vec2 innerDims ;
2021-04-30 18:01:04 +02:00
2021-12-06 12:34:50 +01:00
$ { c }
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
$ { r . output } = result ;
2021-04-30 18:01:04 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function YN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let c=e.shape,l=r.texData.get(e.dataId),u=n.inChannels,d=c[0]*c[1]*c[2],p=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,b=[];if(!((d===1||p===1)&&u>BN)&&l.isPacked&&h&&l.texture!=null&&c[2]%2!=0&&k.arraysEqual(l.shape.slice(-3),c.slice(-3))){let x=c[0]*c[1]*(c[2]+1),w={dataId:e.dataId,shape:[1,x,n.inChannels],dtype:e.dtype},T=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,k.assert(Gd(l.shape,w.shape),()=> ` packed reshape $ { l . shape } to $ { w . shape } isn ' t free ` );let C=ge({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(C);let D=Am({a:w,b:C,backend:r,transposeA:f,transposeB:m,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),F=r.texData.get(D.dataId);k.assert(F.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=T,F.shape=n.outShape,g=sr({inputs:{x:D},backend:r}),g.shape=n.outShape,b.push(D)}else{let x=h?c[0]*c[1]*c[2]:c[0]*c[2]*c[3],w=ge({inputs:{x:e},backend:r,attrs:{shape:[1,x,n.inChannels]}}),T=ge({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),C=Am({a:w,b:T,transposeA:f,transposeB:m,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=ge({inputs:{x:C},backend:r,attrs:{shape:n.outShape}}),b.push(w),b.push(T),b.push(C)}for(let x of b)r.disposeIntermediateTensorInfo(x);return g}function ZN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:c,filterHeight:l,inChannels:u,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=c*l*u,g=p*d,b=[m,g],y=!0,v=!1,x=[],w=ge({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),T=ge({inputs:{x:t},backend:r,attrs:{shape:[1,m,k.sizeFromShape(t.shape)/m]}});x.push(w),x.push(T);let C=new XZ(b,n),D=[w.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],F=r.runWebGLProgram(C,[w],"float32",D),O=ge({inputs:{x:F},backend:r,attrs:{shape:[1,b[0],b[1]]}});x.push(F),x.push(O);let $ =s!=null,R=a!=null,N=i==="leakyrelu",L=i?Nm(i,!0):null,G=new RN(O.shape,T.shape,[1,g,n.outChannels],y,v, $ ,L,R,N),j=[O,T];if(s&&j.push(s),R&&j.push(a),N){let te=r.makeTensorInfo([],"float32",k.createScalarValue(o,"float32"));j.push(te),x.push(te)}let K=r.runWebGLProgram(G,j,"float32"),q=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],Z=ge({inputs:{x:K},backend:r,attrs:{shape:q}});x.push(K);for(let te of x)r.disposeIntermediateTensorInfo(te);return Z}function YZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:c,dilations:l,dimRoundingMode:u}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,a.shape,o,l,i,u,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=YN({x:s,filter:a,convInfo:p,backend:n});else if(Q().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)h=ZN({x:s,filter:a,convInfo:p,backend:n});else{let m=new XN(p);h=n.runWebGLProgram(m,[s,a],"float32")}let f=ge({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var ZZ={kernelName:Ha,backendName:"webgl",kernelFunc:YZ},JZ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int d2 = coords . w ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { t } - $ { r } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { n } - $ { s } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { a } ) {
float dyValue = getDy ( b , yR , yC , d2 ) ;
float xValue = getX ( b , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
} else {
float dyValue = getDy ( b , d2 , yR , yC ) ;
float xValue = getX ( b , d1 , xR , xC ) ;
dotProd += ( xValue * dyValue ) ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput ( dotProd ) ;
}
2021-12-09 20:22:22 +01:00
` }},QZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,c=a?1:2,l=a?2:3,u=a?3:1;this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2 ( $ { o } , $ { i } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2021-12-06 12:34:50 +01:00
int d1 = coords [ $ { u } ] ;
2021-09-11 17:11:38 +02:00
2021-12-06 12:34:50 +01:00
ivec2 dyCorner = ivec2 ( coords [ $ { c } ] , coords [ $ { l } ] ) - pads ;
2021-09-11 17:11:38 +02:00
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { r } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2021-09-11 17:11:38 +02:00
int idyR = int ( dyR ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = $ { t } - 1 - wR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
2021-04-01 19:39:54 +02:00
continue ;
}
2021-09-11 17:11:38 +02:00
int idyC = int ( dyC ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = $ { n } - 1 - wC ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { a } ) {
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
} else {
float xValue = getDy ( batch , d2 , idyR , idyC ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},eJ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int wF = coords . x ;
int wR = coords . y ;
int wC = coords . z ;
int d1 = coords . w ;
int d2 = coords . u ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0 ;
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yF = 0 ; yF < $ { e . outDepth } ; yF ++ ) {
int xF = wF + yF * $ { t } - $ { s } ;
if ( xF < 0 || xF >= $ { e . inDepth } ) {
continue ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { n } - $ { a } ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { r } - $ { o } ;
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float dyValue = getDy ( b , yF , yR , yC , d2 ) ;
float xValue = getX ( b , xF , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},tJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,c=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode= `
2021-12-06 12:34:50 +01:00
const ivec3 pads = ivec3 ( $ { i } , $ { c } , $ { l } ) ;
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyFCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
float dotProd = 0.0 ;
for ( int wF = 0 ; wF < $ { t } ; wF ++ ) {
float dyF = float ( dyFCorner + wF ) / $ { s } . 0 ;
if ( dyF < 0.0 || dyF >= $ { e . outDepth } . 0 || fract ( dyF ) > 0.0 ) {
continue ;
}
int idyF = int ( dyF ) ;
int wFPerm = $ { t } - 1 - wF ;
for ( int wR = 0 ; wR < $ { n } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { a } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
int wRPerm = $ { n } - 1 - wR ;
for ( int wC = 0 ; wC < $ { r } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { o } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
int wCPerm = $ { r } - 1 - wC ;
for ( int d2 = 0 ; d2 < $ { e . outChannels } ; d2 ++ ) {
float xValue = getDy ( batch , idyF , idyR , idyC , d2 ) ;
float wValue = getW ( wFPerm , wRPerm , wCPerm , d1 , d2 ) ;
dotProd += xValue * wValue ;
}
}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function nJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:c,dimRoundingMode:l,filterShape:u}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,u,o,1,i,l,!1,d),h=new JZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var rJ={kernelName:nh,backendName:"webgl",kernelFunc:nJ};function sJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:c,dataFormat:l,dimRoundingMode:u}=r,d=_.convertConv2DDataFormat(l),p=_.computeConv2DInfo(o,a.shape,i,1,c,u,!1,d),h=new QZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var aJ={kernelName:ja,backendName:"webgl",kernelFunc:sJ};function oJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,l=_.computeConv3DInfo(s.shape,a.shape,o,c,i),u=new KZ(l);return n.runWebGLProgram(u,[s,a],"float32")}var iJ={kernelName:Nl,backendName:"webgl",kernelFunc:oJ};function cJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:c}=r,l=_.computeConv3DInfo(s.shape,c,o,1,i),u=new eJ(l);return n.runWebGLProgram(u,[s,a],"float32")}var uJ={kernelName:rh,backendName:"webgl",kernelFunc:cJ};function lJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:c}=r,l=_.computeConv3DInfo(c,a.shape,i,1,o),u=new tJ(l);return n.runWebGLProgram(u,[s,a],"float32")}var dJ={kernelName:sh,backendName:"webgl",kernelFunc:lJ},pJ= $ N+ `
2021-09-11 17:11:38 +02:00
return cos ( x ) ;
2021-12-09 20:22:22 +01:00
` ,hJ=Xe({opSnippet:pJ}),fJ={kernelName:qa,backendName:"webgl",kernelFunc:hJ},mJ= `
2021-09-11 17:11:38 +02:00
float e2x = exp ( - x ) ;
return ( e2x + 1.0 / e2x ) / 2.0 ;
2021-12-09 20:22:22 +01:00
` ,gJ=Xe({opSnippet:mJ}),bJ={kernelName:Ka,backendName:"webgl",kernelFunc:gJ},yJ=class{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,c]=e,[l]=t,[u,d]=n;this.outputShape=[l,u,d,c];let p=r==="bilinear"?1:0,[h,f]=[ ` $ { o - 1 } . 0 ` , ` $ { i - 1 } . 0 ` ],[m,g,b]=u>1?[ ` $ { ( o - 1 ) / ( u - 1 ) } ` ,"(y2-y1) * height_ratio", ` y1 * $ { h } + float ( y ) * ( height _scale ) ` ]:["0.0","0.0", ` 0.5 * ( y1 + y2 ) * $ { h } ` ],[y,v,x]=d>1?[ ` $ { ( i - 1 ) / ( d - 1 ) } ` ,"(x2-x1) * width_ratio", ` x1 * $ { f } + float ( x ) * ( width _scale ) ` ]:["0.0","0.0", ` 0.5 * ( x1 + x2 ) * $ { f } ` ];this.userCode= `
2021-09-11 17:11:38 +02:00
const float height _ratio = float ( $ { m } ) ;
2021-12-09 20:22:22 +01:00
const float width _ratio = float ( $ { y } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int y = coords [ 1 ] ;
int x = coords [ 2 ] ;
int d = coords [ 3 ] ;
// get box vals
float y1 = getBoxes ( b , 0 ) ;
float x1 = getBoxes ( b , 1 ) ;
float y2 = getBoxes ( b , 2 ) ;
float x2 = getBoxes ( b , 3 ) ;
// get image in batch index
int bInd = round ( getBoxInd ( b ) ) ;
if ( bInd < 0 || bInd >= $ { a } ) {
return ;
2021-04-01 19:39:54 +02:00
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float height _scale = $ { g } ;
2021-12-09 20:22:22 +01:00
float width _scale = $ { v } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float in _y = $ { b } ;
if ( in _y < 0.0 || in _y > $ { h } ) {
setOutput ( float ( $ { s } ) ) ;
return ;
}
float in _x = $ { x } ;
if ( in _x < 0.0 || in _x > $ { f } ) {
setOutput ( float ( $ { s } ) ) ;
return ;
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
vec2 sourceFracIndexCR = vec2 ( in _x , in _y ) ;
if ( $ { p } == 1 ) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2 ( sourceFracIndexCR ) ;
ivec2 sourceCeilCR = ivec2 ( ceil ( sourceFracIndexCR ) ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float topLeft = getImage ( b , sourceFloorCR . y , sourceFloorCR . x , d ) ;
float bottomLeft = getImage ( b , sourceCeilCR . y , sourceFloorCR . x , d ) ;
float topRight = getImage ( b , sourceFloorCR . y , sourceCeilCR . x , d ) ;
float bottomRight = getImage ( b , sourceCeilCR . y , sourceCeilCR . x , d ) ;
vec2 fracCR = sourceFracIndexCR - vec2 ( sourceFloorCR ) ;
float top = topLeft + ( topRight - topLeft ) * fracCR . x ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracCR . x ;
float newValue = top + ( bottom - top ) * fracCR . y ;
setOutput ( newValue ) ;
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2 ( floor (
sourceFracIndexCR + vec2 ( 0.5 , 0.5 ) ) ) ;
float newValue = getImage ( b , sourceNearestCR . y , sourceNearestCR . x , d ) ;
setOutput ( newValue ) ;
}
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},vJ=e=>{let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:c,extrapolationValue:l}=r,u=new yJ(s.shape,a.shape,i,c,l);return n.runWebGLProgram(u,[s,a,o],"float32")},xJ={kernelName:cc,backendName:"webgl",kernelFunc:vJ},JN=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let r=e.length,s=t?"0.0": ` getX ( $ { QN ( r , "coords" ) } ) ` ,a=e[e.length-1],o="",i="";t?(o=n? ` end != $ { a - 1 } ` :"end != 0",i=n?"end + 1":"end - 1"):(o=n? ` end + pow2 < $ { a } ` :"end >= pow2",i=n?"end + pow2":"end - pow2"),this.userCode= `
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-12-09 20:22:22 +01:00
$ { mt ( r ) } coords = getOutputCoords ( ) ;
int end = $ { e _ ( r , "coords" ) } ;
2021-09-11 17:11:38 +02:00
float val = $ { s } ;
int pow2 = int ( pow ( 2.0 , index ) ) ;
if ( $ { o } ) {
int idx = $ { i } ;
2021-12-09 20:22:22 +01:00
$ { e _ ( r , "coords" ) } = idx ;
val += getX ( $ { QN ( r , "coords" ) } ) ;
2021-09-11 17:11:38 +02:00
}
setOutput ( val ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function QN(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 e_(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 wJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,c=s.shape.length,l=_.getAxesPermutation([a],c),u=s;l!=null&&(u=Tn({inputs:{x:s},backend:n,attrs:{perm:l}}));let d=_.getInnerMostAxes(1,c)[0];if(d!==c-1)throw new Error( ` WebGL cumsum shader expects an inner - most axis = $ { s . shape . length - 1 } but got axis = $ { a } ` );let p=u.shape[d],h=sr({inputs:{x:u},backend:n});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new JN(u.shape,!1,i),g=[[f]],b=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(b)}if(o){let f=new JN(u.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(l!=null){let f=_.getUndoAxesPermutation(l),m=Tn({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),m}return h}var kJ={kernelName:Xa,backendName:"webgl",kernelFunc:wJ};function IJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let c=n.readSync(s.dataId),l=n.readSync(a.dataId),u=yN(c,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}else if(s.shape.length===2){let c=n.bufferSync(s),l=n.bufferSync(a),u=L7(c,l,o,i);return n.makeTensorInfo(u.shape,a.dtype,u.values)}throw new Error( ` Error in denseBincount : input must be at most rank 2 , but got rank$ { s . shape . length } . ` )}var SJ={kernelName:ah,backendName:"webgl",kernelFunc:IJ},TJ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int h = $ { this . getHeightCoordString ( ) } ;
int w = $ { this . getWidthCoordString ( ) } ;
int d = $ { this . getDepthCoordString ( ) } ;
int in _h = h / $ { t } ;
int offset _h = imod ( h , $ { t } ) ;
int in _w = w / $ { t } ;
int offset _w = imod ( w , $ { t } ) ;
int offset _d = ( offset _h * $ { t } + offset _w ) *
$ { this . getOutputDepthSize ( ) } ;
int in _d = d + offset _d ;
float result = $ { this . getInputSamplingString ( ) } ;
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +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 CJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r,i=s.shape[0],c=o==="NHWC"?s.shape[1]:s.shape[2],l=o==="NHWC"?s.shape[2]:s.shape[3],u=o==="NHWC"?s.shape[3]:s.shape[1],d=c*a,p=l*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=new TJ(f,a,o);return n.runWebGLProgram(m,[s],s.dtype)}var NJ={kernelName:uc,backendName:"webgl",kernelFunc:CJ},t_=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Wn(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,c="",l="";n&&(r?c= ` float activation ( float a ) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
2021-12-06 12:34:50 +01:00
} ` :s?c= ` float activation ( float a ) {
2021-09-11 17:11:38 +02:00
float b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
2021-12-06 12:34:50 +01:00
} ` :c= `
2021-09-11 17:11:38 +02:00
float activation ( float x ) {
$ { n }
}
2021-12-06 12:34:50 +01:00
` ,l="result = activation(result);");let u=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { c }
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
int d1 = d2 / $ { i } ;
int q = d2 - d1 * $ { i } ;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for ( int wR = 0 ; wR < $ { a } ; wR ++ ) {
int xR = xRCorner + wR * dilations [ 0 ] ;
if ( xR < 0 || xR >= inDims [ 0 ] ) {
continue ;
}
for ( int wC = 0 ; wC < $ { o } ; wC ++ ) {
int xC = xCCorner + wC * dilations [ 1 ] ;
if ( xC < 0 || xC >= inDims [ 1 ] ) {
continue ;
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
float xVal = getX ( batch , xR , xC , d1 ) ;
float wVal = getW ( wR , wC , d1 , q ) ;
dotProd += xVal * wVal ;
}
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd ;
2021-12-06 12:34:50 +01:00
$ { u }
2021-10-22 15:06:43 +02:00
$ { l }
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
}
2021-12-09 20:22:22 +01:00
` }},n_=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Wn(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,c=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,d=u,p= `
2021-09-11 17:11:38 +02:00
int xR ; int xC ; int xCOffset ;
2021-12-06 12:34:50 +01:00
vec4 wTexel ; vec4 previous ; vec4 final ; ` ;for(let g=0;g<u;g++)p+= `
2021-09-11 17:11:38 +02:00
vec4 xTexelC$ { g * 2 } ;
int xTexelC$ { g * 2 } Ready ;
vec4 xTexelC$ { g * 2 + 1 } ;
int xTexelC$ { g * 2 + 1 } Ready ;
2021-10-22 15:06:43 +02:00
vec4 xC$ { g } ; ` ;p+= `
for ( int r = 0 ; r < $ { l } ; r ++ ) {
2021-12-06 12:34:50 +01:00
` ;for(let g=0;g<u;g++)p+= `
2021-10-22 15:06:43 +02:00
xTexelC$ { g * 2 } = vec4 ( 0.0 ) ;
xTexelC$ { g * 2 } Ready = 0 ;
xTexelC$ { g * 2 + 1 } = vec4 ( 0.0 ) ;
xTexelC$ { g * 2 + 1 } Ready = 0 ;
xC$ { g } = vec4 ( 0.0 ) ; ` ;p+= `
xR = xRCorner + r * dilations [ 0 ] ;
2021-09-11 17:11:38 +02:00
if ( xR >= 0 && xR < inDims [ 0 ] ) {
2021-10-22 15:06:43 +02:00
` ;for(let g=0;g<(d+1)/2;g++){let b=g*2;if(p+= `
2021-12-06 12:34:50 +01:00
xC = xCCorner + $ { b * c } ;
` ,i===1){if(b<u&&(o%2==1?(p+= `
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1 ;
2021-10-22 15:06:43 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xCOffset , d1 ) ;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2021-10-22 15:06:43 +02:00
xTexelC$ { b } . zw = vec2 ( 0.0 ) ;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC$ { b } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
` ,c===1&&b>0?p+= `
2021-10-22 15:06:43 +02:00
xC$ { b } = vec4 ( xTexelC$ { b - 2 } . zw , xTexelC$ { b } . xy ) ;
2021-09-11 17:11:38 +02:00
` :p+= `
xCOffset = xC + 1 - 2 ;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
previous = getX ( batch , xR , xCOffset , d1 ) ;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
previous . zw = vec2 ( 0.0 ) ;
}
2021-07-29 15:05:49 +02:00
2021-10-22 15:06:43 +02:00
xC$ { b } = vec4 ( previous . zw , xTexelC$ { b } . xy ) ;
2021-04-01 19:39:54 +02:00
} else {
2021-10-22 15:06:43 +02:00
xC$ { b } = vec4 ( 0.0 , 0.0 , xTexelC$ { b } . xy ) ;
2021-09-11 17:11:38 +02:00
}
` ):p+= `
2021-10-22 15:06:43 +02:00
if ( xC >= 0 && xC < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xC , d1 ) ;
2021-09-11 17:11:38 +02:00
if ( xC + 1 >= inDims [ 1 ] ) {
2021-10-22 15:06:43 +02:00
xTexelC$ { b } . zw = vec2 ( 0.0 ) ;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC$ { b } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xC$ { b } = xTexelC$ { b } ;
2021-12-09 20:22:22 +01:00
` ,b+1<u)){let y=o%2==0?k.nearestLargerEven(c):c;c%2==0&&o%2==1||c%2!=0&&o%2!=1?(p+= `
xCOffset = xC + imod ( pads [ 1 ] , 2 ) + $ { y } ;
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b + 1 } Ready == 0 ) {
xTexelC$ { b + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2021-10-22 15:06:43 +02:00
xTexelC$ { b + 1 } . zw = vec2 ( 0.0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC$ { b + 1 } Ready = 1 ;
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
` ,c>1&&(p+= `
2021-09-11 17:11:38 +02:00
xCOffset -= 2 ;
2021-10-22 15:06:43 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xCOffset , d1 ) ;
xTexelC$ { b } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
` ),p+= `
2021-10-22 15:06:43 +02:00
xC$ { b + 1 } = vec4 ( xTexelC$ { b } . zw , xTexelC$ { b + 1 } . xy ) ;
2021-12-09 20:22:22 +01:00
` ):y===1?p+= `
2021-10-22 15:06:43 +02:00
xC$ { b + 1 } = xTexelC$ { b } ;
2021-09-11 17:11:38 +02:00
` :p+= `
2021-12-09 20:22:22 +01:00
xCOffset = xC + $ { y } ;
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b + 1 } Ready == 0 ) {
xTexelC$ { b + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
2021-09-11 17:11:38 +02:00
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2021-10-22 15:06:43 +02:00
xTexelC$ { b + 1 } . zw = vec2 ( 0.0 ) ;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC$ { b + 1 } Ready = 1 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
xC$ { b + 1 } = xTexelC$ { b + 1 } ;
2021-12-06 12:34:50 +01:00
` }}else b<u&&(o%2==1?(p+= `
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1 - strides [ 1 ] ;
2021-10-22 15:06:43 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xCOffset , d1 ) ;
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2021-10-22 15:06:43 +02:00
xTexelC$ { b } . zw = vec2 ( 0.0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC$ { b } Ready = 1 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if ( xC + 1 >= 0 && xC + 1 < inDims [ 1 ] && xTexelC$ { b + 1 } Ready == 0 ) {
xTexelC$ { b + 1 } = getX ( batch , xR , xC + 1 , d1 ) ;
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if ( xC + 2 >= inDims [ 1 ] ) {
2021-10-22 15:06:43 +02:00
xTexelC$ { b + 1 } . zw = vec2 ( 0.0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC$ { b + 1 } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xC$ { b } = vec4 ( xTexelC$ { b } . zw , xTexelC$ { b + 1 } . zw ) ;
2021-12-06 12:34:50 +01:00
` ,b+1<u&&(p+= `
2021-09-11 17:11:38 +02:00
final = vec4 ( 0.0 ) ;
xCOffset = xC + 1 + strides [ 1 ] ;
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] ) {
final = getX ( batch , xR , xCOffset , d1 ) ;
}
2021-10-22 15:06:43 +02:00
xC$ { b + 1 } = vec4 ( xTexelC$ { b + 1 } . xy , final . xy ) ;
2021-09-11 17:11:38 +02:00
` )):(p+= `
2021-10-22 15:06:43 +02:00
if ( xC >= 0 && xC < inDims [ 1 ] && xTexelC$ { b } Ready == 0 ) {
xTexelC$ { b } = getX ( batch , xR , xC , d1 ) ;
2021-09-11 17:11:38 +02:00
if ( xC + 1 >= inDims [ 1 ] ) {
2021-10-22 15:06:43 +02:00
xTexelC$ { b } . zw = vec2 ( 0.0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC$ { b } Ready = 1 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xCOffset = xC + strides [ 1 ] ;
2021-10-22 15:06:43 +02:00
if ( xCOffset >= 0 && xCOffset < inDims [ 1 ] && xTexelC$ { b + 1 } Ready == 0 ) {
xTexelC$ { b + 1 } = getX ( batch , xR , xCOffset , d1 ) ;
2021-09-11 17:11:38 +02:00
if ( xCOffset + 1 >= inDims [ 1 ] ) {
2021-10-22 15:06:43 +02:00
xTexelC$ { b + 1 } . zw = vec2 ( 0. ) ;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC$ { b + 1 } Ready = 1 ;
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
2021-10-22 15:06:43 +02:00
xC$ { b } = vec4 (
xTexelC$ { b } . xy , xTexelC$ { b + 1 } . xy ) ;
2021-12-06 12:34:50 +01:00
` ,b+1<u&&(p+= `
2021-10-22 15:06:43 +02:00
xC$ { b + 1 } = vec4 ( xTexelC$ { b } . zw , xTexelC$ { b + 1 } . zw ) ;
2021-12-06 12:34:50 +01:00
` )));b<u&&(p+= `
2021-10-22 15:06:43 +02:00
wTexel = getW ( r , $ { b } , d1 , q ) ;
dotProd += xC$ { b } * vec4 ( wTexel . xz , wTexel . xz ) ;
2021-12-06 12:34:50 +01:00
` ,b+1<u&&(p+= `
2021-10-22 15:06:43 +02:00
wTexel = getW ( r , $ { b + 1 } , d1 , q ) ;
dotProd += xC$ { b + 1 } * vec4 ( wTexel . xz , wTexel . xz ) ;
2021-09-11 17:11:38 +02:00
` ))}p+= `
2021-10-22 15:06:43 +02:00
}
` ,p+= `
}
` ;let h="",f="";n&&(r?h= ` vec4 activation ( vec4 a ) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords ( ) ;
$ { n }
} ` :s?h= ` vec4 activation ( vec4 a ) {
vec4 b = getLeakyreluAlphaAtOutCoords ( ) ;
$ { n }
} ` :h= ` vec4 activation ( vec4 x ) {
$ { n }
} ` ,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode= `
$ { h }
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
ivec2 xRCCorner = coords . yz * strides - pads ;
int d2 = coords . w ;
int d1 = d2 / $ { a } ;
int q = d2 - d1 * $ { a } ;
int xRCorner = xRCCorner . x ;
int xCCorner = xRCCorner . y ;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4 ( 0.000000000000001 ) ;
$ { p }
vec4 result = dotProd - vec4 ( 0.000000000000001 ) ;
$ { m }
$ { f }
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function _J(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c,dimRoundingMode:l}=r,u=c;u==null&&(u=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(o,u),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { o } and dilations '${u}' ` );let d=_.computeConv2DInfo(s.shape,a.shape,o,u,i,l,!0),p;Q().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels==1?p=new n_(d):p=new t_(d);let h=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return n.runWebGLProgram(p,[s,a],"float32",h)}var EJ={kernelName:Ya,backendName:"webgl",kernelFunc:_J},AJ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int wR = coords . x ;
int wC = coords . y ;
int d1 = coords . z ;
int dm = coords . w ;
int d2 = d1 * $ { a } + dm ;
float dotProd = 0.0 ;
// TO DO: Vec4 over the batch size
for ( int b = 0 ; b < $ { e . batchSize } ; b ++ ) {
for ( int yR = 0 ; yR < $ { e . outHeight } ; yR ++ ) {
int xR = wR + yR * $ { t } - $ { r } ;
if ( xR < 0 || xR >= $ { e . inHeight } ) {
continue ;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int yC = 0 ; yC < $ { e . outWidth } ; yC ++ ) {
int xC = wC + yC * $ { n } - $ { s } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( xC < 0 || xC >= $ { e . inWidth } ) {
continue ;
}
float dyValue = getDy ( b , yR , yC , d2 ) ;
float xValue = getX ( b , xR , xC , d1 ) ;
dotProd += ( xValue * dyValue ) ;
}
}
}
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},DJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2 ( $ { a } , $ { o } ) ;
2021-04-01 19:39:54 +02:00
void main ( ) {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords ( ) ;
2021-04-01 19:39:54 +02:00
int batch = coords [ 0 ] ;
2021-09-11 17:11:38 +02:00
int d1 = coords [ 3 ] ;
ivec2 dyCorner = coords . yz - pads ;
int dyRCorner = dyCorner . x ;
int dyCCorner = dyCorner . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wR = 0 ; wR < $ { t } ; wR ++ ) {
float dyR = float ( dyRCorner + wR ) / $ { r } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = $ { t } - 1 - wR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for ( int wC = 0 ; wC < $ { n } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { s } . 0 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = $ { n } - 1 - wC ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// TO DO: Vec4 over the channelMul
for ( int dm = 0 ; dm < $ { i } ; dm ++ ) {
int d2 = d1 * $ { i } + dm ;
float xValue = getDy ( batch , idyR , idyC , d2 ) ;
float wValue = getW ( wRPerm , wCPerm , d1 , dm ) ;
dotProd += xValue * wValue ;
}
}
}
setOutput ( dotProd ) ;
}
2021-12-09 20:22:22 +01:00
` }};function FJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,filterShape:u}=r,d=_.computeConv2DInfo(s.shape,u,o,i,c,l,!0),p=new AJ(d);return n.runWebGLProgram(p,[s,a],"float32")}var $ J={kernelName:oh,backendName:"webgl",kernelFunc:FJ};function RJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,inputShape:u}=r,d=_.computeConv2DInfo(u,a.shape,o,i,c,l,!0),p=new DJ(d);return n.runWebGLProgram(p,[s,a],"float32")}var PJ={kernelName:ih,backendName:"webgl",kernelFunc:RJ},OJ=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
float val = coords [ 0 ] == coords [ 1 ] ? getX ( coords [ 0 ] ) : 0.0 ;
setOutput ( val ) ;
}
2021-12-09 20:22:22 +01:00
` }};function MJ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=k.sizeFromShape(r.shape),o=ge({inputs:{x:r},backend:n,attrs:{shape:[a]}}),i=new OJ(a),c=n.runWebGLProgram(i,[o],o.dtype),l=ge({inputs:{x:c},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),l}var LJ={kernelName:ch,backendName:"webgl",kernelFunc:MJ},BJ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:c,dilationWidth:l}=e,{top:u,left:d}=r;this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec2 strides = ivec2 ( $ { s } , $ { a } ) ;
2021-12-06 12:34:50 +01:00
const ivec2 pads = ivec2 ( $ { u } , $ { d } ) ;
2021-09-11 17:11:38 +02:00
const float neg _infinity = - 3.4 e38 ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int d1 = coords . w ;
ivec2 outTopLeftCorner =
coords . yz * strides - pads ;
int hBeg = outTopLeftCorner . x ;
int wBeg = outTopLeftCorner . y ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float curVal = neg _infinity ;
for ( int h = 0 ; h < $ { o } ; h ++ ) {
2021-12-06 12:34:50 +01:00
int hIn = hBeg + h * $ { c } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if ( hIn >= 0 && hIn < $ { t } ) {
for ( int w = 0 ; w < $ { i } ; w ++ ) {
2021-10-22 15:06:43 +02:00
int wIn = wBeg + w * $ { l } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( wIn >= 0 && wIn < $ { n } ) {
float xVal = getX ( batch , hIn , wIn , d1 ) ;
float wVal = getW ( h , w , d1 ) ;
float val = xVal + wVal ;
if ( val > curVal ) {
curVal = val ;
}
}
}
}
2021-07-29 15:05:49 +02:00
}
2021-09-11 17:11:38 +02:00
float result = curVal ;
setOutput ( result ) ;
2021-07-29 15:05:49 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function zJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,l=_.computeDilation2DInfo(s.shape,a.shape,o,i,"NHWC",c),u,d=new BJ(l);u=n.runWebGLProgram(d,[s,a],"float32");let p=ge({inputs:{x:u},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(u),p}var WJ={kernelName:_l,backendName:"webgl",kernelFunc:zJ};function VJ(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:c}=_.decodeEinsumEquation(s,a.length);_.checkEinsumDimSizes(o.length,c,a);let{path:l,steps:u}=_.getEinsumComputePath(i,c),d=u.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:b,expandDims:y}=_.getEinsumPermutation(h,c[g]),v;_.isIdentityPermutation(b)?v=a[g]:(v=Tn({inputs:{x:a[g]},backend:n,attrs:{perm:b}}),f.push(v));let x=v.shape.slice();for(let w=0;w<y.length;++w)x.splice(y[w],0,1);k.arraysEqual(v.shape,x)||(v=ge({inputs:{x:v},backend:n,attrs:{shape:x}}),f.push(v)),p===null?p=v:(p=t1({inputs:{a:v,b:p},backend:n}),f.push(p))}m<d-1&&(l[m]>=0&&(p=Em({inputs:{x:p},backend:n,attrs:{axis:l[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var UJ={kernelName:dh,backendName:"webgl",kernelFunc:VJ},GJ="return (x >= 0.0) ? x : (exp(x) - 1.0);",HJ= `
2021-09-11 17:11:38 +02:00
vec4 result ;
result . r = ( x . r >= 0.0 ) ? x . r : ( exp ( x . r ) - 1.0 ) ;
result . g = ( x . g >= 0.0 ) ? x . g : ( exp ( x . g ) - 1.0 ) ;
result . b = ( x . b >= 0.0 ) ? x . b : ( exp ( x . b ) - 1.0 ) ;
result . a = ( x . a >= 0.0 ) ? x . a : ( exp ( x . a ) - 1.0 ) ;
return result ;
2021-12-09 20:22:22 +01:00
` ,jJ=Xe({opSnippet:GJ,packedOpSnippet:HJ}),qJ={kernelName:Ja,backendName:"webgl",kernelFunc:jJ},KJ="return (b >= 1.0) ? a : a * (b + 1.0);",XJ= `
2021-09-11 17:11:38 +02:00
vec4 bGTEZero = vec4 ( greaterThanEqual ( b , vec4 ( 0. ) ) ) ;
return ( bGTEZero * a ) + ( ( vec4 ( 1.0 ) - bGTEZero ) * ( a * ( b + vec4 ( 1.0 ) ) ) ) ;
2021-12-09 20:22:22 +01:00
` ,YJ=e=>{let{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jd(XJ,r.shape,s.shape):new Pu(KJ,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)},ZJ={kernelName:ph,backendName:"webgl",kernelFunc:YJ},JJ= `
2021-09-11 17:11:38 +02:00
return vec4 ( equal ( a , b ) ) ;
2021-12-09 20:22:22 +01:00
` ,QJ="return float(a == b);",eQ=cn({opSnippet:QJ,packedOpSnippet:JJ,dtype:"bool",cpuKernelImpl:W7}),tQ={kernelName:dc,backendName:"webgl",kernelFunc:eQ},nQ= `
2021-09-11 17:11:38 +02:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2021-12-09 20:22:22 +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 } ;
2021-09-11 17:11:38 +02:00
float sign = sign ( x ) ;
x = abs ( x ) ;
float t = 1.0 / ( 1.0 + p * x ) ;
return sign * ( 1.0 - ( ( ( ( ( a5 * t + a4 ) * t ) + a3 ) * t + a2 ) * t + a1 ) * t * exp ( - x * x ) ) ;
2021-12-09 20:22:22 +01:00
` ,rQ=Xe({opSnippet:nQ}),sQ={kernelName:lc,backendName:"webgl",kernelFunc:rQ},r_="return exp(x);",s_=Xe({opSnippet:r_,packedOpSnippet:r_,cpuKernelImpl:V7,dtype:"float32"}),aQ={kernelName:Qa,backendName:"webgl",kernelFunc:s_};function a1(e){let{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),c=s;return s<0&&(k.assert(-(o+1)<=s,()=> ` Axis must be in the interval [ $ { - ( o + 1 ) } , $ { o } ] ` ),c=o+s+1),i.splice(c,0,1),ge({inputs:{x:a},backend:r,attrs:{shape:i}})}var oQ={kernelName:pc,backendName:"webgl",kernelFunc:a1},a_="return exp(x) - 1.0;",iQ=Xe({opSnippet:a_,packedOpSnippet:a_,cpuKernelImpl:U7}),cQ={kernelName:hc,backendName:"webgl",kernelFunc:iQ},o_=class{constructor(e,t,n){this.variableNames=["real","imag"];let r=t[1];this.outputShape=t;let s=n? ` 2.0 * $ { Math . PI } ` : ` - 2.0 * $ { Math . PI } ` ,a=n? ` $ { r } . 0 ` :"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error( ` FFT component must be either "real" or "imag" , got $ { e } . ` );this.userCode= `
2021-09-11 17:11:38 +02:00
const float exponentMultiplier = $ { s } ;
float unaryOpComplex ( float real , float expR , float imag , float expI ) {
$ { o }
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
float mulMatDFT ( int batch , int index ) {
float indexRatio = float ( index ) / float ( $ { r } ) ;
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio ;
float result = 0.0 ;
for ( int i = 0 ; i < $ { r } ; i ++ ) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float ( i ) ;
float expR = cos ( x ) ;
float expI = sin ( x ) ;
float real = getReal ( batch , i ) ;
float imag = getImag ( batch , i ) ;
result +=
unaryOpComplex ( real , expR , imag , expI ) / $ { a } ;
}
return result ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
setOutput ( mulMatDFT ( coords [ 0 ] , coords [ 1 ] ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function i_(e,t,n){let r=n.texData.get(e.dataId),s=k.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=s/a,i=ge({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),c=i.shape,l=new o_("real",c,t),u=new o_("imag",c,t),d=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:c},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:c}],p=n.runWebGLProgram(l,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=Ta({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);let m=ge({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function uQ(e){let{inputs:t,backend:n}=e,{input:r}=t;return i_(r,!1,n)}var lQ={kernelName:hh,backendName:"webgl",kernelFunc:uQ},dQ=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
// Input can be obtained from uniform value.
setOutput ( value ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function Xd(e){let{backend:t,attrs:n}=e,{shape:r,value:s}=n,{dtype:a}=n;if(a=a||k.inferDtype(s),a==="string"){let o=k.getArrayFromDType(a,k.sizeFromShape(r));return o.fill(s),t.makeTensorInfo(r,a,o)}else{let o=new dQ(r,s),i=[[s]];return t.runWebGLProgram(o,[],a,i)}}var pQ={kernelName:El,backendName:"webgl",kernelFunc:Xd},hQ=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
int coordX = $ { t } - x - 1 ;
float outputValue ;
if ( coordX >= 0 && coordX < $ { t } ) {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coordX , coords [ 3 ] ) ;
} else {
outputValue = getImage ( coords [ 0 ] , coords [ 1 ] , coords [ 2 ] , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2021-12-09 20:22:22 +01:00
` }},fQ={kernelName:fc,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new hQ(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},c_="return floor(x);",mQ=Xe({opSnippet:c_,packedOpSnippet:c_,cpuKernelImpl:G7}),gQ={kernelName:eo,backendName:"webgl",kernelFunc:mQ},bQ= `
2021-09-11 17:11:38 +02:00
float s = sign ( a ) * sign ( b ) ;
int ia = round ( a ) ;
int ib = round ( b ) ;
if ( ib != 0 ) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float ( idiv ( ia , ib , s ) ) ;
} else {
return NAN ;
2021-04-30 18:01:04 +02:00
}
2021-12-09 20:22:22 +01:00
` ,yQ= `
2021-09-11 17:11:38 +02:00
ivec4 ia = round ( a ) ;
ivec4 ib = round ( b ) ;
bvec4 cond = notEqual ( ib , ivec4 ( 0 ) ) ;
ivec4 result = ivec4 ( 0 ) ;
vec4 s = sign ( a ) * sign ( b ) ;
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if ( cond [ 0 ] ) {
result [ 0 ] = idiv ( ia [ 0 ] , ib [ 0 ] , s [ 0 ] ) ;
2021-04-30 18:01:04 +02:00
}
2021-09-11 17:11:38 +02:00
if ( cond [ 1 ] ) {
result [ 1 ] = idiv ( ia [ 1 ] , ib [ 1 ] , s [ 1 ] ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( cond [ 2 ] ) {
result [ 2 ] = idiv ( ia [ 2 ] , ib [ 2 ] , s [ 2 ] ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( cond [ 3 ] ) {
result [ 3 ] = idiv ( ia [ 3 ] , ib [ 3 ] , s [ 3 ] ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return vec4 ( result ) ;
2021-12-09 20:22:22 +01:00
` ,vQ=cn({opSnippet:bQ,packedOpSnippet:yQ,dtype:"int32"}),xQ={kernelName:to,backendName:"webgl",kernelFunc:vQ},wQ=class{constructor(e){this.variableNames=["A"];let t=In(),[n,r]=e;this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) / vec2 ( $ { r } . 0 , $ { n } . 0 ) ;
vec4 values = $ { t . texture2D } ( A , uv ) ;
float value ;
if ( depth == 0 ) {
value = values . r ;
} else if ( depth == 1 ) {
value = values . g ;
} else if ( depth == 2 ) {
value = values . b ;
} else if ( depth == 3 ) {
value = values . a ;
2021-03-31 13:01:22 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( floor ( value * 255.0 + 0.5 ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},kQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=In(),[n,r]=e;this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec3 coords = getOutputCoords ( ) ;
int texR = coords [ 0 ] ;
int texC = coords [ 1 ] ;
int depth = coords [ 2 ] ;
vec4 result = vec4 ( 0. ) ;
for ( int row = 0 ; row <= 1 ; row ++ ) {
for ( int col = 0 ; col <= 1 ; col ++ ) {
texC = coords [ 1 ] + row ;
depth = coords [ 2 ] + col ;
vec2 uv = ( vec2 ( texC , texR ) + halfCR ) /
vec2 ( $ { r } . 0 , $ { n } . 0 ) ;
vec4 values = $ { t . texture2D } ( A , uv ) ;
float value ;
if ( depth == 0 ) {
value = values . r ;
} else if ( depth == 1 ) {
value = values . g ;
} else if ( depth == 2 ) {
value = values . b ;
} else if ( depth == 3 ) {
value = values . a ;
}
result [ row * 2 + col ] = floor ( value * 255.0 + 0.5 ) ;
}
2021-03-31 13:01:22 +02:00
}
2021-09-11 17:11:38 +02:00
$ { t . output } = result ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},IQ={kernelName:Ah,backendName:"webgl",kernelFunc:SQ},Lu;function SQ(e){let{inputs:t,backend:n,attrs:r}=e,{pixels:s}=t,{numChannels:a}=r,o=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,[c,l]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],u=[l,c],d=[l,c,a];(i||o)&&(Lu==null&&(Lu=document.createElement("canvas").getContext("2d")),Lu.canvas.width=c,Lu.canvas.height=l,Lu.drawImage(s,0,0,c,l),s=Lu.canvas);let p=n.makeTensorInfo(u,"int32");n.texData.get(p.dataId).usage=mr.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),s);let h=Q().getBool("WEBGL_PACK")?new kQ(d):new wQ(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function TQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=_.convertConv2DDataFormat(u),g=_.computeConv2DInfo(s.shape,a.shape,c,d,l,p,!1,m),b,y=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))b=YN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(Q().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)b=ZN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let x=o!=null,w=i!=null,T=h==="leakyrelu",C=h?Nm(h,!1):null,D=new XN(g,x,C,w,T),F=[s,a];if(o&&F.push(o),i&&F.push(i),T){let O=n.makeTensorInfo([],"float32",k.createScalarValue(f,"float32"));F.push(O),y.push(O)}b=n.runWebGLProgram(D,F,"float32")}let v=ge({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return y.push(b),y.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var CQ={kernelName:Mo,backendName:"webgl",kernelFunc:TQ};function NQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=r,f=[],m=u;m==null&&(m=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(c,m),()=> ` Error in depthwiseConv2d : Either strides or dilations must be 1. Got strides $ { c } and dilations '${m}' ` );let g=_.computeConv2DInfo(s.shape,a.shape,c,m,l,d,!0),b=Q().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,y=p?Nm(p,b):null,v=[s,a],x=o!=null,w=i!=null,T=p==="leakyrelu";if(x&&v.push(o),w&&v.push(i),T){let O=n.makeTensorInfo([],"float32",k.createScalarValue(h,"float32"));v.push(O),f.push(O)}let C;b?C=new n_(g,x,y,w,T):C=new t_(g,x,y,w,T);let D=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],F=n.runWebGLProgram(C,v,"float32",D);return f.forEach(O=>n.disposeIntermediateTensorInfo(O)),F}var _Q={kernelName:Lo,backendName:"webgl",kernelFunc:NQ},EQ=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let r=mt(t.length),s=mt(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode= `
2021-09-11 17:11:38 +02:00
$ { r } strides = $ { r } ( $ { this . strides } ) ;
void main ( ) {
$ { s } coords = getOutputCoords ( ) ;
int flattenIndex = 0 ;
for ( int j = 0 ; j < $ { this . sliceDim } ; j ++ ) {
int index = round ( getIndices ( coords [ 0 ] , j ) ) ;
flattenIndex += index * $ { a } ;
}
setOutput ( getX ( flattenIndex , coords [ 1 ] ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function AQ(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,o=a[a.length-1],i=k.sizeFromShape(r.shape),[c,l,u,d]=_.prepareAndValidate(r,s),p=ge({inputs:{x:s},backend:n,attrs:{shape:[l,o]}}),h=ge({inputs:{x:r},backend:n,attrs:{shape:[k.sizeFromShape(r.shape)/u,u]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.readSync(s.dataId),y=n.bufferSync(r),v=H7(b,y,r.dtype,l,o,u,d,r.shape,i);return n.makeTensorInfo(c,r.dtype,v.values)}let f=new EQ(o,d,[l,u]),m=n.runWebGLProgram(f,[h,p],h.dtype),g=ge({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var DQ={kernelName:gc,backendName:"webgl",kernelFunc:AQ},FQ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=mt(this.rank),r= $ Q(e,2);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { n } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { r } ) ) ;
}
2021-12-09 20:22:22 +01:00
` }};function $ Q(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let s=0;s<e.length;s++)s===2?r.push("int(getIndices(resRC.x, resRC.z))"):r.push( ` $ { n [ s ] } ` );return r.join()}function u_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,c=k.parseAxisParam(o,s.shape)[0],l=n.readSync(a.dataId),u=s.shape[c];for(let x=0;x<l.length;++x){let w=l[x];k.assert(w<=u-1&&w>=0,()=> ` GatherV2 : the index value $ { w } is not in [ 0 , $ { u - 1 } ] ` )}let d=_.segment_util.collectGatherOpShapeInfo(s,a,c,i),p=k.sizeFromShape(a.shape),h=[],f=ge({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=ge({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}});h.push(f),h.push(m);let g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize];if(n.shouldExecuteOnCPU([s,a])||s.dtype==="string"){let x=n.bufferSync(m),w=n.bufferSync(f),T=j7(w,x,g);return h.forEach(C=>n.disposeIntermediateTensorInfo(C)),n.makeTensorInfo(d.outputShape,T.dtype,T.values)}let b=new FQ(f.shape,g),y=n.runWebGLProgram(b,[f,m],f.dtype);h.push(y);let v=ge({inputs:{x:y},backend:n,attrs:{shape:d.outputShape}});return h.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var RQ={kernelName:mc,backendName:"webgl",kernelFunc:u_},PQ="return float(a > b);",OQ= `
2021-09-11 17:11:38 +02:00
return vec4 ( greaterThan ( a , b ) ) ;
2021-12-09 20:22:22 +01:00
` ,MQ=cn({opSnippet:PQ,packedOpSnippet:OQ,cpuKernelImpl:q7,dtype:"bool"}),LQ={kernelName:bc,backendName:"webgl",kernelFunc:MQ},BQ="return float(a >= b);",zQ= `
2021-09-11 17:11:38 +02:00
return vec4 ( greaterThanEqual ( a , b ) ) ;
2021-12-09 20:22:22 +01:00
` ,WQ=cn({opSnippet:BQ,packedOpSnippet:zQ,dtype:"bool",cpuKernelImpl:K7}),VQ={kernelName:ro,backendName:"webgl",kernelFunc:WQ};function UQ(e){let{inputs:t,backend:n}=e,{input:r}=t;return i_(r,!0,n)}var GQ={kernelName:fh,backendName:"webgl",kernelFunc:UQ},HQ="return float(!isnan(x) && !isinf(x));",jQ=Xe({opSnippet:HQ,dtype:"bool"}),qQ={kernelName:yc,backendName:"webgl",kernelFunc:jQ},KQ="return float(isinf(x));",XQ=Xe({opSnippet:KQ,dtype:"bool"}),YQ={kernelName:vc,backendName:"webgl",kernelFunc:XQ},ZQ="return float(isnan(x));",JQ=Xe({opSnippet:ZQ,dtype:"bool"}),QQ={kernelName:xc,backendName:"webgl",kernelFunc:JQ},eee="return float(a < b);",tee= `
2021-09-11 17:11:38 +02:00
return vec4 ( lessThan ( a , b ) ) ;
2021-12-09 20:22:22 +01:00
` ,nee=cn({opSnippet:eee,packedOpSnippet:tee,cpuKernelImpl:X7,dtype:"bool"}),ree={kernelName:wc,backendName:"webgl",kernelFunc:nee},see="return float(a <= b);",aee= `
2021-09-11 17:11:38 +02:00
return vec4 ( lessThanEqual ( a , b ) ) ;
2021-12-09 20:22:22 +01:00
` ,oee=cn({opSnippet:see,packedOpSnippet:aee,cpuKernelImpl:Y7,dtype:"bool"}),iee={kernelName:kc,backendName:"webgl",kernelFunc:oee};function cee(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=Z7(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var uee={kernelName:gh,backendName:"webgl",kernelFunc:cee},lee= ` if ( x < 0.0 ) return NAN ;
return log ( x ) ; ` ,dee= `
2021-09-11 17:11:38 +02: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-12-09 20:22:22 +01:00
` ,pee=Xe({opSnippet:lee,packedOpSnippet:dee,cpuKernelImpl:J7}),hee={kernelName:oo,backendName:"webgl",kernelFunc:pee},fee="return log(1.0 + x);",mee=Xe({opSnippet:fee}),gee={kernelName:Ic,backendName:"webgl",kernelFunc:mee},bee="return float(a >= 1.0 && b >= 1.0);",yee= `
2021-09-11 17:11:38 +02:00
return vec4 (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) *
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ) ;
2021-12-09 20:22:22 +01:00
` ,vee=cn({opSnippet:bee,packedOpSnippet:yee,dtype:"bool"}),xee={kernelName:Sc,backendName:"webgl",kernelFunc:vee},wee="return float(!(x >= 1.0));",kee=Xe({opSnippet:wee}),Iee={kernelName:Al,backendName:"webgl",kernelFunc:kee},See="return float(a >= 1.0 || b >= 1.0);",Tee= `
2021-09-11 17:11:38 +02:00
return min (
vec4 ( greaterThanEqual ( a , vec4 ( 1.0 ) ) ) +
vec4 ( greaterThanEqual ( b , vec4 ( 1.0 ) ) ) ,
vec4 ( 1.0 ) ) ;
2021-12-09 20:22:22 +01:00
` ,Cee=cn({opSnippet:See,packedOpSnippet:Tee,dtype:"bool"}),Nee={kernelName:Dl,backendName:"webgl",kernelFunc:Cee},_ee=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,c= ` float ( $ { n } ) + float ( $ { r } ) * sum ` ;s===.5?i= ` inversesqrt ( $ { c } ) ` :s===1?i= ` 1.0 / ( $ { c } ) ` :i= ` exp ( log ( $ { c } ) * float ( - $ { s } ) ) ; ` ,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
int d = coords [ 3 ] ;
float x = getX ( b , r , c , d ) ;
float sum = 0.0 ;
for ( int j = - $ { a } ; j <= $ { a } ; j ++ ) {
int idx = d + j ;
if ( idx >= 0 && idx <= $ { o } ) {
float z = getX ( b , r , c , idx ) ;
sum += z * z ;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
float val = x * $ { i } ;
setOutput ( val ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},Eee=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,o=e[3]-1;this.outputShape=e;let i,c= ` float ( $ { n } ) + float ( $ { r } ) * sum ` ;s===.5?i= ` inversesqrt ( $ { c } ) ` :s===1?i= ` 1.0 / ( $ { c } ) ` :i= ` exp ( log ( $ { c } ) * float ( - $ { s } ) ) ; ` ,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords . x ;
int r = coords . y ;
int c = coords . z ;
int d = coords . w ;
bool hasNextCol = d < $ { this . outputShape [ 3 ] } ;
bool hasNextRow = c < $ { this . outputShape [ 2 ] } ;
vec4 sum = vec4 ( 0. ) ;
vec4 xFragAtOutputCoords = getX ( b , r , c , d ) ;
vec4 xAtOutputCoords = vec4 (
getChannel ( xFragAtOutputCoords , vec2 ( c , d ) ) ,
hasNextCol ?
getChannel ( xFragAtOutputCoords , vec2 ( c , d + 1 ) ) : 0.0 ,
hasNextRow ?
getChannel ( xFragAtOutputCoords , vec2 ( c + 1 , d ) ) : 0.0 ,
( hasNextRow && hasNextCol ) ?
getChannel ( xFragAtOutputCoords , vec2 ( c + 1 , d + 1 ) ) : 0.0
) ;
int firstChannel = d - $ { a } ;
vec2 cache = vec2 ( 0. ) ;
if ( firstChannel >= 0 ) {
vec4 firstChannelFrag = getX ( b , r , c , firstChannel ) ;
cache . x = getChannel ( firstChannelFrag , vec2 ( c , firstChannel ) ) ;
if ( hasNextRow ) {
cache . y = getChannel ( firstChannelFrag , vec2 ( c + 1 , firstChannel ) ) ;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
ivec2 depth = ivec2 ( d , d + 1 ) ;
for ( int j = - $ { a } ; j <= $ { a } ; j ++ ) {
ivec2 idx = depth + j ;
bvec2 aboveLowerBound = greaterThanEqual ( idx , ivec2 ( 0 ) ) ;
bvec2 belowUpperBound = lessThanEqual ( idx , ivec2 ( $ { o } ) ) ;
bool depthInRange = aboveLowerBound . x && belowUpperBound . x ;
bool depthPlusOneInRange = aboveLowerBound . y && belowUpperBound . y ;
if ( depthInRange || depthPlusOneInRange ) {
vec4 z = vec4 ( 0. ) ;
vec4 xFragAtCurrentDepth ;
z . xz = cache . xy ;
if ( depthPlusOneInRange && hasNextCol ) {
xFragAtCurrentDepth = idx . y != d ?
getX ( b , r , c , idx . y ) : xFragAtOutputCoords ;
z . y = getChannel ( xFragAtCurrentDepth , vec2 ( c , idx . y ) ) ;
if ( hasNextRow ) {
z . w = getChannel ( xFragAtCurrentDepth , vec2 ( c + 1 , idx . y ) ) ;
}
}
cache . xy = z . yw ;
sum += z * z ;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
vec4 result = xAtOutputCoords * $ { i } ;
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},Aee=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:c}=r,l=Q().getBool("WEBGL_PACK_NORMALIZATION")?new Eee(s.shape,a,o,i,c):new _ee(s.shape,a,o,i,c);return n.runWebGLProgram(l,[s],s.dtype)},Dee={kernelName:Fl,backendName:"webgl",kernelFunc:Aee},Fee=class{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
float result = 0.0 ;
for ( int d = 0 ; d < $ { this . depth } ; ++ d ) {
int depthBegin = int ( max ( 0.0 , float ( d - $ { t } ) ) ) ;
int depthEnd = int ( min ( float ( $ { this . depth } ) ,
float ( d + $ { t } + 1 ) ) ) ;
const int MIN _DEPTH _BEGIN = 0 ;
const int MAX _DEPTH _END = $ { this . depth } ;
float norm = 0.0 ;
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
norm += getInputImage ( b , r , c , k ) * getInputImage ( b , r , c , k ) ;
}
else {
break ;
}
}
norm = float ( $ { r } ) * norm + float ( $ { n } ) ;
for ( int k = MIN _DEPTH _BEGIN ; k < MAX _DEPTH _END ; ++ k ) {
if ( k < depthBegin ) {
continue ;
}
else if ( k >= depthBegin && k < depthEnd ) {
float dyi = - 2.0 * float ( $ { r } )
* float ( $ { s } )
* getInputImage ( b , r , c , k ) * getOutputImage ( b , r , c , d )
/ n o r m ;
if ( k == d ) {
dyi += pow ( norm , - 1.0 * $ { s } ) ;
}
if ( k == coords [ 3 ] ) {
dyi *= getDy ( b , r , c , d ) ;
result += dyi ;
}
}
else {
break ;
}
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput ( result ) ;
2021-03-26 15:26:02 +01:00
}
2021-12-09 20:22:22 +01:00
` }}, $ ee=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:c,alpha:l,beta:u}=r,d=new Fee(s.shape,i,c,l,u);return n.runWebGLProgram(d,[s,a,o],s.dtype)},Ree={kernelName:bh,backendName:"webgl",kernelFunc: $ ee};function Pee(e,t,n,r){let s=k.sizeFromShape(t),o=k.sizeFromShape(e.shape)/s,i=ge({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=yi(i,e.dtype,"max",r),l=ge({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),l}function l_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=s.shape.length,c=k.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=u!=null,p=n.shouldExecuteOnCPU([s]),h=s;if(d){if(p){let v=n.texData.get(h.dataId).values,x=new Array(i);for(let C=0;C<x.length;C++)x[C]=s.shape[u[C]];let w=e1(v,s.shape,s.dtype,u,x);h=n.makeTensorInfo(x,s.dtype);let T=n.texData.get(h.dataId);T.values=w}else h=_m(s,u,n);l=_.getInnerMostAxes(l.length,i)}_.assertAxesAreInnerMostDims("max",l,i);let[f,m]=_.computeOutAndReduceShapes(h.shape,l),g=f;o&&(g=_.expandShapeToKeepDim(f,c));let b;if(p){let v=n.texData.get(h.dataId).values,x=Q7(v,k.sizeFromShape(m),g,s.dtype);b=n.makeTensorInfo(g,s.dtype);let w=n.texData.get(b.dataId);w.values=x}else b=Pee(h,m,g,n);return d&&n.disposeIntermediateTensorInfo(h),b}var Oee={kernelName:io,backendName:"webgl",kernelFunc:l_},Mee=_N+ `
2021-09-11 17:11:38 +02:00
return max ( a , b ) ;
2021-12-09 20:22:22 +01:00
` ,Lee= `
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( max ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-12-09 20:22:22 +01:00
` +Cm+ `
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,Bee=cn({opSnippet:Mee,packedOpSnippet:Lee,cpuKernelImpl:e9}),zee={kernelName:co,backendName:"webgl",kernelFunc:Bee};function Wee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Eu(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;k.assert(_.eitherStridesOrDilationsAreOne(o,l),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { o } and dilations '${l}' ` );let u=_.computePool2DInfo(s.shape,a,o,l,i,c);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return sr({inputs:{x:s},backend:n});let d=new qd(u,"max",!1);return n.runWebGLProgram(d,[s],s.dtype)}var Vee={kernelName:uo,backendName:"webgl",kernelFunc:Wee};function Uee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dataFormat:c,dimRoundingMode:l}=r,u=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,u,i,l,c),p=new n1(d,"max",!1);return n.runWebGLProgram(p,[s],s.dtype)}var Gee={kernelName: $ l,backendName:"webgl",kernelFunc:Uee},Hee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=s-1-e.padInfo.top,i=a-1-e.padInfo.left,c=s*a-1;this.userCode= `
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2 ( $ { o } , $ { i } ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 dyRCCorner = coords . yz - pads ;
int dyRCorner = dyRCCorner . x ;
int dyCCorner = dyRCCorner . y ;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wR = 0 ; wR < $ { s } ;
wR += $ { r } ) {
float dyR = float ( dyRCorner + wR ) / $ { t } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 || fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
for ( int wC = 0 ; wC < $ { a } ; wC ++ ) {
float dyC = float ( dyCCorner + wC ) / $ { n } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( b , idyR , idyC , d ) ;
2021-12-06 12:34:50 +01:00
int maxPosValue = $ { c } - int ( getMaxPos ( b , idyR , idyC , d ) ) ;
2021-09-11 17:11:38 +02:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * $ { a } + wC ;
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask ;
}
}
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},jee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,c=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=i-1-e.padInfo.front,d=c-1-e.padInfo.top,p=l-1-e.padInfo.left,h=i*c*l-1;this.userCode= `
2021-12-06 12:34:50 +01:00
const ivec3 pads = ivec3 ( $ { u } , $ { d } , $ { p } ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec5 coords = getOutputCoords ( ) ;
int batch = coords . x ;
int ch = coords . u ;
ivec3 dyCorner = ivec3 ( coords . y , coords . z , coords . w ) - pads ;
int dyDCorner = dyCorner . x ;
int dyRCorner = dyCorner . y ;
int dyCCorner = dyCorner . z ;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0 ;
for ( int wD = 0 ; wD < $ { i } ;
wD += $ { s } ) {
float dyD = float ( dyDCorner + wD ) / $ { t } . 0 ;
if ( dyD < 0.0 || dyD >= $ { e . outDepth } . 0 || fract ( dyD ) > 0.0 ) {
continue ;
}
int idyD = int ( dyD ) ;
2021-12-06 12:34:50 +01:00
for ( int wR = 0 ; wR < $ { c } ;
2021-09-11 17:11:38 +02:00
wR += $ { a } ) {
float dyR = float ( dyRCorner + wR ) / $ { n } . 0 ;
if ( dyR < 0.0 || dyR >= $ { e . outHeight } . 0 ||
fract ( dyR ) > 0.0 ) {
continue ;
}
int idyR = int ( dyR ) ;
2021-10-22 15:06:43 +02:00
for ( int wC = 0 ; wC < $ { l } ;
2021-09-11 17:11:38 +02:00
wC += $ { o } ) {
float dyC = float ( dyCCorner + wC ) / $ { r } . 0 ;
if ( dyC < 0.0 || dyC >= $ { e . outWidth } . 0 ||
fract ( dyC ) > 0.0 ) {
continue ;
}
int idyC = int ( dyC ) ;
float dyValue = getDy ( batch , idyD , idyR , idyC , ch ) ;
int maxPosValue = $ { h } -
int ( getMaxPos ( batch , idyD , idyR , idyC , ch ) ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
2021-12-06 12:34:50 +01:00
wD * $ { c } * $ { l } +
2021-10-22 15:06:43 +02:00
wR * $ { l } + wC ;
2021-09-11 17:11:38 +02:00
float mask = float ( maxPosValue == curPosValue ? 1.0 : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask ;
}
}
}
setOutput ( dotProd ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function qee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:l,dimRoundingMode:u}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,l,u),h=new n1(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new jee(p),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var Kee={kernelName:vh,backendName:"webgl",kernelFunc:qee};function Xee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Eu([a,o],"maxPoolGrad");let{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=r,p=_.computePool2DInfo(i.shape,c,l,1,u,d),h=!0,f=new qd(p,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new Hee(p),b=n.runWebGLProgram(g,[s,m],i.dtype);return n.disposeIntermediateTensorInfo(m),b}var Yee={kernelName:yh,backendName:"webgl",kernelFunc:Xee};function Zee(e,t,n,r){let s=new qd(n,"max",!1),a=r.runWebGLProgram(s,[e],"float32");s=new qd(n,"max",!0,!0,t);let o=r.runWebGLProgram(s,[e],"float32");return[a,o]}var Jee={kernelName:xh,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,c=n;k.assert(r.shape.length===4,()=> ` Error in maxPool : input must be rank 4 but got rank $ { r . shape . length } . ` );let l=[1,1];k.assert(_.eitherStridesOrDilationsAreOne(a,l),()=> ` Error in maxPool : Either strides or dilations must be 1. Got strides $ { a } and dilations '${l}' ` );let u=_.computePool2DInfo(r.shape,s,a,l,o),[d,p]=Zee(r,i,u,c);return[d,p]}};function Qee(e,t,n,r){let s=k.sizeFromShape(t),o=k.sizeFromShape(e.shape)/s,i=ge({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=yi(i,"float32","mean",r),l=ge({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),l}var ete={kernelName:lo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{keepDims:s,axis:a}=t,o=n,i=r.shape.length,c=k.parseAxisParam(a,r.shape),l=c,u=_.getAxesPermutation(l,i),d=u!=null,p=o.shouldExecuteOnCPU([r]),h=[],f=r;if(d){if(p){let x=o.texData.get(f.dataId).values,w=new Array(i);for(let D=0;D<w.length;D++)w[D]=r.shape[u[D]];let T=e1(x,r.shape,r.dtype,u,w);f=o.makeTensorInfo(w,r.dtype);let C=o.texData.get(f.dataId);C.values=T}else f=_m(r,u,o);h.push(f),l=_.getInnerMostAxes(l.length,i)}_.assertAxesAreInnerMostDims("sum",l,i);let[m,g]=_.computeOutAndReduceShapes(f.shape,l),b=m;s&&(b=_.expandShapeToKeepDim(m,c));let y=Qee(f,g,b,o);for(let v of h)o.disposeIntermediateTensorInfo(v);return y}};function tte(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=k.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=Tn({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,s.shape.length)),_.assertAxesAreInnerMostDims("min",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=k.sizeFromShape(h),m=ge({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=yi(m,m.dtype,"min",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=ge({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=ge({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var nte={kernelName:po,backendName:"webgl",kernelFunc:tte},rte=_N+ `
2021-09-11 17:11:38 +02:00
return min ( a , b ) ;
2021-12-09 20:22:22 +01:00
` ,ste= `
2021-09-11 17:11:38 +02:00
vec4 result = vec4 ( min ( a , b ) ) ;
vec4 isNaN = min ( vec4 ( isnan ( a ) ) + vec4 ( isnan ( b ) ) , vec4 ( 1.0 ) ) ;
2021-12-09 20:22:22 +01:00
` +Cm+ `
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,ate=cn({opSnippet:rte,packedOpSnippet:ste,cpuKernelImpl:t9}),ote={kernelName:ho,backendName:"webgl",kernelFunc:ate},ite=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let r=e.length,s=mt(r),a=t.map(l=>l[0]).join(","),o=t.map((l,u)=>l[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),c=n==="reflect"?0:1;if(r===1){this.userCode= `
2021-09-11 17:11:38 +02:00
int start = $ { a } ;
int end = $ { o } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start ) {
2021-12-06 12:34:50 +01:00
outC = start * 2 - outC - $ { c } ;
2021-09-11 17:11:38 +02:00
} else if ( outC >= end ) {
2021-12-06 12:34:50 +01:00
outC = ( end - 1 ) * 2 - outC + $ { c } ;
2021-09-11 17:11:38 +02:00
}
setOutput ( getX ( outC - start ) ) ;
}
` ;return}this.userCode= `
$ { s } start = $ { s } ( $ { a } ) ;
$ { s } end = $ { s } ( $ { o } ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { s } outC = getOutputCoords ( ) ;
for ( int i = 0 ; i < $ { r } ; i ++ ) {
if ( outC [ i ] < start [ i ] ) {
2021-12-06 12:34:50 +01:00
outC [ i ] = start [ i ] * 2 - outC [ i ] - $ { c } ;
2021-09-11 17:11:38 +02:00
} else if ( outC [ i ] >= end [ i ] ) {
2021-12-06 12:34:50 +01:00
outC [ i ] = ( end [ i ] - 1 ) * 2 - outC [ i ] + $ { c } ;
2021-09-11 17:11:38 +02:00
}
}
$ { s } coords = outC - start ;
setOutput ( getX ( $ { i } ) ) ;
}
2021-12-09 20:22:22 +01:00
` }},cte=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let r=e.length,s=mt(r),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=Sn("rc",r),c=Sn("source",r),l= ` $ { i [ r - 1 ] } < $ { this . outputShape [ r - 1 ] } ` ,u=r===1?"source": ` vec2 ( $ { c . slice ( - 2 ) . join ( ) } ) ` ,d=n==="reflect"?0:1,p="";if(r===1){let h= `
2021-09-11 17:11:38 +02:00
$ { s } source = rc ;
if ( source < start ) {
source = start * 2 - source - $ { d } ;
} else if ( source >= end ) {
source = ( end - 1 ) * 2 - source + $ { d } ;
}
source -= start ;
` ;p= `
$ { s } rc = outputLoc ;
$ { h }
2021-12-06 12:34:50 +01:00
result [ 0 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { u } ) ;
2021-09-11 17:11:38 +02:00
$ { i [ r - 1 ] } += 1 ;
2021-10-22 15:06:43 +02:00
if ( $ { l } ) {
2021-09-11 17:11:38 +02:00
$ { h }
2021-12-06 12:34:50 +01:00
result [ 1 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { u } ) ;
2021-09-11 17:11:38 +02:00
}
` }else{let h= `
$ { s } source = rc ;
$ { s } lt = $ { s } ( lessThan ( source , start ) ) ;
$ { s } gte = $ { s } ( greaterThanEqual ( source , end ) ) ;
$ { s } orig = 1 - ( lt + gte ) ;
source = orig * source +
lt * ( start * 2 - source - $ { d } ) +
gte * ( ( end - 1 ) * 2 - source + $ { d } ) ;
source -= start ;
` ;p= `
$ { s } rc = outputLoc ;
$ { h }
2021-12-06 12:34:50 +01:00
result [ 0 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { u } ) ;
2021-09-11 17:11:38 +02:00
$ { i [ r - 1 ] } += 1 ;
2021-10-22 15:06:43 +02:00
if ( $ { l } ) {
2021-09-11 17:11:38 +02:00
$ { h }
2021-12-06 12:34:50 +01:00
result [ 1 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { u } ) ;
2021-09-11 17:11:38 +02:00
}
rc = outputLoc ;
$ { i [ r - 2 ] } += 1 ;
if ( $ { i [ r - 2 ] } < $ { this . outputShape [ r - 2 ] } ) {
$ { h }
2021-12-06 12:34:50 +01:00
result [ 2 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { u } ) ;
2021-09-11 17:11:38 +02:00
$ { i [ r - 1 ] } += 1 ;
2021-10-22 15:06:43 +02:00
if ( $ { l } ) {
2021-09-11 17:11:38 +02:00
$ { h }
2021-12-06 12:34:50 +01:00
result [ 3 ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { u } ) ;
2021-09-11 17:11:38 +02:00
}
}
` }this.userCode= `
const $ { s } start = $ { s } ( $ { a } ) ;
const $ { s } end = $ { s } ( $ { o } ) ;
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { s } outputLoc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
$ { p }
setOutput ( result ) ;
2020-12-15 14:15:43 +01:00
}
2021-12-09 20:22:22 +01:00
` }},ute=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{paddings:s,mode:a}=n,o=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new cte(r.shape,s,a):new ite(r.shape,s,a);return t.runWebGLProgram(o,[r],r.dtype)},lte={kernelName:fo,backendName:"webgl",kernelFunc:ute},dte= ` if ( b == 0.0 ) return NAN ;
return mod ( a , b ) ; ` ,pte= `
2021-09-11 17:11:38 +02:00
vec4 result = mod ( a , b ) ;
vec4 isNaN = vec4 ( equal ( b , vec4 ( 0.0 ) ) ) ;
2021-12-09 20:22:22 +01:00
` +Cm+ `
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,hte=cn({opSnippet:dte,packedOpSnippet:pte}),fte={kernelName:Tc,backendName:"webgl",kernelFunc:hte},mte=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float r = random ( seed ) ;
float cdf = 0.0 ;
for ( int i = 0 ; i < $ { t - 1 } ; i ++ ) {
cdf += getProbs ( batch , i ) ;
if ( r < cdf ) {
setOutput ( float ( i ) ) ;
return ;
}
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// If no other event happened, last event happened.
setOutput ( float ( $ { t - 1 } ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},gte= `
2021-09-11 17:11:38 +02:00
if ( a == b ) {
return 1.0 ;
} ;
2021-12-09 20:22:22 +01:00
return a / b ; ` ,bte= `
2021-09-11 17:11:38 +02:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b ;
if ( a . x == b . x ) {
result . x = 1. ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( a . y == b . y ) {
result . y = 1. ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( a . z == b . z ) {
result . z = 1. ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( a . w == b . w ) {
result . w = 1. ;
2021-04-01 19:39:54 +02:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,d_=cn({opSnippet:gte,packedOpSnippet:bte,checkOutOfBounds:!0}),yte={kernelName:Za,backendName:"webgl",kernelFunc:d_},p_="return a - b;",h_=cn({opSnippet:p_,packedOpSnippet:p_,supportsComplex:!0,cpuKernelImpl:b9}),vte={kernelName:Fo,backendName:"webgl",kernelFunc:h_};function f_(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=k.parseAxisParam([a],s.shape),i=l_({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=_.expandShapeToKeepDim(i.shape,o),l=ge({inputs:{x:i},backend:n,attrs:{shape:c}}),u=h_({inputs:{a:s,b:l},backend:n}),d=s_({inputs:{x:u},backend:n}),p=Em({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=ge({inputs:{x:p},backend:n,attrs:{shape:c}}),f=d_({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}var xte={kernelName:Ao,backendName:"webgl",kernelFunc:f_};function wte(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r,c=i?s:f_({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),l=c.shape[0],u=c.shape[1],d=new mte(l,u,a),p=[[o]],h=n.runWebGLProgram(d,[c],"int32",p);return i||n.disposeIntermediateTensorInfo(c),h}var kte={kernelName:wh,backendName:"webgl",kernelFunc:wte},m_="return -x;";function Ite(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.texData.get(r.dataId),[o,i]=r9(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s;return Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Ru(r.shape,m_):s=new Sa(r.shape,m_),n.runWebGLProgram(s,[r],r.dtype)}var Ste={kernelName:Cc,backendName:"webgl",kernelFunc:Ite},Tte=rs.nonMaxSuppressionV3Impl;function Cte(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c}=r,l=n.readSync(s.dataId),u=n.readSync(a.dataId),{selectedIndices:d}=Tte(l,u,o,i,c);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var Nte={kernelName:_c,backendName:"webgl",kernelFunc:Cte},_te=rs.nonMaxSuppressionV4Impl;function Ete(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,padToMaxOutputSize:l}=r,u=n.readSync(s.dataId),d=n.readSync(a.dataId),{selectedIndices:p,validOutputs:h}=_te(u,d,o,i,c,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Ate={kernelName:Ec,backendName:"webgl",kernelFunc:Ete},Dte=rs.nonMaxSuppressionV5Impl;function Fte(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,softNmsSigma:l}=r,u=n.readSync(s.dataId),d=n.readSync(a.dataId),p=o,h=i,f=c,m=l,{selectedIndices:g,selectedScores:b}=Dte(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var $ te={kernelName:Ac,backendName:"webgl",kernelFunc:Fte},Rte=class{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int index = round ( getIndices ( coords . x ) ) ;
setOutput ( mix ( float ( $ { r } ) , float ( $ { n } ) ,
float ( index == coords . y ) ) ) ;
2021-03-26 15:26:02 +01:00
}
2021-12-09 20:22:22 +01:00
` }},Pte=e=>{let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,c=k.sizeFromShape(s.shape),l=new Rte(c,a,o,i),u=ge({inputs:{x:s},backend:n,attrs:{shape:[c]}}),d=n.runWebGLProgram(l,[u],s.dtype);n.disposeIntermediateTensorInfo(u);let p=[...s.shape,a],h=ge({inputs:{x:d},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(d),h},Ote={kernelName:go,backendName:"webgl",kernelFunc:Pte};function Rm(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=Kd({inputs:{input:r},backend:n}),a=Rm({inputs:{x:s},backend:n}),o= $ m({inputs:{input:r},backend:n}),i=Rm({inputs:{x:o},backend:n}),c=Ta({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Xd({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var Mte={kernelName:Yc,backendName:"webgl",kernelFunc:Rm};function g_(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(r.dtype==="complex64"){let s=Kd({inputs:{input:r},backend:n}),a=g_({inputs:{x:s},backend:n}),o= $ m({inputs:{input:r},backend:n}),i=Rm({inputs:{x:o},backend:n}),c=Ta({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Xd({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var Lte={kernelName:Dc,backendName:"webgl",kernelFunc:g_};function Bte(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return a1({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{k.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),k.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(u=>{let d=a1({inputs:{input:u},backend:n,attrs:{dim:s}});return i.push(d),d}),l=KN({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),l}var zte={kernelName:Fc,backendName:"webgl",kernelFunc:Bte},Wte=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((c,l)=>c[0]+e[l]+c[1]);let r=e.length,s=mt(r),a=t.map(c=>c[0]).join(","),o=t.map((c,l)=>c[0]+e[l]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode= `
2021-09-11 17:11:38 +02:00
int start = $ { a } ;
int end = $ { o } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
int outC = getOutputCoords ( ) ;
if ( outC < start || outC >= end ) {
setOutput ( value ) ;
} else {
setOutput ( getX ( outC - start ) ) ;
}
}
` ;return}this.userCode= `
$ { s } start = $ { s } ( $ { a } ) ;
$ { s } end = $ { s } ( $ { o } ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { s } outC = getOutputCoords ( ) ;
if ( any ( lessThan ( outC , start ) ) || any ( greaterThanEqual ( outC , end ) ) ) {
setOutput ( value ) ;
} else {
$ { s } coords = outC - start ;
setOutput ( getX ( $ { i } ) ) ;
}
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},Vte=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let r=e.length,s=mt(r),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=Sn("rc",r),c=Sn("source",r),l= ` $ { i [ r - 1 ] } < $ { this . outputShape [ r - 1 ] } ` ,u=r===1?"source": ` vec2 ( $ { c . slice ( - 2 ) . join ( ) } ) ` ,d=[ ` $ { s } rc = outputLoc ; ` , ` $ { i [ r - 1 ] } += 1 ;
2021-10-22 15:06:43 +02:00
if ( $ { l } ) {
2021-09-11 17:11:38 +02:00
` ,r===1?"": ` }
rc = outputLoc ;
$ { i [ r - 2 ] } += 1 ;
if ( $ { i [ r - 2 ] } < $ { this . outputShape [ r - 2 ] } ) { ` ,r===1?"": ` $ { i [ r - 1 ] } += 1 ;
2021-10-22 15:06:43 +02:00
if ( $ { l } ) { ` ],p=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=r===1?2:4;f<m;f++)h+= `
2021-09-11 17:11:38 +02:00
$ { d [ f ] }
if ( $ { p } ) {
result [ $ { f } ] = float ( value ) ;
} else {
$ { s } source = rc - start ;
2021-12-06 12:34:50 +01:00
result [ $ { f } ] = getChannel ( getX ( $ { c . join ( ) } ) , $ { u } ) ;
2021-09-11 17:11:38 +02:00
}
` ;h+=r===1?"} ":"}}",this.userCode= `
const $ { s } start = $ { s } ( $ { a } ) ;
const $ { s } end = $ { s } ( $ { o } ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { s } outputLoc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
$ { h }
setOutput ( result ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},b_=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(k.sizeFromShape(s.shape)===0){let l=a.map((u,d)=>u[0]+s.shape[d]+u[1]);return Xd({backend:n,attrs:{shape:l,value:o,dtype:s.dtype}})}let i=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Vte(s.shape,a,o):new Wte(s.shape,a,o),c=[[o]];return n.runWebGLProgram(i,[s],s.dtype,c)},Ute={kernelName:bo,backendName:"webgl",kernelFunc:b_},Gte= `
2021-09-11 17:11:38 +02:00
if ( a < 0.0 && floor ( b ) < b ) {
return NAN ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if ( b == 0.0 ) {
return 1.0 ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return ( round ( mod ( b , 2.0 ) ) != 1 ) ?
pow ( abs ( a ) , b ) : sign ( a ) * pow ( abs ( a ) , b ) ;
2021-12-09 20:22:22 +01:00
` ,Hte= `
2021-09-11 17:11:38 +02:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4 ( equal ( round ( mod ( b , 2.0 ) ) , ivec4 ( 1 ) ) ) ;
vec4 multiplier = sign ( a ) * isModRound1 + ( vec4 ( 1.0 ) - isModRound1 ) ;
vec4 result = multiplier * pow ( abs ( a ) , b ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal ( b , vec4 ( 0.0 ) ) ;
result . r = isExpZero . r ? 1.0 : result . r ;
result . g = isExpZero . g ? 1.0 : result . g ;
result . b = isExpZero . b ? 1.0 : result . b ;
result . a = isExpZero . a ? 1.0 : result . a ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 isNaN = vec4 ( lessThan ( a , vec4 ( 0.0 ) ) ) * vec4 ( lessThan ( floor ( b ) , b ) ) ;
2021-12-09 20:22:22 +01:00
` +Cm+ `
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,jte=cn({opSnippet:Gte,packedOpSnippet:Hte}),qte={kernelName:yo,backendName:"webgl",kernelFunc:jte};function Kte(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=[],l=k.parseAxisParam(a,s.shape),u=l,d=_.getAxesPermutation(u,i),p=s;d!=null&&(p=Tn({inputs:{x:s},backend:n,attrs:{perm:d}}),u=_.getInnerMostAxes(u.length,i),c.push(p)),_.assertAxesAreInnerMostDims("prod",u,i);let h;if(n.shouldExecuteOnCPU([p])){let f=n.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:b}=a9(p.shape,p.dtype,f,u);h=n.makeTensorInfo(g,b,m)}else{let[f,m]=_.computeOutAndReduceShapes(p.shape,u),g=k.sizeFromShape(m),b=ge({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),y=Mh(s.dtype),v=yi(b,y,"prod",n);h=ge({inputs:{x:v},backend:n,attrs:{shape:f}}),c.push(b),c.push(v)}if(o){c.push(h);let f=_.expandShapeToKeepDim(h.shape,l);h=ge({inputs:{x:h},backend:n,attrs:{shape:f}})}return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var Xte={kernelName: $ c,backendName:"webgl",kernelFunc:Kte},y_=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=o9(r,s,a,o);return t.makeTensorInfo([i.length],o,i)},Yte={kernelName:Rl,backendName:"webgl",kernelFunc:y_},Zte="return 1.0 / x;",Jte=Xe({opSnippet:Zte}),Qte={kernelName:Rc,backendName:"webgl",kernelFunc:Jte},ene=qr+ `
2021-09-11 17:11:38 +02:00
return ( x < 0.0 ) ? 0.0 : x ;
2021-12-09 20:22:22 +01:00
` ,tne= `
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2021-12-09 20:22:22 +01:00
` ,nne=Xe({opSnippet:ene,packedOpSnippet:tne}),rne={kernelName:xo,backendName:"webgl",kernelFunc:nne},sne=qr+ `
2021-09-11 17:11:38 +02:00
return ( x < 0.0 ) ? 0.0 : min ( 6.0 , x ) ;
2021-12-09 20:22:22 +01:00
` ,ane= `
2021-09-11 17:11:38 +02:00
vec4 result = min ( x , vec4 ( 6. ) ) * vec4 ( greaterThanEqual ( x , vec4 ( 0.0 ) ) ) ;
bvec4 isNaN = isnan ( x ) ;
result . r = isNaN . r ? x . r : result . r ;
result . g = isNaN . g ? x . g : result . g ;
result . b = isNaN . b ? x . b : result . b ;
result . a = isNaN . a ? x . a : result . a ;
return result ;
2021-12-09 20:22:22 +01:00
` ,one=Xe({opSnippet:sne,packedOpSnippet:ane}),ine={kernelName:ko,backendName:"webgl",kernelFunc:one},cne=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
2021-12-06 12:34:50 +01:00
$ { l [ 0 ] / u [ 0 ] } ,
$ { l [ 1 ] / u [ 1 ] } ) ;
2021-09-11 17:11:38 +02:00
const vec2 inputShapeRC = vec2 ( $ { o } . 0 , $ { i } . 0 ) ;
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec2 sourceFracIndexRC = $ { d } ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2 ( max ( sourceFracIndexRC , vec2 ( 0.0 ) ) ) ;
ivec2 sourceCeilRC = ivec2 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float topLeft = getA ( b , sourceFloorRC . x , sourceFloorRC . y , d ) ;
float bottomLeft = getA ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ;
float topRight = getA ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ;
float bottomRight = getA ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec2 fracRC = sourceFracIndexRC - vec2 ( sourceFloorRC ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float top = topLeft + ( topRight - topLeft ) * fracRC . y ;
float bottom = bottomLeft + ( bottomRight - bottomLeft ) * fracRC . y ;
float newValue = top + ( bottom - top ) * fracRC . x ;
setOutput ( newValue ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},une=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
2021-12-06 12:34:50 +01:00
$ { l [ 0 ] / u [ 0 ] } ,
$ { l [ 1 ] / u [ 1 ] } ,
$ { l [ 1 ] / u [ 1 ] } ) ;
2021-09-11 17:11:38 +02:00
const vec3 inputShapeRC = vec3 ( $ { o } . 0 , $ { i } . 0 ,
$ { i } . 0 ) ;
float getAValue ( int b , int r , int c , int d ) {
return getChannel ( getA ( b , r , c , d ) , vec2 ( c , d ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
// Calculate values for next column in yRC.z.
ivec3 yRC = coords . yzz + ivec3 ( 0 , 0 , 1 ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec3 sourceFracIndexRC = $ { d } ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3 ( max ( sourceFracIndexRC , vec3 ( 0.0 ) ) ) ;
ivec3 sourceCeilRC = ivec3 (
min ( inputShapeRC - 1.0 , ceil ( sourceFracIndexRC ) ) ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
2021-12-06 12:34:50 +01:00
bool hasNextCol = d < $ { c - 1 } ;
2021-09-11 17:11:38 +02:00
bool hasNextRow = coords . z < $ { n - 1 } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4 (
getAValue ( b , sourceFloorRC . x , sourceFloorRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceFloorRC . x , sourceFloorRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceFloorRC . x , sourceFloorRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceFloorRC . x , sourceFloorRC . z , d + 1 ) : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 bottomLeft = vec4 (
getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceFloorRC . z , d + 1 ) : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 topRight = vec4 (
getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceFloorRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 bottomRight = vec4 (
getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceCeilRC . x , sourceCeilRC . z , d + 1 ) : 0.0 ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec3 fracRC = sourceFracIndexRC - vec3 ( sourceFloorRC ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 top = mix ( topLeft , topRight , fracRC . yyzz ) ;
vec4 bottom = mix ( bottomLeft , bottomRight , fracRC . yyzz ) ;
vec4 newValue = mix ( top , bottom , fracRC . x ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( newValue ) ;
}
2021-12-09 20:22:22 +01:00
` }};function lne(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,l]=i,u=Q().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new une(s.shape,c,l,a,o):new cne(s.shape,c,l,a,o);return n.runWebGLProgram(u,[s],"float32")}var dne={kernelName:wo,backendName:"webgl",kernelFunc:lne},pne=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],l=i[0]/c[0],u=i[1]/c[1],d=1/l,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float accumulator = 0.0 ;
2020-10-11 18:41:17 +02:00
2021-10-22 15:06:43 +02:00
const float heightScale = float ( $ { l } ) ;
2021-12-06 12:34:50 +01:00
const float widthScale = float ( $ { u } ) ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
const float invHeightScale = float ( $ { d } ) ;
const float invWidthScale = float ( $ { p } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
const int winHeight = int ( $ { h } ) ;
const int winWidth = int ( $ { f } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor ( float ( r ) * invHeightScale ) ;
int startDyR = int ( startRLerp - float ( winHeight / 2 ) ) ;
2021-05-27 22:04:17 +02:00
2021-09-11 17:11:38 +02:00
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( startCLerp - float ( winWidth / 2 ) ) ;
2021-05-27 22:04:17 +02:00
2021-09-11 17:11:38 +02:00
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if ( dyR < 0 || dyR >= $ { a } ) {
continue ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if ( dyC < 0 || dyC >= $ { o } ) {
continue ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float dxR = float ( dyR ) * heightScale ;
int topDxRIndex = int ( floor ( dxR ) ) ;
int bottomDxRIndex = int ( min ( ceil ( dxR ) , $ { r - 1 } . 0 ) ) ;
float dxRLerp = dxR - float ( topDxRIndex ) ;
float inverseDxRLerp = 1.0 - dxRLerp ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float dxC = float ( dyC ) * widthScale ;
int leftDxCIndex = int ( floor ( dxC ) ) ;
int rightDxCIndex = int ( min ( ceil ( dxC ) , $ { s - 1 } . 0 ) ) ;
float dxCLerp = dxC - float ( leftDxCIndex ) ;
float inverseDxCLerp = 1.0 - dxCLerp ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
if ( r == topDxRIndex && c == leftDxCIndex ) {
// topLeft
accumulator +=
getDy ( b , dyR , dyC , d ) * inverseDxRLerp * inverseDxCLerp ;
}
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
if ( r == topDxRIndex && c == rightDxCIndex ) {
// topRight
accumulator += getDy ( b , dyR , dyC , d ) * inverseDxRLerp * dxCLerp ;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if ( r == bottomDxRIndex && c == leftDxCIndex ) {
// bottomLeft
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * inverseDxCLerp ;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if ( r == bottomDxRIndex && c == rightDxCIndex ) {
// bottomRight
accumulator += getDy ( b , dyR , dyC , d ) * dxRLerp * dxCLerp ;
}
}
}
// End loop over dy
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput ( accumulator ) ;
2021-03-31 13:01:22 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function hne(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new pne(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var fne={kernelName:Sh,backendName:"webgl",kernelFunc:hne},mne=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2 (
2021-12-06 12:34:50 +01:00
$ { l [ 0 ] / u [ 0 ] } ,
$ { l [ 1 ] / u [ 1 ] } ) ;
2021-09-11 17:11:38 +02:00
const vec2 inputShapeRC = vec2 ( $ { o } . 0 , $ { i } . 0 ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
ivec2 yRC = coords . yz ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec2 sourceFracIndexRC = $ { p } ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2 (
min ( inputShapeRC - 1.0 , floor ( sourceFracIndexRC + $ { d } ) ) ) ;
float newValue = getA ( b , sourceNearestRC . x , sourceNearestRC . y , d ) ;
setOutput ( newValue ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }},gne=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode= `
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3 (
2021-12-06 12:34:50 +01:00
$ { l [ 0 ] / u [ 0 ] } ,
$ { l [ 1 ] / u [ 1 ] } ,
$ { l [ 1 ] / u [ 1 ] } ) ;
2021-09-11 17:11:38 +02:00
const vec3 inputShapeRC = vec3 ( $ { o } . 0 , $ { i } . 0 ,
$ { i } . 0 ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float getAValue ( int b , int r , int c , int d ) {
return getChannel ( getA ( b , r , c , d ) , vec2 ( c , d ) ) ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
// Calculate values for next column in yRC.z.
ivec3 yRC = coords . yzz + ivec3 ( 0 , 0 , 1 ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec3 sourceFracIndexRC = $ { p } ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3 (
min ( inputShapeRC - 1.0 , floor ( sourceFracIndexRC + $ { d } ) ) ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
2021-12-06 12:34:50 +01:00
bool hasNextCol = d < $ { c - 1 } ;
2021-09-11 17:11:38 +02:00
bool hasNextRow = coords . z < $ { n - 1 } ;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 newValue = vec4 (
getAValue ( b , sourceNearestRC . x , sourceNearestRC . y , d ) ,
hasNextCol ? getAValue ( b , sourceNearestRC . x , sourceNearestRC . y , d + 1 )
: 0.0 ,
hasNextRow ? getAValue ( b , sourceNearestRC . x , sourceNearestRC . z , d )
: 0.0 ,
( hasNextRow && hasNextCol ) ?
getAValue ( b , sourceNearestRC . x , sourceNearestRC . z , d + 1 ) : 0.0 ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput ( newValue ) ;
}
2021-12-09 20:22:22 +01:00
` }};function bne(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,l]=i,u=Q().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new gne(s.shape,c,l,a,o):new mne(s.shape,c,l,a,o);return n.runWebGLProgram(u,[s],s.dtype)}var yne={kernelName:Pl,backendName:"webgl",kernelFunc:bne},vne=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],l=i[0]/c[0],u=i[1]/c[1],d=1/l,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int b = coords [ 0 ] ;
int d = coords [ 3 ] ;
int r = coords [ 1 ] ;
int c = coords [ 2 ] ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float accumulator = 0.0 ;
2020-12-15 14:15:43 +01:00
2021-10-22 15:06:43 +02:00
const float heightScale = float ( $ { l } ) ;
2021-12-06 12:34:50 +01:00
const float widthScale = float ( $ { u } ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const float invHeightScale = float ( $ { d } ) ;
const float invWidthScale = float ( $ { p } ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const int winHeight = int ( $ { h } ) ;
const int winWidth = int ( $ { f } ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor ( float ( r ) * invHeightScale ) ;
int startDyR = int ( floor ( startRLerp - float ( winHeight / 2 ) ) ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float startCLerp = floor ( float ( c ) * invWidthScale ) ;
int startDyC = int ( floor ( startCLerp - float ( winWidth / 2 ) ) ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Loop over dy
for ( int dyROffset = 0 ; dyROffset < winHeight ; dyROffset ++ ) {
int dyR = dyROffset + startDyR ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if ( dyR < 0 || dyR >= $ { a } ) {
continue ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
for ( int dyCOffset = 0 ; dyCOffset < winWidth ; dyCOffset ++ ) {
int dyC = dyCOffset + startDyC ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if ( dyC < 0 || dyC >= $ { o } ) {
continue ;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracRow =
float ( $ { i [ 0 ] } ) *
2021-12-06 12:34:50 +01:00
( float ( dyR ) / float ( $ { c [ 0 ] } ) ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracCol =
float ( $ { i [ 1 ] } ) *
2021-12-06 12:34:50 +01:00
( float ( dyC ) / float ( $ { c [ 1 ] } ) ) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int sourceNearestRow = int ( min (
float ( int ( $ { r } ) - 1 ) ,
$ { n } ? float ( round ( sourceFracRow ) ) :
float ( floor ( sourceFracRow ) ) ) ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
int sourceNearestCol = int ( min (
float ( int ( $ { s } ) - 1 ) ,
$ { n } ? float ( round ( sourceFracCol ) ) :
float ( floor ( sourceFracCol ) ) ) ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if ( r == sourceNearestRow && c == sourceNearestCol ) {
accumulator += getDy ( b , dyR , dyC , d ) ;
}
}
}
// End loop over dy
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
setOutput ( accumulator ) ;
}
2021-12-09 20:22:22 +01:00
` }};function xne(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new vne(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var wne={kernelName:Ih,backendName:"webgl",kernelFunc:xne},kne=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error( ` WebGL backend : Reverse of rank - $ { n } tensor is not yet supported ` );if(this.outputShape=e,n===1){this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
int coord = getOutputCoords ( ) ;
setOutput ( getX ( $ { e [ 0 ] } - coord - 1 ) ) ;
}
2021-12-09 20:22:22 +01:00
` ;return}let r=o=>t.indexOf(o)!==-1&&e[o]!==1? ` $ { e [ o ] } - coords [ $ { o } ] - 1 ` : ` coords [ $ { o } ] ` ,s=e.map((o,i)=>r(i)).join(","),a=mt(n);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { a } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { s } ) ) ;
}
2021-12-09 20:22:22 +01:00
` }},Ine=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error( ` WebGL backend : Reverse of rank - $ { n } tensor is not yet supported ` );this.outputShape=e;let r=Sn("rc",n),s= ` $ { r [ n - 1 ] } + 1 < $ { this . outputShape [ n - 1 ] } ` ,a= ` $ { r [ n - 2 ] } + 1 < $ { this . outputShape [ n - 2 ] } ` ,o=mt(n);n===1?this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
int rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result . r = getChannel ( getX ( $ { e [ 0 ] } - rc - 1 ) ,
$ { e [ 0 ] } - rc - 1 ) ;
if ( $ { s } ) {
result . g = getChannel ( getX ( $ { e [ 0 ] } - ( rc + 1 ) - 1 ) ,
$ { e [ 0 ] } - ( rc + 1 ) - 1 ) ;
}
setOutput ( result ) ;
}
` :this.userCode= `
void main ( ) {
$ { o } rc = getOutputCoords ( ) ;
vec4 result = vec4 ( 0. ) ;
result . r = $ { i ( r . slice ( ) ) } ;
if ( $ { s } ) {
2021-12-06 12:34:50 +01:00
result . g = $ { c ( r . slice ( ) ) } ;
2021-09-11 17:11:38 +02:00
}
if ( $ { a } ) {
2021-10-22 15:06:43 +02:00
result . b = $ { l ( r . slice ( ) ) } ;
2021-09-11 17:11:38 +02:00
if ( $ { s } ) {
2021-12-06 12:34:50 +01:00
result . a = $ { u ( r . slice ( ) ) } ;
2021-09-11 17:11:38 +02:00
}
}
setOutput ( result ) ;
}
2021-12-09 20:22:22 +01:00
` ;function i(h){return d(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function l(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function u(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let f=e.map((b,y)=>p(y,h)),m=f.join(","),g=f.slice(-2).join(",");return ` getChannel ( getX ( $ { m } ) , vec2 ( $ { g } ) ) ` }function p(h,f){return t.indexOf(h)!==-1&&e[h]!==1? ` $ { e [ h ] } - $ { f [ h ] } - 1 ` : ` $ { f [ h ] } ` }}};function Sne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=s.shape.length,i=k.parseAxisParam(a,s.shape);if(o===0)return sr({inputs:{x:s},backend:n});let c=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ine(s.shape,i):new kne(s.shape,i);return n.runWebGLProgram(c,[s],s.dtype)}var Tne={kernelName:Io,backendName:"webgl",kernelFunc:Sne},Cne=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],r=e[2];this.outputShape=e;let s="";typeof t=="number"?s= ` float outputValue = $ { t . toFixed ( 2 ) } ; ` :s= `
2021-09-11 17:11:38 +02:00
vec3 fill = vec3 ( $ { t . join ( "," ) } ) ;
float outputValue = fill [ coords [ 3 ] ] ; ` ,this.userCode= `
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
int x = coords [ 2 ] ;
int y = coords [ 1 ] ;
float coordXFloat = ( float ( x ) - params [ 0 ] ) * params [ 3 ] -
( float ( y ) - params [ 1 ] ) * params [ 2 ] ;
float coordYFloat = ( float ( x ) - params [ 0 ] ) * params [ 2 ] +
( float ( y ) - params [ 1 ] ) * params [ 3 ] ;
int coordX = int ( round ( coordXFloat + params [ 0 ] ) ) ;
int coordY = int ( round ( coordYFloat + params [ 1 ] ) ) ;
$ { s }
if ( coordX >= 0 && coordX < $ { r } && coordY >= 0 && coordY < $ { n } ) {
outputValue = getImage ( coords [ 0 ] , coordY , coordX , coords [ 3 ] ) ;
}
setOutput ( outputValue ) ;
}
2021-12-09 20:22:22 +01:00
` }},Nne={kernelName:Zc,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,c=new Cne(r.shape,a),[l,u]=_.getImageCenter(o,r.shape[1],r.shape[2]),d=[[l,u,Math.sin(s),Math.cos(s)]];return i.runWebGLProgram(c,[r],r.dtype,d)}},_ne= `
2021-09-11 17:11:38 +02:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor ( x ) ;
if ( ( x - base ) < 0.5 ) {
return floor ( x ) ;
} else if ( ( x - base ) > 0.5 ) {
return ceil ( x ) ;
} else {
if ( mod ( base , 2.0 ) == 0.0 ) {
return base ;
} else {
return base + 1.0 ;
2021-04-01 19:39:54 +02:00
}
}
2021-12-09 20:22:22 +01:00
` ,Ene=Xe({opSnippet:_ne}),Ane={kernelName:So,backendName:"webgl",kernelFunc:Ene},Dne="return inversesqrt(x);",Fne=Xe({opSnippet:Dne,cpuKernelImpl:i9}), $ ne={kernelName:To,backendName:"webgl",kernelFunc:Fne},v_=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=mt(s.length),c=mt(a.length),l="";n===1?l="i":n===2&&(l="i, j");let u= ` getIndices ( $ { l } ) ` ,d="";r===1?d="i":r===2&&(d="i, coords[1]");let p= ` getUpdates ( $ { d } ) ` ,h=t>1?"strides[j]":"strides";this.userCode= `
2021-09-11 17:11:38 +02:00
$ { i } strides = $ { i } ( $ { s } ) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
2021-12-06 12:34:50 +01:00
$ { c } coords = getOutputCoords ( ) ;
2021-09-11 17:11:38 +02:00
float sum = 0.0 ;
bool found = false ;
for ( int i = 0 ; i < $ { e } ; i ++ ) {
int flattenedIndex = 0 ;
for ( int j = 0 ; j < $ { t } ; j ++ ) {
2021-12-06 12:34:50 +01:00
int index = round ( $ { u } ) ;
2021-09-11 17:11:38 +02:00
flattenedIndex += index * $ { h } ;
}
if ( flattenedIndex == coords [ 0 ] ) {
sum += $ { p } ;
found = true ;
}
}
setOutput ( mix ( getDefaultValue ( ) , sum , float ( found ) ) ) ;
}
2021-12-09 20:22:22 +01:00
` }};function Rne(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=_.calculateShapes(a,s,o),p=[d/l,l];if(d===0)return n.makeTensorInfo(o,s.dtype);let h=ge({inputs:{x:s},backend:n,attrs:{shape:[c,i]}}),f=ge({inputs:{x:a},backend:n,attrs:{shape:[c,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new v_(c,i,h.shape.length,f.shape.length,u,p),b=n.runWebGLProgram(g,[f,h,m],f.dtype),y=ge({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(m),y}var Pne={kernelName:Oc,backendName:"webgl",kernelFunc:Rne},One=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let r,s;if(n>4)throw Error( ` Where for rank $ { n } is not yet supported ` );if(n===1)s="resRC",r="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],c=[];for(let l=0;l<t.length;l++)c.push( ` $ { o [ l ] } ` ),l<e&&i.push( ` $ { o [ l ] } ` );r=i.join(),s=c.join()}let a=mt(n);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { a } resRC = getOutputCoords ( ) ;
float cVal = getC ( $ { r } ) ;
if ( cVal >= 1.0 ) {
setOutput ( getA ( $ { s } ) ) ;
} else {
setOutput ( getB ( $ { s } ) ) ;
}
2021-03-26 15:26:02 +01:00
}
2021-12-09 20:22:22 +01:00
` }};function Mne(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new One(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(o,[r,s,a],Sr(s.dtype,a.dtype))}var Lne={kernelName:Mc,backendName:"webgl",kernelFunc:Mne},Bne= `
2021-09-11 17:11:38 +02:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2021-12-09 20:22:22 +01:00
float scaleAlpha = $ { _ . SELU _SCALEALPHA } ;
float scale = $ { _ . SELU _SCALE } ;
2021-09-11 17:11:38 +02:00
return ( x >= 0.0 ) ? scale * x : scaleAlpha * ( exp ( x ) - 1.0 ) ;
2021-12-09 20:22:22 +01:00
` ,zne=Xe({opSnippet:Bne}),Wne={kernelName:Lc,backendName:"webgl",kernelFunc:zne},x_="return 1.0 / (1.0 + exp(-1.0 * x));",Vne=Xe({opSnippet:x_,packedOpSnippet:x_,cpuKernelImpl:c9}),Une={kernelName:No,backendName:"webgl",kernelFunc:Vne},Gne= `
2021-09-11 17:11:38 +02:00
if ( isnan ( x ) ) { return 0.0 ; }
return sign ( x ) ;
2021-12-09 20:22:22 +01:00
` ,Hne=Xe({opSnippet:Gne}),jne={kernelName:Wc,backendName:"webgl",kernelFunc:Hne},qne= $ N+ `
2021-09-11 17:11:38 +02:00
return sin ( x ) ;
2021-12-09 20:22:22 +01:00
` ,Kne=Xe({opSnippet:qne}),Xne={kernelName:Co,backendName:"webgl",kernelFunc:Kne},Yne= `
2021-09-11 17:11:38 +02:00
float e2x = exp ( x ) ;
return ( e2x - 1.0 / e2x ) / 2.0 ;
2021-12-09 20:22:22 +01:00
` ,Zne=Xe({opSnippet:Yne}),Jne={kernelName:zc,backendName:"webgl",kernelFunc:Zne},Qne= `
2021-09-11 17:11:38 +02:00
float epsilon = 1.1920928955078125 e - 7 ;
float threshold = log ( epsilon ) + 2.0 ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
bool too _large = x > - threshold ;
bool too _small = x < threshold ;
float result ;
float exp _x = exp ( x ) ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
if ( too _large ) {
result = x ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
else if ( too _small ) {
result = exp _x ;
}
else {
result = log ( exp _x + 1.0 ) ;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return result ;
2021-12-09 20:22:22 +01:00
` ,ere=Xe({opSnippet:Qne}),tre={kernelName:Vc,backendName:"webgl",kernelFunc:ere},nre=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;k.assert(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((b,y)=>b*y),c=[[0,0]];c.push(...o);for(let b=1+a.length;b<s.shape.length;++b)c.push([0,0]);let l=[],u=b_({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),d=_.getReshaped(u.shape,a,i,!1),p=_.getPermuted(d.length,a.length,!1),h=_.getReshapedPermuted(u.shape,a,i,!1),f=ge({inputs:{x:u},backend:n,attrs:{shape:d}}),m=Tn({inputs:{x:f},backend:n,attrs:{perm:p}}),g=ge({inputs:{x:m},backend:n,attrs:{shape:h}});return l.push(u),l.push(f),l.push(m),l.forEach(b=>n.disposeIntermediateTensorInfo(b)),g},rre={kernelName:Uc,backendName:"webgl",kernelFunc:nre};function sre(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error( ` Dense shape must be a vector , saw :
2021-09-11 17:11:38 +02:00
$ { a . shape } ` );if(r.shape.length!==2)throw new Error( ` Indices must be a matrix , saw :
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Values must be a vector , saw :
$ { s . shape } ` );if(o.shape.length!==0)throw new Error( ` Default value must be a scalar , saw :
2021-12-09 20:22:22 +01:00
$ { o . shape } ` );let i=n.readSync(r.dataId),c=n.readSync(s.dataId),l=n.readSync(a.dataId),u=n.readSync(o.dataId)[0],[d,p,h,f,m]=l9(i,r.shape,r.dtype,c,s.dtype,l,u);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var are={kernelName:Ol,backendName:"webgl",kernelFunc:sre};function ore(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error( ` Input indices should be a matrix but received shape $ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape $ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Target shape should be a vector but received shape $ { a . shape } ` );let o=Array.from(n.readSync(s.dataId)),i=n.readSync(r.dataId),c=Array.from(n.readSync(a.dataId)),[l,u,d]=d9(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(u,r.dtype,l),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var ire={kernelName:Hc,backendName:"webgl",kernelFunc:ore};function cre(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
2021-12-09 20:22:22 +01:00
$ { a . shape } ` );let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[l,u]=xN(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(u,r.dtype,l)}var ure={kernelName:Ml,backendName:"webgl",kernelFunc:cre};function lre(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error( ` Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Segment ids should be a vector but received shape
2021-12-09 20:22:22 +01:00
$ { a . shape } ` );let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[l,u]=xN(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(u,r.dtype,l)}var dre={kernelName:Ll,backendName:"webgl",kernelFunc:lre};function pre(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:l,strides:u,outputSize:d}=_.calculateShapes(a,s,i),p=!1,h=new v_(l,c,s.shape.length,a.shape.length,u,[d,1],p),f=n.runWebGLProgram(h,[a,s,o],a.dtype),m=ge({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var hre={kernelName:Th,backendName:"webgl",kernelFunc:pre};function fre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=k.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=s.shape.length,u=new Array(l).fill(0),d=s.shape.slice();return c.map(p=>{let h=[...d];h[i]=p;let f=Ou({inputs:{x:s},backend:n,attrs:{begin:u,size:h}});return u[i]+=p,f})}var mre={kernelName:Gc,backendName:"webgl",kernelFunc:fre},w_="return sqrt(x);",gre=Xe({opSnippet:w_,packedOpSnippet:w_,cpuKernelImpl:p9}),bre={kernelName:_o,backendName:"webgl",kernelFunc:gre},yre="return x * x;",vre=Xe({opSnippet:yre}),xre={kernelName:Bl,backendName:"webgl",kernelFunc:vre},k_="return (a - b) * (a - b);",wre=cn({opSnippet:k_,packedOpSnippet:k_}),kre={kernelName:Do,backendName:"webgl",kernelFunc:wre};function Ire({inputs:e,attrs:t,backend:n}){let{x:r}=e,s=qr+ `
2021-09-11 17:11:38 +02:00
return x > 0.0 ? 1.0 : float ( $ { t . alpha } ) ;
2021-12-09 20:22:22 +01:00
` ,a=new Sa(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}var Sre={kernelName:ea,backendName:"webgl",kernelFunc:Ire},Tre=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let r=n.length,s=mt(n.length),a=mt(n.length),o="";if(r===1)o="coords * strides + begin";else{let i=0;o=n.map((c,l)=>(i++,n.length===1? ` coords * strides [ $ { l } ] + begin [ $ { l } ] ` : ` coords [ $ { i - 1 } ] * strides [ $ { l } ] + begin [ $ { l } ] ` )).join(",")}this.userCode= `
2021-09-11 17:11:38 +02:00
$ { s } begin = $ { s } ( $ { e } ) ;
$ { s } strides = $ { s } ( $ { t } ) ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { a } coords = getOutputCoords ( ) ;
setOutput ( getX ( $ { o } ) ) ;
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
` }};function Cre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=Gt.sliceInfo(s.shape,a,o,i,c,l,u,d,p),w;if(m)w=ge({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||b){k.assert(s.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { s . shape . length } ` );let C=Gt.computeOutShape(y,v,x),D=Ou({inputs:{x:s},backend:n,attrs:{begin:y,size:C}});w=ge({inputs:{x:D},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(D)}else if(n.shouldExecuteOnCPU([s])){let D=n.readSync(s.dataId),F=Be(s.shape,s.dtype,D),O=h9(h,F,x,y);w=n.makeTensorInfo(f,s.dtype,O.values)}else{let D=new Tre(y,x,h);w=n.runWebGLProgram(D,[s],s.dtype)}let T=ge({inputs:{x:w},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(w),T}var Nre={kernelName:jc,backendName:"webgl",kernelFunc:Cre};function _re(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:l}=r,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=f9(p,h,s,a,o,i,c,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var Ere={kernelName:Ch,backendName:"webgl",kernelFunc:_re};function Are(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error( ` Input must be a vector , got shape : $ { a . shape } ` );if(o.shape.length!==0)throw new Error( ` Delimiter must be a scalar , got shape : $ { o . shape } ` );let i=n.readSync(a.dataId),c=n.readSync(o.dataId)[0],[l,u,d]=m9(i,c,s),p=u.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var Dre={kernelName:Nh,backendName:"webgl",kernelFunc:Are};function Fre(e){let{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");let o=n.readSync(a.dataId),i=g9(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var $ re={kernelName:_h,backendName:"webgl",kernelFunc:Fre},Rre="return tan(x);",Pre=Xe({opSnippet:Rre}),Ore={kernelName: $ o,backendName:"webgl",kernelFunc:Pre},Mre= `
2021-09-11 17:11:38 +02:00
float e2x = exp ( - 2.0 * abs ( x ) ) ;
return sign ( x ) * ( 1.0 - e2x ) / ( 1.0 + e2x ) ;
2021-12-09 20:22:22 +01:00
` ,Lre=Xe({opSnippet:Mre}),Bre={kernelName:Ro,backendName:"webgl",kernelFunc:Lre},zre=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[a]*t[a];this.outputShape=n,this.rank=n.length;let r=mt(this.rank),s=Wre(e);this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
$ { r } resRC = getOutputCoords ( ) ;
setOutput ( getA ( $ { s } ) ) ;
}
2021-12-09 20:22:22 +01:00
` }};function Wre(e){let t=e.length;if(t>5)throw Error( ` Tile for rank $ { t } is not yet supported ` );if(t===1)return ` imod ( resRC , $ { e [ 0 ] } ) ` ;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let s=0;s<e.length;s++)r.push( ` imod ( $ { n [ s ] } , $ { e [ s ] } ) ` );return r.join()}function I_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if(s.dtype==="string"||s.shape.length>5){let c=n.readSync(s.dataId),l=s.dtype==="string"?c.map(p=>k.decodeString(p)):c,u=Be(s.shape,s.dtype,l),d=y9(u,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new zre(s.shape,a);return n.runWebGLProgram(o,[s],s.dtype)}var Vre={kernelName:Qs,backendName:"webgl",kernelFunc:I_},Ure=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int elemIdx = coords [ 1 ] ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
bool isFirstInPair = imod ( elemIdx , 2 * inc ) < inc ;
int i = isFirstInPair ? elemIdx : elemIdx - inc ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i0 = firstPass == 1 ? i : int ( getIndices ( batch , i ) ) ;
int i1 = firstPass == 1 ? i + inc : int ( getIndices ( batch , i + inc ) ) ;
float x0 = i0 < n ? getX ( batch , i0 ) : negativeInf ;
float x1 = i1 < n ? getX ( batch , i1 ) : negativeInf ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod ( elemIdx , 2 * dir ) >= dir ;
bool isGreater = x0 > x1 || ( x0 == x1 && i1 > i0 ) ;
if ( reverse == isGreater ) { // Elements in opposite order of direction
int iTemp = i0 ;
i0 = i1 ;
i1 = iTemp ;
}
if ( isFirstInPair ) {
setOutput ( float ( i0 ) ) ;
} else {
setOutput ( float ( i1 ) ) ;
}
}
2021-12-09 20:22:22 +01:00
` }},Gre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode= `
2021-09-11 17:11:38 +02:00
void main ( ) {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int elemIdx = coords [ 1 ] ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i = elemIdx < k ? elemIdx : ( elemIdx * 2 - imod ( elemIdx , k ) ) ;
int i0 = firstPass == 1 ? i : int ( getIndices ( batch , i ) ) ;
int i1 = firstPass == 1 ? i + k : int ( getIndices ( batch , i + k ) ) ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float x0 = getX ( batch , i0 ) ;
float x1 = i1 < n ? getX ( batch , i1 ) : x0 ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput ( x0 >= x1 ? float ( i0 ) : float ( i1 ) ) ;
}
2021-12-09 20:22:22 +01:00
` }};function vi(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function S_(e){let t=1;for(;t<e;)t*=2;return t}function Hre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r,i=Q().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),c=Q().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=s.shape,u=l[l.length-1];if(n.shouldExecuteOnCPU([s])||u<i||a>c){let O=n.readSync(s.dataId),[ $ ,R]=v9(O,l,s.dtype,a,o);return[n.makeTensorInfo( $ .shape, $ .dtype, $ .values),n.makeTensorInfo(R.shape,R.dtype,R.values)]}if(a===0)return l[l.length-1]=0,[n.makeTensorInfo(l,s.dtype,[]),n.makeTensorInfo(l,"int32",[])];if(u===1)return[s,Xd({attrs:{shape:l,dtype:"int32",value:0},backend:n})];let d=n.texData.get(s.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(s):s,m=k.sizeFromShape(l)/u,g=ge({inputs:{x:h},attrs:{shape:[m,u]},backend:n});p&&vi(n,h);let b=S_(a),y=S_(u),v=null,x=()=>v===null?[g,g]:[g,v],w=(O, $ ,R)=>{let N=x(),L=new Ure(R),j=[[u],[v===null?1:0],[Number.NEGATIVE_INFINITY],[O],[ $ ]],K=v;v=n.runWebGLProgram(L,N,"int32",j),vi(n,K)};for(let O=1;O<b;O*=2){let $ =O*2;for(let R=O;R>=1;R/=2)w( $ ,R,[m,y])}for(let O=y;O>b;O/=2){let $ =x(),R=new Gre([m,O/2]),L=[[u],[v===null?1:0],[b]],G=v;v=n.runWebGLProgram(R, $ ,"int32",L),vi(n,G);let j=b/2,K=j*2;for(let q=j;q>=1;q/=2)w(K,q,v.shape)}let T=v;v=Ou({inputs:{x:v},backend:n,attrs:{begin:0,size:[m,a]}}),vi(n,T);let C=u_({inputs:{x:g,indices:v},backend:n,attrs:{axis:1,batchDims:1}});vi(n,g);let D=l.slice(0,-1);D.push(a),T=v,v=ge({inputs:{x:v},attrs:{shape:D},backend:n}),vi(n,T);let F=C;return C=ge({inputs:{x:C},attrs:{shape:D},backend:n}),vi(n,F),[C,v]}var jre={kernelName:qc,backendName:"webgl",kernelFunc:Hre},qre=class{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(r){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode= `
2021-09-11 17:11:38 +02:00
float mapCoord ( float outCoord , float len ) {
float inCoord = outCoord ;
if ( $ { i } == 2 ) {
if ( inCoord < 0.0 ) {
if ( len <= 1.0 ) {
inCoord = 0.0 ;
} else {
float sz2 = 2.0 * len ;
if ( inCoord < sz2 ) {
inCoord = sz2 * float ( int ( float ( - inCoord / sz2 ) ) ) +
inCoord ;
}
inCoord = inCoord < - len ? inCoord + sz2 : - inCoord - 1.0 ;
}
} else if ( inCoord > len - 1.0 ) {
if ( len <= 1.0 ) {
inCoord = 0.0 ;
} else {
float sz2 = 2.0 * len ;
inCoord -= sz2 * float ( int ( float ( inCoord / sz2 ) ) ) ;
if ( inCoord >= len ) {
inCoord = sz2 - inCoord - 1.0 ;
}
}
}
return clamp ( inCoord , 0.0 , len - 1.0 ) ;
} else if ( $ { i } == 3 ) {
if ( inCoord < 0.0 ) {
if ( len <= 1.0 ) {
inCoord = 0.0 ;
} else {
float sz = len - 1.0 ;
inCoord += len * ( float ( int ( float ( - inCoord / sz ) ) ) + 1.0 ) ;
}
} else if ( inCoord > len - 1.0 ) {
if ( len <= 1.0 ) {
inCoord = 0.0 ;
} else {
float sz = len - 1.0 ;
inCoord -= len * float ( int ( float ( inCoord / sz ) ) ) ;
}
}
return clamp ( inCoord , 0.0 , len - 1.0 ) ;
} else if ( $ { i } == 4 ) {
return clamp ( outCoord , 0.0 , len - 1.0 ) ;
} else {
return outCoord ;
}
}
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float readWithFillValue ( int batch , int coordY , int coordX ,
int channel ) {
float outputValue ;
if ( 0 <= coordY && coordY < $ { e } && 0 <= coordX && coordX < $ { t } ) {
outputValue = getImage ( batch , coordY , coordX , channel ) ;
} else {
outputValue = float ( $ { s } ) ;
}
return outputValue ;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec4 coords = getOutputCoords ( ) ;
float outputValue ;
int batch = coords [ 0 ] ;
int x = coords [ 2 ] ;
int y = coords [ 1 ] ;
int channel = coords [ 3 ] ;
float xf = float ( x ) ;
float yf = float ( y ) ;
float a1 = getTransforms ( batch , 0 ) ;
float a2 = getTransforms ( batch , 1 ) ;
float a3 = getTransforms ( batch , 2 ) ;
float b1 = getTransforms ( batch , 3 ) ;
float b2 = getTransforms ( batch , 4 ) ;
float b3 = getTransforms ( batch , 5 ) ;
float c1 = getTransforms ( batch , 6 ) ;
float c2 = getTransforms ( batch , 7 ) ;
float projection = c1 * xf + c2 * yf + 1.0 ;
if ( projection == 0.0 ) {
outputValue = float ( $ { s } ) ;
} else {
float inX = ( a1 * xf + a2 * yf + a3 ) / projection ;
float inY = ( b1 * xf + b2 * yf + b3 ) / projection ;
float mapX = mapCoord ( inX , float ( $ { t } ) ) ;
float mapY = mapCoord ( inY , float ( $ { e } ) ) ;
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
if ( $ { o } == 1 ) {
int coordY = int ( round ( mapY ) ) ;
int coordX = int ( round ( mapX ) ) ;
outputValue = readWithFillValue ( batch , coordY , coordX ,
channel ) ;
} else {
float yFloor = floor ( mapY ) ;
float xFloor = floor ( mapX ) ;
float yCeil = yFloor + 1.0 ;
float xCeil = xFloor + 1.0 ;
float valueYFloor = ( xCeil - mapX ) *
readWithFillValue ( batch , int ( yFloor ) , int ( xFloor ) , channel ) +
( mapX - xFloor ) *
readWithFillValue ( batch , int ( yFloor ) , int ( xCeil ) , channel ) ;
float valueYCeil = ( xCeil - mapX ) *
readWithFillValue ( batch , int ( yCeil ) , int ( xFloor ) , channel ) +
( mapX - xFloor ) *
readWithFillValue ( batch , int ( yCeil ) , int ( xCeil ) , channel ) ;
outputValue = ( yCeil - mapY ) * valueYFloor +
( mapY - yFloor ) * valueYCeil ;
}
}
setOutput ( outputValue ) ;
}
2021-12-09 20:22:22 +01:00
` }};function Kre(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:c,outputShape:l}=r,[u,d,p,h]=s.shape,[f,m]=l!=null?l:[d,p],g=[u,f,m,h],b=new qre(d,p,o,i,c,g);return n.runWebGLProgram(b,[s,a],"float32")}var Xre={kernelName:Kc,backendName:"webgl",kernelFunc:Kre};function Yre(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Eu(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=r.readSync(a.dataId),{outputValues:i,outputShape:c,indices:l}=x9(o,s,a.shape,a.dtype);return[r.makeTensorInfo(c,a.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}var Zre={kernelName:Eh,backendName:"webgl",kernelFunc:Yre};function Jre(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s,i=o.shape.length,c=s.shape[a],l=new Array(i-1),u=0;for(let m=0;m<i;m++)m!==a&&(l[u++]=o.shape[m]);let d=[],p=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(c);for(let m=0;m<f.length;m++){p[a]=m;let g=Ou({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),b=ge({inputs:{x:g},backend:n,attrs:{shape:l}});f[m]=b,d.push(g)}return d.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var Qre={kernelName:Xc,backendName:"webgl",kernelFunc:Jre},ese=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,o=a*Math.ceil(s/n);this.outputShape=[r,o];let i="0.0",c="sumValue",l=Math.floor(n/4)*4,u=n%4,d= `
2021-09-11 17:11:38 +02:00
sumValue += dot ( values , segFilter ) ;
` ,p="";s%n>0&&(p= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
return initializationValue ;
}
` );let h="";s%n>0&&(h= `
if ( inIdx < 0 || inIdx >= $ { s } ) {
return - 1.0 ;
}
` ),this.userCode= `
const float initializationValue = $ { i } ;
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float getValue ( int batch , int inIdx ) {
$ { p }
return getX ( batch , inIdx ) ;
2021-03-26 15:26:02 +01:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float getSegmentIdAtIndex ( int inIdx ) {
$ { h }
return getSegmentIds ( inIdx ) ;
2021-03-31 13:01:22 +02:00
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main ( ) {
ivec2 coords = getOutputCoords ( ) ;
int batch = coords [ 0 ] ;
int outIdx = coords [ 1 ] ;
int inOffset = int ( floor ( float ( outIdx ) / float (
$ { a } ) ) * float ( $ { n } ) ) ;
int currentSeg = int ( mod ( float ( outIdx ) , float ( $ { a } ) ) ) ;
2021-03-09 23:32:33 +01:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0 ;
2021-03-09 23:32:33 +01:00
2021-10-22 15:06:43 +02:00
for ( int i = 0 ; i < $ { l } ; i += 4 ) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i ;
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
getValue ( batch , inIdx + 3 )
) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 2 ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 3 ) ) == currentSeg ? 1 : 0
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { d }
2020-12-15 14:15:43 +01:00
}
2020-10-29 05:16:50 +01:00
2021-10-22 15:06:43 +02:00
int inIdx = inOffset + $ { l } ;
2021-12-06 12:34:50 +01:00
if ( $ { u === 1 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
initializationValue ,
initializationValue ,
initializationValue
) ;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int inIdxSeg = int ( getSegmentIdAtIndex ( inIdx ) ) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
0 ,
0 ,
0
) ;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
$ { d }
2021-12-06 12:34:50 +01:00
} else if ( $ { u === 2 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
initializationValue ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
0 ,
0
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
$ { d }
2021-12-06 12:34:50 +01:00
} else if ( $ { u === 3 } ) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4 (
getValue ( batch , inIdx ) ,
getValue ( batch , inIdx + 1 ) ,
getValue ( batch , inIdx + 2 ) ,
initializationValue
) ;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4 (
int ( getSegmentIdAtIndex ( inIdx ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 1 ) ) == currentSeg ? 1 : 0 ,
int ( getSegmentIdAtIndex ( inIdx + 2 ) ) == currentSeg ? 1 : 0 ,
0
) ;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
$ { d }
}
2021-12-06 12:34:50 +01:00
setOutput ( $ { c } ) ;
2021-12-01 21:37:52 +01:00
}
2021-12-09 20:22:22 +01:00
` }};function tse(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r,i=s.shape.length,c=[],l=0,u=_.getAxesPermutation([l],i),d=s;u!=null&&(d=Tn({inputs:{x:s},backend:n,attrs:{perm:u}}),c.push(d),l=_.getInnerMostAxes(1,i)[0]);let p=_.segment_util.computeOutShape(d.shape,l,o),h=k.sizeFromShape([d.shape[l]]),f=ge({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});c.push(f);let m=Mh(s.dtype),g=(x,w,T,C,D)=>{let F=x.shape[0],O=x.shape[1], $ =_.segment_util.segOpComputeOptimalWindowSize(O,D),R={windowSize: $ ,inSize:O,batchSize:F,numSegments:D},N=new ese(R,w),L=n.compileAndRun(N,[x,T],C);if(c.push(L),L.shape[1]===D)return L;let G=y_({backend:n,attrs:{start:0,stop:D,step:1,dtype:"float32"}}),j=I_({inputs:{x:G},backend:n,attrs:{reps:[O/ $ ]}});return c.push(G),c.push(j),g(L,w,j,C,D)},b=g(f,"unsortedSegmentSum",a,m,o),y=ge({inputs:{x:b},backend:n,attrs:{shape:p}}),v=y;if(u!=null){c.push(y);let x=_.getUndoAxesPermutation(u);v=Tn({inputs:{x:v},backend:n,attrs:{perm:x}})}return c.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var nse={kernelName:zl,backendName:"webgl",kernelFunc:tse},rse=[Dee,Ree,mY,bY,xY,IY,TY,_Y,AY,FY,OY,LY,WY,GY,ZY,qY,eZ,sZ,nZ,cZ,lZ,pZ,gZ,IZ,TZ,NZ, $ Z,PZ,BZ,VZ,Y9,qZ,rJ,aJ,ZZ,uJ,dJ,iJ,fJ,bJ,xJ,kJ,SJ,NJ, $ J,PJ,EJ,LJ,WJ,UJ,qJ,ZJ,tQ,sQ,aQ,oQ,cQ,lQ,pQ,fQ,gQ,xQ,IQ,CQ,_Q,DQ,RQ,LQ,VQ,X9,GQ,HZ,qQ,YQ,QQ,J9,ree,iee,uee,gee,hee,xee,Iee,Nee,Oee,Gee,Vee,Kee,Yee,Jee,zee,ete,nte,ote,lte,fte,kte,rY,Ste,Nte,Ate, $ te,EZ,Ote,Lte,zte,Ute,qte,eY,Xte,Yte,AZ,yte,Qte,ine,rne,aY,dne,fne,yne,wne,Tne,Nne,Ane, $ ne,Pne,Lne,Wne,Une,jne,Xne,Jne,wZ,xte,tre,rre,are,ire,ure,dre,hre,mre,bre,xre,kre,Sre,Nre,Ere,Dre, $ re,vte,pY,Ore,Bre,Vre,jre,Xre,hY,Zre,Qre,nse,Mte];for(let e of rse)Vl(e);var $ t;(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"})( $ t||( $ t={}));var Yd;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(Yd||(Yd={}));var T_;function sse(e){T_=e.wasm.cwrap(Oo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function ase(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=r,p=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let D=n.dataIdMap.get(o.dataId);if(D.shape.length!==1)throw new Error( ` _FusedMatMul only supports rank - 1 bias but got rank $ { D . shape . length } . ` );f=D.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=Yd[u];if(g==null)throw new Error( ` $ { u } activation not yet supported for FusedConv2D in the wasm backend . ` );let b=c?s.shape[2]:s.shape[1],y=l?a.shape[1]:a.shape[2],v=su.assertAndGetBroadcastShape(s.shape.slice(0,-2),a.shape.slice(0,-2)),x=n.makeOutput([...v,b,y],s.dtype),w=n.dataIdMap.get(x.dataId).id,T=new Uint8Array(new Int32Array(s.shape).buffer),C=new Uint8Array(new Int32Array(a.shape).buffer);return T_(p,T,s.shape.length,h,C,a.shape.length,c,l,g,f,m,d||0,w),x}var ose={kernelName:Oo,backendName:"wasm",setupFunc:sse,kernelFunc:ase};function un(e,t){let n;function r(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function s(a){let{backend:o,inputs:{x:i}}=a,c=o.dataIdMap.get(i.dataId).id,l=o.makeOutput(i.shape,t||i.dtype),u=o.dataIdMap.get(l.dataId).id;return k.sizeFromShape(l.shape)===0||n(c, $ t[i.dtype],u),l}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var ise=un(Yi);function Cn(e,t,n){let r;function s(o){r=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:c}=o,{a:l,b:u}=c,d=i.dataIdMap.get(l.dataId).id,p=i.dataIdMap.get(u.dataId).id,h=n!=null?n:l.dtype,f=_.assertAndGetBroadcastShape(l.shape,u.shape),m=i.makeOutput(f,h);if(k.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(l.shape).buff
$ { r . shape } ` );if(s.shape.length!==1)throw new Error( ` Input shape should be a vector but received shape
2022-01-06 13:59:13 +01:00
$ { s . shape } ` );if(a.shape.length!==1)throw new Error( ` Target shape should be a vector but received shape $ { a . shape } ` );let o=t.dataIdMap.get(r.dataId).id,i=t.dataIdMap.get(s.dataId).id,c=t.dataIdMap.get(a.dataId).id,l=r.shape[0],u=k.sizeFromShape(a.shape),d=t.makeOutput([l,u],r.dtype),p=t.dataIdMap.get(d.dataId).id,h=t.makeOutput([u],a.dtype),f=t.dataIdMap.get(h.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;gE(o,i,c,l,p,f,g);let b=t.readSync(m.dataId),y;switch(b[0]){case 0:{y=_.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(b[1],b[2]);break}case 1:{y=_.getSparseReshapeNegativeOutputDimErrorMessage(b[1],b[2]);break}case 2:y=_.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let v=Array.from(t.readSync(s.dataId)),x=Array.from(t.readSync(h.dataId));y=_.getSparseReshapeInputOutputMultipleErrorMessage(v,x);break}case 4:{let v=Array.from(t.readSync(s.dataId)),x=Array.from(t.readSync(h.dataId));y=_.getSparseReshapeInputOutputMismatchErrorMessage(v,x);break}default:y=""}if(t.disposeData(m.dataId),y)throw t.disposeData(d.dataId),t.disposeData(h.dataId),new Error(y);return[d,h]}var Fie={kernelName:Hc,backendName:"wasm",setupFunc:Aie,kernelFunc:Die},bE;function yE(e){bE=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function vE(e,t){let{backend:n,inputs:r}=e,{data:s,indices:a,segmentIds:o}=r,i=a.shape[0],c=n.readSync(o.dataId,i-1,i)[0],u=i>0?c+1:0;if(u<0)throw new Error(_.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=s.shape.slice();d[0]=u;let p=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=n.dataIdMap.get(o.dataId).id,m=n.makeOutput(d,s.dtype),g=n.dataIdMap.get(m.dataId).id,b=n.makeOutput([4],"int32"),y=n.dataIdMap.get(b.dataId).id;bE(p, $ t[s.dtype],s.shape[0],h,f,g,y,t,0);let v=n.readSync(b.dataId),x;switch(v[0]){case 0:{x=_.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=_.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=_.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(v[1],v[2]);break;case 3:x=_.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(v[1],v[2],v[3]);break;default:x=""}if(n.disposeData(b.dataId),x)throw n.disposeData(m.dataId),new Error(x);return m}function $ ie(e){return vE(e,!0)}var Rie={kernelName:Ml,backendName:"wasm",setupFunc:yE,kernelFunc: $ ie};function Pie(e){return vE(e,!1)}var Oie={kernelName:Ll,backendName:"wasm",setupFunc:yE,kernelFunc:Pie};function Mie(e){let{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=n,i=k.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=new Array(s.shape.length).fill(0),u=s.shape.slice();return c.map(d=>{let p=[...u];p[i]=d;let h=xi({inputs:{x:s},attrs:{begin:l,size:p},backend:r});return l[i]+=d,h})}var Lie={kernelName:Gc,backendName:"wasm",kernelFunc:Mie},Bie=un(_o),zie=un(Bl),Wie=!0,Vie=Cn(Do,Wie),xE;function Uie(e){xE=e.wasm.cwrap(ea,null,["number","number","number","number"])}function Gie(e){let{backend:t,inputs:n,attrs:r}=e,{alpha:s}=r,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),c=t.dataIdMap.get(i.dataId).id;return xE(o,s, $ t[a.dtype],c),i}var Hie={kernelName:ea,backendName:"wasm",setupFunc:Uie,kernelFunc:Gie},wE;function jie(e){wE=e.wasm.cwrap(jc,null,["number","array","number","array","array","array","array","array","number","number"])}function qie(e){let{backend:t,inputs:n,attrs:r}=e,{x:s}=n,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=Gt.sliceInfo(s.shape,a,o,i,c,l,u,d,p),w;if(m)w=Vn({inputs:{x:s},backend:t,attrs:{shape:f}});else if(g||b){k.assert(s.shape.length>=1,()=> ` Input must have rank at least 1 , got : $ { s . shape . length } ` );let T=Gt.computeOutShape(y,v,x),C=xi({inputs:{x:s},backend:t,attrs:{begin:y,size:T}});w=Vn({inputs:{x:C},backend:t,attrs:{shape:f}}),t.disposeData(C.dataId)}else{let T=t.makeOutput(h,"float32"),C=t.dataIdMap.get(
2021-12-01 21:37:52 +01: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 .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ 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 .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
/ * *
* @ 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
*
* https : //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-08-31 18:21:57 +02:00
/ * *
* @ 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 .
* === === === === === === === === === === === === === === === === === === === === === === === === === ==
* /
2021-04-26 20:45:49 +02:00
/** @license See the LICENSE file. */