face-api/dist/face-api.js

4820 lines
1.2 MiB
JavaScript
Raw Normal View History

2021-09-08 19:51:28 +02:00
/*
Face-API
homepage: <https://github.com/vladmandic/face-api>
author: <https://github.com/vladmandic>'
2021-09-08 19:51:28 +02:00
*/
2021-09-11 17:11:38 +02:00
var faceapi=(()=>{var k0=Object.defineProperty;var FA=e=>k0(e,"__esModule",{value:!0});var Li=typeof require!="undefined"?require:e=>{throw new Error('Dynamic require of "'+e+'" is not supported')};var bp=(e,t)=>{FA(e);for(var n in t)k0(e,n,{get:t[n],enumerable:!0})};var Vce={};bp(Vce,{AgeGenderNet:()=>Im,BoundingBox:()=>$u,Box:()=>it,ComposableTask:()=>_r,ComputeAllFaceDescriptorsTask:()=>Sa,ComputeFaceDescriptorsTaskBase:()=>$m,ComputeSingleFaceDescriptorTask:()=>Ca,DetectAllFaceLandmarksTask:()=>Dm,DetectAllFacesTask:()=>Kd,DetectFaceLandmarksTaskBase:()=>Fm,DetectFacesTaskBase:()=>Pm,DetectSingleFaceLandmarksTask:()=>Rm,DetectSingleFaceTask:()=>Om,Dimensions:()=>Tn,FACE_EXPRESSION_LABELS:()=>Xw,FaceDetection:()=>yt,FaceDetectionNet:()=>TE,FaceExpressionNet:()=>wm,FaceExpressions:()=>Ia,FaceLandmark68Net:()=>zu,FaceLandmark68TinyNet:()=>Sm,FaceLandmarkNet:()=>fE,FaceLandmarks:()=>fr,FaceLandmarks5:()=>Q_,FaceLandmarks68:()=>Du,FaceMatch:()=>Md,FaceMatcher:()=>Lm,FaceRecognitionNet:()=>Wu,Gender:()=>Ms,LabeledBox:()=>Ld,LabeledFaceDescriptors:()=>Rs,NetInput:()=>Ps,NeuralNetwork:()=>cn,ObjectDetection:()=>wa,Point:()=>Re,PredictedBox:()=>eE,Rect:()=>Fu,SsdMobilenetv1:()=>wi,SsdMobilenetv1Options:()=>Nr,TinyFaceDetector:()=>ju,TinyFaceDetectorOptions:()=>Am,TinyYolov2:()=>Gu,TinyYolov2Options:()=>ps,allFaces:()=>Lce,allFacesSsdMobilenetv1:()=>WE,allFacesTinyYolov2:()=>Mce,awaitMediaLoaded:()=>Uw,bufferToImage:()=>Gw,computeFaceDescriptor:()=>Ice,createCanvas:()=>bi,createCanvasFromMedia:()=>Wd,createFaceDetectionNet:()=>gce,createFaceRecognitionNet:()=>ace,createSsdMobilenetv1:()=>CE,createTinyFaceDetector:()=>Bce,createTinyYolov2:()=>vce,detectAllFaces:()=>Mm,detectFaceLandmarks:()=>BE,detectFaceLandmarksTiny:()=>kce,detectLandmarks:()=>Pce,detectSingleFace:()=>Oce,draw:()=>Qw,env:()=>Ye,euclideanDistance:()=>u0,extendWithAge:()=>Nm,extendWithFaceDescriptor:()=>Tm,extendWithFaceDetection:()=>fi,extendWithFaceExpressions:()=>km,extendWithFaceLandmarks:()=>Bu,extendWithGender:()=>_m,extractFaceTensors:()=>Pu,extractFaces:()=>Ru,fetchImage:()=>jie,fetchJson:()=>qw,fetchNetWeights:()=>qie,fetchOrThrow:()=>Os,fetchVideo:()=>Kie,getContext2dOrThrow:()=>Mn,getMediaDimensions:()=>gi,imageTensorToCanvas:()=>Hw,imageToSquare:()=>jw,inverseSigmoid:()=>Bie,iou:()=>Fw,isMediaElement:()=>pm,isMediaLoaded:()=>zd,isWithAge:()=>oce,isWithFaceDetection:()=>ls,isWithFaceExpressions:()=>Yw,isWithFaceLandmarks:()=>vi,isWithGender:()=>ice,loadAgeGenderModel:()=>Fce,loadFaceDetectionModel:()=>Dce,loadFaceExpressionModel:()=>$ce,loadFaceLandmarkModel:()=>_ce,loadFaceLandmarkTinyModel:()=>Ece,loadFaceRecognitionModel:()=>Ace,loadSsdMobilenetv1Model:()=>zE,loadTinyFaceDetectorModel:()=>Tce,loadTinyYolov2Model:()=>Nce,loadWeightMap:()=>Kw,locateFaces:()=>Rce,matchDimensions:()=>Xie,minBbox:()=>Dw,nets:()=>Ze,nonMaxSuppression:()=>Rw,normalize:()=>Hr,padToSquare:()=>Pw,predictAgeAndGender:()=>Cce,recognizeFaceExpressions:()=>Sce,resizeResults:()=>VE,resolveInput:()=>mi,shuffleArray:()=>Lie,sigmoid:()=>Od,ssdMobilenetv1:()=>LE,tf:()=>Nw,tinyFaceDetector:()=>xce,tinyYolov2:()=>wce,toNetInput:()=>ft,utils:()=>$w,validateConfig:()=>a0,version:()=>Wce});var Nw={};bp(Nw,{Abs:()=>Vi,Acos:()=>Ui,Acosh:()=>Gi,AdadeltaOptimizer:()=>Vh,AdagradOptimizer:()=>Uh,AdamOptimizer:()=>Gh,AdamaxOptimizer:()=>Hh,Add:()=>Ks,AddN:()=>Da,All:()=>Hi,Any:()=>ji,ArgMax:()=>Ra,ArgMin:()=>pl,Asin:()=>qi,Asinh:()=>Ki,Atan:()=>Xi,Atan2:()=>Zi,Atanh:()=>Yi,AvgPool:()=>Pa,AvgPool3D:()=>hl,AvgPool3DGrad:()=>Cp,AvgPoolGrad:()=>Sp,BackendWasm:()=>Z_,BatchMatMul:()=>Oa,BatchToSpaceND:()=>Ji,Bincount:()=>Tp,BroadcastArgs:()=>bb,BroadcastTo:()=>W0,Callback:()=>qS,CallbackList:()=>BI,Cast:()=>Ma,Ceil:()=>La,ClipByValue:()=>Xs,Complex:()=>Np,ComplexAbs:()=>fl,Concat:()=>Qi,Conv2D:()=>Ba,Conv2DBackpropFilter:()=>_p,Conv2DBackpropInput:()=>za,Conv3D:()=>ml,Conv3DBackpropFilterV2:()=>Ep,Conv3DBackpropInputV2:()=>Ap,Cos:()=>Wa,Cosh:()=>Va,CropAndResize:()=>ec,Cumsum:()=>Ua,CustomCallback:()=>WI,DataStorage:()=>vp,DenseBincount:()=>$p,DepthToSpace:()=>tc,DepthwiseConv2dNative:()=>Ga,Depthwi
`)),c.join(`
`)}function eF(e,t,n,r){let s=$t(t),a=r[r.length-1],o=new Array(a).fill(0),i=t.length,c=n==="complex64"?Dl(e):e;if(i>1)for(let u=0;u<s/a;u++){let l=u*a;for(let d=0;d<a;d++)o[d]=Math.max(o[d],Fl(c[l+d],0,n).length)}return o}function Fl(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(wb))} + ${parseFloat(e[1].toFixed(wb))}j`:js(e)?r=`'${e}'`:n==="bool"?r=X0(e):r=parseFloat(e.toFixed(wb)).toString(),dl(r,t)}function X0(e){return e===0?"false":"true"}function ph(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=Dl(e);return[Fl(m[0],0,n)]}return n==="bool"?[X0(e[0])]:[e[0].toString()]}if(c===1){if(i>K0){let g=$l*o,b=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-$l)*o,i*o));return n==="complex64"&&(b=Dl(b),y=Dl(y)),["["+b.map((v,x)=>Fl(v,s[x],n)).join(", ")+", ..., "+y.map((v,x)=>Fl(v,s[i-$l+x],n)).join(", ")+"]"]}let m=n==="complex64"?Dl(e):Array.from(e);return["["+m.map((g,b)=>Fl(g,s[b],n)).join(", ")+"]"]}let u=t.slice(1),l=r.slice(1),d=r[0]*o,p=[];if(i>K0){for(let m=0;m<$l;m++){let g=m*d,b=g+d;p.push(...ph(e.slice(g,b),u,n,l,s,!1))}p.push("...");for(let m=i-$l;m<i;m++){let g=m*d,b=g+d;p.push(...ph(e.slice(g,b),u,n,l,s,m===i-1))}}else for(let m=0;m<i;m++){let g=m*d,b=g+d;p.push(...ph(e.slice(g,b),u,n,l,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=`,
`;for(let m=2;m<c;m++)f+=`
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function Dl(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Bt=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=$t(e),n!=null){let r=n.length;D(r===this.size,()=>`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||$0(t,this.size),this.strides=zi(e)}set(e,...t){t.length===0&&(t=[0]),D(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let r of e){if(r<0||r>=this.shape[t]){let s=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(s)}t++}let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Yr().makeTensor(this.values,this.shape,this.dtype)}},Yr=null,Gc=null,tF=null;function nF(e){Yr=e}function rF(e){Gc=e}function sF(e){tF=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=$t(e),this.strides=zi(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 Gc.buffer(this.shape,this.dtype,e)}bufferSync(){return Gc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Wi(this.shape,e,this.dtype==="complex64")}arraySync(){return Wi(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Yr().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>dh(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=Yr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>dh(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 Yr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Yr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Gc.print(this,e)}clone(){return this.throwIfDisposed(),Gc.clone(this)}toString(e=!1){let t=this.dataSync();return Q$(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Gc.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Yr().makeVariable(this,e,t,n)}};Object.defineProperty(Ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function aF(){return gb("Tensor",()=>Ee)}aF();var Qs=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(!ys(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Yr().disposeTensor(this),this.dataId=e.dataId,Yr().incRef(this,null)}dispose(){Yr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Qs,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),[]),u=[];c.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;u.push(m)})});let l=await e(u),d={},p=0;return c.forEach(h=>{let f=t[h].paths.length,m=0;for(let x=0;x<f;x++)m+=l[p+x].byteLength;let g=new ArrayBuffer(m),b=new Uint8Array(g),y=0;for(let x=0;x<f;x++){let k=new Uint8Array(l[p+x]);b.set(k,y),y+=k.byteLength}a[h].forEach(x=>{let k=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),C=s1(k,[x.manifestEntry]);for(let N in C)d[N]=C[N]}),p+=f}),d}}var tD="application/octet-stream",nD="application/json",Mb=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(D(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=Q().platform.fetch,D(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&D(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=i1(e,n);t.body.append("model.json",new Blob([JSON.stringify(r)],{type:nD}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:tD}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Ml(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 Fb(t,s=>this.loadWeights(s))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=rD(t),s=this.weightPathPrefix||n,a=[];for(let u of e)a.push(...u.weights);let o=[],i=[];for(let u of e)for(let l of u.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(l)):o.push(s+l+r);this.weightUrlConverter&&o.push(...await Promise.all(i));let c=await y1(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,$b(c)]}};Mb.URL_SCHEME_REGEX=/^https?:\/\//;function rD(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}function Lb(e){return e.match(Mb.URL_SCHEME_REGEX)!=null}var x1=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>Lb(r)):n=Lb(e),n)return Bb(e,t)}return null};Et.registerSaveRouter(x1);Et.registerLoadRouter(x1);function Bb(e,t){return new Mb(e,t)}function sD(e,t){return Bb(e,t)}var zb=class{
Actual: ${s}.
Expected: ${a}.`);for(let o=0;o<a.length;++o){let i=s[o],c=a[o];if(!n(i,c))throw new Error(`Arrays differ: actual[${o}] = ${i}, expected[${o}] = ${c}.
Actual: ${s}.
Expected: ${a}.`)}}function TD(e,t){e().then(()=>t.fail(),()=>t())}function ND(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return js(e)||js(e[0])||js(t)||js(t[0])?jb(e,n,(r,s)=>r==s):jb(e,t,(r,s)=>qb(r,s,0))}function _D(e,t,n){if(n==null&&(n=Hb()),!qb(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function qb(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function ED(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 AD(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function B1(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?B1(n):e[t]=Al(n)}return e}var $D="3.9.0";function FD(){Q().set("PROD",!0)}function DD(){Q().set("DEBUG",!0)}function RD(){Q().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Kb(e){Q().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}sF(Kb);function PD(){B.disposeVariables()}function ws(){return B}function yh(){return B.memory()}function OD(e){return B.profile(e)}function M(e,t){return B.tidy(e,t)}function Ae(e){Nb(e).forEach(n=>n.dispose())}function Xt(e){return B.keep(e)}function MD(e){return B.time(e)}function LD(e){return B.setBackend(e)}function BD(){return B.ready()}function zD(){return B.backendName}function WD(e){B.removeBackend(e)}function VD(e){return B.findBackend(e)}function UD(e){return B.findBackendFactory(e)}function vh(e,t,n=1){return B.registerBackend(e,t,n)}function z1(){return B.backend}function GD(e,t){Q().setPlatform(e,t)}function HD(e,t){let n=E(e,"a","add"),r=E(t,"b","add");[n,r]=Ct(n,r);let s={a:n,b:r};return B.runKernel(Ks,s)}var Y=W({add_:HD});function jD(e,t){let n=E(e,"a","floorDiv"),r=E(t,"b","floorDiv");[n,r]=Ct(n,r);let s={a:n,b:r};return B.runKernel(Xa,s)}var Xb=W({floorDiv_:jD});function qD(e,t){let n=E(e,"a","div"),r=E(t,"b","div");if([n,r]=Ct(n,r),n.dtype==="int32"&&r.dtype==="int32")return Xb(n,r);let s={a:n,b:r},a={};return B.runKernel(Ha,s,a)}var ge=W({div_:qD});function KD(e,t){let n=E(e,"a","mul"),r=E(t,"b","mul");[n,r]=Ct(n,r);let s={a:n,b:r};return B.runKernel(co,s)}var V=W({mul_:KD});function XD(e){let t=E(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return B.runKernel(fl,n)}else{let n={x:t};return B.runKernel(Vi,n)}}var zt=W({abs_:XD});function YD(e){let n={x:E(e,"x","acos")};return B.runKernel(Ui,n)}var W1=W({acos_:YD});function ZD(e){let n={x:E(e,"x","acosh")};return B.runKernel(Gi,n)}var V1=W({acosh_:ZD});function JD(e){D(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),D(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((s,a)=>E(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(!ys(s.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=t;return B.runKernel(Da,r)}var U1=W({addN_:JD});function QD(e,t=null,n=!1){let s={x:E(e,"x","all","bool")},a={axis:t,keepDims:n};return B.runKernel(Hi,s,a)}var Yb=W({all_:QD});function eR(e,t=null,n=!1){let s={x:E(e,"x","any","bool")},a={axis:t,keepDims:n};return B.runKernel(ji,s,a)}var xh=W({any_:eR});function tR(e,t=0){let r={x:E(e,"x","argMax")},s={axis:t};return B.runKernel(Ra,r,s)}var Xc=W({argMax_:tR});function nR(e,t=0){let r={x:E(e,"x","argMin")},s={axis:t};return B.runKernel(pl,r,s)}var G1=W({argMin_:nR});function rR(e){let n={x:E(e,"x","asin")};return B.runKernel(qi,n)}var H1=W({asin_:rR});function sR(e){let n={x:E(e,"x","asinh")};return B.runKernel(Ki,n)}var j1=W({asinh_:sR});function aR(e){let n={x:E(e,"x","atan")};return B.runKernel(Xi,n)}var q1=W({atan_:aR});function oR(e,t){let n=E(e,"a","atan2"),r=E(t,"b","atan2");[n,r]=Ct(n,r);let s={a:n,b:r};return B.runKernel(Zi,s)}var K1=W({atan2_:oR});function iR(e){let n={x:E(
with dtype ${a.dtype}. `)}),n.length===1)return xs(n[0]);let r=n,s={axis:t};return B.runKernel(Qi,r,s)}var et=W({concat_:bR});function yR(e){let n={x:E(e,"x","sigmoid")};return B.runKernel(wo,n)}var xr=W({sigmoid_:yR});function vR(e,t,n){let r=E(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 B.runKernel($c,s,a)}var We=W({slice_:vR});function xR(e){let n={x:E(e,"x","tanh")};return B.runKernel(_o,n)}var Zc=W({tanh_:xR});function wR(e,t,n,r,s,a){let o=E(e,"forgetBias","basicLSTMCell"),i=E(t,"lstmKernel","basicLSTMCell"),c=E(n,"lstmBias","basicLSTMCell"),u=E(r,"data","basicLSTMCell"),l=E(s,"c","basicLSTMCell"),d=E(a,"h","basicLSTMCell"),p=et([u,d],1),h=De(p,i),f=Y(h,c),m=f.shape[0],g=f.shape[1]/4,b=[m,g],y=We(f,[0,0],b),v=We(f,[0,g],b),x=We(f,[0,g*2],b),k=We(f,[0,g*3],b),C=Y(V(xr(y),Zc(v)),V(l,xr(Y(o,x)))),N=V(Zc(C),xr(k));return[C,N]}var kR=W({basicLSTMCell_:wR});function IR(e,t,n){let r=E(e,"x","batchToSpaceND"),s=t.reduce((i,c)=>i*c);D(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),D(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),D(r.shape[0]%s==0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`);let a={x:r},o={blockShape:t,crops:n};return B.runKernel(Ji,a,o)}var kh=W({batchToSpaceND_:IR});function SR(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 CR(e,t,n,r,s,a){a==null&&(a=.001);let o=E(e,"x","batchNorm"),i=E(t,"mean","batchNorm"),c=E(n,"variance","batchNorm"),u;s!=null&&(u=E(s,"scale","batchNorm"));let l;r!=null&&(l=E(r,"offset","batchNorm")),D(i.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),D(l==null||i.rank===l.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),D(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:SR(o),scale:u,offset:l,mean:i,variance:c},h={varianceEpsilon:a},f=B.runKernel(Ya,p,h);return U(f,o.shape)}var aa=W({batchNorm_:CR});function TR(e,t,n,r,s,a){let o=E(e,"x","batchNorm"),i=E(t,"mean","batchNorm"),c=E(n,"variance","batchNorm"),u;s!=null&&(u=E(s,"scale","batchNorm"));let l;return r!=null&&(l=E(r,"offset","batchNorm")),D(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),D(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),D(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&D(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),l!=null&&D(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${l.rank}.`),aa(o,i,c,l,u,a)}var Q1=W({batchNorm2d_:TR});function NR(e,t,n,r,s,a){let o=E(e,"x","batchNorm"),i=E(t,"mean","batchNorm"),c=E(n,"variance","batchNorm"),u;s!=null&&(u=E(s,"scale","batchNorm"));let l;return r!=null&&(l=E(r,"offset","batchNorm")),D(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),D(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),D(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&D(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),l!=null&&D(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${l.rank}.`),aa(o,i,c,l,u,a)}var ek=W({batchNorm3d_:NR});function _R(e,t,n,r,s,a){let o=E(e,"x","batchNorm"),i=E(t,"mean","batchNorm"),c=E(n,"variance","batchNorm"),u;s!=null&&(u=E(s,"scale","batchNorm"));let l;return r!=nul
${s} and ${t} for depthToSpace with input shape
${r.shape}`),D(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${a} and ${t} for depthToSpace with input shape
${r.shape}`),D(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`);let i={x:r},c={blockSize:t,dataFormat:n};return B.runKernel(tc,i,c)}var dk=W({depthToSpace_:XR});function YR(e,t,n,r,s="NHWC",a=[1,1],o){let i=E(e,"x","depthwiseConv2d"),c=E(t,"filter","depthwiseConv2d"),u=i,l=!1;i.rank===3&&(l=!0,u=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),D(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),D(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),D(u.shape[3]===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),o!=null&&D(jt(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:u,filter:c},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},h=B.runKernel(Ga,d,p);return l?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Wo=W({depthwiseConv2d_:YR});function ZR(e){let n={x:E(e,"x","diag")};return B.runKernel(Rp,n)}var JR=W({diag_:ZR});function QR(e,t,n,r,s=[1,1],a="NHWC"){let o=E(e,"x","dilation2d"),i=E(t,"filter","dilation2d");D(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),D(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),D(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let c=o,u=!1;o.rank===3&&(c=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),u=!0);let l={x:c,filter:i},d={strides:n,pad:r,dilations:s},p=B.runKernel(gl,l,d);return u?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var pk=W({dilation2d_:QR});function eP(e,t){let n=e.length,r=[];for(let s=0;s<n;s++){let a=n-1-s,o=e[a]||1;(t[t.length-1-s]||1)>1&&o===1&&r.unshift(a)}return r}function Wt(e,t){let n=[];for(let r=0;r<t.length;r++){let s=e[e.length-r-1],a=t.length-r-1,o=t[a];(s==null||s===1&&o>1)&&n.unshift(a)}return n}function mt(e,t){let n=[],r=Math.max(e.length,t.length);for(let s=0;s<r;s++){let a=e[e.length-s-1];a==null&&(a=1);let o=t[t.length-s-1];if(o==null&&(o=1),a===1)n.unshift(o);else if(o===1)n.unshift(a);else if(a!==o){let i=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(i)}else n.unshift(a)}return n}function tP(e,t){let n=E(e,"a","equal","string_or_numeric"),r=E(t,"b","equal","string_or_numeric");[n,r]=Ct(n,r),mt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(rc,s)}var sr=W({equal_:tP});function nP(e,t,n){let r=E(t,"a","where"),s=E(n,"b","where"),a=E(e,"condition","where","bool"),o=mt(mt(a.shape,r.shape),s.shape),i=zl(a,o),c=zl(r,o),u=zl(s,o),l={condition:i,t:c,e:u};return B.runKernel(Ec,l)}var gn=W({where_:nP});function rP(e){let n={x:E(e,"x","zerosLike")};return B.runKernel(Wc,n)}var He=W({zerosLike_:rP});function sP(e,t){let n=E(e,"a","div"),r=E(t,"b","div");[n,r]=Ct(n,r);let s=ge(n,r),a=He(s),o=sr(r,a);return gn(o,a,s)}var hk=W({divNoNan_:sP});function aP(e,t){let n=E(e,"t1","dot"),r=E(t,"t2","dot");D((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);let s=n.rank===1?n.size:n.shape[1],a=r.rank===1?r.size:r.shape[0];if(D(s===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`),n.rank===1&&r.rank===1){let o=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 oP=W({dot_:aP});function iP(e,...t){let n=t.map((s,a)=>E(s,`tensors${a}`,"einsum")),r={equation:e};return B.runKernel(Mp,n,r)}var fk=W({einsum_:iP});function cP(e){let n={x:E(e,"x","elu")};return B.runKernel(ja,n)}var Wl=W({elu_:cP});function uP(e){let t=E(e,"x","erf");D(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be
rank ${a.rank}.`),D(jt(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},u={depthRadius:t,bias:n,alpha:r,beta:s},l=B.runKernel(xl,c,u);return i?U(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var vk=W({localResponseNormalization_:_P});function EP(e){let n={x:E(e,"x","log")};return B.runKernel(eo,n)}var ar=W({log_:EP});function AP(e){let n={x:E(e,"x","log1p")};return B.runKernel(mc,n)}var Th=W({log1p_:AP});function $P(e){return D(qs(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let r=E(t,"x","tf.grad","string_or_numeric"),s=n!=null?E(n,"dy","tf.grad"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(r),[r],s);return s!=null&&hn(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Nh(o),o[0]})}}function FP(e){return D(qs(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{D(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let r=Ol(t,"args","tf.grads","string_or_numeric"),s=n!=null?E(n,"dy","tf.grads"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(...r),r,s);return s!=null&&hn(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Nh(o),o})}}function DP(e){return D(qs(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{D(t instanceof Ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),D(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:r,value:s}=B.gradients(()=>e(t),[t],n);return Nh(r),{grad:r[0],value:s}}}function RP(e){return D(qs(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{D(Array.isArray(t)&&t.every(s=>s instanceof Ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),D(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let r=B.gradients(()=>e(...t),t,n);return n!=null&&hn(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Nh(r.grads),r}}function xk(e,t){D(qs(e),()=>"The f passed in variableGrads(f) must be a function"),D(t==null||Array.isArray(t)&&t.every(u=>u instanceof Qs),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in B.registeredVariables)t.push(B.registeredVariables[u])}let r=n?t.filter(u=>!u.trainable):null,s=t.length;t=t.filter(u=>u.trainable),D(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);let a=!0,{value:o,grads:i}=B.gradients(e,t,null,a);D(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),D(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let c={};return t.forEach((u,l)=>{i[l]!=null&&(c[u.name]=i[l])}),r!=null&&r.forEach(u=>c[u.name]=null),{value:o,grads:c}}function Qr(e){return B.customGrad(e)}function Nh(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 PP(e){let n={x:E(e,"x","neg")};return B.runKernel(yc,n)}var Tt=W({neg_:PP});function OP(e){let n={x:E(e,"x","softplus")};return B.runKernel(Rc,n)}var Qc=W({softplus_:OP});function MP(e){let t=E(e,"x","logSigmoid");return Qr(r=>({value:Tt(Qc(Tt(r))),gradFunc:o=>V(o,xr(Tt(r)))}))(t)}var LP=W({logSigmoid_:MP});function BP(e,t=null,n=!1){let s={x:E(e,"x","max")},a={reductionIndices:t,keepDims:n};return B.runKernel(to,s,a)}var $r=W({max_:BP});function zP(e,t){let n=E(e,"a","sub"),r=E(t,"b","sub");[n,r]=Ct(n,r);let s={a:n,b:r};return B.runKernel(To,s)}var he=W({sub_:zP});function WP(e,t=null,n=!1){let r=E(e,"x","sum");r.dtype==="bool"&&(r=ce(r,"int32"));let s={x:r},a={axis:t,keepDims:n};return B.runKernel(Io,s,a)}var ve=W({sum_:WP});function VP(e,t=-1){let n=E(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 Qr((s,a)=>{let o=!0,i=$r(s,t,!0),c=he(s,i),u=he(ce(c,"float32"),ar(ve(bn(c),t,o)));return a([u]),{value:u,gradFunc:(d,p)=>{let[h]=p,f=!0,m=bn(h);return he(d,V(ve(d,t,f),m))}}})(n)}var uy=W({logSoftmax_:VP});function ly(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function wk(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 kk(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 Go(e,t){let n=t.map(r=>1);return wk(e,n,t)}function UP(e,t,n){D(ly(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Ik(e,t){if(ly(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 dy(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function GP(e,t){let n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function HP(e,t=null,n=!1){let r=E(e,"x","logSumExp"),s=br(t,r.shape),a=$r(r,s,!0),o=he(r,a),i=bn(o),c=ve(i,s),u=ar(c),l=Y(U(a,u.shape),u);if(n){let d=Go(l.shape,s);return U(l,d)}return l}var Sk=W({logSumExp_:HP});function jP(e,t){let n=E(e,"a","logicalAnd","bool"),r=E(t,"b","logicalAnd","bool");mt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(gc,s)}var Fr=W({logicalAnd_:jP});function qP(e){let n={x:E(e,"x","logicalNot","bool")};return B.runKernel(yl,n)}var _h=W({logicalNot_:qP});function KP(e,t){let n=E(e,"a","logicalOr","bool"),r=E(t,"b","logicalOr","bool");mt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(vl,s)}var py=W({logicalOr_:KP});function XP(e,t){let n=E(e,"a","logicalXor","bool"),r=E(t,"b","logicalXor","bool");return mt(n.shape,r.shape),Fr(py(e,t),_h(Fr(e,t)))}var YP=W({logicalXor_:XP});function ZP(e,t,n,r,s){let a=E(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]])),D(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),D(Jr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),s!=null&&D(jt(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s},d=B.runKernel(ro,u,l);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Rt=W({maxPool_:ZP});function JP(e,t=[1,1,1],n,r,s,a="NDHWC"){let o=E(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]])),D(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),D(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),s!=null&&D(jt(r),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},d=B.runKernel(wl,u,l);return c?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var hy=W({maxPool3d_:JP});function QP(e,
${s.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let c={indices:s,values:a,denseShape:o,defaultValue:i},u=B.runKernel(Zp,c);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var fL=W({sparseFillEmptyRows_:hL});function mL(e,t,n){let r=E(e,"inputIndices","sparseReshape"),s=E(t,"inputShape","sparseReshape"),a=E(n,"newShape","sparseReshape");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=B.runKernel(Jp,o);return{outputIndices:i[0],outputShape:i[1]}}var gL=W({sparseReshape_:mL});function bL(e,t,n){let r=E(e,"data","sparseSegmentMean"),s=E(t,"indices","sparseSegmentMean"),a=E(n,"segmentIds","sparseSegmentMean");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return B.runKernel(Qp,o)}var yL=W({sparseSegmentMean_:bL});function vL(e,t,n){let r=E(e,"data","sparseSegmentSum"),s=E(t,"indices","sparseSegmentSum"),a=E(n,"segmentIds","sparseSegmentSum");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return B.runKernel(eh,o)}var xL=W({sparseSegmentSum_:vL});function wL(e,t,n,r,s,a,o,i){let c=E(e,"data","stringNGrams","string");if(c.dtype!=="string")throw new Error("Data must be of datatype string");if(c.shape.length!==1)throw new Error(`Data must be a vector, saw: ${c.shape}`);let u=E(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let l={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:c,dataSplits:u},p=B.runKernel(nh,d,l);return{nGrams:p[0],nGramsSplits:p[1]}}var kL=W({stringNGrams_:wL});function IL(e,t,n=!0){let r=E(e,"input","stringSplit","string"),s=E(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=B.runKernel(rh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var SL=W({stringSplit_:IL});function CL(e,t){let n=E(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 B.runKernel(sh,s,r)}var TL=W({stringToHashBucketFast_:CL}),NL={fft:Rh,ifft:jl,rfft:Ph,irfft:Sy},_L={hammingWindow:nM,hannWindow:jk,frame:qk,stft:oM},qn={flipLeftRight:lM,grayscaleToRGB:pM,resizeNearestNeighbor:OM,resizeBilinear:RM,rotateWithOffset:fM,cropAndResize:cM,nonMaxSuppression:gM,nonMaxSuppressionAsync:SM,nonMaxSuppressionWithScore:TM,nonMaxSuppressionWithScoreAsync:_M,nonMaxSuppressionPadded:AM,nonMaxSuppressionPaddedAsync:FM,threshold:BM,transform:WM},Qk={bandPart:UM,gramSchmidt:HM,qr:qM},EL={absoluteDifference:YM,computeWeightedLoss:Ss,cosineDistance:JM,hingeLoss:eL,huberLoss:nL,logLoss:sL,meanSquaredError:oL,sigmoidCrossEntropy:uL,softmaxCrossEntropy:pL},Kl={sparseFillEmptyRows:fL,sparseReshape:gL,sparseSegmentMean:yL,sparseSegmentSum:xL},Wh={stringNGrams:kL,stringSplit:SL,stringToHashBucketFast:TL},Cs=class extends O1{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 Ae(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 xk(e,t)}dispose(){this.iterations_!=null&&Ae(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:ke(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 Vh=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=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=B.registeredVariables[n],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:M(()=>He(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:M(()=>He(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 u=Y(V(i,this.rho),V(ut(o),1-this.rho)),l=V(ge(ln(Y(c,this.epsilon)),ln(Y(i,this.epsilon))),o),d=Y(V(c,this.rho),V(ut(l),1-this.rho));i.assign(u),c.assign(d);let p=Y(V(l,-this.learningRate),s);s.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpda
${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,u=1,l=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]),u*=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]),l*=e.shape[d];return{batchSize:c,sliceSize:l,outerSize:u,dimSize:o,outputShape:i}}function dB(e){try{return e.map(t=>dh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function pB(e){return e.map(t=>Al(t))}var ts={};Fe(ts,{nonMaxSuppressionV3Impl:()=>Kk,nonMaxSuppressionV4Impl:()=>Xk,nonMaxSuppressionV5Impl:()=>Yk,whereImpl:()=>Lk});var aI={kernelName:Vi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,ql(ce(n,"float32"),-1))}}},hB={kernelName:Ui,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=ut(ce(n,"float32")),s=ln(he(ke(1),r));return Tt(ge(e,s))}}}},fB={kernelName:Gi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=ln(he(ut(ce(n,"float32")),1));return ge(e,r)}}}},mB={kernelName:Ks,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=mt(n.shape,r.shape);return{a:()=>{let i=e,c=Wt(n.shape,s);return c.length>0&&(i=ve(i,c)),U(i,n.shape)},b:()=>{let i=e,c=Wt(r.shape,s);return c.length>0&&(i=ve(i,c)),U(i,r.shape)}}}},gB={kernelName:Da,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((r,s)=>{n[s]=()=>e.clone()}),n}},bB={kernelName:Ra,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>He(n)}}},yB={kernelName:pl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>He(n)}}},vB={kernelName:qi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,ln(he(ke(1),ut(ce(n,"float32")))))}}},xB={kernelName:Ki,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=ln(Y(ke(1),ut(ce(n,"float32"))));return ge(e,r)}}}},wB={kernelName:Zi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=mt(n.shape,r.shape);return{a:()=>{let i=Y(ut(n),ut(r)),c=V(e,ge(r,i)),u=Wt(n.shape,s);return u.length>0&&(c=ve(c,u)),U(c,n.shape)},b:()=>{let i=Y(ut(n),ut(r)),c=Tt(V(e,ge(n,i))),u=Wt(r.shape,s);return u.length>0&&(c=ve(c,u)),U(c,r.shape)}}}},kB={kernelName:Xi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Y(ut(ce(n,"float32")),1))}}},IB={kernelName:Yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,he(ke(1),ut(ce(n,"float32"))))}}};function SB(e,t,n,r,s,a){let o=E(e,"dy","avgPool3dGrad"),i=E(t,"input","avgPool3dGrad"),c=o,u=i,l=!1;i.rank===4&&(l=!0,c=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),u=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),D(c.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),D(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),a!=null&&D(jt(s),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let d={dy:c,input:u},p={filterSize:n,strides:r,pad:s,dimRoundingMode:a},h=B.runKernel(Cp,d,p);return l?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var CB=W({avgPool3dGrad_:SB}),TB={kernelName:hl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>CB(e,r,s,a,o,i)}}};function NB(e,t,n,r,s){let a=E(e,"dy","avgPoolGrad"),o=E(t,"input","avgPoolGrad");D(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,c=a,u=!1;o.rank===3&&(u=!0,i=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]])),D(c.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${c.rank}.`),D(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let l={dy:c,input:i},d={filterSize:n,strides:r,pad:s},p=B.runKernel(Sp,l,d);return u?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var _B=W({avgPoolGrad_:NB}),EB={kernelName:Pa,inputsToSave:["x"],gradFunc:(e,
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)}.
'className' and 'config' must set.`);let o=a.className,i,c;if(o in n?[i,c]=n[o]:o in kr?[i,c]=kr.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:
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(c!=null){let u={};for(let h of Object.keys(kr))u[h]=kr[h];for(let h of Object.keys(n))u[h]=n[h];let l=a.config;l.customObjects=u;let d=Object.assign({},kr);for(let h of Object.keys(n))kr[h]=n[h];My(a.config);let p=c(i,a.config,n,s);return kr=Object.assign({},d),p}else{let u=Object.assign({},kr);for(let d of Object.keys(n))kr[d]=n[d];let l=new i(a.config);return kr=Object.assign({},u),l}}}function f4(e,t){return e<t?-1:e>t?1:0}function Xh(e,t){return-1*f4(e,t)}function ca(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function m4(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 Xo(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 Ly(e,t,n=0,r=1/0){return ns(n>=0),ns(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(s=>typeof s===t)}function Yt(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,r)=>Yt(n,`element ${r+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${gI(e)}.`)}function gI(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>gI(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function g4(e,t){let n=w.now(),r;return(...a)=>{let o=w.now();return o-n<t||(n=o,r=e(...a)),r}}function bI(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function By(e,t){return M(()=>ln(ve(V(e,e),t,!0)))}var Zl=class extends ae.Serializable{getConfig(){return{}}},zy=class extends Zl{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=By(e,this.axis),n=rn(t,0,this.maxValue);return V(e,ge(n,Y(Vt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};zy.className="MaxNorm";ae.registerClass(zy);var Wy=class extends Zl{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return M(()=>ge(e,Y(Vt(),By(e,this.axis))))}getConfig(){return{axis:this.axis}}};Wy.className="UnitNorm";ae.registerClass(Wy);var Vy=class extends Zl{apply(e){return qe(e)}};Vy.className="NonNeg";ae.registerClass(Vy);var Uy=class extends Zl{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=By(e,this.axis),n=Y(V(this.rate,rn(t,this.minValue,this.maxValue)),V(1-this.rate,t));return V(e,ge(n,Y(Vt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};Uy.className="MinMaxNorm";ae.registerClass(Uy);var yI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Ut(e){return Oy(e)}function vI(e,t={}){return Yl(e,ae.SerializationMap.getMap().classNameMap,t,"constraint")}function Gt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in yI?yI[e]:e,config:{}};return vI(n)}else return e instanceof Zl?e:vI(e)}function b4(e){return new zy(e)}function y4(e){return new Wy(e)}function v4(){return new Vy}function x4(e){return new Uy(e)}var xI={};Fe(xI,{constant:()=>U4,glorotNormal:()=>Y4,glorotUniform:()=>X4,heNormal:()=>Z4,heUniform:()=>J4,identity:()=>q4,leCunNormal:()=>Q4,leCunUniform:()=>eW,ones:()=>V4,orthogonal:()=>tW,randomNormal:()=>H4,randomUniform:()=>G4,truncatedNormal:()=>j4,varianceScaling:()=>K4,zeros:()=>W4});var w4=["channelsFirst","channelsLast"],k4=["nearest","bilinear"],I4=["valid","same","causal"],S4=["max","avg"],C4=["sum","mul","concat","ave"],ou=new Map;function Ft(e){Xo(w4,"DataFormat",e)}function T4(e){Xo
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),Cr(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Xt(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,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 Vn([],[0].concat(this.elementShape));let n=this.readMany(e);return Cr(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Pt(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 Vn([],[0].concat(this.elementShape));let t=[];for(let r=0;r<this.size();r++)t.push(r);let n=this.readMany(t);return Cr(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
tensor.shape[0], but sum of lengths is
${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],u=[0,c,0],l=[1,e[i],s];a[i]=U(We(t,u,l),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},md=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}`);Cr(t,s.shape,"TensorList shape mismatch: "),Xt(s)}),this.idTensor=ke(0),this.maxNumElements=r,Xt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new md([...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.`);Cr(e,this.elementShape,"TensorList shape mismatch: ");let r=fd(this.elementShape,this.tensors,e);return M(()=>{let s=this.tensors.map(a=>U(a,r));return Pt(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=fd(this.elementShape,this.tensors,e),r=this.tensors.pop();return Cr(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(Cr(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Xt(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);Cr(this.tensors[e].shape,t,"TensorList shape mismatch: ");let r=fd(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.`);Cr(this.elementShape,t.shape,"TensorList shape mismatch: "),Xt(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Cr(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let r=fd(this.elementShape,this.tensors,n);return e.length===0?Vn([],[0].concat(r)):M(()=>{let s=e.map(a=>U(this.tensors[a],r));return Pt(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Cr(this.elementShape,t,"TensorList shape mismatch: ");let n=fd(this.elementShape,this.tensors,t);return this.size()===0?Vn([],[0].concat(n)):M(()=>{let r=this.tensors.map(s=>U(s,n));return et(r,0)})}};function SG(e,t,n){let r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor m
tensor.shape[0], but sum of lengths is
${r}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=Dx(a,n),i=r===0?0:e.size/r,c=M(()=>{let l=[];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];l[d]=U(We(e,h,f),o)}return e.dispose(),l}),u=new md([],n,e.dtype,t.length);for(let l=0;l<c.length;l++)u.setItem(l,c[l]);return u}var _G=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let r=I("thenBranch",e,t,n),s=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let r=I("body",e,t,n),s=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(l=>l.id),c=await o[0].data();o.forEach(l=>{!l.kept&&i.indexOf(l.id)===-1&&l.dispose()});let u=a;for(;c[0];){let l=u;u=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let d=u.map(h=>h.id);l.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[s].executeFunctionAsync(u,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 u}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=>wn(s,t,n)!==void 0);if(r){let s=wn(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),u=I("name",e,t,n),l=new IG(u,s,r,a,c,o,i);return n.addTensorArray(l),[l.idTensor,ke(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[ke(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=TG(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=CG(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),Xn(async()=>(await n.iterator()).columnMajorBatch(e,t,NH),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,Xn(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,Xn(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 Xn(async()=>(await t.iterator()).map(n=>M(()=>e(n))),this.size)}mapAsync(e){let t=this;return Xn(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 Xn(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,Xn(async()=>{let r=Mx(async()=>({value:await t.iterator(),done:!1}));return dH(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,Xn(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=rH.alea(t||w.now().toString());return Xn(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,Xn(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()}};fu.MAX_BUFFER_SIZE=1e4;function Xn(e,t=null){return new class extends fu{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function CH(e){return Xn(async()=>DC(e),e.length)}function TH(e){if(!hu(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 Xn(async()=>{let n=await $C(e,r=>{if(r instanceof fu)return{value:r.iterator(),recurse:!1};if(hu(r))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return pH(n,ma.SHORTEST)},t)}function NH(e){if(e===null)return null;let t=e[0];return iH(t)?{value:_H(e),recurse:!1}:{value:null,recurse:!0}}function _H(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ee?Pt(e):Vn(e)}var MC=class extends fu{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))}},$f='"',gd=Symbol("out"),LC=Symbol("field"),Ff=Symbol("quote"),Bx=Symbol("quoteafterquote"),BC=Symbol("quoteinquote"),zC=class extends fu{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 MC(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(w.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((r,s)=>(r[s]=r[s]+1||1,r),{}),n=Object.keys(t).filter(r=>t[r]>1);if(w.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let r of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(r)===-1)throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],o=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!o)){let i=t[s],c=null;if(i==="")if(o&&o.default!==void 0)c=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);c=void 0}else{let u=Number(i);if(isNaN(u))o&&o.dtype==="bool"?c=this.getBoolean(i):c=i;else if(!o||!o.dtype)c=u;else switch(o.dtype){case"float32":c=u;break;case"int32":c=Math.floor(u);break;case"bool":c=this.getBoolean(i);break;default:c=u}}o&&o.isLabel?r[a]=c:n[a]=c}}return Object.keys(r).length===0?n:{xs:n,ys:r}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],r=0,s=e.length,a=gd;for(let o=0;o<s;o++)switch(a){case gd:switch(e.charAt(o)){case $f:r=o+1,a=Ff;break;case this.delimiter:if(r=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=gd;break;default:a=LC,r=o;break}break;case LC:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o)),a=gd,r=o+1;break;default:}break;case Ff:switch(e.charAt(o)){case $f:a=Bx;break;default:}break;case Bx:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o-1)),a=gd,r=o+1;break;case $f:a=Ff;break;default:a=BC;break}break;case BC:switch(e.charAt(o)){case $f:a=Ff;break;default:}break;default:}if(a===Bx?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}},WC=class extends Zt{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
============================
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
============================`));let r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return _.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=>w.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 ws().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=w.now();return e(),{kernelMs:w.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){we([e],"where");let t=this.readSync(e.dataId);return VH(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Df.nextDataId=0;var zx={};Fe(zx,{addImpl:()=>YC,bincountImpl:()=>Vx,bincountReduceImpl:()=>ZC,ceilImpl:()=>JC,concatImpl:()=>Ux,equalImpl:()=>QC,expImpl:()=>tT,expm1Impl:()=>rT,floorImpl:()=>sT,gatherNdImpl:()=>aT,gatherV2Impl:()=>oT,greaterEqualImpl:()=>cT,greaterImpl:()=>iT,lessEqualImpl:()=>lT,lessImpl:()=>uT,linSpaceImpl:()=>dT,logImpl:()=>pT,maxImpl:()=>hT,maximumImpl:()=>fT,minimumImpl:()=>mT,multiplyImpl:()=>Gx,negImpl:()=>gT,notEqualImpl:()=>bT,prodImpl:()=>yT,rangeImpl:()=>jx,rsqrtImpl:()=>vT,sigmoidImpl:()=>A6,simpleAbsImpl:()=>XC,sliceImpl:()=>Of,sparseFillEmptyRowsImpl:()=>wT,sparseReshapeImpl:()=>kT,sparseSegmentReductionImpl:()=>qx,sqrtImpl:()=>D6,squaredDifferenceImpl:()=>IT,stridedSliceImpl:()=>ST,stringNGramsImpl:()=>CT,stringSplitImpl:()=>TT,stringToHashBucketFastImpl:()=>NT,subImpl:()=>_T,tileImpl:()=>ET,topKImpl:()=>$T,transposeImpl:()=>Hx,uniqueImpl:()=>FT});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 UH=e=>{let{x:t}=e.inputs,n=e.backend;we(t,"abs");let r=new Float32Array(w.sizeFromShape(t.shape)),s=n.data.get(t.dataId).values;return r=XC(s),n.makeOutput(r,t.shape,"float32")},GH={kernelName:Vi,backendName:"cpu",kernelFunc:UH};function Mt(e){return(t,n,r,s,a)=>{let o=_.assertAndGetBroadcastShape(t,n),i=o.length,c=w.computeStrides(o),u=w.sizeFromShape(o),l=w.getTypedArrayFromDType(a,u),d=t.length,p=n.length,h=w.computeStrides(t),f=w.computeStrides(n),m=_.getBroadcastDims(t,o),g=_.getBroadcastDims(n,o);if(m.length+g.length===0)for(let b=0;b<l.length;++b)l[b]=e(r[b%r.length],s[b%s.length]);else for(let b=0;b<l.length;++b){let y=w.indexToLoc(b,i,c),v=y.slice(-d);m.forEach(N=>v[N]=0);let x=w.locToIndex(v,d,h),k=y.slice(-p);g.forEach(N=>k[N]=0);let C=w.locToIndex(k,p,f);l[b]=e(r[x],s[C])}return[l,o]}}function Yn(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 HH={kernelName:Np,backendName:"cpu",kernelFunc:Yn};function Rf(e,t,n="float32"){if(n==="complex64"){let s=Rf(e,t,"float32"),a=Rf(e,t,"float32
indices.shape[0] = ${i}`);let g=w.getArrayFromDType(n,0),b=w.getArrayFromDType(s,0);return[g,[0,d],b,u,l]}let p=!0,h=0,f=new Array(c).fill(0);for(let g=0;g<i;++g){let b=e[g*d];if(b<0)throw new Error(`indices(${g}, 0) is invalid: ${b} < 0`);if(b>=c)throw new Error(`indices(${g}, 0) is invalid: ${b} >= ${c}`);++f[b],p=p&&b>=h,h=b}let m=!0;for(let g=0;g<c;++g){let b=f[g]===0;u[g]=b,m=m&&!b,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&p){let g=e,b=r;for(let y=0;y<i;++y)l[y]=y;return[g,[i,d],b,u,l]}else{let g=f[c-1],b=w.getArrayFromDType(n,g*d),y=w.getArrayFromDType(s,g),v=new Array(c).fill(0);for(let x=0;x<i;++x){let k=e[x*d],C=v[k],N=(k===0?0:f[k-1])+C;v[k]++;for(let F=0;F<d;++F)b[N*d+F]=e[x*d+F];y[N]=r[x],l[x]=N}for(let x=0;x<c;++x)if(v[x]===0){let C=x===0?0:f[x-1];b[C*d+0]=x;for(let N=1;N<d;++N)b[C*d+N]=0;y[C]=o}return[b,[g,d],y,u,l]}}function kT(e,t,n,r,s){let a=w.sizeFromShape(r),o=t[0],i=s.length,c=[],u=1,l=-1;for(let g=0;g<i;++g){let b=s[g];if(b===-1){if(l!==-1)throw new Error(`only one output dimension may be -1, not both ${l} and ${g}`);l=g,c.push(1)}else{if(b<0)throw new Error(`size ${g} must be non-negative, not ${b}`);u*=b,c.push(b)}}if(l!==-1){if(u<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");let g=Math.trunc(a/u);if(u*g!==a)throw new Error(`Input to reshape is a SparseTensor with ${a}
dense values, but the requested shape requires a multiple of ${u}. inputShape=${r} outputShape= ${c}`);c[l]=g}let d=w.sizeFromShape(c);if(d!==a)throw new Error(`Input to reshape is a tensor with ${a} dense values, but the requested shape has ${d}. inputShape=${r} outputShape=${c}`);let p=r.length,h=[];if(p>0){h[p-1]=1;for(let g=p-2;g>=0;--g)h[g]=h[g+1]*r[g+1]}let f=[];if(i>0){f[i-1]=1;for(let g=i-2;g>=0;--g)f[g]=f[g+1]*c[g+1]}let m=w.getArrayFromDType(n,o*i);for(let g=0;g<o;++g){let b=0;for(let y=0;y<p;++y)b+=e[g*p+y]*h[y];for(let y=0;y<i;++y)m[g*i+y]=Math.trunc(b/f[y]),b%=f[y]}return[m,[o,i],c]}function qx(e,t,n,r,s,a=!1,o=0){let i=r.length;if(i!==s.length)throw new Error("segmentIds and indices should have same size.");let c=[t[0],e.length/t[0]],u=c[1],d=i>0?s[i-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let p=t.slice();p[0]=d;let h=p.reduce((v,x)=>v*x,1),f=w.getArrayFromDType(n,h);if(i===0)return d>0&&f.fill(o),[f,p];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,g=1,b=0,y=s[m];for(;;){let v=0;if(g<i){if(v=s[g],y===v){++g;continue}if(y>=v)throw new Error("segment ids are not increasing")}if(y<0||y>=d)throw new Error(`Segment id ${y} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);y>b&&f.fill(o,b*u,y*u);for(let x=m;x<g;++x){let k=r[x];if(k<0||k>=c[0])throw new Error(`Bad: indices[${x}] == ${r[x]} out of range [0, ${c[0]})`);for(let C=0;C<u;C++)f[y*u+C]+=e[k*u+C]}if(a)for(let x=0;x<u;x++)f[y*u+x]/=g-m;if(m=g,++g,b=y+1,y=v,g>i)break}return b<d&&f.fill(o,b*u,d*u),[f,p]}var D6=ba(e=>Math.sqrt(e)),R6=at(ko,e=>Math.sqrt(e)),P6={kernelName:ko,backendName:"cpu",kernelFunc:R6},IT=Mt((e,t)=>{let n=e-t;return n*n}),O6=Jt(Co,IT),M6={kernelName:Co,backendName:"cpu",kernelFunc:O6};function ST(e,t,n,r){let s=Be(e,t.dtype);for(let a=0;a<s.size;a++){let o=s.indexToLoc(a),i=new Array(o.length);for(let c=0;c<i.length;c++)i[c]=o[c]*n[c]+r[c];s.set(t.get(...i),...o)}return s}var L6=class{constructor(e,t,n,r,s,a){this.separator=w.encodeString(e),this.nGramWidths=t,this.leftPad=w.encodeString(n),this.rightPad=w.encodeString(r),this.padWidth=s,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,s,a){for(let o=0;o<s;++o){let i=this.getPadWidth(a),c=Math.max(0,i-o),u=Math.max(0,i-(s-(o+1))),l=a-(c+u),d=t+(c>0?0:o-i),p=0;p+=c*this.leftPad.length;for(let b=0;b<l;++b)p+=e[d+b].length;p+=u*this.rightPad.length,p+=(c+u+l-1)*this.separator.length,n[r+o]=new Uint8Array(p);let f=n[r+o],m=0,g=b=>b.forEach(y=>f[m++]=y);for(let b=0;b<c;++b)g(this.leftPad),g(this.separator);for(let b=0;b<l-1;++b)g(e[d+b]),g(this.separator);if(l>0){g(e[d+l-1]);for(let b=0;b<u;++b)g(this.separator),g(this.rightPad)}else{for(let b=0;b<u-1;++b)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let n=e.length,r=t.length;if(r>0){let i=t[0];if(i!==0)throw new Error(`First split value must be 0, got ${i}`);for(let c=1;c<r;++c){let u=t[c]>=i;if(u=u&&t[c]<=n,!u)throw new Error(`Invalid split value ${t[c]}, must be in [${i}, ${n}]`);i=t[c]}if(i!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`)}let s=r-1,a=w.getArrayFromDType("int32",r);if(n===0||r===0){let i=new Array(n);for(let c=0;c<=s;++c)a[c]=0;return[i,a]}a[0]=0;for(let i=1;i<=s;++i){let c=t[i]-t[i-1],u=0;this.nGramWidths.forEach(l=>{u+=this.getNumNGrams(c,l)}),this.preserveShort&&c>0&&u===0&&(u=1),a[i]=a[i-1]+u}let o=new Array(a[s]);for(let i=0;i<s;++i){let c=t[i],u=a[i];if(this.nGramWidths.forEach(l=>{let d=t[i+1]-t[i],p=this.getNumNGrams(d,l);this.createNGrams(e,c,o,u,p,l),u+=p}),this.preserveShort&&u===a[i]){let l=t[i+1]-t[i];if(l===0)continue;let d=l+2*this.padWidth,p=1;this.createNGrams(e,c,o,u,p,d)}}return[o,a]}};function CT(e,t,n,r,s,a,o,i){return new L6(n,r,s,a,o,i).compute(e,t)}function B6(e,t,n,r){if(!e.length)return;if(t.length===0){for(let a=0;a<e.length;++a)r.push(e.subarray(a,a+1));return}if(t.length===1){let a=t[0],o=e.indexOf(a);for(;o!==-1;){let i=e.subarray(0,o);(!n|
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${o.shape}`);let i=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values[0],[d,p,h,f,m]=wT(i,r.shape,r.dtype,c,s.dtype,u,l);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 tK={kernelName:Zp,backendName:"cpu",kernelFunc:eK};function nK(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.data.get(s.dataId).values),i=n.data.get(r.dataId).values,c=Array.from(n.data.get(a.dataId).values),[u,l,d]=kT(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(l,r.dtype,u),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var rK={kernelName:Jp,backendName:"cpu",kernelFunc:nK};function sK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${a.shape}`);let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[u,l]=qx(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(l,r.dtype,u)}var aK={kernelName:Qp,backendName:"cpu",kernelFunc:sK};function oK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${a.shape}`);let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[u,l]=qx(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(l,r.dtype,u)}var iK={kernelName:eh,backendName:"cpu",kernelFunc:oK};function cK(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:u,sliceSize:l,strides: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=XT(f,m,i,p,l,u,c,d,g,h);return n.makeTensorInfo(i,b.dtype,b.values)}var uK={kernelName:th,backendName:"cpu",kernelFunc:cK};function lK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),u=new Array(s.shape.length).fill(0),l=s.shape.slice();return c.map(d=>{let p=[...l];p[i]=d;let h=ri({inputs:{x:s},backend:n,attrs:{begin:u,size:p}});return u[i]+=d,h})}var dK={kernelName:Oc,backendName:"cpu",kernelFunc:lK},pK={kernelName:Sl,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,r=t;we(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}}},hK=at(Zs,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),fK={kernelName:Zs,backendName:"cpu",kernelFunc:hK};function mK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:u,ellipsisMask:l,newAxisMask:d,shrinkAxisMask:p}=r;we(s,"stridedSlice");let{nonStrided:h,$begin:f,$strides:m,size:g,newShape:b,outShape:y}=mn.sliceInfo(s.shape,a,o,i,c,u,l,d,p),v=bt({inputs:{x:s},backend:n,attrs:{shape:b}}),x;if(h){let C=ri({inputs:{x:v},backend:n,attrs:{begin:f,size:g}});x=bt({inputs:{x:C},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(C)}else if(y.some(C=>C===0))x=n.makeTensorInfo(y,s.dtype,[]);else{let C=n.bufferSync(v),N=ST(y,C,m,f);x=n.makeTensorInfo(N.shape,N.dtype,N.values)}let k=bt({inputs:{x},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),k}var gK={kernelName:Mc,backendName:"cpu",kernelFunc:mK};function bK(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:u}=r,{data:l,dataSplits:d}=t,p=n.data.get(l.dataId).values,h=n.data.get(d.dataId).values,[f,m]=CT(p,h,s,a,o,i,c,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var yK={kernelName:nh,backendName:"cpu",kernelFunc:bK};function vK(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,c=n.data.get(o.dataId).values[0],[u,l,d]=TT(i,c,s),p=l.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",l),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var xK={kernelName:rh,backendName:"cpu",kernelFunc:vK};function wK(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=NT(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var kK={kernelName:sh,backendName:"cpu",kernelFunc:wK},IK=at(No,e=>Math.tan(e)),SK={kernelName:No,backendName:"cpu",kernelFunc:IK},CK=at(_o,e=>Math.tanh(e)),TK={kernelName:_o,backendName:"cpu",kernelFunc:CK};function NK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;we(s,"tile");let o=ET(n.bufferSync(s),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var _K={kernelName:Ys,backendName:"cpu",kernelFunc:NK};function EK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r;we(s,"topk");let i=n.data.get(s.dataId).values,[c,u]=$T(i,s.shape,s.dtype,a,o);return
`),a=s.length.toString().length+2,o=s.map((d,p)=>w.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),u=o.slice(r-1,r),l=o.slice(r);console.log(c.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${w.rightPad(u[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(l.join(`
`))}function s2(e){return $s(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function a2(e,t){if(ye(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 zf(e,t){if(ye(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function o2(e,t){let n=$s(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return ye(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),ye(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function i2(e,t){let n=$s(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return ye(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),ye(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function tX(){return Q().getNumber("WEBGL_VERSION")===2?1:4}function c2(e){return $s(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function u2(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 l2(e){return $s(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function rw(e,t,n,r,s,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(ye(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),ye(e,()=>e.vertexAttribPointer(i,s,e.FLOAT,!1,a,o)),ye(e,()=>e.enableVertexAttribArray(i)),!0)}function d2(e,t,n){g2(e,n),ye(e,()=>e.activeTexture(e.TEXTURE0+n)),ye(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function nX(e,t){g2(e,t),ye(e,()=>e.activeTexture(e.TEXTURE0+t)),ye(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function p2(e,t,n){return $s(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function h2(e,t,n){return e.getUniformLocation(t,n)}function f2(e,t,n,r){ye(e,()=>d2(e,t,r)),ye(e,()=>e.uniform1i(n,r))}function rX(e){ye(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),ye(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),ye(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function Wf(e,t,n){ye(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),ye(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function sw(e,t){ye(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),ye(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Sd(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+m2(e,t))}function m2(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 $s(e,t,n){let r=ye(e,()=>t());if(r==null)throw new Error(n);return r}function g2(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 ai(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function oi(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 Vf(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[ai(e),...oi(e)]),t}function b2(e,t=!1){let n=Q().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((s,a)=>a>=e.length-2?w.nearestLargerEven(e[a]):e[a]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let r=w.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]
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)
`,c="",u=`
#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-09-11 17:11:38 +02:00
`,c=`
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-09-11 17:11:38 +02:00
`,u=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:c,defineRound:u}}function ii(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / ${s}`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${s}`:`index -= ${e[a]} * ${s}`;return`${o}; ${i};`}).join("")}function jf(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / outShapeStrides[${a}]`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`;return`${o}; ${i};`}).join("")}function iX(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 cX(e,t,n="index"){let r=e.map((a,o)=>o),s=iX(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 iw(e){let t=w.computeStrides(e).map(n=>n.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}function cw(){return`
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
`}var S2=`
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
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;
}
`,{getBroadcastDims:C2}=_;function uX(e,t,n){let r=[];if(e.forEach(h=>{let f=w.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?r.push(`uniform float ${h.name}${f>1?`[${f}]`:""};`):(r.push(`uniform sampler2D ${h.name};`),r.push(`uniform int offset${h.name};`)),n.enableShapeUniforms){let{uniformShape:m}=uw(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=>lX(h,t,n.packedInputs,n.enableShapeUniforms)).join(`
`),o=t.texShape,i=kn(),c=hX(i),u,l,d=gX(i);return t.isPacked?(u=dX(t.logicalShape,o,n.enableShapeUniforms),l=mX(i)):(u=pX(t.logicalShape,o,n.enableShapeUniforms),l=fX(i)),n.packedInputs&&(d+=xX),[d,c,l,s,u,a,n.userCode].join(`
`)}function xu(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return FX(e,t);case 1:return RX(e,t);case 2:return OX(e,t);case 3:return LX(e,t);case 4:return zX(e,t);case 5:return WX(e);case 6:return VX(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function T2(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return $X(e);case 1:return DX(e,t);case 2:return PX(e,t);case 3:return MX(e,t);default:return BX(e,t)}}function lX(e,t,n=!1,r){let s="";n?s+=T2(e,r):s+=xu(e,r);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?s+=UX(e,t):s+=GX(e,t)),s}function dX(e,t,n){switch(e.length){case 0:return N2();case 1:return wX(e,t,n);case 2:return EX(e,t,n);case 3:return IX(e,t,n);default:return CX(e,t,n)}}function pX(e,t,n){switch(e.length){case 0:return N2();case 1:return kX(e,t,n);case 2:return AX(e,t,n);case 3:return SX(e,t,n);case 4:return TX(e,t,n);case 5:return NX(e,t);case 6:return _X(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function hX(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`}function fX(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`}function mX(e){return`
void setOutput(vec4 val) {
${e.output} = val;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`}function gX(e){return`${e.version}
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
${bX}
${yX}
${vX}
`}var bX=`
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);
}
`,yX=`
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);
}
`,vX=`
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);
}
`,xX=`
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;
}
`;function N2(){return`
int getOutputCoords() {
return 0;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`}function wX(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return r[0]===1?n?`
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-09-11 17:11:38 +02:00
`}function kX(e,t,n){return t[0]===1?n?`
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-09-11 17:11:38 +02:00
`}function IX(e,t,n){if(n)return`
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-09-11 17:11:38 +02:00
`}function SX(e,t,n){if(n)return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${jf(["r","c","d"],e)}
return ivec3(r, c, d);
}
`;let r=ii(["r","c","d"],e);return`
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-09-11 17:11:38 +02:00
`}function CX(e,t,n){if(n)return`
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-09-11 17:11:38 +02:00
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2),o=a,i="",c="b, r, c";for(let u=2;u<e.length-1;u++)o*=e[e.length-u-1],i=`
int b${u} = index / ${o};
index -= b${u} * ${o};
`+i,c=`b${u}, `+c;return`
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;
return ivec${e.length}(${c});
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`}function TX(e,t,n){if(n)return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${jf(["r","c","d","d2"],e)}
return ivec4(r, c, d, d2);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`;let r=ii(["r","c","d","d2"],e);return`
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-09-11 17:11:38 +02:00
`}function NX(e,t){let n=ii(["r","c","d","d2","d3"],e);return`
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-09-11 17:11:38 +02:00
`}function _X(e,t){let n=ii(["r","c","d","d2","d3","d4"],e);return`
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-09-11 17:11:38 +02:00
`}function EX(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return n?`
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-09-11 17:11:38 +02:00
`}function AX(e,t,n){return w.arraysEqual(e,t)?n?`
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-09-11 17:11:38 +02:00
`}function ci(e){return`offset${e}`}function $X(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=kn();return`
vec4 ${n}() {
return ${r.texture2D}(${t}, halfCR);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}function FX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;let[s,a]=e.shapeInfo.texShape;if(s===1&&a===1)return`
float ${r}() {
return sampleTexture(${n}, halfCR);
}
`;let o=ci(n);if(t)return`
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-09-11 17:11:38 +02:00
`;let[i,c]=e.shapeInfo.texShape;return`
float ${r}() {
vec2 uv = uvFromFlat(${i}, ${c}, ${o});
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}function DX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=kn();if(t)return`
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);
}
`}function RX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
float ${r}(int index) {
${wu(e)}
}
`;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);
}
`;let i=ci(n);return o===1?t?`
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);
}
`}function PX(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=kn();if(a!=null&&w.arraysEqual(n,a))return t?`
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return ${c.texture2D}(${r}, uv);
}
`:`
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);
return ${c.texture2D}(${r}, uv);
}
`;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);
return ${c.texture2D}(${r}, uv);
}
`;let u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],l=Math.ceil(n[1]/2);return`
vec4 ${s}(int row, int col) {
vec2 uv = packedUVfrom2D(${l}, ${u[0]}, ${u[1]}, row, col);
return ${c.texture2D}(${r}, uv);
}
`}function OX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(a!=null&&w.arraysEqual(n,a)){if(t)return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`;let 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);
}
`}let{newShape:o,keptDims:i}=w.squeezeShape(n),c=o;if(c.length<n.length){let p=ku(e,c),h=["row","col"];return`
${xu(p,t)}
float ${s}(int row, int col) {
return ${s}(${Iu(h,i)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
${wu(e)}
}
`;let u=a[0],l=a[1],d=ci(r);return l===1?t?`
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));
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
return sampleTexture(${r}, uv);
}
`:u===1?t?`
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));
vec2 uv = vec2((index + 0.5) / ${l}.0, 0.5);
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};
vec2 uv = uvFromFlat(${u}, ${l}, index);
return sampleTexture(${r}, uv);
}
`}function MX(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=ku(e,p),m=["b","row","col"];return`
${T2(f,t)}
vec4 ${s}(int b, int row, int col) {
return ${s}(${Iu(m,h)});
}
`}let i=kn();if(t)return`
vec4 ${s}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));
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-09-11 17:11:38 +02:00
`;let c=o[0],u=o[1],l=Math.ceil(n[2]/2),d=l*Math.ceil(n[1]/2);return`
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${c}, ${u}, ${d}, ${l}, b, row, col);
return ${i.texture2D}(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}function LX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],o=n[2],{newShape:i,keptDims:c}=w.squeezeShape(n),u=i;if(u.length<n.length){let m=ku(e,u),g=["row","col","depth"];return`
${xu(m,t)}
float ${s}(int row, int col, int depth) {
return ${s}(${Iu(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)));
${wu(e)}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;let l=e.shapeInfo.texShape,d=l[0],p=l[1],h=e.shapeInfo.flatOffset;if(p===a&&h==null)return t?`
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-09-11 17:11:38 +02:00
`;let f=ci(r);return t?`
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);
}
`}function BX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=kn();if(t)return`
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);
}
`;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],u=c[0],l=c[1],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`
vec4 ${r}(${h}) {
int index = ${f};
int texR = index / ${l};
int texC = index - texR * ${l};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${u});
return ${s.texture2D}(${n}, uv);
}
`}function zX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:c,keptDims:u}=w.squeezeShape(n);if(c.length<n.length){let y=ku(e,c),v=["row","col","depth","depth2"];return`
${xu(y,t)}
float ${s}(int row, int col, int depth, int depth2) {
return ${s}(${Iu(v,u)});
}
`}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)));
${wu(e)}
}
`;let l=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&&l==null)return t?`
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);
}
`;if(h===a&&l==null)return t?`
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);
}
`;let b=ci(r);return t?`
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);
}
`}function WX(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,o=t[2]*a,i=t[1]*o,{newShape:c,keptDims:u}=w.squeezeShape(t);if(c.length<t.length){let m=ku(e,c),g=["row","col","depth","depth2","depth3"];return`
${xu(m)}
float ${r}(int row, int col, int depth, int depth2, int depth3) {
return ${r}(${Iu(g,u)});
}
`}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;
${wu(e)}
}
`;let l=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&l==null)return`
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);
}
`;if(h===s&&l==null)return`
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);
}
`;let f=ci(n);return`
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);
}
`}function VX(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=w.squeezeShape(t);if(s.length<t.length){let g=ku(e,s),b=["row","col","depth","depth2","depth3","depth4"];return`
${xu(g)}
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${r}(${Iu(b,a)});
}
`}let o=t[5],i=t[4]*o,c=t[3]*i,u=t[2]*c,l=t[1]*u;if(e.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${l}, ${u}, ${c}, ${i})) +
dot(
vec2(depth3, depth4),
vec2(${o}, 1)));
${wu(e)}
}
`;let d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===l&&d==null)return`
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),
vec4(${u}, ${c}, ${i}, ${o})) +
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);
}
`;let m=ci(n);return`
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${l} + col * ${u} + depth * ${c} +
depth2 * ${i} + depth3 * ${o} + depth4 + ${m};
vec2 uv = uvFromFlat(${h}, ${f}, index);
return sampleTexture(${n}, uv);
}
`}function wu(e){let t=e.name,n=w.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function UX(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=C2(e.shapeInfo.logicalShape,t.logicalShape),c=dt(o),u=o-a,l,d=["x","y","z","w","u","v"];a===0?l="":o<2&&i.length>=1?l="coords = 0;":l=i.map(y=>`coords.${d[y+u]} = 0;`).join(`
`);let p="";o<2&&a>0?p="coords":p=e.shapeInfo.logicalShape.map((y,v)=>`coords.${d[v+u]}`).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,b=w.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!b)h=`
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);
`;else if(i.length){let y=a-2,v=a-1;i.indexOf(y)>-1&&i.indexOf(v)>-1?h="return vec4(outputValue.x);":i.indexOf(y)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(v)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${s}() {
${c} coords = getOutputCoords();
${l}
vec4 outputValue = get${r}(${p});
${h}
}
`}function GX(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===c&&e.shapeInfo.flatOffset==null&&w.arraysEqual(o,a))return`
float ${s}() {
return sampleTexture(${n}, resultUV);
}
`;let u=dt(c),l=C2(e.shapeInfo.logicalShape,t.logicalShape),d=c-i,p,h=["x","y","z","w","u","v"];i===0?p="":c<2&&l.length>=1?p="coords = 0;":p=l.map(m=>`coords.${h[m+d]} = 0;`).join(`
`);let f="";return c<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+d]}`).join(", "),`
float ${s}() {
${u} coords = getOutputCoords();
${p}
return get${r}(${f});
}
`}function dt(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 uw(e,t,n){let{newShape:r,keptDims:s}=w.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):r,c=!e&&a>1&&!w.arraysEqual(t,n)&&r.length<a||o;return{useSqueezeShape:c,uniformShape:c?i:t,keptDims:s}}function ku(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Iu(e,t){return t.map(n=>e[n]).join(", ")}function HX(e,t,n,r){let s=n.map((v,x)=>{let k={logicalShape:v.shape,texShape:v.isUniform?null:v.texData.texShape,isUniform:v.isUniform,isPacked:v.isUniform?!1:v.texData.isPacked,flatOffset:null};return v.texData!=null&&v.texData.slice!=null&&v.texData.slice.flatOffset>0&&(k.flatOffset=v.texData.slice.flatOffset),{name:t.variableNames[x],shapeInfo:k}}),a=s.map(v=>v.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=uX(s,o,t),c=e.createProgram(i),u=null,l=e.getUniformLocation(c,"NAN",!1);Q().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(c,"INFINITY",!1));let d=!1,p={},h={},f={};for(let v=0;v<t.variableNames.length;v++){let x=t.variableNames[v];p[x]=e.getUniformLocation(c,x,d),p[`offset${x}`]=e.getUniformLocation(c,`offset${x}`,d),t.enableShapeUniforms&&(h[`${x}Shape`]=e.getUniformLocation(c,`${x}Shape`,d),f[`${x}TexShape`]=e.getUniformLocation(c,`${x}TexShape`,d))}let m,g,b;t.enableShapeUniforms&&(m=e.getUniformLocation(c,"outShape",d),b=e.getUniformLocation(c,"outShapeStrides",d),g=e.getUniformLocation(c,"outTexShape",d));let y=[];return t.customUniforms&&t.customUniforms.forEach((v,x)=>{y[x]=e.getUniformLocation(c,v.name,d)}),{program:t,source:i,webGLProgram:c,uniformLocations:p,customUniformLocations:y,inShapeInfos:a,outShapeInfo:o,infLoc:u,nanLoc:l,inShapesLocations:h,inTexShapesLocations:f,outShapeLocation:m,outShapeStridesLocation:b,outTexShapeLocation:g}}function _2(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,r)=>{let s=n.logicalShape,a=t[r],o=a.shape;if(!w.arraysEqual(s,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${o} must match`);if(n.isUniform&&a.isUniform)return;let i=n.texShape,c=a.isUniform?null:a.texData.texShape;if(!w.arraysEqual(i,c))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${c} must match`)})}function jX(e,t,n,r,s){t.program.enableShapeUniforms||(_2(t.inShapeInfos,n),_2([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,u)=>{let l=t.program.variableNames[u],d=t.uniformLocations[l],p=t.uniformLocations[`offset${l}`],h=t.inShapesLocations[`${l}Shape`],f=t.inTexShapesLocations[`${l}TexShape`];if(h){let{uniformShape:m}=uw(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(w.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,u)}});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.uniform3iv(i,new Int32Array(r
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?jf(["r","c","d"],e):ii(["r","c","d"],e)}
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;
}
`}},XX=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=wd.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=kn();this.outputShape=e,this.enableShapeUniforms=pr(this.outputShape.length),this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?jf(["r","c","d"],e):ii(["r","c","d"],e)}
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-09-11 17:11:38 +02:00
`}},YX=class{constructor(e){this.variableNames=["A"],this.outTexUsage=lr.DOWNLOAD;let t=kn();this.outputShape=e,this.userCode=`
${S2}
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);
}
`}},ZX=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=lr.DOWNLOAD;let t=kn();this.outputShape=e,this.userCode=`
${S2}
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);
}
`}},JX=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=kn();this.outputShape=e,this.enableShapeUniforms=pr(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode=`
${this.enableShapeUniforms?cw():iw(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.);
}
`}},QX=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=kn();this.outputShape=e,this.enableShapeUniforms=pr(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+=`
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=`
${this.enableShapeUniforms?cw():iw(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-09-11 17:11:38 +02:00
`}},E2={};Fe(E2,{bindVertexProgramAttributeStreams:()=>L2,createBufferFromOutputTexture:()=>W2,createFloat16MatrixTexture:()=>R2,createFloat16PackedMatrixTexture:()=>M2,createFloat32MatrixTexture:()=>D2,createIndexBuffer:()=>F2,createPackedMatrixTexture:()=>O2,createUnsignedBytesMatrixTexture:()=>P2,createVertexBuffer:()=>$2,createVertexShader:()=>A2,downloadByteEncodedFloatMatrixFromOutputTexture:()=>U2,downloadFloat32MatrixFromBuffer:()=>V2,downloadMatrixFromPackedOutputTexture:()=>H2,downloadPackedMatrixFromBuffer:()=>G2,getInternalFormatForFloat16MatrixTexture:()=>dw,getInternalFormatForFloat16PackedMatrixTexture:()=>fw,getInternalFormatForFloat32MatrixTexture:()=>lw,getInternalFormatForPackedMatrixTexture:()=>hw,getInternalFormatForUnsignedBytesMatrixTexture:()=>pw,uploadDenseMatrixToTexture:()=>B2,uploadPixelDataToTexture:()=>z2});function A2(e){let t=kn(),n=`${t.version}
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;
}`;return n2(e,n)}function $2(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 o2(e,t)}function F2(e){let t=new Uint16Array([0,1,2,2,1,3]);return i2(e,t)}function Td(e,t,n,r,s,a){u2(t,n);let o=c2(e),i=e.TEXTURE_2D;return ye(e,()=>e.bindTexture(i,o)),ye(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),ye(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),ye(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),ye(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),ye(e,()=>e.texImage2D(i,0,r,t,n,0,s,a,null)),ye(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function lw(e){return e.internalFormatFloat}function D2(e,t,n,r){let[s,a]=kd(t,n);return Td(e,s,a,lw(r),r.textureFormatFloat,e.FLOAT)}function dw(e){return e.internalFormatHalfFloat}function R2(e,t,n,r){let[s,a]=kd(t,n);return Td(e,s,a,dw(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function pw(e){return e.downloadTextureFormat}function P2(e,t,n,r){let[s,a]=kd(t,n);return Td(e,s,a,pw(r),e.RGBA,e.UNSIGNED_BYTE)}function hw(e){return e.internalFormatPackedFloat}function O2(e,t,n,r){let[s,a]=yu(t,n);return Td(e,s,a,hw(r),e.RGBA,e.FLOAT)}function fw(e){return e.internalFormatPackedHalfFloat}function M2(e,t,n,r){let[s,a]=yu(t,n);return Td(e,s,a,fw(r),e.RGBA,r.textureTypeHalfFloat)}function L2(e,t,n){let r=0,s=3*4,a=3*4+2*4;return ye(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),rw(e,t,"clipSpacePos",n,3,a,r)&&rw(e,t,"uv",n,2,a,s)}function B2(e,t,n,r,s,a){ye(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),ye(e,()=>e.texImage2D(e.TEXTURE_2D,0,c,n,r,0,e.RGBA,i,o)),ye(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function z2(e,t,n){ye(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?ye(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):ye(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),ye(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function W2(e,t,n,r){let s=e.createBuffer();ye(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));let i=4*4*t*n;return ye(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),ye(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),ye(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function V2(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 U2(e,t,n,r){let[s,a]=kd(t,n),o=4,i=new Uint8Array(KK(t*n,o));return ye(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function G2(e,t,n,r,s,a,o,i){let c=e,u=new Float32Array(XK(a,o));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,u),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),u}function H2(e,t,n){let r=new Float32Array(t*n*4);return ye(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}var j2=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,QT(t,e)):this.gl=cs(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=Id(this.gl,s),dr(this.gl,a))this.textureHalfFloatExtension=Id(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.colorBufferFloatExtension=this.gl.getExtension(n),dr(this.gl,r))this.colorBufferHalfFloatExtension=Id(this.gl,r);else if(Q().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",dr(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(dr(this.gl,r))this.
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{let n=In("rc",t),r=dt(t),s=V7(t,e,n),a=U7(t,e[e.length-1],e[e.length-2],n),o=G7(e,n);this.userCode=`
void main() {
${r} rc = getOutputCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(${s}) {
setOutput(vec4(0));
} else {
${a}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(vec4(${o}));
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
`}}};function W7(e,t){let n=[];for(let r=0;r<=1;r++)for(let s=0;s<=1;s++){let a=`${r===0?"r":"rp1"}, ${s===0?"c":"cp1"}`;for(let o=2;o<e;o++)a=`${t[t.length-1-o]},`+a;n.push(a)}return n}function V7(e,t,n){if(e===1)return`rc > ${t[0]}`;let r="";for(let s=e-2;s<e;s++)r+=`${n[s]} >= ${t[s]}`,s<e-1&&(r+="||");return r}function U7(e,t,n,r){if(e===1)return"";let s=r.slice(-2);return`
int r = ${s[0]};
int c = ${s[1]};
int rp1 = r + 1;
int cp1 = c + 1;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
bool cEdge = cp1 >= ${t};
bool rEdge = rp1 >= ${n};
`}function G7(e,t){let n=e.length,r=W7(n,t);return n===1?`getA(rc),
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${r[0]}),
cEdge ? 0. : getA(${r[1]}),
rEdge ? 0. : getA(${r[2]}),
rEdge || cEdge ? 0. : getA(${r[3]})`}var Z2=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=pr(this.outputShape.length);let n="";for(let r=0;r<4;r++){let s="thisRC = rc;";r%2==1&&(s+="thisRC.z += 1;"),r>1&&(s+="thisRC.y += 1;"),n+=`
${s}
${r>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
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=`
${H7(t,this.enableShapeUniforms)}
${this.enableShapeUniforms?cw():iw(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-09-11 17:11:38 +02:00
`}};function H7(e,t){return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t?cX(["r","c","d"],"inputShape"):ii(["r","c","d"],e)}
return ivec3(r, c, d);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}var j7=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=Q2(t,n),s=eN(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=J2(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===sn.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===sn.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===sn.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===sn.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===sn.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=Q2(n,r),a=eN(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);let o=J2(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],u=c.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});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 q7(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;throw new Error(`Unknown internal format ${t}`)}function J2(e,t,n,r,s){let a=K7(t,r),o;if(s){let[c,u]=yu(e[0],e[1]);o=c*u}else{let[c,u]=kd(e[0],e[1]);o=c*u}let i=q7(n,a);return o*i}function K7(e,t){switch(e){case sn.PACKED_2X2_FLOAT32:return hw(t);case sn.PACKED_2X2_FLOAT16:return fw(t);case sn.UNPACKED_FLOAT32:return lw(t);case sn.UNPACKED_FLOAT16:return dw(t);case sn.PACKED_4X1_UNSIGNED_BYTE:return pw(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function X7(e){return Q().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?sn.PACKED_2X2_FLOAT32:sn.UNPACKED_FLOAT32:e?sn.PACKED_2X2_FLOAT16:sn.UNPACKED_FLOAT16}function Q2(e,t){if(e===lr.UPLOAD)return sn.PACKED_2X2_FLOAT32;if(e===lr.RENDER||e==null)return X7(t);if(e===lr.DOWNLOAD||e===lr.PIXELS)return sn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function eN(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var ya=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=pr(this.outputShape.length),this.userCode=`
float unaryOperation(float x) {
${t}
}
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-09-11 17:11:38 +02:00
setOutput(y);
}
`}},Ur="if (isnan(x)) return x;",Y7="return x;",tN="return abs(x);",Z7="return (x >= 0.0) ? x : (exp(x) - 1.0);",J7=Ur+`
return (x < 0.0) ? 0.0 : x;
`,Q7=Ur+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,qf="return x;",e9="return 1.0 / (1.0 + exp(-1.0 * x));",t9="return x;",n9=`
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;
`,r9=`
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;
`,s9=`
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;
`,a9="return 1.0 / (1.0 + exp(-1.0 * x));",Su=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=pr(this.outputShape.length),this.userCode=`
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-09-11 17:11:38 +02:00
`}},o9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=In("rc",t),r=dt(t),s=B7(t,n),a=n.slice(-2),o=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
void main() {
${r} rc = getOutputCoords();
vec4 packedInput = getA(${s});
setOutput(getChannel(packedInput, ${o}));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}},i9=ts.whereImpl,c9=1e-7,u9=1e-4,Kf={};function l9(e){return e in Kf||(Kf[e]={}),Kf[e]}var d9=Q().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),p9=600;function h9(){return Q().global.screen==null?1024:Q().global.screen.height*Q().global.screen.width*window.devicePixelRatio*p9/1024/1024}var Xf=class extends ul{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=cs(Q().getNumber("WEBGL_VERSION"));this.binaryCache=l9(Q().getNumber("WEBGL_VERSION")),this.gpgpu=new j2(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 j7(this.gpgpu),this.numMBBeforeWarning=h9(),this.texData=new vp(this,ws())}nextDataId(){return Xf.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:lr.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:lr.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 Su(o,qf):d=new ya(o,qf);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,u;c&&(u=w.now());let l;if(r==="complex64"){let d=this.readSync(s.real.dataId),p=this.readSync(s.imag.dataId);l=_.mergeRealAndImagArrays(d,p)}else l=this.getValuesFromTexture(e);return c&&(this.downloadWaitMs+=w.now()-u),this.convertAndCacheOnCPU(e,l)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(s!=null){let h;i?h=new Su(r,qf):h=new ya(r,qf);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("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&Q().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c=null,u;if(a!=="complex64"&&Q().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let h=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(h.texture,...Bf(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let l;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];l=_.mergeRealAndImagArrays(f,m)}else if(c==null)l=this.getValuesFromTexture(e);else{let h=w.sizeFromShape(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,h)}if(u!=null&&this.disposeIntermediateTensorInfo(u),c!=null){let h=this.gpgpu.gl;ye(h,()=>h.deleteBuffer(c))}let d=this.convertAndCacheOnCPU(e,l),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(h=>h(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&ws().remo
if (isnan(a)) return a;
if (isnan(b)) return b;
`,Cu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=pr(this.outputShape.length),this.userCode=`
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));
}
`}},Yf=`
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;
`,Nd=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=pr(s);let a="";if(r)if(s===0||w.sizeFromShape(this.outputShape)===1)a=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else if(a=`
${dt(s)} coords = getOutputCoords();
`,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.;
`;else{let i=In("coords",s);this.enableShapeUniforms?a+=`
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-09-11 17:11:38 +02:00
`}};function Zn(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 b9={kernelName:Ja,backendName:"webgl",kernelFunc:Zn};function va(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=Zn({inputs:{x:r},backend:n}),c=Zn({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:c},a}var y9={kernelName:Np,backendName:"webgl",kernelFunc:va},sN="return (a < 0.) ? b * a : a;",aN=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function v9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=n.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),i=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Nd(aN,s.shape,o.shape):new Cu(sN,s.shape,o.shape),c=n.runWebGLProgram(i,[s,o],s.dtype);return n.disposeIntermediateTensorInfo(o),c}var x9={kernelName:Qa,backendName:"webgl",kernelFunc:v9},oN="return (a < 0.) ? b * a : a;",iN=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function w9(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Nd(iN,r.shape,s.shape):new Cu(oN,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)}var k9={kernelName:ho,backendName:"webgl",kernelFunc:w9},cN="if (isnan(x)) return x;",I9=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,S9=`
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;
`;function Ke({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 u=Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,l;return u?l=new Su(o.shape,t):l=new ya(o.shape,e),i.runWebGLProgram(l,[o],c)}}function an({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:o,backend:i})=>{let{a:c,b:u}=o,l=i;if(r&&c.dtype==="complex64"){let f=l.texData.get(c.dataId),m=l.texData.get(u.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(v=>{let[x,k]=v,C={dataId:x.dataId,dtype:x.dtype,shape:c.shape},N={dataId:k.dataId,dtype:k.dtype,shape:u.shape},F=new Cu(e,c.shape,u.shape);return l.runWebGLProgram(F,[C,N],yr(x.dtype,k.dtype))}),y=va({inputs:{real:g,imag:b},backend:l});return l.disposeIntermediateTensorInfo(g),l.disposeIntermediateTensorInfo(b),y}let d=a||yr(c.dtype,u.dtype);if((c.dtype==="string"||u.dtype==="string"||l.shouldExecuteOnCPU([c,u]))&&s!=null){let f=l.texData.get(c.dataId).values,m=l.texData.get(u.dataId).values,g=c.dtype==="string"?_.fromUint8ToStringArray(f):f,b=c.dtype==="string"?_.fromUint8ToStringArray(m):m,[y,v]=s(c.shape,u.shape,g,b,d),x=l.makeTensorInfo(v,d),k=l.texData.get(x.dataId);return k.values=y,x}let p=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new Nd(t,c.shape,u.shape,n):h=new Cu(e,c.shape,u.shape),l.runWebGLProgram(h,[c,u],d)}}function Zf(e,t=!1){if(e==="linear")return t?t9:Y7;if(e==="relu")return t?r9:J7;if(e==="elu")return t?n9:Z7;if(e==="relu6")return t?s9:Q7;if(e==="prelu")return t?iN:oN;if(e==="leakyrelu")return t?aN:sN;if(e==="sigmoid")return t?a9:e9;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var uN=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=pr(this.outputShape.length);let u=r?e[1]:e[2],l=Math.ceil(u/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) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
}`:c?m=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${o}
}`:m=`vec4 activation(vec4 x) {
${o}
}`,g="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let y="rc.x",v="rc.x";e[0]<t[0]?y=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(v=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
${m}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${l}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${l}; i++) {
int batchA = ${y};
int batchB = ${v};
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);
}
`}},lN={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},dN=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode=`
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));
}
`}},pN="return a * b;";function gw(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),u=new dN(lN.REAL,r.shape,s.shape),l=new dN(lN.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(u,d,"float32"),h=n.runWebGLProgram(l,d,"float32"),f=va({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),[u,l]=x7(r.shape,s.shape,i.values,c.values,a),d=n.makeTensorInfo(l,a),p=n.texData.get(d.dataId);return p.values=u,d}let o;return Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?o=new Nd(pN,r.shape,s.shape):o=new Cu(pN,r.shape,s.shape),n.runWebGLProgram(o,[r,s],a)}var C9={kernelName:co,backendName:"webgl",kernelFunc:gw};function T9(e,t,n){let r=[ai(e.shape),...oi(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[ai(t),...oi(t)],o=new Z2(a,r),i=!0,c=[r],u=n.runWebGLProgram(o,[s],e.dtype,c,i);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function me(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=n,i=w.sizeFromShape(s.shape),c=w.inferFromImplicitShape(a,i),u=w.sizeFromShape(c);w.assert(i===u,()=>`The new shape (${c}) has ${u} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let l=o.texData.get(s.dataId);return l.isPacked&&!Cd(s.shape,c)&&!(l.texture!==null&&Cd(l.shape,c))?T9(s,c,o):(o.incRef(s.dataId),{dataId:s.dataId,shape:c,dtype:s.dtype})}var N9={kernelName:Nc,backendName:"webgl",kernelFunc:me},hN=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o=Math.floor(n/4)*4,i=n%4,c="sumValue += dot(values, ones);";if(t!=null){let l=1/t;c=`sumValue += dot(values * ${w.isInt(l)?l.toPrecision(2):l}, ones);`}let u="";s%n>0&&(u=`
if (inIdx < 0 || inIdx >= ${s}) {
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) {
${u}
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-09-11 17:11:38 +02:00
${c}
}
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-09-11 17:11:38 +02:00
${c}
} 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-09-11 17:11:38 +02:00
${c}
} 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-09-11 17:11:38 +02:00
${c}
}
setOutput(sumValue);
}
`}},_9=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let c=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?c="sumValue":t==="prod"?c="prodValue":t==="all"?c="allValue":t==="any"&&(c="anyValue");let u=Math.floor(n/4)*4,l=n%4,d=`
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;
for (int i = 0; i < ${u}; i += 4) {
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-09-11 17:11:38 +02:00
int inIdx = inOffset + ${u};
if (${l===1}) {
${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}
} else if (${l===2}) {
${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}
} else if (${l===3}) {
${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}
}
setOutput(${c});
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}};function E9(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 ui(e,t,n,r){let s=E9(e.shape),a=e;for(let o=0;o<s.length;o++){let{inSize:i,windowSize:c,outSize:u}=s[o],l,d;n==="mean"?l=o===0?new hN({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u},i):new hN({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u}):l=new _9({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u},n),d=a,a=r.runWebGLProgram(l,[a],t),d.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(d)}return a}var A9=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=dt(this.rank),s=$9(t);this.userCode=`
void main() {
${r} resRC = getOutputCoords();
setOutput(getA(${s}));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}};function $9(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 F9=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let u=0;u<n.length;u++)n[u]=e[t[u]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let r=dt(this.rank),s=Y2("rc",this.rank),a=new Array(this.rank);for(let u=0;u<t.length;u++)a[t[u]]=s[u];let o=`vec2(${a.slice(-2).join()})`,i=`++${s[this.rank-1]} < ${n[this.rank-1]}`,c=`getChannel(getA(${a.join()}), ${o})`;this.userCode=`
void main() {
${r} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${c};
if(${i}) {
result[1] = ${c};
}
2021-09-11 17:11:38 +02:00
--${s[this.rank-1]};
if(++${s[this.rank-2]} < ${n[this.rank-2]}) {
result[2] = ${c};
if(${i}) {
result[3] = ${c};
}
}
2021-09-11 17:11:38 +02:00
setOutput(result);
}
2021-09-11 17:11:38 +02:00
`}};function Jf(e,t,n){let r=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new F9(e.shape,t):new A9(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function D9(e,t,n,r){let s=t,a=e.shape.length,o=w.parseAxisParam(s,e.shape),i=o,c=_.getAxesPermutation(i,a),u=c!=null,l=e;u&&(l=Jf(e,c,r),i=_.getInnerMostAxes(i.length,a)),_.assertAxesAreInnerMostDims("sum",i,a);let[d,p]=_.computeOutAndReduceShapes(l.shape,i),h=d;n&&(h=_.expandShapeToKeepDim(d,o));let f=w.sizeFromShape(p),g=w.sizeFromShape(e.shape)/f,b=me({inputs:{x:l},attrs:{shape:[g,f]},backend:r}),y=hh(e.dtype),v=ui(b,y,"sum",r),x=me({inputs:{x:v},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(v),u&&r.disposeIntermediateTensorInfo(l),x}function Qf(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return D9(s,a,o,n)}var R9={kernelName:Io,backendName:"webgl",kernelFunc:Qf};function Sn(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,o=n,i=s.shape.length,c=new Array(i);for(let l=0;l<c.length;l++)c[l]=s.shape[a[l]];let u;if(o.shouldExecuteOnCPU([s])){let d=o.texData.get(s.dataId).values,p=mw(d,s.shape,s.dtype,a,c);u=o.makeTensorInfo(c,s.dtype);let h=o.texData.get(u.dataId);h.values=p}else u=Jf(s,a,o);return u}var P9={kernelName:Eo,backendName:"webgl",kernelFunc:Sn},fN=1e3;function em({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:c=null}){let u=e.shape.length,l=t.shape.length,d=n?e.shape[u-2]:e.shape[u-1],p=r?t.shape[l-1]:t.shape[l-2],h=n?e.shape[u-1]:e.shape[u-2],f=r?t.shape[l-2]:t.shape[l-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=w.sizeFromShape(m),y=w.sizeFromShape(g),v=b===y||b===1||y===1;w.assert(u>=2&&l>=2&&v,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let k=(b>y?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);w.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 C=n?[b,d,h]:[b,h,d],N=r?[y,f,p]:[y,p,f],F=me({inputs:{x:e},backend:s,attrs:{shape:C}}),R=me({inputs:{x:t},backend:s,attrs:{shape:N}}),O=[F,R],$=Math.max(b,y),P=n?F.shape[1]:F.shape[2],T=a!=null,L=o!=null,G=c==="leakyrelu",j=c!=null?Zf(c,!0):null,q=T||L||G||j!=null,K;if((h===1||f===1)&&P>fN&&q===!1){let te=F,ne=R;n&&(te=Sn({inputs:{x:F},backend:s,attrs:{perm:[0,2,1]}}),O.push(te)),r&&(ne=Sn({inputs:{x:R},backend:s,attrs:{perm:[0,2,1]}}),O.push(ne));let re=f!==1,J=f===1,oe=te;re&&(oe=me({inputs:{x:te},backend:s,attrs:{shape:[$,P,1]}}),O.push(oe));let ie=f===1?2:1,ue=ne;J&&(ue=me({inputs:{x:ne},backend:s,attrs:{shape:[$,1,P]}}),O.push(ue));let fe=gw({inputs:{a:oe,b:ue},backend:s});K=Qf({inputs:{x:fe},backend:s,attrs:{axis:ie,keepDims:!0}}),O.push(fe)}else{let te=yr(e.dtype,t.dtype),ne=new uN(C,N,[$,h,f],n,r,T,j,L,G),re=[F,R];if(a!=null&&re.push(a),L&&re.push(o),G){let J=s.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));re.push(J),O.push(J)}K=s.runWebGLProgram(ne,re,te)}let ee=me({inputs:{x:K},backend:s,attrs:{shape:k}});O.push(K);for(let te of O)s.disposeIntermediateTensorInfo(te);return ee}function O9(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:c,transposeB:u,activation:l,leakyreluAlpha:d}=r;return em({a:s,b:a,transposeA:c,transposeB:u,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:l})}var M9={kernelName:Ao,backendName:"webgl",kernelFunc:O9},mN="return abs(x);";function L9(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=K2(a.values);return n.makeTensorInfo(r.shape,r.dtype,o)}let s;return Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Su(r.shape,mN):s=new ya(r.shape,mN),n.runWebGLProgram(s,[r],r.dtype)}var B9={kernelName:Vi,backendName:"webgl",kernelFunc:L9},z9=Ur+`
if (abs(x) > 1.) {
return NAN;
}
2021-09-11 17:11:38 +02:00
return acos(x);
`,W9=Ke({opSnippet:z9}),V9={kernelName:Ui,backendName:"webgl",kernelFunc:W9},U9=Ur+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,G9=Ke({opSnippet:U9}),H9={kernelName:Gi,backendName:"webgl",kernelFunc:G9},gN="return a + b;",j9=an({opSnippet:gN,packedOpSnippet:gN,supportsComplex:!0,cpuKernelImpl:t7}),q9={kernelName:Ks,backendName:"webgl",kernelFunc:j9},K9=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=`
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-09-11 17:11:38 +02:00
`}},X9=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=`
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-09-11 17:11:38 +02:00
`}};function tm(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return Zn({inputs:{x:r[0]},backend:n});if(r.length>Q().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),u=tm({inputs:r.slice(0,c),backend:n}),l=tm({inputs:r.slice(c),backend:n});return tm({inputs:[u,l],backend:n})}let s=r.map(c=>c.dtype).reduce((c,u)=>yr(c,u)),a=r.map(c=>c.shape),i=Q().getBool("WEBGL_PACK")?new X9(r[0].shape,a):new K9(r[0].shape,a);return n.runWebGLProgram(i,r,s)}var Y9={kernelName:Da,backendName:"webgl",kernelFunc:tm};function Z9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=_.getAxesPermutation(u,i),d=s;l!=null&&(d=Sn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=_.getInnerMostAxes(u.length,i)),_.assertAxesAreInnerMostDims("all",u,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,u),f=w.sizeFromShape(h),m=me({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=ui(m,m.dtype,"all",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=me({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=me({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(d),b}var J9={kernelName:Hi,backendName:"webgl",kernelFunc:Z9};function Q9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=_.getAxesPermutation(u,i),d=s;l!=null&&(d=Sn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=_.getInnerMostAxes(u.length,i)),_.assertAxesAreInnerMostDims("any",u,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,u),f=w.sizeFromShape(h),m=me({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=ui(m,m.dtype,"any",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=me({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=me({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(d),b}var eY={kernelName:ji,backendName:"webgl",kernelFunc:Q9},tY=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=`
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-09-11 17:11:38 +02:00
`}},nY=class{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,c=dt(i),u=In("coords",i),l,d;if(a===1){d=i+1;let N=dt(d);l=`
${N} sourceLocR = ${N}(${u.join()}, 0);
++${u[i-1]};
${N} sourceLocG = ${N}(${u.join()}, 0);
++${u[i-2]};
${N} sourceLocA = ${N}(${u.join()}, 0);
--${u[i-1]};
${N} sourceLocB = ${N}(${u.join()}, 0);
--${u[i-2]};`}else d=i,l=`
${c} sourceLocR = coords;
++${u[i-1]};
${c} sourceLocG = coords;
++${u[i-2]};
${c} sourceLocA = coords;
--${u[i-1]};
${c} sourceLocB = coords;
--${u[i-2]};`;let p=["x","y","z","w","u","v"].slice(0,d),h="."+p[d-1],f=p.map(N=>"int "+N),m=In("sourceLocR",d-1).concat("inIdx.r"),g=In("sourceLocG",d-1).concat("inIdx.g"),b=In("sourceLocB",d-1).concat("inIdx.b"),y=In("sourceLocA",d-1).concat("inIdx.a"),v=n==="max"?"greaterThan":"lessThan",x=r?"":`
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${b.join()}),
getBestIndicesAChannel(${y.join()})));`,k=`vec4(
getAChannel(${m.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${b.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${y.join()}) : 0.)`,C=r?"":`
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()}));
}
${C}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
${c} coords = getOutputCoords();
bool hasNextCol = ${u[i-1]} < ${o[i-1]-1};
bool hasNextRow = ${u[i-2]} < ${o[i-2]-1};
${l}
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
sourceLocB${h}, sourceLocA${h}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${k};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${x}
vec4 candidate = ${k};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${v}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(bestIndex);
}
`}};function bN(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 tY(i,n,r==null),u=[t];r!=null&&u.push(r);let l=e.runWebGLProgram(c,u,"int32");if(l.shape[1]===1)return l;let d=bN(e,t,n,l);return e.disposeIntermediateTensorInfo(l),d}function yN(e,t,n,r=null){let s=r!=null?r.shape:t.shape,a=s[s.length-1],o=_.computeOptimalWindowSize(a),i=new nY(s,o,n,r==null),c=r==null?[t]:[t,r],u=e.runWebGLProgram(i,c,"int32");if(u.shape.length===t.shape.length){let l=yN(e,t,n,u);return e.disposeIntermediateTensorInfo(u),l}return u}function vN(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[u,l]=_.computeOutAndReduceShapes(c.shape,s),d=w.sizeFromShape(l),p=me({inputs:{x:c},backend:e,attrs:{shape:[-1,d]}});a.push(p);let h=bN(e,p,r);a.push(h);let f=me({inputs:{x:h},backend:e,attrs:{shape:u}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return yN(e,t,r)}function rY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,u=[];i!=null&&(c=Sn({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMax",[o[0]],c.shape.length);let l=vN(n,c,o[0],"max");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),l}var sY={kernelName:Ra,backendName:"webgl",kernelFunc:rY};function aY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,u=[];i!=null&&(c=Sn({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);let l=vN(n,c,o[0],"min");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),l}var oY={kernelName:pl,backendName:"webgl",kernelFunc:aY},iY=Ur+`
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);
`,cY=Ke({opSnippet:iY}),uY={kernelName:qi,backendName:"webgl",kernelFunc:cY},lY=Ur+"return log(x + sqrt(x * x + 1.0));",dY=Ke({opSnippet:lY}),pY={kernelName:Ki,backendName:"webgl",kernelFunc:dY},hY=Ur+`
return atan(x);
`,fY=Ke({opSnippet:hY}),mY={kernelName:Xi,backendName:"webgl",kernelFunc:fY},gY=I9+`
return atan(a, b);
`,bY=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+S9+`
return result;
`,yY=an({opSnippet:gY,packedOpSnippet:bY}),vY={kernelName:Zi,backendName:"webgl",kernelFunc:yY},xY=Ur+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,wY=Ke({opSnippet:xY}),kY={kernelName:Yi,backendName:"webgl",kernelFunc:wY},_d=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,c=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterHeight,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 N=">=";this.userCode=`
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-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${l};
wR += ${c}) {
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};
wC += ${u}) {
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);
if (value ${N} currMinMaxValue) {
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-09-11 17:11:38 +02:00
`;return}let y="max",v=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(v="avgValue / count");let x=Math.floor(a/4)*4,k=a%4,C=`
if (${f}) {
avgValue += dot(values, ones);
2021-04-01 19:39:54 +02:00
} else {
2021-09-11 17:11:38 +02: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;
for (int wR = 0; wR < ${l};
wR += ${c}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${x}; wC += 4) {
int xC = xCCorner + wC * ${u};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
getValue(batch, xR, xC + 2 * ${u}, d),
getValue(batch, xR, xC + 3 * ${u}, d)
);
${C}
}
int xC = xCCorner + ${x};
if (${k===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${C}
} else if (${k===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
initializationValue,
initializationValue
);
${C}
} else if (${k===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
getValue(batch, xR, xC + 2 * ${u}, d),
initializationValue
);
${C}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput(${v});
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}},bw=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,c=e.strideWidth,u=e.dilationDepth,l=e.dilationHeight,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 R=">=";this.userCode=`
const ivec3 strides =
ivec3(${o}, ${i}, ${c});
const ivec3 pads = ivec3(${m}, ${g}, ${b});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wD = 0; wD < ${p};
wD += ${u}) {
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};
wR += ${l}) {
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);
if (value ${R} currMinMaxValue) {
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-09-11 17:11:38 +02:00
`;return}let x="max",k=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(k="avgValue / count");let C=Math.floor(a/4)*4,N=a%4,F=`
if (${y}) {
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 =
ivec3(${o}, ${i}, ${c});
const ivec3 pads = ivec3(${m}, ${g}, ${b});
const float initializationValue = ${v};
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
vec4 minMaxValue = vec4(${v});
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};
wD += ${u}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${h};
wR += ${l}) {
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
for (int wC = 0; wC < ${C}; wC += 4) {
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)
);
${F}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
int xC = xCCorner + ${C};
if (${N===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${F}
} else if (${N===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
initializationValue,
initializationValue
);
${F}
} else if (${N===3}) {
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-09-11 17:11:38 +02:00
${F}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput(${k});
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
`}};function IY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;vu(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,u=1;w.assert(_.eitherStridesOrDilationsAreOne(o,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let l=_.computePool2DInfo(s.shape,a,o,u,i,c);if(l.filterWidth===1&&l.filterHeight===1&&w.arraysEqual(l.inShape,l.outShape))return Zn({inputs:{x:s},backend:n});let d=new _d(l,"avg",!1);return n.runWebGLProgram(d,[s],"float32")}var SY={kernelName:Pa,backendName:"webgl",kernelFunc:IY};function CY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:u}=r,l=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,l,i,c,u),p=new bw(d,"avg",!1);return n.runWebGLProgram(p,[s],"float32")}var TY={kernelName:hl,backendName:"webgl",kernelFunc:CY},NY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=i-1-e.padInfo.top,l=c-1-e.padInfo.left,d=1/(t*n);this.userCode=`
const ivec2 pads = ivec2(${u}, ${l});
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-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${c};
wC+= ${o}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier;
2021-04-01 19:39:54 +02:00
}
}
setOutput(dotProd);
}
2021-09-11 17:11:38 +02:00
`}},_Y=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=l-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`
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-09-11 17:11:38 +02:00
for (int wD = 0; wD < ${l};
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
int idyD = int(dyD);
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${d};
wR += ${c}) {
float dyR = float(dyRCorner + wR) / ${a}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p};
wC += ${u}) {
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-09-11 17:11:38 +02:00
`}};function EY(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:u,dimRoundingMode:l}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,u,l),h=new _Y(p);return n.runWebGLProgram(h,[s],o.dtype)}var AY={kernelName:Cp,backendName:"webgl",kernelFunc:EY};function $Y(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;vu([s,a],"avgPoolGrad");let{filterSize:i,strides:c,pad:u}=r,l=_.computePool2DInfo(o.shape,i,c,1,u),d=new NY(l);return n.runWebGLProgram(d,[s],o.dtype)}var FY={kernelName:Sp,backendName:"webgl",kernelFunc:$Y};function DY(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return em({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var RY={kernelName:Oa,backendName:"webgl",kernelFunc:DY},PY=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-09-11 17:11:38 +02:00
`}},OY=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);
}
`}},MY=({inputs:e,backend:t,attrs:n})=>{let{x:r,mean:s,variance:a,offset:o,scale:i}=e;w.assert(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(o==null||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(i==null||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:c}=n;c==null&&(c=.001);let u=[r,s,a],l=null;o!=null&&(l=o.shape,u.push(o));let d=null;i!=null&&(d=i.shape,u.push(i));let p=Q().getBool("WEBGL_PACK_NORMALIZATION")?new OY(r.shape,s.shape,a.shape,l,d,c):new PY(r.shape,s.shape,a.shape,l,d,c);return t.runWebGLProgram(p,u,u[0].dtype)},LY={kernelName:Ya,backendName:"webgl",kernelFunc:MY},BY=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=dt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=zY(this.rank),r,s=e.map((a,o)=>`sourceLoc.${yw[o]} = start[${o}] + coords.${yw[o]};`);r=`
${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}));
}
`}},yw=["x","y","z","w","u","v"];function zY(e){if(e===1)return"sourceLoc";if(e<=6)return yw.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var WY=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=dt(this.rank),n=In("coords",this.rank),r=In("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,o=`
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};
}
}
`,c=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((u,l)=>`start[${l}]`).join()});`:e.map((u,l)=>`${r[l]} = ${n[l]} + start[${l}];`).join(`
`);this.userCode=`
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${c}
vec4 result = vec4(0.);
${o}
${i}
setOutput(result);
}
`}};function VY(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=mn.computeFlatOffset(t,w.computeStrides(e.shape));s.slice&&(i+=s.slice.flatOffset),o.slice={flatOffset:i,origDataId:s.slice&&s.slice.origDataId||e.dataId};let c=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,c+1),a}function Tu(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,c]=mn.parseSliceParams(s,a,o);if(mn.assertParamsValid(s,i,c),w.sizeFromShape(c)===0)return n.makeTensorInfo(c,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||s.dtype==="string"){let d=n.texData.get(s.dataId),p=N7(d.values,i,c,s.shape,s.dtype);return n.makeTensorInfo(c,s.dtype,p)}let{isPacked:u}=n.texData.get(s.dataId),l=mn.isSliceContinous(s.shape,i,c);if(u||!l){let d=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new WY(c):new BY(c),p=[i];return n.runWebGLProgram(d,[s],s.dtype,p)}return n.uploadToGPU(s.dataId),VY(s,i,c,n)}var UY={kernelName:$c,backendName:"webgl",kernelFunc:Tu},GY=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;w.assert(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,v)=>y*v),c=_.getReshaped(s.shape,a,i),u=_.getPermuted(c.length,a.length),l=_.getReshapedPermuted(s.shape,a,i),d=_.getSliceBeginCoords(o,a.length),p=_.getSliceSize(l,o,a.length),h=[],f=me({inputs:{x:s},backend:n,attrs:{shape:c}}),m=Sn({inputs:{x:f},backend:n,attrs:{perm:u}}),g=me({inputs:{x:m},backend:n,attrs:{shape:l}}),b=Tu({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},HY={kernelName:Ji,backendName:"webgl",kernelFunc:GY};function jY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.readSync(s.dataId),c=n.readSync(a.dataId),u=q2(i,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}var qY={kernelName:Tp,backendName:"webgl",kernelFunc:jY},KY="return float(a != b);",xN=an({opSnippet:KY,cpuKernelImpl:k7,dtype:"bool"}),XY={kernelName:vc,backendName:"webgl",kernelFunc:xN};function Ed(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return Zn({inputs:{x:s.complexTensorInfos.real},backend:n})}var YY={kernelName:Kp,backendName:"webgl",kernelFunc:Ed},ZY="return float(int(x));";function JY(e,t){let n=new ya(e.shape,ZY),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function vw(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return Zn({inputs:{x:s},backend:n});let o=wt(s.shape),i=vw({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),c=va({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),c}if(s.dtype==="complex64"){let o=Ed({inputs:{input:s},backend:n}),i=vw({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=Zn({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return JY(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),c=xN({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 QY={kernelName:Ma,backendName:"webgl",kernelFunc:vw},wN="return ceil(x);",eZ=Ke({opSnippet:wN,packedOpSnippet:wN,cpuKernelImpl:r7}),tZ={kernelName:La,backendName:"webgl",kernelFunc:eZ},nZ=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));
}
`}},rZ=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=`
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)));
}
`}};function sZ(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 rZ(s.shape):i=new nZ(s.shape);let c=[[a],[o]];return n.runWebGLProgram(i,[s],s.dtype,c)}var aZ={kernelName:Xs,backendName:"webgl",kernelFunc:sZ},oZ=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
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))
);
}
`}};function kN(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function iZ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new oZ(r.shape),o=[kN(r,s.complexTensorInfos.real),kN(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var cZ={kernelName:fl,backendName:"webgl",kernelFunc:iZ},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=`
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-09-11 17:11:38 +02:00
`}},lZ=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=dt(r),a=In("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((f,m)=>`T${m}`);let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let c=o[t],u=o.slice(-2),l=o.join(),d=`if (${c} < ${i[0]}) {
return getChannel(
getT0(${l}), vec2(${u.join()}));
}`;for(let f=1;f<i.length;f++){let m=i[f-1];d+=`
if (${c} < ${i[f]} && ${c} >= ${i[f-1]}) {
return getChannel(
getT${f}(${nm(o,c,m)}),
vec2(${nm(u,c,m)}));
}`}let p=i.length,h=i[i.length-1];d+=`
return getChannel(
getT${p}(${nm(o,c,h)}),
vec2(${nm(u,c,h)}));`,this.userCode=`
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-09-11 17:11:38 +02:00
`}};function nm(e,t,n){let r=e.indexOf(t);return e.map((a,o)=>o===r?`${a} - ${n}`:a).join()}function rm(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return Zn({inputs:{x:s.complexTensorInfos.imag},backend:n})}var dZ={kernelName:Wp,backendName:"webgl",kernelFunc:rm};function Nu(e,t,n){let r=e[0].dtype;if(r==="complex64"){let l=e.map(m=>Ed({inputs:{input:m},backend:n})),d=e.map(m=>rm({inputs:{input:m},backend:n})),p=Nu(l,t,n),h=Nu(d,t,n),f=va({inputs:{real:p,imag:h},backend:n});return l.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 l=e.map(b=>{let y=w.sizeFromShape(b.shape.slice(t));return me({inputs:{x:b},backend:n,attrs:{shape:[-1,y]}})}),d=l.map(b=>({vals:n.readSync(b.dataId),shape:b.shape})),p=_.computeOutShape(l.map(b=>b.shape),1),h=l[0].shape[0]===1,f=s7(d,p,r,h),m=_.computeOutShape(e.map(b=>b.shape),t),g=n.makeTensorInfo(m,r,f);return l.forEach(b=>n.disposeIntermediateTensorInfo(b)),g}if(e.length>Q().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(e.length/2),d=Nu(e.slice(0,l),t,n),p=Nu(e.slice(l),t,n),h=Nu([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 l=new lZ(e.map(d=>d.shape),t);return n.runWebGLProgram(l,e,r)}let{tensors2D:a,outShape:o}=pZ(e,t,n),i=new uZ(a.map(l=>l.shape)),c=n.runWebGLProgram(i,a,r);a.forEach(l=>n.disposeIntermediateTensorInfo(l));let u=me({inputs:{x:c},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(c),u}function pZ(e,t,n){let r=_.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>me({inputs:{x:a},attrs:{shape:[-1,w.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:r}}function IN(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=_.computeOutShape(t.map(u=>u.shape),a);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(u=>w.sizeFromShape(u.shape)>0);if(i.length===1)return Zn({inputs:{x:i[0]},backend:n});let c=i.map(u=>u.shape);return _.assertParamsConsistent(c,a),Nu(i,a,n)}var hZ={kernelName:Qi,backendName:"webgl",kernelFunc:IN},SN=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,c=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,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) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?v=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}`:v=`
float activation(float x) {
${n}
}
`,x="result = activation(result);");let k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${v}
const ivec2 strides = ivec2(${i}, ${c});
const ivec2 pads = ivec2(${a}, ${o});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int batch = coords[0];
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++) {
int xR = xRCorner + wR * ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p}; wC++) {
int xC = xCCorner + wC * ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
2021-04-01 19:39:54 +02:00
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;
${k}
${x}
setOutput(result);
}
`}},fZ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,l=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${s}, ${a}, ${o});
const ivec3 pads = ivec3(${t}, ${n}, ${r});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${l}; wF++) {
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++) {
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++) {
int xC = xCCorner + wC * ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
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-09-11 17:11:38 +02:00
`}},mZ=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=pr(this.outputShape.length);let{dataFormat:n}=t,r=kn(),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 u=0;u<=1;u++)for(let l=0;l<=1;l++)c+=`
blockIndex = rc.y + ${l};
pos = rc.x + ${u};
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);
result[${u*2+l}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${u*2+l}] = getChannel(
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-09-11 17:11:38 +02: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-09-11 17:11:38 +02:00
`}};function CN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let c=e.shape,u=r.texData.get(e.dataId),l=n.inChannels,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)&&l>fN)&&u.isPacked&&h&&u.texture!=null&&c[2]%2!=0&&w.arraysEqual(u.shape.slice(-3),c.slice(-3))){let x=c[0]*c[1]*(c[2]+1),k={dataId:e.dataId,shape:[1,x,n.inChannels],dtype:e.dtype},C=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,w.assert(Cd(u.shape,k.shape),()=>`packed reshape ${u.shape} to ${k.shape} isn't free`);let N=me({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(N);let F=em({a:k,b:N,backend:r,transposeA:f,transposeB:m,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),R=r.texData.get(F.dataId);w.assert(R.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=C,R.shape=n.outShape,g=Zn({inputs:{x:F},backend:r}),g.shape=n.outShape,b.push(F)}else{let x=h?c[0]*c[1]*c[2]:c[0]*c[2]*c[3],k=me({inputs:{x:e},backend:r,attrs:{shape:[1,x,n.inChannels]}}),C=me({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),N=em({a:k,b:C,transposeA:f,transposeB:m,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=me({inputs:{x:N},backend:r,attrs:{shape:n.outShape}}),b.push(k),b.push(C),b.push(N)}for(let x of b)r.disposeIntermediateTensorInfo(x);return g}function TN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:c,filterHeight:u,inChannels:l,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=c*u*l,g=p*d,b=[m,g],y=!0,v=!1,x=[],k=me({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),C=me({inputs:{x:t},backend:r,attrs:{shape:[1,m,w.sizeFromShape(t.shape)/m]}});x.push(k),x.push(C);let N=new mZ(b,n),F=[k.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],R=r.runWebGLProgram(N,[k],"float32",F),O=me({inputs:{x:R},backend:r,attrs:{shape:[1,b[0],b[1]]}});x.push(R),x.push(O);let $=s!=null,P=a!=null,T=i==="leakyrelu",L=i?Zf(i,!0):null,G=new uN(O.shape,C.shape,[1,g,n.outChannels],y,v,$,L,P,T),j=[O,C];if(s&&j.push(s),P&&j.push(a),T){let te=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));j.push(te),x.push(te)}let q=r.runWebGLProgram(G,j,"float32"),K=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],ee=me({inputs:{x:q},backend:r,attrs:{shape:K}});x.push(q);for(let te of x)r.disposeIntermediateTensorInfo(te);return ee}function gZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:c,dilations:u,dimRoundingMode:l}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,a.shape,o,u,i,l,!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=CN({x:s,filter:a,convInfo:p,backend:n});else if(Q().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)h=TN({x:s,filter:a,convInfo:p,backend:n});else{let m=new SN(p);h=n.runWebGLProgram(m,[s,a],"float32")}let f=me({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var bZ={kernelName:Ba,backendName:"webgl",kernelFunc:gZ},yZ=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);
}
`}},vZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,c=a?1:2,u=a?2:3,l=a?3:1;this.userCode=`
const ivec2 pads = ivec2(${o}, ${i});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${l}];
ivec2 dyCorner = ivec2(coords[${c}], coords[${u}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${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-09-11 17:11:38 +02:00
`}},xZ=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=`
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-09-11 17:11:38 +02:00
`}},wZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,c=n-1-e.padInfo.top,u=r-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${i}, ${c}, ${u});
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-09-11 17:11:38 +02:00
`}};function kZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:c,dimRoundingMode:u,filterShape:l}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,l,o,1,i,u,!1,d),h=new yZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var IZ={kernelName:_p,backendName:"webgl",kernelFunc:kZ};function SZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:c,dataFormat:u,dimRoundingMode:l}=r,d=_.convertConv2DDataFormat(u),p=_.computeConv2DInfo(o,a.shape,i,1,c,l,!1,d),h=new vZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var CZ={kernelName:za,backendName:"webgl",kernelFunc:SZ};function TZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,u=_.computeConv3DInfo(s.shape,a.shape,o,c,i),l=new fZ(u);return n.runWebGLProgram(l,[s,a],"float32")}var NZ={kernelName:ml,backendName:"webgl",kernelFunc:TZ};function _Z(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:c}=r,u=_.computeConv3DInfo(s.shape,c,o,1,i),l=new xZ(u);return n.runWebGLProgram(l,[s,a],"float32")}var EZ={kernelName:Ep,backendName:"webgl",kernelFunc:_Z};function AZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:c}=r,u=_.computeConv3DInfo(c,a.shape,i,1,o),l=new wZ(u);return n.runWebGLProgram(l,[s,a],"float32")}var $Z={kernelName:Ap,backendName:"webgl",kernelFunc:AZ},FZ=cN+`
return cos(x);
`,DZ=Ke({opSnippet:FZ}),RZ={kernelName:Wa,backendName:"webgl",kernelFunc:DZ},PZ=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,OZ=Ke({opSnippet:PZ}),MZ={kernelName:Va,backendName:"webgl",kernelFunc:OZ},LZ=class{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,c]=e,[u]=t,[l,d]=n;this.outputShape=[u,l,d,c];let p=r==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,b]=l>1?[`${(o-1)/(l-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[y,v,x]=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=`
const float height_ratio = float(${m});
const float width_ratio = float(${y});
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
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};
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-09-11 17:11:38 +02:00
`}},BZ=e=>{let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:c,extrapolationValue:u}=r,l=new LZ(s.shape,a.shape,i,c,u);return n.runWebGLProgram(l,[s,a,o],"float32")},zZ={kernelName:ec,backendName:"webgl",kernelFunc:BZ},NN=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(${_N(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-09-11 17:11:38 +02:00
${dt(r)} coords = getOutputCoords();
int end = ${EN(r,"coords")};
float val = ${s};
int pow2 = int(pow(2.0, index));
if (${o}) {
int idx = ${i};
${EN(r,"coords")} = idx;
val += getX(${_N(r,"coords")});
}
setOutput(val);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}};function _N(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 EN(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 WZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,c=s.shape.length,u=_.getAxesPermutation([a],c),l=s;u!=null&&(l=Sn({inputs:{x:s},backend:n,attrs:{perm:u}}));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=l.shape[d],h=Zn({inputs:{x:l},backend:n});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new NN(l.shape,!1,i),g=[[f]],b=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(b)}if(o){let f=new NN(l.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(u!=null){let f=_.getUndoAxesPermutation(u),m=Sn({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(l),m}return h}var VZ={kernelName:Ua,backendName:"webgl",kernelFunc:WZ};function UZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let c=n.readSync(s.dataId),u=n.readSync(a.dataId),l=q2(c,u,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,l)}else if(s.shape.length===2){let c=n.bufferSync(s),u=n.bufferSync(a),l=n7(c,u,o,i);return n.makeTensorInfo(l.shape,a.dtype,l.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}var GZ={kernelName:$p,backendName:"webgl",kernelFunc:UZ},HZ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${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-09-11 17:11:38 +02: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 jZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r;w.assert(a>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${a}`);let i=s.shape[0],c=o==="NHWC"?s.shape[1]:s.shape[2],u=o==="NHWC"?s.shape[2]:s.shape[3],l=o==="NHWC"?s.shape[3]:s.shape[1],d=c*a,p=u*a,h=l/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=new HZ(f,a,o);return n.runWebGLProgram(m,[s],s.dtype)}var qZ={kernelName:tc,backendName:"webgl",kernelFunc:jZ},AN=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=pr(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,c="",u="";n&&(r?c=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?c=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}`:c=`
float activation(float x) {
${n}
}
`,u="result = activation(result);");let l=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${c}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
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;
${l}
${u}
setOutput(result);
}
`}},$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=pr(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,c=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,d=l,p=`
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<l;g++)p+=`
vec4 xTexelC${g*2};
int xTexelC${g*2}Ready;
vec4 xTexelC${g*2+1};
int xTexelC${g*2+1}Ready;
vec4 xC${g};`;for(let g=0;g<u;g++){for(let b=0;b<l;b++)p+=`
xTexelC${b*2} = vec4(0.0);
xTexelC${b*2}Ready = 0;
xTexelC${b*2+1} = vec4(0.0);
xTexelC${b*2+1}Ready = 0;
xC${b} = vec4(0.0);`;p+=`
xR = xRCorner + ${g} * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;for(let b=0;b<(d+1)/2;b++){let y=b*2;if(p+=`
xC = xCCorner + ${y*c};
`,i===1){if(y<l&&(o%2==1?(p+=`
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = 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]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
`,c===1&&y>0?p+=`
xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy);
`: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-09-11 17:11:38 +02:00
xC${y} = vec4(previous.zw, xTexelC${y}.xy);
2021-04-01 19:39:54 +02:00
} else {
2021-09-11 17:11:38 +02:00
xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);
}
`):p+=`
if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
xC${y} = xTexelC${y};
`,y+1<l)){let v=o%2==0?w.nearestLargerEven(c):c;c%2==0&&o%2==1||c%2!=0&&o%2!=1?(p+=`
xCOffset = xC + imod(pads[1], 2) + ${v};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xTexelC${y+1}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`,c>1&&(p+=`
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
xTexelC${y}Ready = 1;
}
`),p+=`
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);
`):v===1?p+=`
xC${y+1} = xTexelC${y};
`:p+=`
xCOffset = xC + ${v};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
}
xTexelC${y+1}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xC${y+1} = xTexelC${y+1};
`}}else y<l&&(o%2==1?(p+=`
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xTexelC${y}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xC + 1, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xTexelC${y+1}Ready = 1;
}
xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
`,y+1<l&&(p+=`
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy);
`)):(p+=`
if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xTexelC${y}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.);
}
xTexelC${y+1}Ready = 1;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
xC${y} = vec4(
xTexelC${y}.xy, xTexelC${y+1}.xy);
`,y+1<l&&(p+=`
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
`)));y<l&&(p+=`
wTexel = getW(${g}, ${y}, d1, q);
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
`,y+1<l&&(p+=`
wTexel = getW(${g}, ${y+1}, d1, q);
dotProd += xC${y+1} * vec4(wTexel.xz, wTexel.xz);
`))}p+=`
}
`}let h="",f="";n&&(r?h=`vec4 activation(vec4 a) {
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-09-11 17:11:38 +02:00
`}};function KZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c,dimRoundingMode:u}=r,l=c;l==null&&(l=[1,1]),w.assert(_.eitherStridesOrDilationsAreOne(o,l),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let d=_.computeConv2DInfo(s.shape,a.shape,o,l,i,u,!0),p;Q().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels==1?p=new $N(d):p=new AN(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 XZ={kernelName:Ga,backendName:"webgl",kernelFunc:KZ},YZ=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=`
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-09-11 17:11:38 +02:00
`}},ZZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${a}, ${o});
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
int batch = coords[0];
2021-09-11 17:11:38 +02:00
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${t}; wR++) {
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);
}
`}};function JZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:u,filterShape:l}=r,d=_.computeConv2DInfo(s.shape,l,o,i,c,u,!0),p=new YZ(d);return n.runWebGLProgram(p,[s,a],"float32")}var QZ={kernelName:Fp,backendName:"webgl",kernelFunc:JZ};function eJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:u,inputShape:l}=r,d=_.computeConv2DInfo(l,a.shape,o,i,c,u,!0),p=new ZZ(d);return n.runWebGLProgram(p,[s,a],"float32")}var tJ={kernelName:Dp,backendName:"webgl",kernelFunc:eJ},nJ=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`}};function rJ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=w.sizeFromShape(r.shape),o=me({inputs:{x:r},backend:n,attrs:{shape:[a]}}),i=new nJ(a),c=n.runWebGLProgram(i,[o],o.dtype),u=me({inputs:{x:c},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),u}var sJ={kernelName:Rp,backendName:"webgl",kernelFunc:rJ},aJ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:c,dilationWidth:u}=e,{top:l,left:d}=r;this.userCode=`
const ivec2 strides = ivec2(${s}, ${a});
const ivec2 pads = ivec2(${l}, ${d});
const float neg_infinity = -3.4e38;
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++) {
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++) {
int wIn = wBeg + w * ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (wIn >= 0 && wIn < ${n}) {
float xVal = getX(batch, hIn, wIn, d1);
float wVal = getW(h, w, d1);
float val = xVal + wVal;
if (val > curVal) {
curVal = val;
}
}
}
}
2021-07-29 15:05:49 +02:00
}
2021-09-11 17:11:38 +02:00
float result = curVal;
setOutput(result);
2021-07-29 15:05:49 +02:00
}
2021-09-11 17:11:38 +02:00
`}};function oJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,u=_.computeDilation2DInfo(s.shape,a.shape,o,i,"NHWC",c),l,d=new aJ(u);l=n.runWebGLProgram(d,[s,a],"float32");let p=me({inputs:{x:l},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(l),p}var iJ={kernelName:gl,backendName:"webgl",kernelFunc:oJ};function cJ(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:u,steps:l}=_.getEinsumComputePath(i,c),d=l.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of l[m]){let{permutationIndices:b,expandDims:y}=_.getEinsumPermutation(h,c[g]),v;_.isIdentityPermutation(b)?v=a[g]:(v=Sn({inputs:{x:a[g]},backend:n,attrs:{perm:b}}),f.push(v));let x=v.shape.slice();for(let k=0;k<y.length;++k)x.splice(y[k],0,1);w.arraysEqual(v.shape,x)||(v=me({inputs:{x:v},backend:n,attrs:{shape:x}}),f.push(v)),p===null?p=v:(p=gw({inputs:{a:v,b:p},backend:n}),f.push(p))}m<d-1&&(u[m]>=0&&(p=Qf({inputs:{x:p},backend:n,attrs:{axis:u[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:Mp,backendName:"webgl",kernelFunc:cJ},lJ="return (x >= 0.0) ? x : (exp(x) - 1.0);",dJ=`
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;
`,pJ=Ke({opSnippet:lJ,packedOpSnippet:dJ}),hJ={kernelName:ja,backendName:"webgl",kernelFunc:pJ},fJ="return (b >= 1.0) ? a : a * (b + 1.0);",mJ=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,gJ=e=>{let{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Nd(mJ,r.shape,s.shape):new Cu(fJ,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)},bJ={kernelName:Lp,backendName:"webgl",kernelFunc:gJ},yJ=`
return vec4(equal(a, b));
`,vJ="return float(a == b);",xJ=an({opSnippet:vJ,packedOpSnippet:yJ,dtype:"bool",cpuKernelImpl:a7}),wJ={kernelName:rc,backendName:"webgl",kernelFunc:xJ},kJ=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${_.ERF_P};
float a1 = ${_.ERF_A1};
float a2 = ${_.ERF_A2};
float a3 = ${_.ERF_A3};
float a4 = ${_.ERF_A4};
float a5 = ${_.ERF_A5};
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));
`,IJ=Ke({opSnippet:kJ}),SJ={kernelName:nc,backendName:"webgl",kernelFunc:IJ},FN="return exp(x);",DN=Ke({opSnippet:FN,packedOpSnippet:FN,cpuKernelImpl:o7}),CJ={kernelName:qa,backendName:"webgl",kernelFunc:DN};function xw(e){let{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),c=s;return s<0&&(w.assert(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),c=o+s+1),i.splice(c,0,1),me({inputs:{x:a},backend:r,attrs:{shape:i}})}var TJ={kernelName:sc,backendName:"webgl",kernelFunc:xw},RN="return exp(x) - 1.0;",NJ=Ke({opSnippet:RN,packedOpSnippet:RN,cpuKernelImpl:i7}),_J={kernelName:ac,backendName:"webgl",kernelFunc:NJ},PN=class{constructor(e,t,n){this.variableNames=["real","imag"];let r=t[1];this.outputShape=t;let s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${r}.0`:"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
const float exponentMultiplier = ${s};
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-09-11 17:11:38 +02:00
`}};function ON(e,t,n){let r=n.texData.get(e.dataId),s=w.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=s/a,i=me({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),c=i.shape,u=new PN("real",c,t),l=new PN("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(u,d,"float32"),h=n.runWebGLProgram(l,d,"float32"),f=va({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);let m=me({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function EJ(e){let{inputs:t,backend:n}=e,{input:r}=t;return ON(r,!1,n)}var AJ={kernelName:Bp,backendName:"webgl",kernelFunc:EJ},$J=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
void main() {
// Input can be obtained from uniform value.
setOutput(value);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}};function Ad(e){let{backend:t,attrs:n}=e,{shape:r,value:s}=n,{dtype:a}=n;if(a=a||w.inferDtype(s),a==="string"){let o=w.getArrayFromDType(a,w.sizeFromShape(r));return o.fill(s),t.makeTensorInfo(r,a,o)}else{let o=new $J(r,s),i=[[s]];return t.runWebGLProgram(o,[],a,i)}}var FJ={kernelName:bl,backendName:"webgl",kernelFunc:Ad},DJ=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=`
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);
}
`}},RJ={kernelName:oc,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new DJ(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},MN="return floor(x);",PJ=Ke({opSnippet:MN,packedOpSnippet:MN,cpuKernelImpl:c7}),OJ={kernelName:Ka,backendName:"webgl",kernelFunc:PJ},MJ=`
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-09-11 17:11:38 +02:00
`,LJ=`
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);
`,BJ=an({opSnippet:MJ,packedOpSnippet:LJ,dtype:"int32"}),zJ={kernelName:Xa,backendName:"webgl",kernelFunc:BJ},WJ=class{constructor(e){this.variableNames=["A"];let t=kn(),[n,r]=e;this.outputShape=e,this.userCode=`
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-09-11 17:11:38 +02:00
`}},VJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=kn(),[n,r]=e;this.outputShape=e,this.userCode=`
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-09-11 17:11:38 +02:00
`}},UJ={kernelName:oh,backendName:"webgl",kernelFunc:GJ},_u;function GJ(e){let{inputs:t,backend:n,attrs:r}=e,{pixels:s}=t,{numChannels:a}=r,o=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,[c,u]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],l=[u,c],d=[u,c,a];(i||o)&&(_u==null&&(_u=document.createElement("canvas").getContext("2d")),_u.canvas.width=c,_u.canvas.height=u,_u.drawImage(s,0,0,c,u),s=_u.canvas);let p=n.makeTensorInfo(l,"int32");n.texData.get(p.dataId).usage=lr.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),s);let h=Q().getBool("WEBGL_PACK")?new VJ(d):new WJ(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function HJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:u,dataFormat:l,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=_.convertConv2DDataFormat(l),g=_.computeConv2DInfo(s.shape,a.shape,c,d,u,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=CN({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=TN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let x=o!=null,k=i!=null,C=h==="leakyrelu",N=h?Zf(h,!1):null,F=new SN(g,x,N,k,C),R=[s,a];if(o&&R.push(o),i&&R.push(i),C){let O=n.makeTensorInfo([],"float32",w.createScalarValue(f,"float32"));R.push(O),y.push(O)}b=n.runWebGLProgram(F,R,"float32")}let v=me({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return y.push(b),y.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var jJ={kernelName:$o,backendName:"webgl",kernelFunc:HJ};function qJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:u,dilations:l,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=r,f=[],m=l;m==null&&(m=[1,1]),w.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,u,d,!0),b=Q().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,y=p?Zf(p,b):null,v=[s,a],x=o!=null,k=i!=null,C=p==="leakyrelu";if(x&&v.push(o),k&&v.push(i),C){let O=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));v.push(O),f.push(O)}let N;b?N=new $N(g,x,y,k,C):N=new AN(g,x,y,k,C);let F=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],R=n.runWebGLProgram(N,v,"float32",F);return f.forEach(O=>n.disposeIntermediateTensorInfo(O)),R}var KJ={kernelName:Fo,backendName:"webgl",kernelFunc:qJ},XJ=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let r=dt(t.length),s=dt(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${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-09-11 17:11:38 +02:00
`}};function YJ(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,o=a[a.length-1],i=w.sizeFromShape(r.shape),[c,u,l,d]=_.prepareAndValidate(r,s),p=me({inputs:{x:s},backend:n,attrs:{shape:[u,o]}}),h=me({inputs:{x:r},backend:n,attrs:{shape:[w.sizeFromShape(r.shape)/l,l]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.readSync(s.dataId),y=n.bufferSync(r),v=u7(b,y,r.dtype,u,o,l,d,r.shape,i);return n.makeTensorInfo(c,r.dtype,v.values)}let f=new XJ(o,d,[u,l]),m=n.runWebGLProgram(f,[h,p],h.dtype),g=me({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var ZJ={kernelName:cc,backendName:"webgl",kernelFunc:YJ},JJ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=dt(this.rank),r=QJ(e,2);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`}};function QJ(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 LN(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,c=w.parseAxisParam(o,s.shape)[0],u=_.segment_util.collectGatherOpShapeInfo(s,a,c,i),l=w.sizeFromShape(a.shape),d=[],p=me({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=me({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,l/u.batchSize]}});d.push(p),d.push(h);let f=[u.batchSize,u.outerSize,l/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([s,a])||s.dtype==="string"){let y=n.bufferSync(h),v=n.bufferSync(p),x=l7(v,y,f);return d.forEach(k=>n.disposeIntermediateTensorInfo(k)),n.makeTensorInfo(u.outputShape,x.dtype,x.values)}let m=new JJ(p.shape,f),g=n.runWebGLProgram(m,[p,h],p.dtype);d.push(g);let b=me({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return d.forEach(y=>n.disposeIntermediateTensorInfo(y)),b}var eQ={kernelName:ic,backendName:"webgl",kernelFunc:LN},tQ="return float(a > b);",nQ=`
return vec4(greaterThan(a, b));
`,rQ=an({opSnippet:tQ,packedOpSnippet:nQ,cpuKernelImpl:d7,dtype:"bool"}),sQ={kernelName:uc,backendName:"webgl",kernelFunc:rQ},aQ="return float(a >= b);",oQ=`
return vec4(greaterThanEqual(a, b));
`,iQ=an({opSnippet:aQ,packedOpSnippet:oQ,dtype:"bool",cpuKernelImpl:p7}),cQ={kernelName:Za,backendName:"webgl",kernelFunc:iQ};function uQ(e){let{inputs:t,backend:n}=e,{input:r}=t;return ON(r,!0,n)}var lQ={kernelName:zp,backendName:"webgl",kernelFunc:uQ},dQ="return float(!isnan(x) && !isinf(x));",pQ=Ke({opSnippet:dQ,dtype:"bool"}),hQ={kernelName:lc,backendName:"webgl",kernelFunc:pQ},fQ="return float(isinf(x));",mQ=Ke({opSnippet:fQ,dtype:"bool"}),gQ={kernelName:dc,backendName:"webgl",kernelFunc:mQ},bQ="return float(isnan(x));",yQ=Ke({opSnippet:bQ,dtype:"bool"}),vQ={kernelName:pc,backendName:"webgl",kernelFunc:yQ},xQ="return float(a < b);",wQ=`
return vec4(lessThan(a, b));
`,kQ=an({opSnippet:xQ,packedOpSnippet:wQ,cpuKernelImpl:h7,dtype:"bool"}),IQ={kernelName:hc,backendName:"webgl",kernelFunc:kQ},SQ="return float(a <= b);",CQ=`
return vec4(lessThanEqual(a, b));
`,TQ=an({opSnippet:SQ,packedOpSnippet:CQ,cpuKernelImpl:f7,dtype:"bool"}),NQ={kernelName:fc,backendName:"webgl",kernelFunc:TQ};function _Q(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=m7(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var EQ={kernelName:Vp,backendName:"webgl",kernelFunc:_Q},AQ=`if (x < 0.0) return NAN;
return log(x);`,$Q=`
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;
`,FQ=Ke({opSnippet:AQ,packedOpSnippet:$Q,cpuKernelImpl:g7}),DQ={kernelName:eo,backendName:"webgl",kernelFunc:FQ},RQ="return log(1.0 + x);",PQ=Ke({opSnippet:RQ}),OQ={kernelName:mc,backendName:"webgl",kernelFunc:PQ},MQ="return float(a >= 1.0 && b >= 1.0);",LQ=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,BQ=an({opSnippet:MQ,packedOpSnippet:LQ,dtype:"bool"}),zQ={kernelName:gc,backendName:"webgl",kernelFunc:BQ},WQ="return float(!(x >= 1.0));",VQ=Ke({opSnippet:WQ}),UQ={kernelName:yl,backendName:"webgl",kernelFunc:VQ},GQ="return float(a >= 1.0 || b >= 1.0);",HQ=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,jQ=an({opSnippet:GQ,packedOpSnippet:HQ,dtype:"bool"}),qQ={kernelName:vl,backendName:"webgl",kernelFunc:jQ},KQ=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=`
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-09-11 17:11:38 +02:00
`}},XQ=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=`
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-09-11 17:11:38 +02:00
`}},YQ=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:c}=r,u=Q().getBool("WEBGL_PACK_NORMALIZATION")?new XQ(s.shape,a,o,i,c):new KQ(s.shape,a,o,i,c);return n.runWebGLProgram(u,[s],s.dtype)},ZQ={kernelName:xl,backendName:"webgl",kernelFunc:YQ},JQ=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=`
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)
/ norm;
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-09-11 17:11:38 +02:00
`}},QQ=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:c,alpha:u,beta:l}=r,d=new JQ(s.shape,i,c,u,l);return n.runWebGLProgram(d,[s,a,o],s.dtype)},eee={kernelName:Up,backendName:"webgl",kernelFunc:QQ};function tee(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=me({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=ui(i,e.dtype,"max",r),u=me({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),u}function BN(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=_.getAxesPermutation(u,i),d=l!=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 N=0;N<x.length;N++)x[N]=s.shape[l[N]];let k=mw(v,s.shape,s.dtype,l,x);h=n.makeTensorInfo(x,s.dtype);let C=n.texData.get(h.dataId);C.values=k}else h=Jf(s,l,n);u=_.getInnerMostAxes(u.length,i)}_.assertAxesAreInnerMostDims("max",u,i);let[f,m]=_.computeOutAndReduceShapes(h.shape,u),g=f;o&&(g=_.expandShapeToKeepDim(f,c));let b;if(p){let v=n.texData.get(h.dataId).values,x=b7(v,w.sizeFromShape(m),g,s.dtype);b=n.makeTensorInfo(g,s.dtype);let k=n.texData.get(b.dataId);k.values=x}else b=tee(h,m,g,n);return d&&n.disposeIntermediateTensorInfo(h),b}var nee={kernelName:to,backendName:"webgl",kernelFunc:BN},ree=rN+`
return max(a, b);
`,see=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Yf+`
return result;
`,aee=an({opSnippet:ree,packedOpSnippet:see,cpuKernelImpl:y7}),oee={kernelName:no,backendName:"webgl",kernelFunc:aee};function iee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;vu(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,u=1;w.assert(_.eitherStridesOrDilationsAreOne(o,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let l=_.computePool2DInfo(s.shape,a,o,u,i,c);if(l.filterWidth===1&&l.filterHeight===1&&w.arraysEqual(l.inShape,l.outShape))return Zn({inputs:{x:s},backend:n});let d=new _d(l,"max",!1);return n.runWebGLProgram(d,[s],s.dtype)}var cee={kernelName:ro,backendName:"webgl",kernelFunc:iee};function uee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dataFormat:c,dimRoundingMode:u}=r,l=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,l,i,u,c),p=new bw(d,"max",!1);return n.runWebGLProgram(p,[s],s.dtype)}var lee={kernelName:wl,backendName:"webgl",kernelFunc:uee},dee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=s-1-e.padInfo.top,i=a-1-e.padInfo.left,c=s*a-1;this.userCode=`
const ivec2 pads = ivec2(${o}, ${i});
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);
int maxPosValue = ${c} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${a} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
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-09-11 17:11:38 +02:00
`}},pee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,c=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=i-1-e.padInfo.front,d=c-1-e.padInfo.top,p=u-1-e.padInfo.left,h=i*c*u-1;this.userCode=`
const ivec3 pads = ivec3(${l}, ${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);
for (int wR = 0; wR < ${c};
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);
for (int wC = 0; wC < ${u};
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 =
wD * ${c} * ${u} +
wR * ${u} + 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-09-11 17:11:38 +02:00
`}};function hee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:u,dimRoundingMode:l}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,u,l),h=new bw(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new pee(p),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var fee={kernelName:Hp,backendName:"webgl",kernelFunc:hee};function mee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;vu([a,o],"maxPoolGrad");let{filterSize:c,strides:u,pad:l,dimRoundingMode:d}=r,p=_.computePool2DInfo(i.shape,c,u,1,l,d),h=!0,f=new _d(p,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new dee(p),b=n.runWebGLProgram(g,[s,m],i.dtype);return n.disposeIntermediateTensorInfo(m),b}var gee={kernelName:Gp,backendName:"webgl",kernelFunc:mee};function bee(e,t,n,r){let s=new _d(n,"max",!1),a=r.runWebGLProgram(s,[e],"float32");s=new _d(n,"max",!0,!0,t);let o=r.runWebGLProgram(s,[e],"float32");return[a,o]}var yee={kernelName:jp,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,c=n;w.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let u=[1,1];w.assert(_.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let l=_.computePool2DInfo(r.shape,s,a,u,o),[d,p]=bee(r,i,l,c);return[d,p]}};function vee(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=me({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=ui(i,"float32","mean",r),u=me({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),u}var xee={kernelName:so,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{keepDims:s,axis:a}=t,o=n,i=r.shape.length,c=w.parseAxisParam(a,r.shape),u=c,l=_.getAxesPermutation(u,i),d=l!=null,p=o.shouldExecuteOnCPU([r]),h=[],f=r;if(d){if(p){let x=o.texData.get(f.dataId).values,k=new Array(i);for(let F=0;F<k.length;F++)k[F]=r.shape[l[F]];let C=mw(x,r.shape,r.dtype,l,k);f=o.makeTensorInfo(k,r.dtype);let N=o.texData.get(f.dataId);N.values=C}else f=Jf(r,l,o);h.push(f),u=_.getInnerMostAxes(u.length,i)}_.assertAxesAreInnerMostDims("sum",u,i);let[m,g]=_.computeOutAndReduceShapes(f.shape,u),b=m;s&&(b=_.expandShapeToKeepDim(m,c));let y=vee(f,g,b,o);for(let v of h)o.disposeIntermediateTensorInfo(v);return y}};function wee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=_.getAxesPermutation(u,i),d=s;l!=null&&(d=Sn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=_.getInnerMostAxes(u.length,s.shape.length)),_.assertAxesAreInnerMostDims("min",u,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,u),f=w.sizeFromShape(h),m=me({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=ui(m,m.dtype,"min",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=me({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=me({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(d),b}var kee={kernelName:ao,backendName:"webgl",kernelFunc:wee},Iee=rN+`
return min(a, b);
`,See=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Yf+`
return result;
`,Cee=an({opSnippet:Iee,packedOpSnippet:See,cpuKernelImpl:v7}),Tee={kernelName:oo,backendName:"webgl",kernelFunc:Cee},Nee=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,l)=>u[0]+e[l]+u[1]);let r=e.length,s=dt(r),a=t.map(u=>u[0]).join(","),o=t.map((u,l)=>u[0]+e[l]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),c=n==="reflect"?0:1;if(r===1){this.userCode=`
int start = ${a};
int end = ${o};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${c};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${c};
}
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]) {
outC[i] = start[i] * 2 - outC[i] - ${c};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${c};
}
}
${s} coords = outC - start;
setOutput(getX(${i}));
}
`}},_ee=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=dt(r),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=In("rc",r),c=In("source",r),u=`${i[r-1]} < ${this.outputShape[r-1]}`,l=r===1?"source":`vec2(${c.slice(-2).join()})`,d=n==="reflect"?0:1,p="";if(r===1){let h=`
${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}
result[0] = getChannel(getX(${c.join()}), ${l});
${i[r-1]} += 1;
if(${u}) {
${h}
result[1] = getChannel(getX(${c.join()}), ${l});
}
`}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}
result[0] = getChannel(getX(${c.join()}), ${l});
${i[r-1]} += 1;
if(${u}) {
${h}
result[1] = getChannel(getX(${c.join()}), ${l});
}
rc = outputLoc;
${i[r-2]} += 1;
if(${i[r-2]} < ${this.outputShape[r-2]}) {
${h}
result[2] = getChannel(getX(${c.join()}), ${l});
${i[r-1]} += 1;
if(${u}) {
${h}
result[3] = getChannel(getX(${c.join()}), ${l});
}
}
`}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-09-11 17:11:38 +02:00
`}},Eee=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{paddings:s,mode:a}=n,o=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _ee(r.shape,s,a):new Nee(r.shape,s,a);return t.runWebGLProgram(o,[r],r.dtype)},Aee={kernelName:io,backendName:"webgl",kernelFunc:Eee},$ee=`if (b == 0.0) return NAN;
return mod(a, b);`,Fee=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+Yf+`
return result;
`,Dee=an({opSnippet:$ee,packedOpSnippet:Fee}),Ree={kernelName:bc,backendName:"webgl",kernelFunc:Dee},Pee=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`
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-09-11 17:11:38 +02:00
`}},Oee=`
if (a == b) {
return 1.0;
};
return a / b;`,Mee=`
// 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;
`,zN=an({opSnippet:Oee,packedOpSnippet:Mee,checkOutOfBounds:!0}),Lee={kernelName:Ha,backendName:"webgl",kernelFunc:zN},WN="return a - b;",VN=an({opSnippet:WN,packedOpSnippet:WN,supportsComplex:!0,cpuKernelImpl:P7}),Bee={kernelName:To,backendName:"webgl",kernelFunc:VN};function UN(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=w.parseAxisParam([a],s.shape),i=BN({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=_.expandShapeToKeepDim(i.shape,o),u=me({inputs:{x:i},backend:n,attrs:{shape:c}}),l=VN({inputs:{a:s,b:u},backend:n}),d=DN({inputs:{x:l},backend:n}),p=Qf({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=me({inputs:{x:p},backend:n,attrs:{shape:c}}),f=zN({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}var zee={kernelName:So,backendName:"webgl",kernelFunc:UN};function Wee(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r,c=i?s:UN({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),u=c.shape[0],l=c.shape[1],d=new Pee(u,l,a),p=[[o]],h=n.runWebGLProgram(d,[c],"int32",p);return i||n.disposeIntermediateTensorInfo(c),h}var Vee={kernelName:qp,backendName:"webgl",kernelFunc:Wee},GN="return -x;";function Uee(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.texData.get(r.dataId),[o,i]=w7(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s;return Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Su(r.shape,GN):s=new ya(r.shape,GN),n.runWebGLProgram(s,[r],r.dtype)}var Gee={kernelName:yc,backendName:"webgl",kernelFunc:Uee},Hee=ts.nonMaxSuppressionV3Impl;function jee(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,u=n.readSync(s.dataId),l=n.readSync(a.dataId),{selectedIndices:d}=Hee(u,l,o,i,c);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var qee={kernelName:xc,backendName:"webgl",kernelFunc:jee},Kee=ts.nonMaxSuppressionV4Impl;function Xee(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:u}=r,l=n.readSync(s.dataId),d=n.readSync(a.dataId),{selectedIndices:p,validOutputs:h}=Kee(l,d,o,i,c,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Yee={kernelName:wc,backendName:"webgl",kernelFunc:Xee},Zee=ts.nonMaxSuppressionV5Impl;function Jee(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:u}=r,l=n.readSync(s.dataId),d=n.readSync(a.dataId),p=o,h=i,f=c,m=u,{selectedIndices:g,selectedScores:b}=Zee(l,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var Qee={kernelName:kc,backendName:"webgl",kernelFunc:Jee},ete=class{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
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-09-11 17:11:38 +02:00
`}},tte=e=>{let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,c=w.sizeFromShape(s.shape),u=new ete(c,a,o,i),l=me({inputs:{x:s},backend:n,attrs:{shape:[c]}}),d=n.runWebGLProgram(u,[l],s.dtype);n.disposeIntermediateTensorInfo(l);let p=[...s.shape,a],h=me({inputs:{x:d},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(d),h},nte={kernelName:uo,backendName:"webgl",kernelFunc:tte};function sm(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=Ed({inputs:{input:r},backend:n}),a=sm({inputs:{x:s},backend:n}),o=rm({inputs:{input:r},backend:n}),i=sm({inputs:{x:o},backend:n}),c=va({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Ad({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var rte={kernelName:Wc,backendName:"webgl",kernelFunc:sm};function HN(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=Ed({inputs:{input:r},backend:n}),a=HN({inputs:{x:s},backend:n}),o=rm({inputs:{input:r},backend:n}),i=sm({inputs:{x:o},backend:n}),c=va({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Ad({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var ste={kernelName:Ic,backendName:"webgl",kernelFunc:HN};function ate(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return xw({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(l=>{w.assertShapesMatch(a,l.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===l.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(l=>{let d=xw({inputs:{input:l},backend:n,attrs:{dim:s}});return i.push(d),d}),u=IN({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(l=>n.disposeIntermediateTensorInfo(l)),u}var ote={kernelName:Sc,backendName:"webgl",kernelFunc:ate},ite=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((c,u)=>c[0]+e[u]+c[1]);let r=e.length,s=dt(r),a=t.map(c=>c[0]).join(","),o=t.map((c,u)=>c[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=`
int start = ${a};
int end = ${o};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${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-09-11 17:11:38 +02:00
`}},cte=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=dt(r),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=In("rc",r),c=In("source",r),u=`${i[r-1]} < ${this.outputShape[r-1]}`,l=r===1?"source":`vec2(${c.slice(-2).join()})`,d=[`${s} rc = outputLoc;`,`${i[r-1]} += 1;
if(${u}) {
`,r===1?"":`}
rc = outputLoc;
${i[r-2]} += 1;
if(${i[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":` ${i[r-1]} += 1;
if(${u}) {`],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+=`
${d[f]}
if (${p}) {
result[${f}] = float(value);
} else {
${s} source = rc - start;
result[${f}] = getChannel(getX(${c.join()}), ${l});
}
`;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-09-11 17:11:38 +02:00
`}},jN=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(w.sizeFromShape(s.shape)===0){let u=a.map((l,d)=>l[0]+s.shape[d]+l[1]);return Ad({backend:n,attrs:{shape:u,value:o,dtype:s.dtype}})}let i=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new cte(s.shape,a,o):new ite(s.shape,a,o),c=[[o]];return n.runWebGLProgram(i,[s],s.dtype,c)},ute={kernelName:lo,backendName:"webgl",kernelFunc:jN},lte=`
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);
`,dte=`
// 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));
`+Yf+`
return result;
`,pte=an({opSnippet:lte,packedOpSnippet:dte}),hte={kernelName:po,backendName:"webgl",kernelFunc:pte};function fte(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=[],u=w.parseAxisParam(a,s.shape),l=u,d=_.getAxesPermutation(l,i),p=s;d!=null&&(p=Sn({inputs:{x:s},backend:n,attrs:{perm:d}}),l=_.getInnerMostAxes(l.length,i),c.push(p)),_.assertAxesAreInnerMostDims("prod",l,i);let h;if(n.shouldExecuteOnCPU([p])){let f=n.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:b}=I7(p.shape,p.dtype,f,l);h=n.makeTensorInfo(g,b,m)}else{let[f,m]=_.computeOutAndReduceShapes(p.shape,l),g=w.sizeFromShape(m),b=me({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),y=hh(s.dtype),v=ui(b,y,"prod",n);h=me({inputs:{x:v},backend:n,attrs:{shape:f}}),c.push(b),c.push(v)}if(o){c.push(h);let f=_.expandShapeToKeepDim(h.shape,u);h=me({inputs:{x:h},backend:n,attrs:{shape:f}})}return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var mte={kernelName:Cc,backendName:"webgl",kernelFunc:fte},qN=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=S7(r,s,a,o);return t.makeTensorInfo([i.length],o,i)},gte={kernelName:kl,backendName:"webgl",kernelFunc:qN},bte="return 1.0 / x;",yte=Ke({opSnippet:bte}),vte={kernelName:Tc,backendName:"webgl",kernelFunc:yte},xte=Ur+`
return (x < 0.0) ? 0.0 : x;
`,wte=`
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;
`,kte=Ke({opSnippet:xte,packedOpSnippet:wte}),Ite={kernelName:fo,backendName:"webgl",kernelFunc:kte},Ste=Ur+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,Cte=`
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;
`,Tte=Ke({opSnippet:Ste,packedOpSnippet:Cte}),Nte={kernelName:go,backendName:"webgl",kernelFunc:Tte},_te=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0]/l[0]},
${u[1]/l[1]});
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-09-11 17:11:38 +02:00
`}},Ete=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${u[0]/l[0]},
${u[1]/l[1]},
${u[1]/l[1]});
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.
bool hasNextCol = d < ${c-1};
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);
}
`}};function Ate(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,u]=i,l=Q().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Ete(s.shape,c,u,a,o):new _te(s.shape,c,u,a,o);return n.runWebGLProgram(l,[s],"float32")}var $te={kernelName:mo,backendName:"webgl",kernelFunc:Ate},Fte=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],u=i[0]/c[0],l=i[1]/c[1],d=1/u,p=1/l,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
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-09-11 17:11:38 +02:00
const float heightScale = float(${u});
const float widthScale = float(${l});
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-09-11 17:11:38 +02:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
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-09-11 17:11:38 +02:00
`}};function Dte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Fte(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Rte={kernelName:Yp,backendName:"webgl",kernelFunc:Dte},Pte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],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=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0]/l[0]},
${u[1]/l[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
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-09-11 17:11:38 +02:00
`}},Ote=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],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=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${u[0]/l[0]},
${u[1]/l[1]},
${u[1]/l[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
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.
bool hasNextCol = d < ${c-1};
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);
}
`}};function Mte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,u]=i,l=Q().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Ote(s.shape,c,u,a,o):new Pte(s.shape,c,u,a,o);return n.runWebGLProgram(l,[s],s.dtype)}var Lte={kernelName:Il,backendName:"webgl",kernelFunc:Mte},Bte=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],u=i[0]/c[0],l=i[1]/c[1],d=1/u,p=1/l,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
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-09-11 17:11:38 +02:00
const float heightScale = float(${u});
const float widthScale = float(${l});
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]}) *
(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]}) *
(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);
}
`}};function zte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Bte(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Wte={kernelName:Xp,backendName:"webgl",kernelFunc:zte},Vte=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=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;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=dt(n);this.userCode=`
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${s}));
}
`}},Ute=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=In("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=dt(n);n===1?this.userCode=`
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}){
result.g = ${c(r.slice())};
}
if(${a}) {
result.b = ${u(r.slice())};
if(${s}) {
result.a = ${l(r.slice())};
}
}
setOutput(result);
}
`;function i(h){return d(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function u(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function l(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 Gte(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=s.shape.length,i=w.parseAxisParam(a,s.shape);if(o===0)return Zn({inputs:{x:s},backend:n});let c=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ute(s.shape,i):new Vte(s.shape,i);return n.runWebGLProgram(c,[s],s.dtype)}var Hte={kernelName:bo,backendName:"webgl",kernelFunc:Gte},jte=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=`
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);
}
`}},qte={kernelName:Vc,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,c=new jte(r.shape,a),[u,l]=_.getImageCenter(o,r.shape[1],r.shape[2]),d=[[u,l,Math.sin(s),Math.cos(s)]];return i.runWebGLProgram(c,[r],r.dtype,d)}},Kte=`
// 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-09-11 17:11:38 +02:00
`,Xte=Ke({opSnippet:Kte}),Yte={kernelName:yo,backendName:"webgl",kernelFunc:Xte},Zte="return inversesqrt(x);",Jte=Ke({opSnippet:Zte,cpuKernelImpl:C7}),Qte={kernelName:vo,backendName:"webgl",kernelFunc:Jte},KN=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=dt(s.length),c=dt(a.length),u="";n===1?u="i":n===2&&(u="i, j");let l=`getIndices(${u})`,d="";r===1?d="i":r===2&&(d="i, coords[1]");let p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=`
${i} strides = ${i}(${s});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${c} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${l});
flattenedIndex += index * ${h};
}
if (flattenedIndex == coords[0]) {
sum += ${p};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}};function ene(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:c,sliceSize:u,strides:l,outputSize:d}=_.calculateShapes(a,s,o),p=[d/u,u];if(d===0)return n.makeTensorInfo(o,s.dtype);let h=me({inputs:{x:s},backend:n,attrs:{shape:[c,i]}}),f=me({inputs:{x:a},backend:n,attrs:{shape:[c,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new KN(c,i,h.shape.length,f.shape.length,l,p),b=n.runWebGLProgram(g,[f,h,m],f.dtype),y=me({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(m),y}var tne={kernelName:_c,backendName:"webgl",kernelFunc:ene},nne=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let r,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",r="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],c=[];for(let u=0;u<t.length;u++)c.push(`${o[u]}`),u<e&&i.push(`${o[u]}`);r=i.join(),s=c.join()}let a=dt(n);this.userCode=`
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-09-11 17:11:38 +02:00
`}};function rne(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new nne(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(o,[r,s,a],yr(s.dtype,a.dtype))}var sne={kernelName:Ec,backendName:"webgl",kernelFunc:rne},ane=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${_.SELU_SCALEALPHA};
float scale = ${_.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`,one=Ke({opSnippet:ane}),ine={kernelName:Ac,backendName:"webgl",kernelFunc:one},XN="return 1.0 / (1.0 + exp(-1.0 * x));",cne=Ke({opSnippet:XN,packedOpSnippet:XN,cpuKernelImpl:T7}),une={kernelName:wo,backendName:"webgl",kernelFunc:cne},lne=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,dne=Ke({opSnippet:lne}),pne={kernelName:Dc,backendName:"webgl",kernelFunc:dne},hne=cN+`
return sin(x);
`,fne=Ke({opSnippet:hne}),mne={kernelName:xo,backendName:"webgl",kernelFunc:fne},gne=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,bne=Ke({opSnippet:gne}),yne={kernelName:Fc,backendName:"webgl",kernelFunc:bne},vne=`
float epsilon = 1.1920928955078125e-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;
`,xne=Ke({opSnippet:vne}),wne={kernelName:Rc,backendName:"webgl",kernelFunc:xne},kne=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;w.assert(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((b,y)=>b*y),c=[[0,0]];c.push(...o);for(let b=1+a.length;b<s.shape.length;++b)c.push([0,0]);let u=[],l=jN({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),d=_.getReshaped(l.shape,a,i,!1),p=_.getPermuted(d.length,a.length,!1),h=_.getReshapedPermuted(l.shape,a,i,!1),f=me({inputs:{x:l},backend:n,attrs:{shape:d}}),m=Sn({inputs:{x:f},backend:n,attrs:{perm:p}}),g=me({inputs:{x:m},backend:n,attrs:{shape:h}});return u.push(l),u.push(f),u.push(m),u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g},Ine={kernelName:Pc,backendName:"webgl",kernelFunc:kne};function Sne(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${o.shape}`);let i=n.readSync(r.dataId),c=n.readSync(s.dataId),u=n.readSync(a.dataId),l=n.readSync(o.dataId)[0],[d,p,h,f,m]=_7(i,r.shape,r.dtype,c,s.dtype,u,l);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 Cne={kernelName:Zp,backendName:"webgl",kernelFunc:Sne};function Tne(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.readSync(s.dataId)),i=n.readSync(r.dataId),c=Array.from(n.readSync(a.dataId)),[u,l,d]=E7(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(l,r.dtype,u),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var Nne={kernelName:Jp,backendName:"webgl",kernelFunc:Tne};function _ne(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[u,l]=X2(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(l,r.dtype,u)}var Ene={kernelName:Qp,backendName:"webgl",kernelFunc:_ne};function Ane(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[u,l]=X2(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(l,r.dtype,u)}var $ne={kernelName:eh,backendName:"webgl",kernelFunc:Ane};function Fne(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:u,strides:l,outputSize:d}=_.calculateShapes(a,s,i),p=!1,h=new KN(u,c,s.shape.length,a.shape.length,l,[d,1],p),f=n.runWebGLProgram(h,[a,s,o],a.dtype),m=me({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var Dne={kernelName:th,backendName:"webgl",kernelFunc:Fne};function Rne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),u=s.shape.length,l=new Array(u).fill(0),d=s.shape.slice();return c.map(p=>{let h=[...d];h[i]=p;let f=Tu({inputs:{x:s},backend:n,attrs:{begin:l,size:h}});return l[i]+=p,f})}var Pne={kernelName:Oc,backendName:"webgl",kernelFunc:Rne},YN="return sqrt(x);",One=Ke({opSnippet:YN,packedOpSnippet:YN,cpuKernelImpl:A7}),Mne={kernelName:ko,backendName:"webgl",kernelFunc:One},Lne="return x * x;",Bne=Ke({opSnippet:Lne}),zne={kernelName:Sl,backendName:"webgl",kernelFunc:Bne},ZN="return (a - b) * (a - b);",Wne=an({opSnippet:ZN,packedOpSnippet:ZN}),Vne={kernelName:Co,backendName:"webgl",kernelFunc:Wne};function Une({inputs:e,attrs:t,backend:n}){let{x:r}=e,s=Ur+`
return x > 0.0 ? 1.0 : float(${t.alpha});
`,a=new ya(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}var Gne={kernelName:Zs,backendName:"webgl",kernelFunc:Une},Hne=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let r=n.length,s=dt(n.length),a=dt(n.length),o="";if(r===1)o="coords * strides + begin";else{let i=0;o=n.map((c,u)=>(i++,n.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${i-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
${s} begin = ${s}(${e});
${s} strides = ${s}(${t});
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${o}));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}};function jne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:u,ellipsisMask:l,newAxisMask:d,shrinkAxisMask:p}=r,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:b,outShape:y}=mn.sliceInfo(s.shape,a,o,i,c,u,l,d,p),v=me({inputs:{x:s},backend:n,attrs:{shape:b}}),x;if(h){let C=Tu({inputs:{x:v},backend:n,attrs:{begin:f,size:g}});x=me({inputs:{x:C},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(C)}else if(y.some(C=>C===0))x=n.makeTensorInfo(y,s.dtype,[]);else if(n.shouldExecuteOnCPU([v])){let F=n.texData.get(v.dataId).values,R=Be(v.shape,v.dtype,F),O=$7(y,R,m,f);x=n.makeTensorInfo(y,v.dtype,O.values)}else{let N=new Hne(f,m,y);x=n.runWebGLProgram(N,[v],v.dtype)}let k=me({inputs:{x},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),k}var qne={kernelName:Mc,backendName:"webgl",kernelFunc:jne};function Kne(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:u}=r,{data:l,dataSplits:d}=t,p=n.readSync(l.dataId),h=n.readSync(d.dataId),[f,m]=F7(p,h,s,a,o,i,c,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var Xne={kernelName:nh,backendName:"webgl",kernelFunc:Kne};function Yne(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),c=n.readSync(o.dataId)[0],[u,l,d]=D7(i,c,s),p=l.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",l),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var Zne={kernelName:rh,backendName:"webgl",kernelFunc:Yne};function Jne(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=R7(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var Qne={kernelName:sh,backendName:"webgl",kernelFunc:Jne},ere="return tan(x);",tre=Ke({opSnippet:ere}),nre={kernelName:No,backendName:"webgl",kernelFunc:tre},rre=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,sre=Ke({opSnippet:rre}),are={kernelName:_o,backendName:"webgl",kernelFunc:sre},ore=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=dt(this.rank),s=ire(e);this.userCode=`
void main() {
${r} resRC = getOutputCoords();
setOutput(getA(${s}));
}
`}};function ire(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 JN(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if(s.dtype==="string"||s.shape.length>5){let c=n.readSync(s.dataId),u=s.dtype==="string"?c.map(p=>w.decodeString(p)):c,l=Be(s.shape,s.dtype,u),d=O7(l,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new ore(s.shape,a);return n.runWebGLProgram(o,[s],s.dtype)}var cre={kernelName:Ys,backendName:"webgl",kernelFunc:JN},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=`
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));
}
}
`}},lre=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=`
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));
}
`}};function li(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function QN(e){let t=1;for(;t<e;)t*=2;return t}function dre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r,i=Q().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),c=Q().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=s.shape,l=u[u.length-1];if(n.shouldExecuteOnCPU([s])||l<i||a>c){let O=n.readSync(s.dataId),[$,P]=M7(O,u,s.dtype,a,o);return[n.makeTensorInfo($.shape,$.dtype,$.values),n.makeTensorInfo(P.shape,P.dtype,P.values)]}if(a===0)return u[u.length-1]=0,[n.makeTensorInfo(u,s.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(l===1)return[s,Ad({attrs:{shape:u,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=w.sizeFromShape(u)/l,g=me({inputs:{x:h},attrs:{shape:[m,l]},backend:n});p&&li(n,h);let b=QN(a),y=QN(l),v=null,x=()=>v===null?[g,g]:[g,v],k=(O,$,P)=>{let T=x(),L=new ure(P),j=[[l],[v===null?1:0],[Number.NEGATIVE_INFINITY],[O],[$]],q=v;v=n.runWebGLProgram(L,T,"int32",j),li(n,q)};for(let O=1;O<b;O*=2){let $=O*2;for(let P=O;P>=1;P/=2)k($,P,[m,y])}for(let O=y;O>b;O/=2){let $=x(),P=new lre([m,O/2]),L=[[l],[v===null?1:0],[b]],G=v;v=n.runWebGLProgram(P,$,"int32",L),li(n,G);let j=b/2,q=j*2;for(let K=j;K>=1;K/=2)k(q,K,v.shape)}let C=v;v=Tu({inputs:{x:v},backend:n,attrs:{begin:0,size:[m,a]}}),li(n,C);let N=LN({inputs:{x:g,indices:v},backend:n,attrs:{axis:1,batchDims:1}});li(n,g);let F=u.slice(0,-1);F.push(a),C=v,v=me({inputs:{x:v},attrs:{shape:F},backend:n}),li(n,C);let R=N;return N=me({inputs:{x:N},attrs:{shape:F},backend:n}),li(n,R),[N,v]}var pre={kernelName:Lc,backendName:"webgl",kernelFunc:dre},hre=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=`
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);
}
`}};function fre(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:c,outputShape:u}=r,[l,d,p,h]=s.shape,[f,m]=u!=null?u:[d,p],g=[l,f,m,h],b=new hre(d,p,o,i,c,g);return n.runWebGLProgram(b,[s,a],"float32")}var mre={kernelName:Bc,backendName:"webgl",kernelFunc:fre};function gre(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;vu(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=r.readSync(a.dataId),{outputValues:i,outputShape:c,indices:u}=L7(o,s,a.shape,a.dtype);return[r.makeTensorInfo(c,a.dtype,i),r.makeTensorInfo([u.length],"int32",u)]}var bre={kernelName:ah,backendName:"webgl",kernelFunc:gre};function yre(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s,i=o.shape.length,c=s.shape[a],u=new Array(i-1),l=0;for(let m=0;m<i;m++)m!==a&&(u[l++]=o.shape[m]);let 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=Tu({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),b=me({inputs:{x:g},backend:n,attrs:{shape:u}});f[m]=b,d.push(g)}return d.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var vre={kernelName:zc,backendName:"webgl",kernelFunc:yre},xre=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,o=a*Math.ceil(s/n);this.outputShape=[r,o];let i="0.0",c="sumValue",u=Math.floor(n/4)*4,l=n%4,d=`
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-09-11 17:11:38 +02:00
for (int i = 0; i < ${u}; 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-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-09-11 17:11:38 +02:00
int inIdx = inOffset + ${u};
if (${l===1}) {
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}
} else if (${l===2}) {
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}
} else if (${l===3}) {
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}
}
setOutput(${c});
}
`}};function wre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r,i=s.shape.length,c=[],u=0,l=_.getAxesPermutation([u],i),d=s;l!=null&&(d=Sn({inputs:{x:s},backend:n,attrs:{perm:l}}),c.push(d),u=_.getInnerMostAxes(1,i)[0]);let p=_.segment_util.computeOutShape(d.shape,u,o),h=w.sizeFromShape([d.shape[u]]),f=me({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});c.push(f);let m=hh(s.dtype),g=(x,k,C,N,F)=>{let R=x.shape[0],O=x.shape[1],$=_.segment_util.segOpComputeOptimalWindowSize(O,F),P={windowSize:$,inSize:O,batchSize:R,numSegments:F},T=new xre(P,k),L=n.compileAndRun(T,[x,C],N);if(c.push(L),L.shape[1]===F)return L;let G=qN({backend:n,attrs:{start:0,stop:F,step:1,dtype:"float32"}}),j=JN({inputs:{x:G},backend:n,attrs:{reps:[O/$]}});return c.push(G),c.push(j),g(L,k,j,N,F)},b=g(f,"unsortedSegmentSum",a,m,o),y=me({inputs:{x:b},backend:n,attrs:{shape:p}}),v=y;if(l!=null){c.push(y);let x=_.getUndoAxesPermutation(l);v=Sn({inputs:{x:v},backend:n,attrs:{perm:x}})}return c.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var kre={kernelName:Cl,backendName:"webgl",kernelFunc:wre},Ire=[ZQ,eee,M9,B9,V9,H9,q9,Y9,J9,eY,sY,oY,uY,pY,vY,mY,kY,TY,SY,AY,FY,RY,LY,HY,qY,QY,tZ,aZ,cZ,y9,hZ,IZ,CZ,bZ,EZ,$Z,NZ,RZ,MZ,zZ,VZ,GZ,qZ,QZ,tJ,XZ,sJ,iJ,uJ,hJ,bJ,wJ,SJ,CJ,TJ,_J,AJ,FJ,RJ,OJ,zJ,UJ,jJ,KJ,ZJ,eQ,sQ,cQ,b9,lQ,dZ,hQ,gQ,vQ,x9,IQ,NQ,EQ,OQ,DQ,zQ,UQ,qQ,nee,lee,cee,fee,gee,yee,oee,xee,kee,Tee,Aee,Ree,Vee,C9,Gee,qee,Yee,Qee,XY,nte,ste,ote,ute,hte,k9,mte,gte,YY,Lee,vte,Nte,Ite,N9,$te,Rte,Lte,Wte,Hte,qte,Yte,Qte,tne,sne,ine,une,pne,mne,yne,UY,zee,wne,Ine,Cne,Nne,Ene,$ne,Dne,Pne,Mne,zne,Vne,Gne,qne,Xne,Zne,Qne,Bee,R9,nre,are,cre,pre,mre,P9,bre,vre,kre,rte];for(let e of Ire)Nl(e);var Pn;(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"})(Pn||(Pn={}));var $d;(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"})($d||($d={}));var e_;function Sre(e){e_=e.wasm.cwrap(Ao,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Cre(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:c,transposeB:u,activation:l,leakyreluAlpha:d}=r,p=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let F=n.dataIdMap.get(o.dataId);if(F.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${F.shape.length}.`);f=F.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=$d[l];if(g==null)throw new Error(`${l} activation not yet supported for FusedConv2D in the wasm backend.`);let b=c?s.shape[2]:s.shape[1],y=u?a.shape[1]:a.shape[2],v=s.shape[0],x=n.makeOutput([v,b,y],s.dtype),k=n.dataIdMap.get(x.dataId).id,C=new Uint8Array(new Int32Array(s.shape).buffer),N=new Uint8Array(new Int32Array(a.shape).buffer);return e_(p,C,s.shape.length,h,N,a.shape.length,c,u,g,f,m,d||0,k),x}var Tre={kernelName:Ao,backendName:"wasm",setupFunc:Sre,kernelFunc:Cre};function on(e){let t;function n(s){t=s.wasm.cwrap(e,null,["number","number"])}function r(s){let{backend:a,inputs:{x:o}}=s,i=a.dataIdMap.get(o.dataId).id,c=a.makeOutput(o.shape,o.dtype),u=a.dataIdMap.get(c.dataId).id;return w.sizeFromShape(c.shape)===0||t(i,u),c}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:r}}var Nre=on(Vi);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:u,b:l}=c,d=i.dataIdMap.get(u.dataId).id,p=i.dataIdMap.get(l.dataId).id,h=n!=null?n:u.dtype,f=_.assertAndGetBroadcastShape(u.shape,l.shape),m=i.makeOutput(f,h);if(w.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(u.shape).buffer),b=new Uint8Array(new Int32Array(l.shape).buffer),y=i.dataIdMap.get(m.dataId).id,v=()=>r(d,g,u.sha
2021-04-26 20:45:49 +02:00
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @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.
* =============================================================================
*/
2021-04-30 18:01:04 +02:00
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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. */