face-api/dist/face-api.js

4824 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-10-28 19:58:21 +02:00
var faceapi=(()=>{var J1=Object.defineProperty;var JA=e=>J1(e,"__esModule",{value:!0});var Qr=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var Rp=(e,t)=>{JA(e);for(var n in t)J1(e,n,{get:t[n],enumerable:!0})};var cue={};Rp(cue,{AgeGenderNet:()=>jm,BoundingBox:()=>Lu,Box:()=>ut,ComposableTask:()=>Ar,ComputeAllFaceDescriptorsTask:()=>Da,ComputeFaceDescriptorsTaskBase:()=>eg,ComputeSingleFaceDescriptorTask:()=>Fa,DetectAllFaceLandmarksTask:()=>ng,DetectAllFacesTask:()=>ip,DetectFaceLandmarksTaskBase:()=>tg,DetectFacesTaskBase:()=>sg,DetectSingleFaceLandmarksTask:()=>rg,DetectSingleFaceTask:()=>ag,Dimensions:()=>An,FACE_EXPRESSION_LABELS:()=>S1,FaceDetection:()=>yt,FaceDetectionNet:()=>WE,FaceExpressionNet:()=>Gm,FaceExpressions:()=>Aa,FaceLandmark68Net:()=>qu,FaceLandmark68TinyNet:()=>qm,FaceLandmarkNet:()=>EE,FaceLandmarks:()=>gr,FaceLandmarks5:()=>fE,FaceLandmarks68:()=>zu,FaceMatch:()=>Yd,FaceMatcher:()=>ig,FaceRecognitionNet:()=>Ku,Gender:()=>Ws,LabeledBox:()=>Zd,LabeledFaceDescriptors:()=>Ls,NetInput:()=>Bs,NeuralNetwork:()=>hn,ObjectDetection:()=>_a,Point:()=>Pe,PredictedBox:()=>mE,Rect:()=>Bu,SsdMobilenetv1:()=>Di,SsdMobilenetv1Options:()=>Er,TinyFaceDetector:()=>Qu,TinyFaceDetectorOptions:()=>Qm,TinyYolov2:()=>Zu,TinyYolov2Options:()=>ys,allFaces:()=>sue,allFacesSsdMobilenetv1:()=>nA,allFacesTinyYolov2:()=>rue,awaitMediaLoaded:()=>y1,bufferToImage:()=>v1,computeFaceDescriptor:()=>Uce,createCanvas:()=>Ni,createCanvasFromMedia:()=>ep,createFaceDetectionNet:()=>Oce,createFaceRecognitionNet:()=>Cce,createSsdMobilenetv1:()=>zE,createTinyFaceDetector:()=>aue,createTinyYolov2:()=>Bce,detectAllFaces:()=>og,detectFaceLandmarks:()=>eA,detectFaceLandmarksTiny:()=>Vce,detectLandmarks:()=>tue,detectSingleFace:()=>nue,draw:()=>_1,env:()=>Je,euclideanDistance:()=>L1,extendWithAge:()=>Ym,extendWithFaceDescriptor:()=>Xm,extendWithFaceDetection:()=>Si,extendWithFaceExpressions:()=>Hm,extendWithFaceLandmarks:()=>ju,extendWithGender:()=>Zm,extractFaceTensors:()=>Vu,extractFaces:()=>Wu,fetchImage:()=>pce,fetchJson:()=>k1,fetchNetWeights:()=>hce,fetchOrThrow:()=>zs,fetchVideo:()=>fce,getContext2dOrThrow:()=>Un,getMediaDimensions:()=>Ti,imageTensorToCanvas:()=>x1,imageToSquare:()=>w1,inverseSigmoid:()=>ace,iou:()=>i1,isMediaElement:()=>Pm,isMediaLoaded:()=>Qd,isWithAge:()=>Tce,isWithFaceDetection:()=>gs,isWithFaceExpressions:()=>C1,isWithFaceLandmarks:()=>Ei,isWithGender:()=>Nce,loadAgeGenderModel:()=>Jce,loadFaceDetectionModel:()=>Qce,loadFaceExpressionModel:()=>Zce,loadFaceLandmarkModel:()=>Kce,loadFaceLandmarkTinyModel:()=>Xce,loadFaceRecognitionModel:()=>Yce,loadSsdMobilenetv1Model:()=>tA,loadTinyFaceDetectorModel:()=>jce,loadTinyYolov2Model:()=>qce,loadWeightMap:()=>I1,locateFaces:()=>eue,matchDimensions:()=>mce,minBbox:()=>c1,nets:()=>Qe,nonMaxSuppression:()=>u1,normalize:()=>Kr,padToSquare:()=>l1,predictAgeAndGender:()=>Hce,recognizeFaceExpressions:()=>Gce,resizeResults:()=>rA,resolveInput:()=>Ci,shuffleArray:()=>sce,sigmoid:()=>Xd,ssdMobilenetv1:()=>QE,tf:()=>n1,tinyFaceDetector:()=>zce,tinyYolov2:()=>Wce,toNetInput:()=>mt,utils:()=>o1,validateConfig:()=>R1,version:()=>iue});var n1={};Rp(n1,{Abs:()=>Xi,Acos:()=>Yi,Acosh:()=>Zi,AdadeltaOptimizer:()=>mf,AdagradOptimizer:()=>gf,AdamOptimizer:()=>bf,AdamaxOptimizer:()=>yf,Add:()=>Qs,AddN:()=>za,All:()=>Ji,Any:()=>Qi,ArgMax:()=>Wa,ArgMin:()=>xl,Asin:()=>ec,Asinh:()=>tc,Atan:()=>nc,Atan2:()=>sc,Atanh:()=>rc,AvgPool:()=>Va,AvgPool3D:()=>wl,AvgPool3DGrad:()=>Vp,AvgPoolGrad:()=>Wp,BackendWasm:()=>dE,BatchMatMul:()=>Ua,BatchToSpaceND:()=>ac,Bincount:()=>Up,BroadcastArgs:()=>Gp,BroadcastTo:()=>b0,Callback:()=>oC,CallbackList:()=>JI,Cast:()=>Ga,Ceil:()=>Ha,ClipByValue:()=>ea,Complex:()=>Hp,ComplexAbs:()=>kl,Concat:()=>oc,Conv2D:()=>ja,Conv2DBackpropFilter:()=>jp,Conv2DBackpropInput:()=>qa,Conv3D:()=>Il,Conv3DBackpropFilterV2:()=>qp,Conv3DBackpropInputV2:()=>
2021-09-11 17:11:38 +02:00
`)),c.join(`
2021-10-28 19:58:21 +02:00
`)}function pF(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"?Wl(e):e;if(i>1)for(let l=0;l<s/a;l++){let u=l*a;for(let d=0;d<a;d++)o[d]=Math.max(o[d],zl(c[u+d],0,n).length)}return o}function zl(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(Vb))} + ${parseFloat(e[1].toFixed(Vb))}j`:Zs(e)?r=`'${e}'`:n==="bool"?r=C0(e):r=parseFloat(e.toFixed(Vb)).toString(),vl(r,t)}function C0(e){return e===0?"false":"true"}function Ah(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=Wl(e);return[zl(m[0],0,n)]}return n==="bool"?[C0(e[0])]:[e[0].toString()]}if(c===1){if(i>S0){let g=Bl*o,b=Array.from(e.slice(0,g)),v=Array.from(e.slice((i-Bl)*o,i*o));return n==="complex64"&&(b=Wl(b),v=Wl(v)),["["+b.map((y,x)=>zl(y,s[x],n)).join(", ")+", ..., "+v.map((y,x)=>zl(y,s[i-Bl+x],n)).join(", ")+"]"]}let m=n==="complex64"?Wl(e):Array.from(e);return["["+m.map((g,b)=>zl(g,s[b],n)).join(", ")+"]"]}let l=t.slice(1),u=r.slice(1),d=r[0]*o,p=[];if(i>S0){for(let m=0;m<Bl;m++){let g=m*d,b=g+d;p.push(...Ah(e.slice(g,b),l,n,u,s,!1))}p.push("...");for(let m=i-Bl;m<i;m++){let g=m*d,b=g+d;p.push(...Ah(e.slice(g,b),l,n,u,s,m===i-1))}}else for(let m=0;m<i;m++){let g=m*d,b=g+d;p.push(...Ah(e.slice(g,b),l,n,u,s,m===i-1))}let h=c===2?",":"";p[0]="["+p[0]+h;for(let m=1;m<p.length-1;m++)p[m]=" "+p[m]+h;let f=`,
2021-09-11 17:11:38 +02:00
`;for(let m=2;m<c;m++)f+=`
2021-10-28 19:58:21 +02:00
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function Wl(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Ut=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=$t(e),n!=null){let r=n.length;R(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||i0(t,this.size),this.strides=ji(e)}set(e,...t){t.length===0&&(t=[0]),R(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 ts().makeTensor(this.values,this.shape,this.dtype)}},ts=null,Zc=null,hF=null;function fF(e){ts=e}function mF(e){Zc=e}function gF(e){hF=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=ji(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 Zc.buffer(this.shape,this.dtype,e)}bufferSync(){return Zc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return qi(this.shape,e,this.dtype==="complex64")}arraySync(){return qi(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=ts().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>Eh(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=ts().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Eh(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 ts().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(ts().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Zc.print(this,e)}clone(){return this.throwIfDisposed(),Zc.clone(this)}toString(e=!1){let t=this.dataSync();return dF(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Zc.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),ts().makeVariable(this,e,t,n)}};Object.defineProperty(Ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function Q(){return Lb("Tensor",()=>Ee)}Q();var sa=class extends Ee{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ks(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ts().disposeTensor(this),this.dataId=e.dataId,ts().incRef(this,null)}dispose(){ts().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(sa,Symbol.hasInstance,{value:e=>e instanceof Ee&&e.assi
Manifest JSON has weights with names: ${i.join(", ")}.`)}let c=s.reduce((h,f,m)=>(f&&h.push(m),h),[]),l=[];c.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;l.push(m)})});let u=await e(l),d={},p=0;return c.forEach(h=>{let f=t[h].paths.length,m=0;for(let x=0;x<f;x++)m+=u[p+x].byteLength;let g=new ArrayBuffer(m),b=new Uint8Array(g),v=0;for(let x=0;x<f;x++){let k=new Uint8Array(u[p+x]);b.set(k,v),v+=k.byteLength}a[h].forEach(x=>{let k=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),C=R0(k,[x.manifestEntry]);for(let N in C)d[N]=C[N]}),p+=f}),d}}var h$="application/octet-stream",f$="application/json",ay=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?(R(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=J().platform.fetch,R(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&R(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=M0(e,n);t.body.append("model.json",new Blob([JSON.stringify(r)],{type:f$}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:h$}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Hl(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 ey(t,s=>this.loadWeights(s))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=m$(t),s=this.weightPathPrefix||n,a=[];for(let l of e)a.push(...l.weights);let o=[],i=[];for(let l of e)for(let u of l.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(s+u+r);this.weightUrlConverter&&o.push(...await Promise.all(i));let c=await K0(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Qb(c)]}};ay.URL_SCHEME_REGEX=/^https?:\/\//;function m$(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}function oy(e){return e.match(ay.URL_SCHEME_REGEX)!=null}var Y0=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>oy(r)):n=oy(e),n)return iy(e,t)}return null};Ft.registerSaveRouter(Y0);Ft.registerLoadRouter(Y0);function iy(e,t){return new ay(e,t)}function g$(e,t){return iy(e,t)}var cy=class{
2021-09-11 17:11:38 +02:00
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}.
2021-10-28 19:58:21 +02:00
Expected: ${a}.`)}}function U$(e,t){e().then(()=>t.fail(),()=>t())}function G$(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Zs(e)||Zs(e[0])||Zs(t)||Zs(t[0])?my(e,n,(r,s)=>r==s):my(e,t,(r,s)=>gy(r,s,0))}function H$(e,t,n){if(n==null&&(n=fy()),!gy(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function gy(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function j$(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 q$(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function fk(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?fk(n):e[t]=Ll(n)}return e}var K$="3.11.0";function X$(){J().set("PROD",!0)}function Y$(){J().set("DEBUG",!0)}function Z$(){J().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function by(e){J().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}gF(by);function J$(){z.disposeVariables()}function Cs(){return z}function Ph(){return z.memory()}function Q$(e){return z.profile(e)}function M(e,t){return z.tidy(e,t)}function De(e){Kb(e).forEach(n=>n.dispose())}function Qt(e){return z.keep(e)}function eR(e){return z.time(e)}function tR(e){return z.setBackend(e)}function nR(){return z.ready()}function rR(){return z.backendName}function sR(e){z.removeBackend(e)}function aR(e){return z.findBackend(e)}function oR(e){return z.findBackendFactory(e)}function Oh(e,t,n=1){return z.registerBackend(e,t,n)}function mk(){return z.backend}function iR(e,t){J().setPlatform(e,t)}function cR(e,t){let n=A(e,"a","add"),r=A(t,"b","add");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(Qs,s)}var Y=W({add_:cR});function uR(e,t){let n=A(e,"a","floorDiv"),r=A(t,"b","floorDiv");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(no,s)}var Mh=W({floorDiv_:uR});function lR(e,t){let n=A(e,"a","div"),r=A(t,"b","div");if([n,r]=_t(n,r),n.dtype==="int32"&&r.dtype==="int32")return Mh(n,r);let s={a:n,b:r},a={};return z.runKernel(Ja,s,a)}var ge=W({div_:lR});function dR(e,t){let n=A(e,"a","mul"),r=A(t,"b","mul");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(go,s)}var V=W({mul_:dR});function pR(e){let t=A(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return z.runKernel(kl,n)}else{let n={x:t};return z.runKernel(Xi,n)}}var Lt=W({abs_:pR});function hR(e){let n={x:A(e,"x","acos")};return z.runKernel(Yi,n)}var yy=W({acos_:hR});function fR(e){let n={x:A(e,"x","acosh")};return z.runKernel(Zi,n)}var vy=W({acosh_:fR});function mR(e){R(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),R(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((s,a)=>A(s,`tensors${a}`,"addN")),n=t[0];t.forEach(s=>{if(s.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(s=>{if(!ks(s.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=t;return z.runKernel(za,r)}var gk=W({addN_:mR});function gR(e,t=null,n=!1){let s={x:A(e,"x","all","bool")},a={axis:t,keepDims:n};return z.runKernel(Ji,s,a)}var Lh=W({all_:gR});function bR(e,t=null,n=!1){let s={x:A(e,"x","any","bool")},a={axis:t,keepDims:n};return z.runKernel(Qi,s,a)}var jl=W({any_:bR});function yR(e,t=0){let r={x:A(e,"x","argMax")},s={axis:t};return z.runKernel(Wa,r,s)}var Ko=W({argMax_:yR});function vR(e,t=0){let r={x:A(e,"x","argMin")},s={axis:t};return z.runKernel(xl,r,s)}var xy=W({argMin_:vR});function xR(e){let n={x:A(e,"x","asin")};return z.runKernel(ec,n)}var wy=W({asin_:xR});function wR(e){let n={x:A(e,"x","asinh")};return z.runKernel(tc,n)}var ky=W({asinh_:wR});function kR(e){let n={x:A(e,"x","atan")};return z.runKernel(nc,n)}var Iy=W({atan_:kR});function IR(e,t){let n=A(e,"a","atan2"),r=A(t,"b","atan2");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel(sc,s)}var Sy=W({atan2_:IR});function SR(e){let n={x:A
with dtype ${a.dtype}. `)}),n.length===1)return Ss(n[0]);let r=n,s={axis:t};return z.runKernel(oc,r,s)}var Ze=W({concat_:RR});function PR(e){let n={x:A(e,"x","sigmoid","float32")};return z.runKernel(_o,n)}var cr=W({sigmoid_:PR});function OR(e,t,n){let r=A(e,"x","slice","string_or_numeric");if(r.rank===0)throw new Error("Slicing scalar is not possible");let s={x:r},a={begin:t,size:n};return z.runKernel(Lc,s,a)}var We=W({slice_:OR});function MR(e){let n={x:A(e,"x","tanh","float32")};return z.runKernel(Po,n)}var Yo=W({tanh_:MR});function LR(e,t,n,r,s,a){let o=A(e,"forgetBias","basicLSTMCell"),i=A(t,"lstmKernel","basicLSTMCell"),c=A(n,"lstmBias","basicLSTMCell"),l=A(r,"data","basicLSTMCell"),u=A(s,"c","basicLSTMCell"),d=A(a,"h","basicLSTMCell"),p=Ze([l,d],1),h=Ae(p,i),f=Y(h,c),m=f.shape[0],g=f.shape[1]/4,b=[m,g],v=We(f,[0,0],b),y=We(f,[0,g],b),x=We(f,[0,g*2],b),k=We(f,[0,g*3],b),C=Y(V(cr(v),Yo(y)),V(u,cr(Y(o,x)))),N=V(Yo(C),cr(k));return[C,N]}var BR=W({basicLSTMCell_:LR});function zR(e,t,n){let r=A(e,"x","batchToSpaceND"),s=t.reduce((i,c)=>i*c);R(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),R(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),R(r.shape[0]%s==0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`);let a={x:r},o={blockShape:t,crops:n};return z.runKernel(ac,a,o)}var Kl=W({batchToSpaceND_:zR});function WR(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 VR(e,t,n,r,s,a){a==null&&(a=.001);let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;r!=null&&(u=A(r,"offset","batchNorm")),R(i.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),R(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),R(l==null||i.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:WR(o),scale:l,offset:u,mean:i,variance:c},h={varianceEpsilon:a},f=z.runKernel(ro,p,h);return U(f,o.shape)}var Ts=W({batchNorm_:VR});function UR(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;return r!=null&&(u=A(r,"offset","batchNorm")),R(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),R(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),R(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),l!=null&&R(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&R(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),Ts(o,i,c,u,l,a)}var xk=W({batchNorm2d_:UR});function GR(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;return r!=null&&(u=A(r,"offset","batchNorm")),R(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),R(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),R(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),l!=null&&R(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&R(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),Ts(o,i,c,u,l,a)}var wk=W({batchNorm3d_:GR});function HR(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"))
2021-09-11 17:11:38 +02:00
${s} and ${t} for depthToSpace with input shape
2021-10-28 19:58:21 +02:00
${r.shape}`),R(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
2021-09-11 17:11:38 +02:00
${a} and ${t} for depthToSpace with input shape
2021-10-28 19:58:21 +02:00
${r.shape}`),R(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`);let i={x:r},c={blockSize:t,dataFormat:n};return z.runKernel(cc,i,c)}var $y=W({depthToSpace_:pP});function hP(e,t,n,r,s="NHWC",a=[1,1],o){let i=A(e,"x","depthwiseConv2d","float32"),c=A(t,"filter","depthwiseConv2d","float32"),l=i,u=!1;i.rank===3&&(u=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),R(l.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`),R(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),R(l.shape[3]===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),o!=null&&R(Yt(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:l,filter:c},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},h=z.runKernel(Za,d,p);return u?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var la=W({depthwiseConv2d_:hP});function fP(e){let n={x:A(e,"x","diag")};return z.runKernel(Jp,n)}var mP=W({diag_:fP});function gP(e,t,n,r,s=[1,1],a="NHWC"){let o=A(e,"x","dilation2d"),i=A(t,"filter","dilation2d");R(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),R(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),R(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let c=o,l=!1;o.rank===3&&(c=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=!0);let u={x:c,filter:i},d={strides:n,pad:r,dilations:s},p=z.runKernel(Sl,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Ry=W({dilation2d_:gP});function bP(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 Ht(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 gt(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 yP(e,t){let n=A(e,"a","equal","string_or_numeric"),r=A(t,"b","equal","string_or_numeric");[n,r]=_t(n,r),gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(lc,s)}var Kn=W({equal_:yP});function vP(e,t,n){let r=A(t,"a","where"),s=A(n,"b","where"),a=A(e,"condition","where","bool"),o=gt(gt(a.shape,r.shape),s.shape),i=ru(a,o),c=ru(r,o),l=ru(s,o),u={condition:i,t:c,e:l};return z.runKernel(Oc,u)}var gn=W({where_:vP});function xP(e){let n={x:A(e,"x","zerosLike")};return z.runKernel(Kc,n)}var Ue=W({zerosLike_:xP});function wP(e,t){let n=A(e,"a","div"),r=A(t,"b","div");[n,r]=_t(n,r);let s=ge(n,r),a=Ue(s),o=Kn(r,a);return gn(o,a,s)}var Py=W({divNoNan_:wP});function kP(e,t){let n=A(e,"t1","dot"),r=A(t,"t2","dot");R((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(R(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=Ae(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=Ae(o,i);return U(c,[c.size])}else if(n.rank===2&&r.rank===1){let o=U(r,[-1,1]),i=Ae(n,o);return U(i,[i.size])}else{let o=U(r,[r.shape[0],r.shape[1]]);return Ae(n,o)}}var Dk=W({dot_:kP});function IP(e,...t){let n=t.map((s,a)=>A(s,`tensors${a}`,"einsum")),r={equation:e};return z.runKernel(th,n,r)}var Fk=W({einsum_:IP});function SP(e){let n={x:A(e,"x","elu","float32")};return z.runKernel(Qa,n)}var su=W({elu_:SP});function CP(e){let t=A(e,"x","erf");R(t.dtype==="int32"||t.dtype==="floa
rank ${a.rank}.`),R(Yt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=U(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let c={x:o},l={depthRadius:t,bias:n,alpha:r,beta:s},u=z.runKernel(_l,c,l);return i?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var zy=W({localResponseNormalization_:VP});function UP(e){let n={x:A(e,"x","log","float32")};return z.runKernel(io,n)}var Xn=W({log_:UP});function GP(e){let n={x:A(e,"x","log1p")};return z.runKernel(kc,n)}var Zl=W({log1p_:GP});function HP(e){return R(Js(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let r=A(t,"x","tf.grad","string_or_numeric"),s=n!=null?A(n,"dy","tf.grad"):null;return z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(r),[r],s);return s!=null&&wn(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),jh(o),o[0]})}}function jP(e){return R(Js(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{R(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let r=Gl(t,"args","tf.grads","string_or_numeric"),s=n!=null?A(n,"dy","tf.grads"):null;return z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(...r),r,s);return s!=null&&wn(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),jh(o),o})}}function qP(e){return R(Js(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{R(t instanceof Ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),R(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:r,value:s}=z.gradients(()=>e(t),[t],n);return jh(r),{grad:r[0],value:s}}}function KP(e){return R(Js(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{R(Array.isArray(t)&&t.every(s=>s instanceof Ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),R(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let r=z.gradients(()=>e(...t),t,n);return n!=null&&wn(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),jh(r.grads),r}}function Ok(e,t){R(Js(e),()=>"The f passed in variableGrads(f) must be a function"),R(t==null||Array.isArray(t)&&t.every(l=>l instanceof sa),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let l in z.registeredVariables)t.push(z.registeredVariables[l])}let r=n?t.filter(l=>!l.trainable):null,s=t.length;t=t.filter(l=>l.trainable),R(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);let a=!0,{value:o,grads:i}=z.gradients(e,t,null,a);R(i.some(l=>l!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),R(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let c={};return t.forEach((l,u)=>{i[u]!=null&&(c[l.name]=i[u])}),r!=null&&r.forEach(l=>c[l.name]=null),{value:o,grads:c}}function ss(e){return z.customGrad(e)}function jh(e){if(e.filter(n=>n==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`)}function XP(e){let n={x:A(e,"x","neg")};return z.runKernel(Cc,n)}var kt=W({neg_:XP});function YP(e){let n={x:A(e,"x","softplus")};return z.runKernel(Wc,n)}var Jo=W({softplus_:YP});function ZP(e){let t=A(e,"x","logSigmoid");return ss(r=>({value:kt(Jo(kt(r))),gradFunc:o=>V(o,cr(kt(r)))}))(t)}var Mk=W({logSigmoid_:ZP});function JP(e,t=null,n=!1){let s={x:A(e,"x","max")},a={reductionIndices:t,keepDims:n};return z.runKernel(co,s,a)}var kr=W({max_:JP});function QP(e,t){let n=A(e,"a","sub"),r=A(t,"b","sub");[n,r]=_t(n,r);let s={a:n,b:r};return z.runKernel($o,s)}var fe=W({sub_:QP});function eO(e,t=null,n=!1){let r=A(e,"x","sum");r.dtype==="bool"&&(r=ce(r,"int32"));let s={x:r},a={axis:t,keepDims:n};return z.runKernel(Ao,s,a)}var ve=W({sum_:eO});function tO(e,t=-1){let n=A(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return ss((s,a)=>{let o=!0,i=kr(s,t,!0),c=fe(s,i),l=fe(ce(c,"float32"),Xn(ve(bn(c),t,o)));return a([l]),{value:l,gradFunc:(d,p)=>{let[h]=p,f=!0,m=bn(h);return fe(d,V(ve(d,t,f),m))}}})(n)}var qh=W({logSoftmax_:tO});function Wy(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Lk(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 Bk(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 Qo(e,t){let n=t.map(r=>1);return Lk(e,n,t)}function nO(e,t,n){R(Wy(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function zk(e,t){if(Wy(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 Vy(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function rO(e,t){let n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function sO(e,t=null,n=!1){let r=A(e,"x","logSumExp"),s=xr(t,r.shape),a=kr(r,s,!0),o=fe(r,a),i=bn(o),c=ve(i,s),l=Xn(c),u=Y(U(a,l.shape),l);if(n){let d=Qo(u.shape,s);return U(u,d)}return u}var Uy=W({logSumExp_:sO});function aO(e,t){let n=A(e,"a","logicalAnd","bool"),r=A(t,"b","logicalAnd","bool");gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(Ic,s)}var Ir=W({logicalAnd_:aO});function oO(e){let n={x:A(e,"x","logicalNot","bool")};return z.runKernel(Tl,n)}var Jl=W({logicalNot_:oO});function iO(e,t){let n=A(e,"a","logicalOr","bool"),r=A(t,"b","logicalOr","bool");gt(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(Nl,s)}var Kh=W({logicalOr_:iO});function cO(e,t){let n=A(e,"a","logicalXor","bool"),r=A(t,"b","logicalXor","bool");return gt(n.shape,r.shape),Ir(Kh(e,t),Jl(Ir(e,t)))}var Wk=W({logicalXor_:cO});function uO(e,t,n,r,s){let a=A(e,"x","maxPool"),o=1,i=a,c=!1;a.rank===3&&(c=!0,i=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),R(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),R(rs(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),s!=null&&R(Yt(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s},d=z.runKernel(lo,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Pt=W({maxPool_:uO});function lO(e,t=[1,1,1],n,r,s,a="NDHWC"){let o=A(e,"x","maxPool3d"),i=o,c=!1;o.rank===4&&(c=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),R(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),R(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),s!=null&&R(Yt(r),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},d=z.runKernel(El,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Gy=W({maxPool3d_:lO});function dO(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},l=z.runKernel(mh,c);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}var IL=W({sparseFillEmptyRows_:kL});function SL(e,t,n){let r=A(e,"inputIndices","sparseReshape"),s=A(t,"inputShape","sparseReshape"),a=A(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=z.runKernel(gh,o);return{outputIndices:i[0],outputShape:i[1]}}var CL=W({sparseReshape_:SL});function TL(e,t,n){let r=A(e,"data","sparseSegmentMean"),s=A(t,"indices","sparseSegmentMean"),a=A(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
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
2021-10-28 19:58:21 +02:00
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return z.runKernel(bh,o)}var NL=W({sparseSegmentMean_:TL});function _L(e,t,n){let r=A(e,"data","sparseSegmentSum"),s=A(t,"indices","sparseSegmentSum"),a=A(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
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
2021-10-28 19:58:21 +02:00
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return z.runKernel(yh,o)}var EL=W({sparseSegmentSum_:_L});function AL(e,t,n,r,s,a,o,i){let c=A(e,"data","stringNGrams","string");if(c.dtype!=="string")throw new Error("Data must be of datatype string");if(c.shape.length!==1)throw new Error(`Data must be a vector, saw: ${c.shape}`);let l=A(t,"dataSplits","stringNGrams");if(l.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:c,dataSplits:l},p=z.runKernel(xh,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var DL=W({stringNGrams_:AL});function FL(e,t,n=!0){let r=A(e,"input","stringSplit","string"),s=A(t,"delimiter","stringSplit","string");if(r.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(s.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);let a={skipEmpty:n},o={input:r,delimiter:s},i=z.runKernel(wh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var $L=W({stringSplit_:FL});function RL(e,t){let n=A(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let s={input:n};return z.runKernel(kh,s,r)}var PL=W({stringToHashBucketFast_:RL}),OL={fft:sd,ifft:lu,rfft:ad,irfft:sf},ML={hammingWindow:hM,hannWindow:nI,frame:rI,stft:bM},Qn={flipLeftRight:wM,grayscaleToRGB:IM,resizeNearestNeighbor:uI,resizeBilinear:cI,rotateWithOffset:CM,cropAndResize:vM,nonMaxSuppression:NM,nonMaxSuppressionAsync:PM,nonMaxSuppressionWithScore:MM,nonMaxSuppressionWithScoreAsync:BM,nonMaxSuppressionPadded:WM,nonMaxSuppressionPaddedAsync:UM,threshold:KM,transform:YM},dI={bandPart:JM,gramSchmidt:eL,qr:nL},LL={absoluteDifference:aL,computeWeightedLoss:_s,cosineDistance:iL,hingeLoss:uL,huberLoss:dL,logLoss:hL,meanSquaredError:mL,sigmoidCrossEntropy:yL,softmaxCrossEntropy:wL},od={sparseFillEmptyRows:IL,sparseReshape:CL,sparseSegmentMean:NL,sparseSegmentSum:EL},ff={stringNGrams:DL,stringSplit:$L,stringToHashBucketFast:PL},Es=class extends dk{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 De(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 Ok(e,t)}dispose(){this.iterations_!=null&&De(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Se(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(Es,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var mf=class extends Es{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=z.registeredVariables[n],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:M(()=>Ue(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:M(()=>Ue(s).variable(a))});let o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;M(()=>{let l=Y(V(i,this.rho),V(ct(o),1-this.rho)),u=V(ge(un(Y(c,this.epsilon)),un(Y(i,this.epsilon))),o),d=Y(V(c,this.rho),V(ct(u),1-this.rho));i.assign(l),c.assign(d);let p=Y(V(u,-this.learningRate),s);s.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpda
${a}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let d=0;d<r;++d)if(e.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${e.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);let o=e.shape[n],i=[],c=1,l=1,u=1;for(let d=0;d<r;++d)i.push(e.shape[d]),c*=e.shape[d];for(let d=r;d<n;d++)i.push(e.shape[d]),l*=e.shape[d];for(let d=r;d<s;d++)i.push(t.shape[d]);for(let d=n+1;d<a;d++)i.push(e.shape[d]),u*=e.shape[d];return{batchSize:c,sliceSize:u,outerSize:l,dimSize:o,outputShape:i}}function xB(e){try{return e.map(t=>Eh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function wB(e){return e.map(t=>Ll(t))}var is={};$e(is,{nonMaxSuppressionV3Impl:()=>sI,nonMaxSuppressionV4Impl:()=>aI,nonMaxSuppressionV5Impl:()=>oI,whereImpl:()=>Kk});var yI={kernelName:Xi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,du(ce(n,"float32"),-1))}}},kB={kernelName:Yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=ct(ce(n,"float32")),s=un(fe(Se(1),r));return kt(ge(e,s))}}}},IB={kernelName:Zi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=un(fe(ct(ce(n,"float32")),1));return ge(e,r)}}}},SB={kernelName:Qs,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=e,c=Ht(n.shape,s);return c.length>0&&(i=ve(i,c)),U(i,n.shape)},b:()=>{let i=e,c=Ht(r.shape,s);return c.length>0&&(i=ve(i,c)),U(i,r.shape)}}}},CB={kernelName:za,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((r,s)=>{n[s]=()=>e.clone()}),n}},TB={kernelName:Wa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ue(n)}}},NB={kernelName:xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ue(n)}}},_B={kernelName:ec,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,un(fe(Se(1),ct(ce(n,"float32")))))}}},EB={kernelName:tc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=un(Y(Se(1),ct(ce(n,"float32"))));return ge(e,r)}}}},AB={kernelName:sc,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=Y(ct(n),ct(r)),c=V(e,ge(r,i)),l=Ht(n.shape,s);return l.length>0&&(c=ve(c,l)),U(c,n.shape)},b:()=>{let i=Y(ct(n),ct(r)),c=kt(V(e,ge(n,i))),l=Ht(r.shape,s);return l.length>0&&(c=ve(c,l)),U(c,r.shape)}}}},DB={kernelName:nc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Y(ct(ce(n,"float32")),1))}}},FB={kernelName:rc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,fe(Se(1),ct(ce(n,"float32"))))}}};function $B(e,t,n,r,s,a){let o=A(e,"dy","avgPool3dGrad"),i=A(t,"input","avgPool3dGrad"),c=o,l=i,u=!1;i.rank===4&&(u=!0,c=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),l=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),R(c.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),R(l.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`),a!=null&&R(Yt(s),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let d={dy:c,input:l},p={filterSize:n,strides:r,pad:s,dimRoundingMode:a},h=z.runKernel(Vp,d,p);return u?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var RB=W({avgPool3dGrad_:$B}),PB={kernelName:wl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>RB(e,r,s,a,o,i)}}};function OB(e,t,n,r,s){let a=A(e,"dy","avgPoolGrad"),o=A(t,"input","avgPoolGrad");R(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,c=a,l=!1;o.rank===3&&(l=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),R(c.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${c.rank}.`),R(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let u={dy:c,input:i},d={filterSize:n,strides:r,pad:s},p=z.runKernel(Wp,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var MB=W({avgPoolGrad_:OB}),LB={kernelName:Va,inputsToSave:["x"],gradFunc:(e,
2021-09-11 17:11:38 +02:00
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{let a=e;if(a.className==null||a.config==null)throw new H(`${r}: Improper config format: ${JSON.stringify(a)}.
2021-10-22 15:06:43 +02:00
'className' and 'config' must set.`);let o=a.className,i,c;if(o in n?[i,c]=n[o]:o in Sr?[i,c]=Sr.className:o in t&&([i,c]=t[o]),i==null)throw new H(`Unknown ${r}: ${o}. This may be due to one of the following reasons:
2021-09-11 17:11:38 +02:00
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2021-10-28 19:58:21 +02:00
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(c!=null){let l={};for(let h of Object.keys(Sr))l[h]=Sr[h];for(let h of Object.keys(n))l[h]=n[h];let u=a.config;u.customObjects=l;let d=Object.assign({},Sr);for(let h of Object.keys(n))Sr[h]=n[h];dv(a.config);let p=c(i,a.config,n,s);return Sr=Object.assign({},d),p}else{let l=Object.assign({},Sr);for(let d of Object.keys(n))Sr[d]=n[d];let u=new i(a.config);return Sr=Object.assign({},l),u}}}function I4(e,t){return e<t?-1:e>t?1:0}function wf(e,t){return-1*I4(e,t)}function ma(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function S4(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 ai(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 pv(e,t,n=0,r=1/0){return cs(n>=0),cs(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(s=>typeof s===t)}function tn(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,r)=>tn(n,`element ${r+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${EI(e)}.`)}function EI(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>EI(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function C4(e,t,n){let r=n!=null?n():w.now(),s;return(...o)=>{let i=n!=null?n():w.now();return i-r<t||(r=i,s=e(...o)),s}}function AI(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function hv(e,t){return M(()=>un(ve(V(e,e),t,!0)))}var ud=class extends ie.Serializable{getConfig(){return{}}},fv=class extends ud{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=hv(e,this.axis),n=en(t,0,this.maxValue);return V(e,ge(n,Y(jt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};fv.className="MaxNorm";ie.registerClass(fv);var mv=class extends ud{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return M(()=>ge(e,Y(jt(),hv(e,this.axis))))}getConfig(){return{axis:this.axis}}};mv.className="UnitNorm";ie.registerClass(mv);var gv=class extends ud{apply(e){return je(e)}};gv.className="NonNeg";ie.registerClass(gv);var bv=class extends ud{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=hv(e,this.axis),n=Y(V(this.rate,en(t,this.minValue,this.maxValue)),V(1-this.rate,t));return V(e,ge(n,Y(jt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};bv.className="MinMaxNorm";ie.registerClass(bv);var DI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function qt(e){return lv(e)}function FI(e,t={}){return cd(e,ie.SerializationMap.getMap().classNameMap,t,"constraint")}function Kt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in DI?DI[e]:e,config:{}};return FI(n)}else return e instanceof ud?e:FI(e)}function T4(e){return new fv(e)}function N4(e){return new mv(e)}function _4(){return new gv}function E4(e){return new bv(e)}var $I={};$e($I,{constant:()=>J4,glorotNormal:()=>aW,glorotUniform:()=>sW,heNormal:()=>oW,heUniform:()=>iW,identity:()=>nW,leCunNormal:()=>cW,leCunUniform:()=>uW,ones:()=>Z4,orthogonal:()=>lW,randomNormal:()=>eW,randomUniform:()=>Q4,truncatedNormal:()=>tW,varianceScaling:()=>rW,zeros:()=>Y4});var A4=["channelsFirst","channelsLast"],D4=["nearest","bilinear"],F4=["valid","same","causal"],$4=["max","avg"],R4=["sum","mul","concat","ave"],hu=new Map;function Mt(e){ai(A4,"DataFo
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Nr(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,Qt(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 qn([],[0].concat(this.elementShape));let n=this.readMany(e);return Nr(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Ot(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return qn([],[0].concat(this.elementShape));let t=[];for(let r=0;r<this.size();r++)t.push(r);let n=this.readMany(t);return Nr(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Ze(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,dt(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,r=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
2021-09-11 17:11:38 +02:00
tensor.shape[0], but sum of lengths is
2021-10-28 19:58:21 +02:00
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let s=n===0?0:t.size/n,a=[];M(()=>{t=U(t,[1,n,s]);for(let i=0;i<e.length;++i){let c=i===0?0:r[i-1],l=[0,c,0],u=[1,e[i],s];a[i]=U(We(t,l,u),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},Nd=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}`);Nr(t,s.shape,"TensorList shape mismatch: "),Qt(s)}),this.idTensor=Se(0),this.maxNumElements=r,Qt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Nd([...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.`);Nr(e,this.elementShape,"TensorList shape mismatch: ");let r=Td(this.elementShape,this.tensors,e);return M(()=>{let s=this.tensors.map(a=>U(a,r));return Ot(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Td(this.elementShape,this.tensors,e),r=this.tensors.pop();return Nr(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(Nr(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Qt(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.`);Nr(this.tensors[e].shape,t,"TensorList shape mismatch: ");let r=Td(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.`);Nr(this.elementShape,t.shape,"TensorList shape mismatch: "),Qt(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}`);Nr(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let r=Td(this.elementShape,this.tensors,n);return e.length===0?qn([],[0].concat(r)):M(()=>{let s=e.map(a=>U(this.tensors[a],r));return Ot(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Nr(this.elementShape,t,"TensorList shape mismatch: ");let n=Td(this.elementShape,this.tensors,t);return this.size()===0?qn([],[0].concat(n)):M(()=>{let r=this.tensors.map(s=>U(s,n));return Ze(r,0)})}};function $G(e,t,n){let r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor m
2021-09-11 17:11:38 +02:00
tensor.shape[0], but sum of lengths is
2021-10-28 19:58:21 +02:00
${r}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=iw(a,n),i=r===0?0:e.size/r,c=M(()=>{let u=[];e=U(e,[1,r,i]);for(let d=0;d<t.length;++d){let p=d===0?0:s[d-1],h=[0,p,0],f=[1,t[d],i];u[d]=U(We(e,h,f),o)}return e.dispose(),u}),l=new Nd([],n,e.dtype,t.length);for(let u=0;u<c.length;u++)l.setItem(u,c[u]);return l}var MG=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let r=I("thenBranch",e,t,n),s=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let r=I("body",e,t,n),s=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(u=>u.id),c=await o[0].data();o.forEach(u=>{!u.kept&&i.indexOf(u.id)===-1&&u.dispose()});let l=a;for(;c[0];){let u=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);let d=l.map(h=>h.id);u.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[s].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);c=await p[0].data(),p.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return l}case"LoopCond":{let r=I("pred",e,t,n);return[Rs(r)]}case"Switch":{let r=I("pred",e,t,n),s=I("data",e,t,n);return s.kept||(s=Rs(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{let r=e.inputNames.find(s=>Cn(s,t,n)!==void 0);if(r){let s=Cn(r,t,n);return[Rs(s)]}return}case"Enter":{let r=I("frameName",e,t,n),s=I("tensor",e,t,n);return n.enterFrame(r),[Rs(s)]}case"Exit":{let r=I("tensor",e,t,n);return n.exitFrame(),[Rs(r)]}case"NextIteration":{let r=I("tensor",e,t,n);return n.nextIteration(),[Rs(r)]}case"TensorArrayV3":{let r=I("size",e,t,n),s=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),c=I("identicalElementShapes",e,t,n),l=I("name",e,t,n),u=new FG(l,s,r,a,c,o,i);return n.addTensorArray(u),[u.idTensor,Se(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[Se(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=PG(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=RG(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),tr(async()=>(await n.iterator()).columnMajorBatch(e,t,OH),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,tr(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,tr(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 tr(async()=>(await t.iterator()).map(n=>M(()=>e(n))),this.size)}mapAsync(e){let t=this;return tr(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 tr(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,tr(async()=>{let r=dw(async()=>({value:await t.iterator(),done:!1}));return xH(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,tr(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=pH.alea(t||w.now().toString());return tr(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,tr(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()}};wu.MAX_BUFFER_SIZE=1e4;function tr(e,t=null){return new class extends wu{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function RH(e){return tr(async()=>jC(e),e.length)}function PH(e){if(!xu(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 tr(async()=>{let n=await GC(e,r=>{if(r instanceof wu)return{value:r.iterator(),recurse:!1};if(xu(r))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return wH(n,ka.SHORTEST)},t)}function OH(e){if(e===null)return null;let t=e[0];return gH(t)?{value:MH(e),recurse:!1}:{value:null,recurse:!0}}function MH(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ee?Ot(e):qn(e)}var YC=class extends wu{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))}},nm='"',_d=Symbol("out"),ZC=Symbol("field"),rm=Symbol("quote"),hw=Symbol("quoteafterquote"),JC=Symbol("quoteinquote"),QC=class extends wu{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 YC(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 l=Number(i);if(isNaN(l))o&&o.dtype==="bool"?c=this.getBoolean(i):c=i;else if(!o||!o.dtype)c=l;else switch(o.dtype){case"float32":c=l;break;case"int32":c=Math.floor(l);break;case"bool":c=this.getBoolean(i);break;default:c=l}}o&&o.isLabel?r[a]=c:n[a]=c}}return Object.keys(r).length===0?n:{xs:n,ys:r}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],r=0,s=e.length,a=_d;for(let o=0;o<s;o++)switch(a){case _d:switch(e.charAt(o)){case nm:r=o+1,a=rm;break;case this.delimiter:if(r=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=_d;break;default:a=ZC,r=o;break}break;case ZC:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o)),a=_d,r=o+1;break;default:}break;case rm:switch(e.charAt(o)){case nm:a=hw;break;default:}break;case hw:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o-1)),a=_d,r=o+1;break;case nm:a=rm;break;default:a=JC;break}break;case JC:switch(e.charAt(o)){case nm:a=rm;break;default:}break;default:}if(a===hw?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}},eT=class extends nn{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSi
2021-09-11 17:11:38 +02:00
============================
Hi there \u{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.
2021-10-28 19:58:21 +02:00
============================`));let r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return E.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 ze(e.shape,e.dtype,n)}makeOutput(e,t,n){let r=this.write(e,t,n);return Cs().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){Ie([e],"where");let t=this.readSync(e.dataId);return ZH(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};fw.nextDataId=0;var cT={};$e(cT,{addImpl:()=>lT,bincountImpl:()=>gw,bincountReduceImpl:()=>dT,ceilImpl:()=>pT,concatImpl:()=>bw,equalImpl:()=>hT,expImpl:()=>mT,expm1Impl:()=>bT,floorImpl:()=>yT,gatherNdImpl:()=>vT,gatherV2Impl:()=>xT,greaterEqualImpl:()=>kT,greaterImpl:()=>wT,lessEqualImpl:()=>ST,lessImpl:()=>IT,linSpaceImpl:()=>CT,logImpl:()=>TT,maxImpl:()=>NT,maximumImpl:()=>_T,minimumImpl:()=>ET,multiplyImpl:()=>yw,negImpl:()=>AT,notEqualImpl:()=>DT,prodImpl:()=>FT,rangeImpl:()=>xw,rsqrtImpl:()=>$T,sigmoidImpl:()=>B6,simpleAbsImpl:()=>uT,sliceImpl:()=>om,sparseFillEmptyRowsImpl:()=>PT,sparseReshapeImpl:()=>OT,sparseSegmentReductionImpl:()=>ww,sqrtImpl:()=>V6,squaredDifferenceImpl:()=>MT,stridedSliceImpl:()=>LT,stringNGramsImpl:()=>BT,stringSplitImpl:()=>zT,stringToHashBucketFastImpl:()=>WT,subImpl:()=>VT,tileImpl:()=>UT,topKImpl:()=>HT,transposeImpl:()=>vw,uniqueImpl:()=>jT});function uT(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var JH=e=>{let{x:t}=e.inputs,n=e.backend;Ie(t,"abs");let r=new Float32Array(w.sizeFromShape(t.shape)),s=n.data.get(t.dataId).values;return r=uT(s),n.makeOutput(r,t.shape,t.dtype)},QH={kernelName:Xi,backendName:"cpu",kernelFunc:JH};function zt(e){return(t,n,r,s,a)=>{let o=E.assertAndGetBroadcastShape(t,n),i=o.length,c=w.computeStrides(o),l=w.sizeFromShape(o),u=w.getTypedArrayFromDType(a,l),d=t.length,p=n.length,h=w.computeStrides(t),f=w.computeStrides(n),m=E.getBroadcastDims(t,o),g=E.getBroadcastDims(n,o);if(m.length+g.length===0)for(let b=0;b<u.length;++b)u[b]=e(r[b%r.length],s[b%s.length]);else for(let b=0;b<u.length;++b){let v=w.indexToLoc(b,i,c),y=v.slice(-d);m.forEach(N=>y[N]=0);let x=w.locToIndex(y,d,h),k=v.slice(-p);g.forEach(N=>k[N]=0);let C=w.locToIndex(k,p,f);u[b]=e(r[x],s[C])}return[u,o]}}function nr(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 e6={kernelName:Hp,backendName:"cpu",kernelFunc:nr};function sm(e,t,n="float32"){if(n==="complex64"){let s=sm(e,t,"float32"),a=sm(e,t,"float32")
indices.shape[0] = ${i}`);let g=w.getArrayFromDType(n,0),b=w.getArrayFromDType(s,0);return[g,[0,d],b,l,u]}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;l[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 v=0;v<i;++v)u[v]=v;return[g,[i,d],b,l,u]}else{let g=f[c-1],b=w.getArrayFromDType(n,g*d),v=w.getArrayFromDType(s,g),y=new Array(c).fill(0);for(let x=0;x<i;++x){let k=e[x*d],C=y[k],N=(k===0?0:f[k-1])+C;y[k]++;for(let D=0;D<d;++D)b[N*d+D]=e[x*d+D];v[N]=r[x],u[x]=N}for(let x=0;x<c;++x)if(y[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;v[C]=o}return[b,[g,d],v,l,u]}}function OT(e,t,n,r,s){let a=w.sizeFromShape(r),o=t[0],i=s.length,c=[],l=1,u=-1;for(let g=0;g<i;++g){let b=s[g];if(b===-1){if(u!==-1)throw new Error(`only one output dimension may be -1, not both ${u} and ${g}`);u=g,c.push(1)}else{if(b<0)throw new Error(`size ${g} must be non-negative, not ${b}`);l*=b,c.push(b)}}if(u!==-1){if(l<=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/l);if(l*g!==a)throw new Error(`Input to reshape is a SparseTensor with ${a}
dense values, but the requested shape requires a multiple of ${l}. inputShape=${r} outputShape= ${c}`);c[u]=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 v=0;v<p;++v)b+=e[g*p+v]*h[v];for(let v=0;v<i;++v)m[g*i+v]=Math.trunc(b/f[v]),b%=f[v]}return[m,[o,i],c]}function ww(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]],l=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((y,x)=>y*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,v=s[m];for(;;){let y=0;if(g<i){if(y=s[g],v===y){++g;continue}if(v>=y)throw new Error("segment ids are not increasing")}if(v<0||v>=d)throw new Error(`Segment id ${v} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);v>b&&f.fill(o,b*l,v*l);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<l;C++)f[v*l+C]+=e[k*l+C]}if(a)for(let x=0;x<l;x++)f[v*l+x]/=g-m;if(m=g,++g,b=v+1,v=y,g>i)break}return b<d&&f.fill(o,b*l,d*l),[f,p]}var V6=Sa(e=>Math.sqrt(e)),U6=ot(Eo,e=>Math.sqrt(e)),G6={kernelName:Eo,backendName:"cpu",kernelFunc:U6},MT=zt((e,t)=>{let n=e-t;return n*n}),H6=rn(Fo,MT),j6={kernelName:Fo,backendName:"cpu",kernelFunc:H6};function LT(e,t,n,r){let s=ze(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 q6=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),l=Math.max(0,i-(s-(o+1))),u=a-(c+l),d=t+(c>0?0:o-i),p=0;p+=c*this.leftPad.length;for(let b=0;b<u;++b)p+=e[d+b].length;p+=l*this.rightPad.length,p+=(c+l+u-1)*this.separator.length,n[r+o]=new Uint8Array(p);let f=n[r+o],m=0,g=b=>b.forEach(v=>f[m++]=v);for(let b=0;b<c;++b)g(this.leftPad),g(this.separator);for(let b=0;b<u-1;++b)g(e[d+b]),g(this.separator);if(u>0){g(e[d+u-1]);for(let b=0;b<l;++b)g(this.separator),g(this.rightPad)}else{for(let b=0;b<l-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 l=t[c]>=i;if(l=l&&t[c]<=n,!l)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],l=0;this.nGramWidths.forEach(u=>{l+=this.getNumNGrams(c,u)}),this.preserveShort&&c>0&&l===0&&(l=1),a[i]=a[i-1]+l}let o=new Array(a[s]);for(let i=0;i<s;++i){let c=t[i],l=a[i];if(this.nGramWidths.forEach(u=>{let d=t[i+1]-t[i],p=this.getNumNGrams(d,u);this.createNGrams(e,c,o,l,p,u),l+=p}),this.preserveShort&&l===a[i]){let u=t[i+1]-t[i];if(u===0)continue;let d=u+2*this.padWidth,p=1;this.createNGrams(e,c,o,l,p,d)}}return[o,a]}};function BT(e,t,n,r,s,a,o,i){return new q6(n,r,s,a,o,i).compute(e,t)}function K6(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|
2021-09-11 17:11:38 +02:00
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
2021-10-28 19:58:21 +02:00
${o.shape}`);let i=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,u=n.data.get(o.dataId).values[0],[d,p,h,f,m]=PT(i,r.shape,r.dtype,c,s.dtype,l,u);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var uK={kernelName:mh,backendName:"cpu",kernelFunc:cK};function lK(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
2021-09-11 17:11:38 +02:00
${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
2021-10-28 19:58:21 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.data.get(s.dataId).values),i=n.data.get(r.dataId).values,c=Array.from(n.data.get(a.dataId).values),[l,u,d]=OT(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(u,r.dtype,l),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var dK={kernelName:gh,backendName:"cpu",kernelFunc:lK};function pK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2021-10-28 19:58:21 +02:00
${a.shape}`);let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[l,u]=ww(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(u,r.dtype,l)}var hK={kernelName:bh,backendName:"cpu",kernelFunc:pK};function fK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2021-10-28 19:58:21 +02:00
${a.shape}`);let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[l,u]=ww(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(u,r.dtype,l)}var mK={kernelName:yh,backendName:"cpu",kernelFunc:fK};function gK(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:p}=E.calculateShapes(a,s,i),h=!1,f=n.bufferSync(s),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],b=u2(f,m,i,p,u,l,c,d,g,h);return n.makeTensorInfo(i,b.dtype,b.values)}var bK={kernelName:vh,backendName:"cpu",kernelFunc:gK};function yK(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=E.prepareSplitSize(s,a,i),l=new Array(s.shape.length).fill(0),u=s.shape.slice();return c.map(d=>{let p=[...u];p[i]=d;let h=hi({inputs:{x:s},backend:n,attrs:{begin:l,size:p}});return l[i]+=d,h})}var vK={kernelName:Uc,backendName:"cpu",kernelFunc:yK},xK={kernelName:Fl,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,r=t;Ie(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}}},wK=ot(na,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),kK={kernelName:na,backendName:"cpu",kernelFunc:wK};function IK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r;Ie(s,"stridedSlice");let{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:v,end:y,strides:x}=Gt.sliceInfo(s.shape,a,o,i,c,l,u,d,p),k;if(m)k=Tt({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||b){w.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let C=Gt.computeOutShape(v,y,x),N=hi({inputs:{x:s},backend:n,attrs:{begin:v,size:C}});k=Tt({inputs:{x:N},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(N)}else{let C=n.bufferSync(s),N=LT(h,C,x,v);k=n.makeTensorInfo(f,N.dtype,N.values)}return k}var SK={kernelName:Gc,backendName:"cpu",kernelFunc:IK};function CK(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:l}=r,{data:u,dataSplits:d}=t,p=n.data.get(u.dataId).values,h=n.data.get(d.dataId).values,[f,m]=BT(p,h,s,a,o,i,c,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var TK={kernelName:xh,backendName:"cpu",kernelFunc:CK};function NK(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,c=n.data.get(o.dataId).values[0],[l,u,d]=zT(i,c,s),p=u.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var _K={kernelName:wh,backendName:"cpu",kernelFunc:NK};function EK(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=WT(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var AK={kernelName:kh,backendName:"cpu",kernelFunc:EK},DK=ot(Ro,e=>Math.tan(e)),FK={kernelName:Ro,backendName:"cpu",kernelFunc:DK},$K=ot(Po,e=>Math.tanh(e)),RK={kernelName:Po,backendName:"cpu",kernelFunc:$K};function PK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;Ie(s,"tile");let o=UT(n.bufferSync(s),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var OK={kernelName:ta,backendName:"cpu",kernelFunc:PK};function MK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r;Ie(s,"topk");let i=n.data.get(s.dataId).values,[c,l]=HT(i,s.shape,s.dtype,a,o);return[n.makeTensorInfo
2021-10-22 15:06:43 +02:00
`),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),l=o.slice(r-1,r),u=o.slice(r);console.log(c.join(`
2021-09-11 17:11:38 +02:00
`)),console.log(t.split(`
2021-10-22 15:06:43 +02:00
`)[0]),console.log(`%c ${w.rightPad(l[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
2021-10-28 19:58:21 +02:00
`))}function y2(e){return Ps(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function v2(e,t){if(xe(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 lm(e,t){if(xe(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function x2(e,t){let n=Ps(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),xe(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function w2(e,t){let n=Ps(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return xe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),xe(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function uX(){return J().getNumber("WEBGL_VERSION")===2?1:4}function k2(e){return Ps(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function I2(e,t){let n=J().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let r=`[${e}x${t}]`;throw new Error("Requested texture size "+r+" is invalid.")}if(e>n||t>n){let r=`[${e}x${t}]`,s=`[${n}x${n}]`;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+s+".")}}function S2(e){return Ps(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Dw(e,t,n,r,s,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),xe(e,()=>e.vertexAttribPointer(i,s,e.FLOAT,!1,a,o)),xe(e,()=>e.enableVertexAttribArray(i)),!0)}function C2(e,t,n){A2(e,n),xe(e,()=>e.activeTexture(e.TEXTURE0+n)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function lX(e,t){A2(e,t),xe(e,()=>e.activeTexture(e.TEXTURE0+t)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function T2(e,t,n){return Ps(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function N2(e,t,n){return e.getUniformLocation(t,n)}function _2(e,t,n,r){xe(e,()=>C2(e,t,r)),xe(e,()=>e.uniform1i(n,r))}function dX(e){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),xe(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),xe(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function dm(e,t,n){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),xe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Fw(e,t){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),xe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Od(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+E2(e,t))}function E2(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function Ps(e,t,n){let r=xe(e,()=>t());if(r==null)throw new Error(n);return r}function A2(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n){let s=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${s}.`)}}function mi(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function gi(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 pm(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[mi(e),...gi(e)]),t}function D2(e,t=!1){let n=J().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]
2021-09-11 17:11:38 +02:00
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
#define isnan(value) isnan_custom(value)
2021-10-22 15:06:43 +02:00
`,c="",l=`
2021-09-11 17:11:38 +02:00
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
`):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",o="",i=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
2021-06-04 14:54:48 +02:00
}
2021-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-10-22 15:06:43 +02:00
`,l=`
2021-09-11 17:11:38 +02:00
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2021-10-28 19:58:21 +02:00
`),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:c,defineRound:l}}function bi(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 gm(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 mX(e,t){let n=e.length,r=e.map(a=>`${t}[${a}]`),s=new Array(n-1);s[n-2]=r[n-1];for(let a=n-3;a>=0;--a)s[a]=`(${s[a+1]} * ${r[a+1]})`;return s}function gX(e,t,n="index"){let r=e.map((a,o)=>o),s=mX(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 Pw(e){let t=w.computeStrides(e).map(n=>n.toString());return`
2021-09-11 17:11:38 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
2021-10-22 15:06:43 +02:00
`}function Ow(){return`
2021-09-11 17:11:38 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
2021-10-28 19:58:21 +02:00
`}var L2=`
2021-09-11 17:11:38 +02:00
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;
}
2021-10-28 19:58:21 +02:00
`,{getBroadcastDims:B2}=E;function bX(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}=Mw(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=>yX(h,t,n.packedInputs,n.enableShapeUniforms)).join(`
`),o=t.texShape,i=Tn(),c=wX(i),l,u,d=SX(i);return t.isPacked?(l=vX(t.logicalShape,o,n.enableShapeUniforms),u=IX(i)):(l=xX(t.logicalShape,o,n.enableShapeUniforms),u=kX(i)),n.packedInputs&&(d+=_X),[d,c,u,s,l,a,n.userCode].join(`
`)}function Nu(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return zX(e,t);case 1:return VX(e,t);case 2:return GX(e,t);case 3:return jX(e,t);case 4:return KX(e,t);case 5:return XX(e);case 6:return YX(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function z2(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return BX(e);case 1:return WX(e,t);case 2:return UX(e,t);case 3:return HX(e,t);default:return qX(e,t)}}function yX(e,t,n=!1,r){let s="";n?s+=z2(e,r):s+=Nu(e,r);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?s+=ZX(e,t):s+=JX(e,t)),s}function vX(e,t,n){switch(e.length){case 0:return W2();case 1:return EX(e,t,n);case 2:return MX(e,t,n);case 3:return DX(e,t,n);default:return $X(e,t,n)}}function xX(e,t,n){switch(e.length){case 0:return W2();case 1:return AX(e,t,n);case 2:return LX(e,t,n);case 3:return FX(e,t,n);case 4:return RX(e,t,n);case 5:return PX(e,t);case 6:return OX(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function wX(e){return`
2021-09-11 17:11:38 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function kX(e){return`
2021-09-11 17:11:38 +02:00
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function IX(e){return`
2021-09-11 17:11:38 +02:00
void setOutput(vec4 val) {
${e.output} = val;
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function SX(e){return`${e.version}
2021-09-11 17:11:38 +02:00
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
2021-10-28 19:58:21 +02:00
${CX}
${TX}
${NX}
`}var CX=`
2021-09-11 17:11:38 +02:00
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2021-10-28 19:58:21 +02:00
`,TX=`
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2021-10-28 19:58:21 +02:00
`,NX=`
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2021-10-28 19:58:21 +02:00
`,_X=`
2021-09-11 17:11:38 +02:00
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
2021-10-28 19:58:21 +02:00
`;function W2(){return`
2021-09-11 17:11:38 +02:00
int getOutputCoords() {
return 0;
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function EX(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return r[0]===1?n?`
2021-09-11 17:11:38 +02:00
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.x * ${r[1]}.0);
}
`:r[1]===1?n?`
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.y * ${r[0]}.0);
}
`:n?`
int getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function AX(e,t,n){return t[0]===1?n?`
2021-09-11 17:11:38 +02:00
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
`:`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?n?`
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
`:`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:n?`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
return resTexRC.x * outTexShape[1] + resTexRC.y;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function DX(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec3(b, r, c);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
int index = resTexRC.x * ${r[1]} + resTexRC.y;
int b = index / ${a};
index -= b * ${a};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec3(b, r, c);
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function FX(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
2021-10-28 19:58:21 +02:00
${gm(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2021-10-28 19:58:21 +02:00
`;let r=bi(["r","c","d"],e);return`
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${r}
return ivec3(r, c, d);
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function $X(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
int texelsInBatchN = texelsInBatch * outShape[1];
int b2 = index / texelsInBatchN;
index -= b2 * texelsInBatchN;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec4(b2, b, r, c);
2021-05-18 14:11:17 +02:00
}
2021-10-22 15:06:43 +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 l=2;l<e.length-1;l++)o*=e[e.length-l-1],i=`
int b${l} = index / ${o};
index -= b${l} * ${o};
`+i,c=`b${l}, `+c;return`
2021-09-11 17:11:38 +02:00
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
int index = resTexRC.x * ${r[1]} + resTexRC.y;
${i}
int b = index / ${a};
index -= b * ${a};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec${e.length}(${c});
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function RX(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
2021-10-28 19:58:21 +02:00
${gm(["r","c","d","d2"],e)}
2021-09-11 17:11:38 +02:00
return ivec4(r, c, d, d2);
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`;let r=bi(["r","c","d","d2"],e);return`
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${r}
return ivec4(r, c, d, d2);
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function PX(e,t){let n=bi(["r","c","d","d2","d3"],e);return`
2021-09-11 17:11:38 +02:00
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function OX(e,t){let n=bi(["r","c","d","d2","d3","d4"],e);return`
2021-09-11 17:11:38 +02:00
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
2021-05-18 14:11:17 +02:00
}
2021-10-28 19:58:21 +02:00
`}function MX(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return n?`
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
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-10-28 19:58:21 +02:00
`}function LX(e,t,n){return w.arraysEqual(e,t)?n?`
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:e[1]===1?n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:e[0]===1?n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
int r = index / outShape[1];
int c = index - r * outShape[1];
return ivec2(r, c);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}function yi(e){return`offset${e}`}function BX(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=Tn();return`
2021-09-11 17:11:38 +02:00
vec4 ${n}() {
return ${r.texture2D}(${t}, halfCR);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}function zX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;let[s,a]=e.shapeInfo.texShape;if(s===1&&a===1)return`
2021-09-11 17:11:38 +02:00
float ${r}() {
return sampleTexture(${n}, halfCR);
}
2021-10-28 19:58:21 +02:00
`;let o=yi(n);if(t)return`
2021-09-11 17:11:38 +02:00
float ${r}() {
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2021-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-10-28 19:58:21 +02:00
`}function WX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=Tn();if(t)return`
2021-09-11 17:11:38 +02:00
vec4 ${r}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${a.texture2D}(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;let o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return`
vec4 ${r}(int index) {
vec2 uv = packedUVfrom1D(
${o[0]}, ${o[1]}, index);
return ${a.texture2D}(${n}, uv);
}
2021-10-28 19:58:21 +02:00
`}function VX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
2021-09-11 17:11:38 +02:00
float ${r}(int index) {
2021-10-22 15:06:43 +02:00
${_u(e)}
2021-09-11 17:11:38 +02:00
}
`;let s=e.shapeInfo.texShape,a=s[0],o=s[1];if(o===1&&a===1)return`
float ${r}(int index) {
return sampleTexture(${n}, halfCR);
}
2021-10-28 19:58:21 +02:00
`;let i=yi(n);return o===1?t?`
2021-09-11 17:11:38 +02:00
float ${r}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${a}.0);
return sampleTexture(${n}, uv);
}
`:a===1?t?`
float ${r}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);
return sampleTexture(${n}, uv);
}
`:t?`
float ${r}(int index) {
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int index) {
vec2 uv = uvFromFlat(${a}, ${o}, index + ${i});
return sampleTexture(${n}, uv);
}
2021-10-28 19:58:21 +02:00
`}function UX(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=Tn();if(a!=null&&w.arraysEqual(n,a))return t?`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
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);
}
2021-10-22 15:06:43 +02:00
`;let l=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],u=Math.ceil(n[1]/2);return`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int row, int col) {
2021-10-22 15:06:43 +02:00
vec2 uv = packedUVfrom2D(${u}, ${l[0]}, ${l[1]}, row, col);
2021-09-11 17:11:38 +02:00
return ${c.texture2D}(${r}, uv);
}
2021-10-28 19:58:21 +02:00
`}function GX(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`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`;let p=a[0],h=a[1];return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
2021-10-22 15:06:43 +02:00
`}let{newShape:o,keptDims:i}=w.squeezeShape(n),c=o;if(c.length<n.length){let p=Eu(e,c),h=["row","col"];return`
${Nu(p,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
2021-10-22 15:06:43 +02:00
return ${s}(${Au(h,i)});
2021-09-11 17:11:38 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
2021-10-22 15:06:43 +02:00
${_u(e)}
2021-09-11 17:11:38 +02:00
}
2021-10-28 19:58:21 +02:00
`;let l=a[0],u=a[1],d=yi(r);return u===1?t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${r}Shape[1], 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
2021-10-22 15:06:43 +02:00
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
2021-09-11 17:11:38 +02:00
return sampleTexture(${r}, uv);
}
2021-10-22 15:06:43 +02:00
`:l===1?t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${r}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
2021-10-22 15:06:43 +02:00
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
2021-09-11 17:11:38 +02:00
return sampleTexture(${r}, uv);
}
`:t?`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${r}Shape[1] + col + ${d};
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${n[1]} + col + ${d};
2021-10-22 15:06:43 +02:00
vec2 uv = uvFromFlat(${l}, ${u}, index);
2021-09-11 17:11:38 +02:00
return sampleTexture(${r}, uv);
}
2021-10-28 19:58:21 +02:00
`}function HX(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=Eu(e,p),m=["b","row","col"];return`
${z2(f,t)}
2021-09-11 17:11:38 +02:00
vec4 ${s}(int b, int row, int col) {
2021-10-22 15:06:43 +02:00
return ${s}(${Au(m,h)});
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
`}let i=Tn();if(t)return`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${i.texture2D}(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
`;let c=o[0],l=o[1],u=Math.ceil(n[2]/2),d=u*Math.ceil(n[1]/2);return`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
2021-10-22 15:06:43 +02:00
${c}, ${l}, ${d}, ${u}, b, row, col);
2021-09-11 17:11:38 +02:00
return ${i.texture2D}(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}function jX(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),l=i;if(l.length<n.length){let m=Eu(e,l),g=["row","col","depth"];return`
2021-10-22 15:06:43 +02:00
${Nu(m,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth) {
2021-10-22 15:06:43 +02:00
return ${s}(${Au(g,c)});
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${a}, ${o}, 1)));
2021-10-22 15:06:43 +02:00
${_u(e)}
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
`;let u=e.shapeInfo.texShape,d=u[0],p=u[1],h=e.shapeInfo.flatOffset;if(p===a&&h==null)return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth) {
int stride1 = ${r}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${p}.0, ${d}.0);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;if(p===o&&h==null)return t?`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${n[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${d}.0);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`;let f=yi(r);return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${r}Shape[1] * ${r}Shape[2];
int stride1 = ${r}Shape[2];
int index = row * ${a} + col * ${o} + depth + ${f};
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} + depth + ${f};
vec2 uv = uvFromFlat(${d}, ${p}, index);
return sampleTexture(${r}, uv);
}
2021-10-28 19:58:21 +02:00
`}function qX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=Tn();if(t)return`
2021-09-11 17:11:38 +02:00
vec4 ${r}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${n}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${s.texture2D}(${n}, uv);
}
2021-10-22 15:06:43 +02:00
`;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=c[0],u=c[1],d=Math.ceil(a[o-1]/2),p=d*Math.ceil(a[o-2]/2),h="int b, int row, int col",f=`b * ${p} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<o-1;m++)h=`int b${m}, `+h,p*=a[o-m-1],f=`b${m} * ${p} + `+f;return`
2021-09-11 17:11:38 +02:00
vec4 ${r}(${h}) {
int index = ${f};
2021-10-22 15:06:43 +02:00
int texR = index / ${u};
int texC = index - texR * ${u};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${l});
2021-09-11 17:11:38 +02:00
return ${s.texture2D}(${n}, uv);
}
2021-10-28 19:58:21 +02:00
`}function KX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:c,keptDims:l}=w.squeezeShape(n);if(c.length<n.length){let v=Eu(e,c),y=["row","col","depth","depth2"];return`
${Nu(v,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2021-10-28 19:58:21 +02:00
return ${s}(${Au(y,l)});
2021-09-11 17:11:38 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${i}, ${o}, ${a}, 1)));
2021-10-22 15:06:43 +02:00
${_u(e)}
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(h===i&&u==null)return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
${f}
${m}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${o}, ${a}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
2021-10-22 15:06:43 +02:00
`;if(h===a&&u==null)return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${n[1]*n[2]}, ${n[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
2021-10-28 19:58:21 +02:00
`;let b=yi(r);return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
${f}
${m}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${b});
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} +
depth * ${a} + depth2;
vec2 uv = uvFromFlat(${p}, ${h}, index + ${b});
return sampleTexture(${r}, uv);
}
2021-10-28 19:58:21 +02:00
`}function XX(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,o=t[2]*a,i=t[1]*o,{newShape:c,keptDims:l}=w.squeezeShape(t);if(c.length<t.length){let m=Eu(e,c),g=["row","col","depth","depth2","depth3"];return`
2021-10-22 15:06:43 +02:00
${Nu(m)}
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
2021-10-22 15:06:43 +02:00
return ${r}(${Au(g,l)});
2021-09-11 17:11:38 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${i}, ${o}, ${a}, ${s})) +
depth3;
2021-10-22 15:06:43 +02:00
${_u(e)}
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&u==null)return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${o}, ${a}, ${s}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
2021-10-22 15:06:43 +02:00
`;if(h===s&&u==null)return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
2021-10-28 19:58:21 +02:00
`;let f=yi(n);return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} + depth * ${a} +
depth2 * ${s} + depth3 + ${f};
vec2 uv = uvFromFlat(${p}, ${h}, index);
return sampleTexture(${n}, uv);
}
2021-10-28 19:58:21 +02:00
`}function YX(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=Eu(e,s),b=["row","col","depth","depth2","depth3","depth4"];return`
2021-10-22 15:06:43 +02:00
${Nu(g)}
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
2021-10-22 15:06:43 +02:00
return ${r}(${Au(b,a)});
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
`}let o=t[5],i=t[4]*o,c=t[3]*i,l=t[2]*c,u=t[1]*l;if(e.shapeInfo.isUniform)return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
2021-10-22 15:06:43 +02:00
vec4(${u}, ${l}, ${c}, ${i})) +
2021-09-11 17:11:38 +02:00
dot(
vec2(depth3, depth4),
vec2(${o}, 1)));
2021-10-22 15:06:43 +02:00
${_u(e)}
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
`;let d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===u&&d==null)return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
2021-10-22 15:06:43 +02:00
vec4(${l}, ${c}, ${i}, ${o})) +
2021-09-11 17:11:38 +02:00
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
`;if(f===o&&d==null)return`
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
2021-10-28 19:58:21 +02:00
`;let m=yi(n);return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
2021-10-22 15:06:43 +02:00
int index = row * ${u} + col * ${l} + depth * ${c} +
2021-09-11 17:11:38 +02:00
depth2 * ${i} + depth3 * ${o} + depth4 + ${m};
vec2 uv = uvFromFlat(${h}, ${f}, index);
return sampleTexture(${n}, uv);
}
2021-10-22 15:06:43 +02:00
`}function _u(e){let t=e.name,n=w.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
2021-10-28 19:58:21 +02:00
`}function ZX(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=B2(e.shapeInfo.logicalShape,t.logicalShape),c=ht(o),l=o-a,u,d=["x","y","z","w","u","v"];a===0?u="":o<2&&i.length>=1?u="coords = 0;":u=i.map(v=>`coords.${d[v+l]} = 0;`).join(`
`);let p="";o<2&&a>0?p="coords":p=e.shapeInfo.logicalShape.map((v,y)=>`coords.${d[y+l]}`).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,b=w.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!b)h=`
2021-09-11 17:11:38 +02:00
return vec4(outputValue.xy, outputValue.xy);
`;else if(m&&!b)o===1?h=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:h=`
return vec4(outputValue.x);
2021-10-28 19:58:21 +02:00
`;else if(i.length){let v=a-2,y=a-1;i.indexOf(v)>-1&&i.indexOf(y)>-1?h="return vec4(outputValue.x);":i.indexOf(v)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(y)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
2021-09-11 17:11:38 +02:00
vec4 ${s}() {
${c} coords = getOutputCoords();
2021-10-22 15:06:43 +02:00
${u}
2021-09-11 17:11:38 +02:00
vec4 outputValue = get${r}(${p});
${h}
}
2021-10-28 19:58:21 +02:00
`}function JX(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`
2021-09-11 17:11:38 +02:00
float ${s}() {
return sampleTexture(${n}, resultUV);
}
2021-10-28 19:58:21 +02:00
`;let l=ht(c),u=B2(e.shapeInfo.logicalShape,t.logicalShape),d=c-i,p,h=["x","y","z","w","u","v"];i===0?p="":c<2&&u.length>=1?p="coords = 0;":p=u.map(m=>`coords.${h[m+d]} = 0;`).join(`
2021-09-11 17:11:38 +02:00
`);let f="";return c<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+d]}`).join(", "),`
float ${s}() {
2021-10-22 15:06:43 +02:00
${l} coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
${p}
return get${r}(${f});
}
2021-10-28 19:58:21 +02:00
`}function ht(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 Mw(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 Eu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Au(e,t){return t.map(n=>e[n]).join(", ")}function QX(e,t,n,r){let s=n.map((y,x)=>{let k={logicalShape:y.shape,texShape:y.isUniform?null:y.texData.texShape,isUniform:y.isUniform,isPacked:y.isUniform?!1:y.texData.isPacked,flatOffset:null};return y.texData!=null&&y.texData.slice!=null&&y.texData.slice.flatOffset>0&&(k.flatOffset=y.texData.slice.flatOffset),{name:t.variableNames[x],shapeInfo:k}}),a=s.map(y=>y.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=bX(s,o,t),c=e.createProgram(i),l=null,u=e.getUniformLocation(c,"NAN",!1);J().getNumber("WEBGL_VERSION")===1&&(l=e.getUniformLocation(c,"INFINITY",!1));let d=!1,p={},h={},f={};for(let y=0;y<t.variableNames.length;y++){let x=t.variableNames[y];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 v=[];return t.customUniforms&&t.customUniforms.forEach((y,x)=>{v[x]=e.getUniformLocation(c,y.name,d)}),{program:t,source:i,webGLProgram:c,uniformLocations:p,customUniformLocations:v,inShapeInfos:a,outShapeInfo:o,infLoc:l,nanLoc:u,inShapesLocations:h,inTexShapesLocations:f,outShapeLocation:m,outShapeStridesLocation:b,outTexShapeLocation:g}}function V2(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 e7(e,t,n,r,s){t.program.enableShapeUniforms||(V2(t.inShapeInfos,n),V2([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),J().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((c,l)=>{let u=t.program.variableNames[l],d=t.uniformLocations[u],p=t.uniformLocations[`offset${u}`],h=t.inShapesLocations[`${u}Shape`],f=t.inTexShapesLocations[`${u}TexShape`];if(h){let{uniformShape:m}=Mw(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,l)}});let i=t.outShapeLocation;if(i)switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(r
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2021-10-28 19:58:21 +02:00
${this.enableShapeUniforms?gm(["r","c","d"],e):bi(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${t.output} = result;
}
2021-10-28 19:58:21 +02:00
`}},r7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=$d.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Tn();this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2021-10-28 19:58:21 +02:00
${this.enableShapeUniforms?gm(["r","c","d"],e):bi(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
${t.output} = result;
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},s7=class{constructor(e){this.variableNames=["A"],this.outTexUsage=pr.DOWNLOAD;let t=Tn();this.outputShape=e,this.userCode=`
${L2}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
2021-10-28 19:58:21 +02:00
`}},a7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=pr.DOWNLOAD;let t=Tn();this.outputShape=e,this.userCode=`
${L2}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
2021-10-28 19:58:21 +02:00
`}},o7=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Tn();this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode=`
2021-10-22 15:06:43 +02:00
${this.enableShapeUniforms?Ow():Pw(e)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = idiv(flatIndex, 4, 1.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
vec4 values = ${n.texture2D}(A, uv);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${n.output} = vec4(${r}, 0., 0., 0.);
}
2021-10-28 19:58:21 +02:00
`}},i7=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Tn();this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let o=0;o<=1;o++){let i=a*2+o;r+=`
2021-09-11 17:11:38 +02:00
localCoords = coords;
if(localCoords[2] + ${o} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
localCoords[2] += ${o};
if (localCoords[1] + ${a} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
localCoords[1] += ${a};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = idiv(flatIndex, 4, 1.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
values = ${n.texture2D}(A, uv);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (offset == 0) {
result[${i}] = values[0];
} else if (offset == 1) {
result[${i}] = values[1];
} else if (offset == 2) {
result[${i}] = values[2];
} else {
result[${i}] = values[3];
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
`}this.userCode=`
2021-10-22 15:06:43 +02:00
${this.enableShapeUniforms?Ow():Pw(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-10-28 19:58:21 +02:00
`}},U2={};$e(U2,{bindVertexProgramAttributeStreams:()=>J2,createBufferFromOutputTexture:()=>tN,createFloat16MatrixTexture:()=>K2,createFloat16PackedMatrixTexture:()=>Z2,createFloat32MatrixTexture:()=>q2,createIndexBuffer:()=>j2,createPackedMatrixTexture:()=>Y2,createUnsignedBytesMatrixTexture:()=>X2,createVertexBuffer:()=>H2,createVertexShader:()=>G2,downloadByteEncodedFloatMatrixFromOutputTexture:()=>rN,downloadFloat32MatrixFromBuffer:()=>nN,downloadMatrixFromPackedOutputTexture:()=>aN,downloadPackedMatrixFromBuffer:()=>sN,getInternalFormatForFloat16MatrixTexture:()=>Bw,getInternalFormatForFloat16PackedMatrixTexture:()=>Vw,getInternalFormatForFloat32MatrixTexture:()=>Lw,getInternalFormatForPackedMatrixTexture:()=>Ww,getInternalFormatForUnsignedBytesMatrixTexture:()=>zw,uploadDenseMatrixToTexture:()=>Q2,uploadPixelDataToTexture:()=>eN});function G2(e){let t=Tn(),n=`${t.version}
2021-09-11 17:11:38 +02:00
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
2021-10-28 19:58:21 +02:00
}`;return g2(e,n)}function H2(e){let t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return x2(e,t)}function j2(e){let t=new Uint16Array([0,1,2,2,1,3]);return w2(e,t)}function Ld(e,t,n,r,s,a){I2(t,n);let o=k2(e),i=e.TEXTURE_2D;return xe(e,()=>e.bindTexture(i,o)),xe(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),xe(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),xe(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),xe(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),xe(e,()=>e.texImage2D(i,0,r,t,n,0,s,a,null)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function Lw(e){return e.internalFormatFloat}function q2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,Lw(r),r.textureFormatFloat,e.FLOAT)}function Bw(e){return e.internalFormatHalfFloat}function K2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,Bw(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function zw(e){return e.downloadTextureFormat}function X2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,zw(r),e.RGBA,e.UNSIGNED_BYTE)}function Ww(e){return e.internalFormatPackedFloat}function Y2(e,t,n,r){let[s,a]=Cu(t,n);return Ld(e,s,a,Ww(r),e.RGBA,e.FLOAT)}function Vw(e){return e.internalFormatPackedHalfFloat}function Z2(e,t,n,r){let[s,a]=Cu(t,n);return Ld(e,s,a,Vw(r),e.RGBA,r.textureTypeHalfFloat)}function J2(e,t,n){let r=0,s=3*4,a=3*4+2*4;return xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Dw(e,t,"clipSpacePos",n,3,a,r)&&Dw(e,t,"uv",n,2,a,s)}function Q2(e,t,n,r,s,a){xe(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),xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,c,n,r,0,e.RGBA,i,o)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function eN(e,t,n){xe(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function tN(e,t,n,r){let s=e.createBuffer();xe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));let i=4*4*t*n;return xe(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),xe(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),xe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function nN(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 rN(e,t,n,r){let[s,a]=Rd(t,n),o=4,i=new Uint8Array(nX(t*n,o));return xe(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function sN(e,t,n,r,s,a,o,i){let c=e,l=new Float32Array(rX(a,o));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,l),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),l}function aN(e,t,n){let r=new Float32Array(t*n*4);return xe(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}var oN=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=J().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,h2(t,e)):this.gl=fs(t);let n="WEBGL_color_buffer_float",r="EXT_color_buffer_half_float";if(J().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Pd(this.gl,s),hr(this.gl,a))this.textureHalfFloatExtension=Pd(this.gl,a);else if(J().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),hr(this.gl,r))this.colorBufferHalfFloatExtension=Pd(this.gl,r);else if(J().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",hr(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(hr(this.gl,r))this.
2021-09-11 17:11:38 +02:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2021-10-28 19:58:21 +02:00
`;else{let n=Nn("rc",t),r=ht(t),s=Y7(t,e,n),a=Z7(t,e[e.length-1],e[e.length-2],n),o=J7(e,n);this.userCode=`
2021-09-11 17:11:38 +02:00
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-10-28 19:58:21 +02:00
`}}};function X7(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 Y7(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 Z7(e,t,n,r){if(e===1)return"";let s=r.slice(-2);return`
2021-09-11 17:11:38 +02:00
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};
2021-10-28 19:58:21 +02:00
`}function J7(e,t){let n=e.length,r=X7(n,t);return n===1?`getA(rc),
2021-09-11 17:11:38 +02:00
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${r[0]}),
cEdge ? 0. : getA(${r[1]}),
rEdge ? 0. : getA(${r[2]}),
2021-10-28 19:58:21 +02:00
rEdge || cEdge ? 0. : getA(${r[3]})`}var dN=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length);let n="";for(let r=0;r<4;r++){let s="thisRC = rc;";r%2==1&&(s+="thisRC.z += 1;"),r>1&&(s+="thisRC.y += 1;"),n+=`
2021-09-11 17:11:38 +02:00
${s}
${r>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result[${r}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${r>0?"}":""}
`}this.userCode=`
2021-10-28 19:58:21 +02:00
${Q7(t,this.enableShapeUniforms)}
2021-10-22 15:06:43 +02:00
${this.enableShapeUniforms?Ow():Pw(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-10-28 19:58:21 +02:00
`}};function Q7(e,t){return`
2021-09-11 17:11:38 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
2021-10-28 19:58:21 +02:00
${t?gX(["r","c","d"],"inputShape"):bi(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}var e9=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=hN(t,n),s=fN(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=pN(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===ln.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===ln.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===ln.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===ln.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===ln.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=hN(n,r),a=fN(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);let o=pN(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=J().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let c=this.usedTextures[a],l=c.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c.splice(l,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function t9(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function pN(e,t,n,r,s){let a=n9(t,r),o;if(s){let[c,l]=Cu(e[0],e[1]);o=c*l}else{let[c,l]=Rd(e[0],e[1]);o=c*l}let i=t9(n,a);return o*i}function n9(e,t){switch(e){case ln.PACKED_2X2_FLOAT32:return Ww(t);case ln.PACKED_2X2_FLOAT16:return Vw(t);case ln.UNPACKED_FLOAT32:return Lw(t);case ln.UNPACKED_FLOAT16:return Bw(t);case ln.PACKED_4X1_UNSIGNED_BYTE:return zw(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function r9(e){return J().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?ln.PACKED_2X2_FLOAT32:ln.UNPACKED_FLOAT32:e?ln.PACKED_2X2_FLOAT16:ln.UNPACKED_FLOAT16}function hN(e,t){if(e===pr.UPLOAD)return ln.PACKED_2X2_FLOAT32;if(e===pr.RENDER||e==null)return r9(t);if(e===pr.DOWNLOAD||e===pr.PIXELS)return ln.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function fN(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var Ca=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
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);
}
2021-10-28 19:58:21 +02:00
`}},jr="if (isnan(x)) return x;",s9="return x;",mN="return abs(x);",a9="return (x >= 0.0) ? x : (exp(x) - 1.0);",o9=jr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : x;
2021-10-28 19:58:21 +02:00
`,i9=jr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2021-10-28 19:58:21 +02:00
`,bm="return x;",c9="return 1.0 / (1.0 + exp(-1.0 * x));",u9="return x;",l9=`
2021-09-11 17:11:38 +02:00
vec4 result;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,d9=`
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,p9=`
2021-09-11 17:11:38 +02:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,h9="return 1.0 / (1.0 + exp(-1.0 * x));",Du=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
vec4 unaryOperation(vec4 x) {
${t}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},f9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=Nn("rc",t),r=ht(t),s=q7(t,n),a=n.slice(-2),o=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} rc = getOutputCoords();
vec4 packedInput = getA(${s});
setOutput(getChannel(packedInput, ${o}));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},m9=is.whereImpl,g9=1e-7,b9=1e-4,ym={};function y9(e){return e in ym||(ym[e]={}),ym[e]}var v9=J().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),x9=600;function w9(){return J().global.screen==null?1024:J().global.screen.height*J().global.screen.width*window.devicePixelRatio*x9/1024/1024}var vm=class extends bl{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,!J().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=fs(J().getNumber("WEBGL_VERSION"));this.binaryCache=y9(J().getNumber("WEBGL_VERSION")),this.gpgpu=new oN(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 e9(this.gpgpu),this.numMBBeforeWarning=w9(),this.texData=new Op(this,Cs())}nextDataId(){return vm.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((J().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||J().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:pr.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(J().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:pr.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 Du(o,bm):d=new Ca(o,bm);let p=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:r}],r),h=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return n;let c=this.activeTimers!=null,l;c&&(l=w.now());let u;if(r==="complex64"){let d=this.readSync(s.real.dataId),p=this.readSync(s.imag.dataId);u=E.mergeRealAndImagArrays(d,p)}else u=this.getValuesFromTexture(e);return c&&(this.downloadWaitMs+=w.now()-l),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(s!=null){let h;i?h=new Du(r,bm):h=new Ca(r,bm);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(!J().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&J().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c=null,l;if(a!=="complex64"&&J().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);let h=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(h.texture,...um(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];u=E.mergeRealAndImagArrays(f,m)}else if(c==null)u=this.getValuesFromTexture(e);else{let h=w.sizeFromShape(r);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,h)}if(l!=null&&this.disposeIntermediateTensorInfo(l),c!=null){let h=this.gpgpu.gl;xe(h,()=>h.deleteBuffer(c))}let d=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(h=>h(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Cs().remo
2021-09-11 17:11:38 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2021-10-28 19:58:21 +02:00
`,Fu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=fr(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
float binaryOperation(float a, float b) {
${e}
2021-04-01 19:39:54 +02:00
}
void main() {
2021-09-11 17:11:38 +02:00
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
2021-10-28 19:58:21 +02:00
`}},xm=`
2021-09-11 17:11:38 +02:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2021-10-28 19:58:21 +02:00
`,Bd=class{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=E.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length;this.enableShapeUniforms=fr(s);let a="";if(r)if(s===0||w.sizeFromShape(this.outputShape)===1)a=`
2021-09-11 17:11:38 +02:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else if(a=`
2021-09-16 14:30:50 +02:00
${ht(s)} coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
`,s===1)this.enableShapeUniforms?a+=`
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`:a+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
2021-10-22 15:06:43 +02:00
`;else{let i=Nn("coords",s);this.enableShapeUniforms?a+=`
2021-09-11 17:11:38 +02:00
bool nextRowOutOfBounds =
(${i[s-2]} + 1) >= outShape[${s} - 2];
bool nextColOutOfBounds =
(${i[s-1]} + 1) >= outShape[${s} - 1];
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`:a+=`
bool nextRowOutOfBounds =
(${i[s-2]} + 1) >= ${this.outputShape[s-2]};
bool nextColOutOfBounds =
(${i[s-1]} + 1) >= ${this.outputShape[s-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = binaryOperation(a, b);
${a}
2021-04-01 19:39:54 +02:00
setOutput(result);
}
2021-10-28 19:58:21 +02:00
`}};function rr(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 C9={kernelName:ao,backendName:"webgl",kernelFunc:rr};function Ta(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(a.dataId),i=rr({inputs:{x:r},backend:n}),c=rr({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:c},a}var T9={kernelName:Hp,backendName:"webgl",kernelFunc:Ta},yN="return (a < 0.) ? b * a : a;",vN=`
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2021-10-28 19:58:21 +02:00
`;function N9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=n.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),i=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(vN,s.shape,o.shape):new Fu(yN,s.shape,o.shape),c=n.runWebGLProgram(i,[s,o],"float32");return n.disposeIntermediateTensorInfo(o),c}var _9={kernelName:oo,backendName:"webgl",kernelFunc:N9},xN="return (a < 0.) ? b * a : a;",wN=`
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2021-10-28 19:58:21 +02:00
`;function E9(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(wN,r.shape,s.shape):new Fu(xN,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}var A9={kernelName:xo,backendName:"webgl",kernelFunc:E9},kN="if (isnan(x)) return x;",D9=`
2021-09-11 17:11:38 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2021-10-28 19:58:21 +02:00
`,F9=`
2021-09-11 17:11:38 +02:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2021-10-28 19:58:21 +02:00
`;function Xe({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{let{x:o}=s,i=a,c=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let d=i.texData.get(o.dataId),p=n(d.values,c);return i.makeTensorInfo(o.shape,c,p)}let l=J().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return l?u=new Du(o.shape,t):u=new Ca(o.shape,e),i.runWebGLProgram(u,[o],c)}}function dn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:o,backend:i})=>{let{a:c,b:l}=o,u=i;if(r&&c.dtype==="complex64"){let f=u.texData.get(c.dataId),m=u.texData.get(l.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(y=>{let[x,k]=y,C={dataId:x.dataId,dtype:x.dtype,shape:c.shape},N={dataId:k.dataId,dtype:k.dtype,shape:l.shape},D=new Fu(e,c.shape,l.shape);return u.runWebGLProgram(D,[C,N],wr(x.dtype,k.dtype))}),v=Ta({inputs:{real:g,imag:b},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(b),v}let d=a||wr(c.dtype,l.dtype);if((c.dtype==="string"||l.dtype==="string"||u.shouldExecuteOnCPU([c,l]))&&s!=null){let f=u.texData.get(c.dataId).values,m=u.texData.get(l.dataId).values,g=c.dtype==="string"?E.fromUint8ToStringArray(f):f,b=c.dtype==="string"?E.fromUint8ToStringArray(m):m,[v,y]=s(c.shape,l.shape,g,b,d),x=u.makeTensorInfo(y,d),k=u.texData.get(x.dataId);return k.values=v,x}let p=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new Bd(t,c.shape,l.shape,n):h=new Fu(e,c.shape,l.shape),u.runWebGLProgram(h,[c,l],d)}}function wm(e,t=!1){if(e==="linear")return t?u9:s9;if(e==="relu")return t?d9:o9;if(e==="elu")return t?l9:a9;if(e==="relu6")return t?p9:i9;if(e==="prelu")return t?wN:xN;if(e==="leakyrelu")return t?vN:yN;if(e==="sigmoid")return t?h9:c9;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var IN=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=fr(this.outputShape.length);let l=r?e[1]:e[2],u=Math.ceil(l/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=s?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m=`vec4 activation(vec4 a) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
}`:c?m=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${o}
}`:m=`vec4 activation(vec4 x) {
${o}
2021-10-28 19:58:21 +02:00
}`,g="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let v="rc.x",y="rc.x";e[0]<t[0]?v=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(y=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
2021-09-11 17:11:38 +02:00
${m}
// Don't use uniform for sharedDimensionPacked for performance.
2021-10-22 15:06:43 +02:00
const float sharedDimension = ${u}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
2021-10-22 15:06:43 +02:00
for (int i = 0; i < ${u}; i++) {
2021-10-28 19:58:21 +02:00
int batchA = ${v};
int batchB = ${y};
2021-09-11 17:11:38 +02:00
vec4 a = getMatrixA(batchA, ${d});
vec4 b = getMatrixB(batchB, ${p});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${h[0]} * ${f[0]});
result += (${h[1]} * ${f[1]});
}
return result;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${b}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${g}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(result);
}
2021-10-28 19:58:21 +02:00
`}},SN={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},CN=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.userCode=`
2021-09-11 17:11:38 +02:00
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
2021-10-28 19:58:21 +02:00
`}},TN="return a * b;";function Gw(e){let{inputs:t,backend:n}=e,{a:r,b:s}=t,a=E.upcastType(r.dtype,s.dtype);if(r.dtype==="complex64"){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),l=new CN(SN.REAL,r.shape,s.shape),u=new CN(SN.IMAG,r.shape,s.shape),d=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:r.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape}],p=n.runWebGLProgram(l,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=Ta({inputs:{real:p,imag:h},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}if(n.shouldExecuteOnCPU([r,s])){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),[l,u]=_7(r.shape,s.shape,i.values,c.values,a),d=n.makeTensorInfo(u,a),p=n.texData.get(d.dataId);return p.values=l,d}let o;return J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?o=new Bd(TN,r.shape,s.shape):o=new Fu(TN,r.shape,s.shape),n.runWebGLProgram(o,[r,s],a)}var $9={kernelName:go,backendName:"webgl",kernelFunc:Gw};function R9(e,t,n){let r=[mi(e.shape),...gi(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[mi(t),...gi(t)],o=new dN(a,r),i=!0,c=[r],l=n.runWebGLProgram(o,[s],e.dtype,c,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function be(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),l=w.sizeFromShape(c);w.assert(i===l,()=>`The new shape (${c}) has ${l} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let u=o.texData.get(s.dataId);return u.isPacked&&!Md(s.shape,c)&&!(u.texture!==null&&Md(u.shape,c))?R9(s,c,o):(o.incRef(s.dataId),{dataId:s.dataId,shape:c,dtype:s.dtype})}var P9={kernelName:Rc,backendName:"webgl",kernelFunc:be},NN=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o=Math.floor(n/4)*4,i=n%4,c="sumValue += dot(values, ones);";if(t!=null){let u=1/t;c=`sumValue += dot(values * ${w.isInt(u)?u.toPrecision(2):u}, ones);`}let l="";s%n>0&&(l=`
2021-09-11 17:11:38 +02:00
if (inIdx < 0 || inIdx >= ${s}) {
return 0.0;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
2021-10-22 15:06:43 +02:00
${l}
2021-09-11 17:11:38 +02:00
return getX(batch, inIdx);
2021-04-01 19:39:54 +02:00
}
void main() {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
int batch = coords[0];
2021-09-11 17:11:38 +02:00
int outIdx = coords[1];
int inOffset = outIdx * ${n};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${o}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-04-01 19:39:54 +02:00
2021-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);
}
2021-10-28 19:58:21 +02:00
`}},O9=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let c=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?c="sumValue":t==="prod"?c="prodValue":t==="all"?c="allValue":t==="any"&&(c="anyValue");let l=Math.floor(n/4)*4,u=n%4,d=`
2021-09-11 17:11:38 +02:00
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${i}(values, minMaxValue);
if (${t==="min"} || ${t==="max"}) {
minMaxValue = ${i}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
`,p="vec4";t==="all"?(o="1.0",d=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,p="bvec4"):t==="any"&&(o="0.0",d=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,p="bvec4");let h="";s%n>0&&(h=`
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${o};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${h}
return getX(batch, inIdx);
2021-04-01 19:39:54 +02:00
}
void main() {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
vec4 minMaxValue = vec4(${o});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
2021-10-22 15:06:43 +02:00
for (int i = 0; i < ${l}; i += 4) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i;
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
}
2021-04-01 19:39:54 +02:00
2021-10-22 15:06:43 +02:00
int inIdx = inOffset + ${l};
if (${u===1}) {
2021-09-11 17:11:38 +02:00
${p} values = ${p}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2021-10-22 15:06:43 +02:00
} else if (${u===2}) {
2021-09-11 17:11:38 +02:00
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2021-10-22 15:06:43 +02:00
} else if (${u===3}) {
2021-09-11 17:11:38 +02:00
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
}
setOutput(${c});
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function M9(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=E.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}function vi(e,t,n,r){let s=M9(e.shape),a=e;for(let o=0;o<s.length;o++){let{inSize:i,windowSize:c,outSize:l}=s[o],u,d;n==="mean"?u=o===0?new NN({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l},i):new NN({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l}):u=new O9({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l},n),d=a,a=r.runWebGLProgram(u,[a],t),d.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(d)}return a}var L9=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=ht(this.rank),s=B9(t);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} resRC = getOutputCoords();
setOutput(getA(${s}));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function B9(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 z9=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let l=0;l<n.length;l++)n[l]=e[t[l]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let r=ht(this.rank),s=lN("rc",this.rank),a=new Array(this.rank);for(let l=0;l<t.length;l++)a[t[l]]=s[l];let o=`vec2(${a.slice(-2).join()})`,i=`++${s[this.rank-1]} < ${n[this.rank-1]}`,c=`getChannel(getA(${a.join()}), ${o})`;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} rc = getOutputCoords();
vec4 result = vec4(0.);
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-10-28 19:58:21 +02:00
`}};function km(e,t,n){let r=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new z9(e.shape,t):new L9(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function W9(e,t,n,r){let s=t,a=e.shape.length,o=w.parseAxisParam(s,e.shape),i=o,c=E.getAxesPermutation(i,a),l=c!=null,u=e;l&&(u=km(e,c,r),i=E.getInnerMostAxes(i.length,a)),E.assertAxesAreInnerMostDims("sum",i,a);let[d,p]=E.computeOutAndReduceShapes(u.shape,i),h=d;n&&(h=E.expandShapeToKeepDim(d,o));let f=w.sizeFromShape(p),g=w.sizeFromShape(e.shape)/f,b=be({inputs:{x:u},attrs:{shape:[g,f]},backend:r}),v=Dh(e.dtype),y=vi(b,v,"sum",r),x=be({inputs:{x:y},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(y),l&&r.disposeIntermediateTensorInfo(u),x}function Im(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return W9(s,a,o,n)}var V9={kernelName:Ao,backendName:"webgl",kernelFunc:Im};function _n(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,o=n,i=s.shape.length,c=new Array(i);for(let u=0;u<c.length;u++)c[u]=s.shape[a[u]];let l;if(o.shouldExecuteOnCPU([s])){let d=o.texData.get(s.dataId).values,p=Uw(d,s.shape,s.dtype,a,c);l=o.makeTensorInfo(c,s.dtype);let h=o.texData.get(l.dataId);h.values=p}else l=km(s,a,o);return l}var U9={kernelName:Oo,backendName:"webgl",kernelFunc:_n},_N=1e3;function Sm({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:c=null}){let l=e.shape.length,u=t.shape.length,d=n?e.shape[l-2]:e.shape[l-1],p=r?t.shape[u-1]:t.shape[u-2],h=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=w.sizeFromShape(m),v=w.sizeFromShape(g),y=b===v||b===1||v===1;w.assert(l>=2&&u>=2&&y,()=>`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>v?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?[v,f,p]:[v,p,f],D=be({inputs:{x:e},backend:s,attrs:{shape:C}}),F=be({inputs:{x:t},backend:s,attrs:{shape:N}}),O=[D,F],$=Math.max(b,v),P=n?D.shape[1]:D.shape[2],T=a!=null,L=o!=null,G=c==="leakyrelu",j=c!=null?wm(c,!0):null,q=T||L||G||j!=null,K;if((h===1||f===1)&&P>_N&&q===!1){let te=D,ne=F;n&&(te=_n({inputs:{x:D},backend:s,attrs:{perm:[0,2,1]}}),O.push(te)),r&&(ne=_n({inputs:{x:F},backend:s,attrs:{perm:[0,2,1]}}),O.push(ne));let ae=f!==1,se=f===1,re=te;ae&&(re=be({inputs:{x:te},backend:s,attrs:{shape:[$,P,1]}}),O.push(re));let ue=f===1?2:1,de=ne;se&&(de=be({inputs:{x:ne},backend:s,attrs:{shape:[$,1,P]}}),O.push(de));let me=Gw({inputs:{a:re,b:de},backend:s});K=Im({inputs:{x:me},backend:s,attrs:{axis:ue,keepDims:!0}}),O.push(me)}else{let te=wr(e.dtype,t.dtype),ne=new IN(C,N,[$,h,f],n,r,T,j,L,G),ae=[D,F];if(a!=null&&ae.push(a),L&&ae.push(o),G){let se=s.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));ae.push(se),O.push(se)}K=s.runWebGLProgram(ne,ae,te)}let ee=be({inputs:{x:K},backend:s,attrs:{shape:k}});O.push(K);for(let te of O)s.disposeIntermediateTensorInfo(te);return ee}function G9(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=r;return Sm({a:s,b:a,transposeA:c,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var H9={kernelName:Mo,backendName:"webgl",kernelFunc:G9},EN="return abs(x);";function j9(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=cN(a.values);return n.makeTensorInfo(r.shape,r.dtype,o)}let s;return J().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Du(r.shape,EN):s=new Ca(r.shape,EN),n.runWebGLProgram(s,[r],r.dtype)}var q9={kernelName:Xi,backendName:"webgl",kernelFunc:j9},K9=jr+`
2021-09-11 17:11:38 +02:00
if (abs(x) > 1.) {
return NAN;
}
2021-09-11 17:11:38 +02:00
return acos(x);
2021-10-28 19:58:21 +02:00
`,X9=Xe({opSnippet:K9}),Y9={kernelName:Yi,backendName:"webgl",kernelFunc:X9},Z9=jr+`
2021-09-11 17:11:38 +02:00
if (x < 1.0) return NAN;
2021-10-28 19:58:21 +02:00
return log(x + sqrt(x * x - 1.0));`,J9=Xe({opSnippet:Z9}),Q9={kernelName:Zi,backendName:"webgl",kernelFunc:J9},AN="return a + b;",eY=dn({opSnippet:AN,packedOpSnippet:AN,supportsComplex:!0,cpuKernelImpl:u7}),tY={kernelName:Qs,backendName:"webgl",kernelFunc:eY},nY=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let n=[];this.variableNames.forEach(s=>{n.push(`float v${s} = get${s}AtOutCoords();`)});let r=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${n.join(`
`)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result = ${r};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},rY=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let n=[];this.variableNames.forEach(s=>{n.push(`vec4 v${s} = get${s}AtOutCoords();`)});let r=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${n.join(`
`)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = ${r};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function Cm(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return rr({inputs:{x:r[0]},backend:n});if(r.length>J().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),l=Cm({inputs:r.slice(0,c),backend:n}),u=Cm({inputs:r.slice(c),backend:n});return Cm({inputs:[l,u],backend:n})}let s=r.map(c=>c.dtype).reduce((c,l)=>wr(c,l)),a=r.map(c=>c.shape),i=J().getBool("WEBGL_PACK")?new rY(r[0].shape,a):new nY(r[0].shape,a);return n.runWebGLProgram(i,r,s)}var sY={kernelName:za,backendName:"webgl",kernelFunc:Cm};function aY(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),l=c,u=E.getAxesPermutation(l,i),d=s;u!=null&&(d=_n({inputs:{x:s},backend:n,attrs:{perm:u}}),l=E.getInnerMostAxes(l.length,i)),E.assertAxesAreInnerMostDims("all",l,i);let[p,h]=E.computeOutAndReduceShapes(d.shape,l),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=vi(m,m.dtype,"all",n),b;if(o){let v=E.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:v}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var oY={kernelName:Ji,backendName:"webgl",kernelFunc:aY};function iY(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),l=c,u=E.getAxesPermutation(l,i),d=s;u!=null&&(d=_n({inputs:{x:s},backend:n,attrs:{perm:u}}),l=E.getInnerMostAxes(l.length,i)),E.assertAxesAreInnerMostDims("any",l,i);let[p,h]=E.computeOutAndReduceShapes(d.shape,l),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=vi(m,m.dtype,"any",n),b;if(o){let v=E.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:v}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var cY={kernelName:Qi,backendName:"webgl",kernelFunc:iY},uY=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let o=t==="max"?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${r};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${r}; i++) {
int inIdx = ${i};
float candidate = getA(batch, inIdx);
if (candidate ${o} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(float(bestIndex));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},lY=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=ht(i),l=Nn("coords",i),u,d;if(a===1){d=i+1;let N=ht(d);u=`
2021-10-22 15:06:43 +02:00
${N} sourceLocR = ${N}(${l.join()}, 0);
++${l[i-1]};
${N} sourceLocG = ${N}(${l.join()}, 0);
++${l[i-2]};
${N} sourceLocA = ${N}(${l.join()}, 0);
--${l[i-1]};
${N} sourceLocB = ${N}(${l.join()}, 0);
--${l[i-2]};`}else d=i,u=`
2021-09-11 17:11:38 +02:00
${c} sourceLocR = coords;
2021-10-22 15:06:43 +02:00
++${l[i-1]};
2021-09-11 17:11:38 +02:00
${c} sourceLocG = coords;
2021-10-22 15:06:43 +02:00
++${l[i-2]};
2021-09-11 17:11:38 +02:00
${c} sourceLocA = coords;
2021-10-22 15:06:43 +02:00
--${l[i-1]};
2021-09-11 17:11:38 +02:00
${c} sourceLocB = coords;
2021-10-28 19:58:21 +02:00
--${l[i-2]};`;let p=["x","y","z","w","u","v"].slice(0,d),h="."+p[d-1],f=p.map(N=>"int "+N),m=Nn("sourceLocR",d-1).concat("inIdx.r"),g=Nn("sourceLocG",d-1).concat("inIdx.g"),b=Nn("sourceLocB",d-1).concat("inIdx.b"),v=Nn("sourceLocA",d-1).concat("inIdx.a"),y=n==="max"?"greaterThan":"lessThan",x=r?"":`
2021-09-11 17:11:38 +02:00
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${b.join()}),
2021-10-28 19:58:21 +02:00
getBestIndicesAChannel(${v.join()})));`,k=`vec4(
2021-09-11 17:11:38 +02:00
getAChannel(${m.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${b.join()}) : 0.,
2021-10-28 19:58:21 +02:00
hasNextRow && hasNextCol ? getAChannel(${v.join()}) : 0.)`,C=r?"":`
2021-09-11 17:11:38 +02:00
float getBestIndicesAChannel(${f.join()}) {
return getChannel(getBestIndicesA(${p.join()}),
vec2(${p.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${f.join()}) {
return getChannel(getA(${p.join()}),
vec2(${p.slice(-2).join()}));
}
${C}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
${c} coords = getOutputCoords();
2021-10-22 15:06:43 +02:00
bool hasNextCol = ${l[i-1]} < ${o[i-1]-1};
bool hasNextRow = ${l[i-2]} < ${o[i-2]-1};
${u}
2021-09-11 17:11:38 +02:00
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
sourceLocB${h}, sourceLocA${h}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
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(
2021-10-28 19:58:21 +02:00
vec4(${y}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2021-09-11 17:11:38 +02:00
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(bestIndex);
}
2021-10-28 19:58:21 +02:00
`}};function DN(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=E.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:s,outSize:Math.ceil(a/o)},c=new uY(i,n,r==null),l=[t];r!=null&&l.push(r);let u=e.runWebGLProgram(c,l,"int32");if(u.shape[1]===1)return u;let d=DN(e,t,n,u);return e.disposeIntermediateTensorInfo(u),d}function FN(e,t,n,r=null){let s=r!=null?r.shape:t.shape,a=s[s.length-1],o=E.computeOptimalWindowSize(a),i=new lY(s,o,n,r==null),c=r==null?[t]:[t,r],l=e.runWebGLProgram(i,c,"int32");if(l.shape.length===t.shape.length){let u=FN(e,t,n,l);return e.disposeIntermediateTensorInfo(l),u}return l}function $N(e,t,n,r){let s=[n];if(E.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!J().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let a=[],o=e.texData.get(t.dataId),i=o!==null&&o.isPacked,c=t;i&&(c=e.unpackTensor(t),a.push(c));let[l,u]=E.computeOutAndReduceShapes(c.shape,s),d=w.sizeFromShape(u),p=be({inputs:{x:c},backend:e,attrs:{shape:[-1,d]}});a.push(p);let h=DN(e,p,r);a.push(h);let f=be({inputs:{x:h},backend:e,attrs:{shape:l}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return FN(e,t,r)}function dY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=E.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=_n({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=E.getInnerMostAxes(o.length,c.shape.length)),E.assertAxesAreInnerMostDims("argMax",[o[0]],c.shape.length);let u=$N(n,c,o[0],"max");return l.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var pY={kernelName:Wa,backendName:"webgl",kernelFunc:dY};function hY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=E.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=_n({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=E.getInnerMostAxes(o.length,c.shape.length)),E.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);let u=$N(n,c,o[0],"min");return l.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var fY={kernelName:xl,backendName:"webgl",kernelFunc:hY},mY=jr+`
2021-09-11 17:11:38 +02:00
if (abs(x) > 1.) {
2021-04-01 19:39:54 +02:00
return NAN;
}
2021-09-11 17:11:38 +02:00
return asin(x);
2021-10-28 19:58:21 +02:00
`,gY=Xe({opSnippet:mY}),bY={kernelName:ec,backendName:"webgl",kernelFunc:gY},yY=jr+"return log(x + sqrt(x * x + 1.0));",vY=Xe({opSnippet:yY}),xY={kernelName:tc,backendName:"webgl",kernelFunc:vY},wY=jr+`
2021-09-11 17:11:38 +02:00
return atan(x);
2021-10-28 19:58:21 +02:00
`,kY=Xe({opSnippet:wY}),IY={kernelName:nc,backendName:"webgl",kernelFunc:kY},SY=D9+`
2021-09-11 17:11:38 +02:00
return atan(a, b);
2021-10-28 19:58:21 +02:00
`,CY=`
2021-09-11 17:11:38 +02:00
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2021-10-28 19:58:21 +02:00
`+F9+`
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,TY=dn({opSnippet:SY,packedOpSnippet:CY}),NY={kernelName:sc,backendName:"webgl",kernelFunc:TY},_Y=jr+`
2021-09-11 17:11:38 +02:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2021-10-28 19:58:21 +02:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,EY=Xe({opSnippet:_Y}),AY={kernelName:rc,backendName:"webgl",kernelFunc:EY},zd=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(f||(b="-1.0 / 1e-20"),n){let N=">=";this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 strides = ivec2(${o}, ${i});
const ivec2 pads = ivec2(${p}, ${h});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
2021-04-01 19:39:54 +02:00
2021-10-22 15:06:43 +02:00
for (int wR = 0; wR < ${u};
2021-09-11 17:11:38 +02:00
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};
2021-10-22 15:06:43 +02:00
wC += ${l}) {
2021-09-11 17:11:38 +02:00
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
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-10-28 19:58:21 +02:00
`;return}let v="max",y=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(y="avgValue / count");let x=Math.floor(a/4)*4,k=a%4,C=`
2021-09-11 17:11:38 +02:00
if (${f}) {
avgValue += dot(values, ones);
2021-04-01 19:39:54 +02:00
} else {
2021-10-28 19:58:21 +02:00
minMaxValue = ${v}(values, minMaxValue);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;this.userCode=`
const ivec2 strides = ivec2(${o}, ${i});
const ivec2 pads = ivec2(${p}, ${h});
const float initializationValue = ${b};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int batch = coords[0];
2021-04-01 19:39:54 +02:00
int d = coords[3];
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${b});
float avgValue = 0.0;
count = 0.0;
2021-10-22 15:06:43 +02:00
for (int wR = 0; wR < ${u};
2021-09-11 17:11:38 +02:00
wR += ${c}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${x}; wC += 4) {
2021-10-22 15:06:43 +02:00
int xC = xCCorner + wC * ${l};
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2021-10-22 15:06:43 +02:00
getValue(batch, xR, xC + ${l}, d),
getValue(batch, xR, xC + 2 * ${l}, d),
getValue(batch, xR, xC + 3 * ${l}, d)
2021-09-11 17:11:38 +02:00
);
${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),
2021-10-22 15:06:43 +02:00
getValue(batch, xR, xC + ${l}, d),
2021-09-11 17:11:38 +02:00
initializationValue,
initializationValue
);
${C}
} else if (${k===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
2021-10-22 15:06:43 +02:00
getValue(batch, xR, xC + ${l}, d),
getValue(batch, xR, xC + 2 * ${l}, d),
2021-09-11 17:11:38 +02:00
initializationValue
);
${C}
2021-04-01 19:39:54 +02:00
}
}
2021-10-28 19:58:21 +02:00
setOutput(${y});
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},Hw=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,c=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let v=t==="avg",y="0.0";if(v||(y="-1.0 / 1e-20"),n){let F=">=";this.userCode=`
2021-09-11 17:11:38 +02:00
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};
2021-10-22 15:06:43 +02:00
wD += ${l}) {
2021-09-11 17:11:38 +02:00
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${h};
2021-10-22 15:06:43 +02:00
wR += ${u}) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${f};
wC += ${d}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
2021-10-28 19:58:21 +02:00
if (value ${F} currMinMaxValue) {
2021-09-11 17:11:38 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${r?s?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} +
wR * ${f} + wC`};
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput(float(minMaxPosition));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +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,D=`
if (${v}) {
2021-09-11 17:11:38 +02:00
avgValue += dot(values, ones);
} else {
minMaxValue = ${x}(values, minMaxValue);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;this.userCode=`
const ivec3 strides =
ivec3(${o}, ${i}, ${c});
const ivec3 pads = ivec3(${m}, ${g}, ${b});
2021-10-28 19:58:21 +02:00
const float initializationValue = ${y};
2021-09-11 17:11:38 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2021-10-28 19:58:21 +02:00
vec4 minMaxValue = vec4(${y});
2021-09-11 17:11:38 +02:00
float avgValue = 0.0;
count = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wD = 0; wD < ${p};
2021-10-22 15:06:43 +02:00
wD += ${l}) {
2021-09-11 17:11:38 +02:00
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${h};
2021-10-22 15:06:43 +02:00
wR += ${u}) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
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)
);
2021-10-28 19:58:21 +02:00
${D}
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
);
2021-10-28 19:58:21 +02:00
${D}
2021-09-11 17:11:38 +02:00
} else if (${N===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
initializationValue,
initializationValue
);
2021-10-28 19:58:21 +02:00
${D}
2021-09-11 17:11:38 +02:00
} 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-10-28 19:58:21 +02:00
${D}
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-10-28 19:58:21 +02:00
`}};function DY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Tu(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;w.assert(E.eitherStridesOrDilationsAreOne(o,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let u=E.computePool2DInfo(s.shape,a,o,l,i,c);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return rr({inputs:{x:s},backend:n});let d=new zd(u,"avg",!1);return n.runWebGLProgram(d,[s],"float32")}var FY={kernelName:Va,backendName:"webgl",kernelFunc:DY};function $Y(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:l}=r,u=[1,1,1],d=E.computePool3DInfo(s.shape,a,o,u,i,c,l),p=new Hw(d,"avg",!1);return n.runWebGLProgram(p,[s],"float32")}var RY={kernelName:wl,backendName:"webgl",kernelFunc:$Y},PY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,c=e.effectiveFilterWidth,l=i-1-e.padInfo.top,u=c-1-e.padInfo.left,d=1/(t*n);this.userCode=`
2021-10-22 15:06:43 +02:00
const ivec2 pads = ivec2(${l}, ${u});
2021-09-11 17:11:38 +02:00
const float avgMultiplier = float(${d});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${i};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${r}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
int idyR = int(dyR);
2021-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-10-28 19:58:21 +02:00
`}},OY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=u-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3(${h}, ${f}, ${m});
const float avgMultiplier = float(${g});
2021-04-01 19:39:54 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2021-09-11 17:11:38 +02:00
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
2021-04-01 19:39:54 +02:00
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2021-10-22 15:06:43 +02:00
for (int wD = 0; wD < ${u};
2021-09-11 17:11:38 +02:00
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
int idyD = int(dyD);
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${d};
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};
2021-10-22 15:06:43 +02:00
wC += ${l}) {
2021-09-11 17:11:38 +02:00
float dyC = float(dyCCorner + wC) / ${o}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier;
2021-04-01 19:39:54 +02:00
}
}
}
setOutput(dotProd);
}
2021-10-28 19:58:21 +02:00
`}};function MY(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:l,dimRoundingMode:u}=r,d=[1,1,1],p=E.computePool3DInfo(o.shape,i,c,d,l,u),h=new OY(p);return n.runWebGLProgram(h,[s],o.dtype)}var LY={kernelName:Vp,backendName:"webgl",kernelFunc:MY};function BY(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Tu([s,a],"avgPoolGrad");let{filterSize:i,strides:c,pad:l}=r,u=E.computePool2DInfo(o.shape,i,c,1,l),d=new PY(u);return n.runWebGLProgram(d,[s],o.dtype)}var zY={kernelName:Wp,backendName:"webgl",kernelFunc:BY};function WY(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return Sm({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var VY={kernelName:Ua,backendName:"webgl",kernelFunc:WY},UY=class{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n);let o="0.0";r!=null&&(E.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";s!=null&&(E.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-10-28 19:58:21 +02:00
`}},GY=class{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";r!=null&&(E.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";s!=null&&(E.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
vec4 offset = ${o};
vec4 scale = ${i};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput((x - mean) * inv + offset);
}
2021-10-28 19:58:21 +02:00
`}},HY=({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 l=[r,s,a],u=null;o!=null&&(u=o.shape,l.push(o));let d=null;i!=null&&(d=i.shape,l.push(i));let p=J().getBool("WEBGL_PACK_NORMALIZATION")?new GY(r.shape,s.shape,a.shape,u,d,c):new UY(r.shape,s.shape,a.shape,u,d,c);return t.runWebGLProgram(p,l,l[0].dtype)},jY={kernelName:ro,backendName:"webgl",kernelFunc:HY},qY=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=ht(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=KY(this.rank),r,s=e.map((a,o)=>`sourceLoc.${jw[o]} = start[${o}] + coords.${jw[o]};`);r=`
2021-09-11 17:11:38 +02:00
${t} sourceLoc;
${t} coords = getOutputCoords();
${s.join(`
`)}
`,this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
${r}
setOutput(getSource(${n}));
}
2021-10-28 19:58:21 +02:00
`}},jw=["x","y","z","w","u","v"];function KY(e){if(e===1)return"sourceLoc";if(e<=6)return jw.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var XY=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=ht(this.rank),n=Nn("coords",this.rank),r=Nn("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,o=`
2021-09-11 17:11:38 +02:00
result.x = ${a};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${r[this.rank-1]};
result.y = ${a};
--${r[this.rank-1]};
}
`,i=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
++${r[this.rank-2]};
result.z = ${a};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${r[this.rank-1]};
result.w = ${a};
}
}
`,c=this.rank<=4?`sourceLoc = coords +
2021-10-22 15:06:43 +02:00
${t}(${e.map((l,u)=>`start[${u}]`).join()});`:e.map((l,u)=>`${r[u]} = ${n[u]} + start[${u}];`).join(`
2021-09-11 17:11:38 +02:00
`);this.userCode=`
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${c}
vec4 result = vec4(0.);
${o}
${i}
setOutput(result);
}
2021-10-28 19:58:21 +02:00
`}};function YY(e,t,n,r){let s=r.texData.get(e.dataId),a=r.makeTensorInfo(n,e.dtype),o=r.texData.get(a.dataId);Object.assign(o,s),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=Gt.computeFlatOffset(t,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 $u(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,c]=Gt.parseSliceParams(s,a,o);if(Gt.assertParamsValid(s,i,c),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=P7(d.values,i,c,s.shape,s.dtype);return n.makeTensorInfo(c,s.dtype,p)}let{isPacked:l}=n.texData.get(s.dataId),u=Gt.isSliceContinous(s.shape,i,c);if(l||!u){let d=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new XY(c):new qY(c),p=[i];return n.runWebGLProgram(d,[s],s.dtype,p)}return n.uploadToGPU(s.dataId),YY(s,i,c,n)}var ZY={kernelName:Lc,backendName:"webgl",kernelFunc:$u},JY=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((v,y)=>v*y),c=E.getReshaped(s.shape,a,i),l=E.getPermuted(c.length,a.length),u=E.getReshapedPermuted(s.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=[],f=be({inputs:{x:s},backend:n,attrs:{shape:c}}),m=_n({inputs:{x:f},backend:n,attrs:{perm:l}}),g=be({inputs:{x:m},backend:n,attrs:{shape:u}}),b=$u({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach(v=>n.disposeIntermediateTensorInfo(v)),b},QY={kernelName:ac,backendName:"webgl",kernelFunc:JY};function eZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.readSync(s.dataId),c=n.readSync(a.dataId),l=iN(i,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,l)}var tZ={kernelName:Up,backendName:"webgl",kernelFunc:eZ};function nZ(e){let{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),o=n.readSync(s.dataId),i=E.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var rZ={kernelName:Gp,backendName:"webgl",kernelFunc:nZ},sZ="return float(a != b);",RN=dn({opSnippet:sZ,cpuKernelImpl:A7,dtype:"bool"}),aZ={kernelName:Tc,backendName:"webgl",kernelFunc:RN};function Wd(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return rr({inputs:{x:s.complexTensorInfos.real},backend:n})}var oZ={kernelName:ph,backendName:"webgl",kernelFunc:Wd},iZ="return float(int(x));";function cZ(e,t){let n=new Ca(e.shape,iZ),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function qw(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return rr({inputs:{x:s},backend:n});let o=It(s.shape),i=qw({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),c=Ta({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),c}if(s.dtype==="complex64"){let o=Wd({inputs:{input:s},backend:n}),i=qw({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=rr({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return cZ(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),c=RN({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 uZ={kernelName:Ga,backendName:"webgl",kernelFunc:qw},PN="return ceil(x);",lZ=Xe({opSnippet:PN,packedOpSnippet:PN,cpuKernelImpl:d7}),dZ={kernelName:Ha,backendName:"webgl",kernelFunc:lZ},pZ=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(clamp(value, minVal, maxVal));
}
2021-10-28 19:58:21 +02:00
`}},hZ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
vec4 value = getAAtOutCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (any(isnan(value))) {
setOutput(value);
return;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
2021-10-28 19:58:21 +02:00
`}};function fZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i;J().getBool("WEBGL_PACK_CLIP")?i=new hZ(s.shape):i=new pZ(s.shape);let c=[[a],[o]];return n.runWebGLProgram(i,[s],s.dtype,c)}var mZ={kernelName:ea,backendName:"webgl",kernelFunc:fZ},gZ=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
2021-10-28 19:58:21 +02:00
`}};function ON(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function bZ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new gZ(r.shape),o=[ON(r,s.complexTensorInfos.real),ON(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var yZ={kernelName:kl,backendName:"webgl",kernelFunc:bZ},vZ=class{constructor(e){this.outputShape=[],this.outputShape=E.computeOutShape(e,1),this.variableNames=e.map((a,o)=>`T${o}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let o=t[a-1];n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${o}));`)}let r=t.length,s=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${s}));`),this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${n.join(`
`)}
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},xZ=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=E.computeOutShape(e,t);let n=this.outputShape,r=n.length,s=ht(r),a=Nn("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((f,m)=>`T${m}`);let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let c=o[t],l=o.slice(-2),u=o.join(),d=`if (${c} < ${i[0]}) {
2021-09-11 17:11:38 +02:00
return getChannel(
2021-10-22 15:06:43 +02:00
getT0(${u}), vec2(${l.join()}));
2021-09-11 17:11:38 +02:00
}`;for(let f=1;f<i.length;f++){let m=i[f-1];d+=`
if (${c} < ${i[f]} && ${c} >= ${i[f-1]}) {
return getChannel(
2021-10-28 19:58:21 +02:00
getT${f}(${Tm(o,c,m)}),
vec2(${Tm(l,c,m)}));
2021-09-11 17:11:38 +02:00
}`}let p=i.length,h=i[i.length-1];d+=`
return getChannel(
2021-10-28 19:58:21 +02:00
getT${p}(${Tm(o,c,h)}),
vec2(${Tm(l,c,h)}));`,this.userCode=`
2021-09-11 17:11:38 +02:00
float getValue(${o.map(f=>"int "+f)}) {
${d}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
${s} coords = getOutputCoords();
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
${a[r-1]} = ${a[r-1]} + 1;
if (${a[r-1]} < ${n[r-1]}) {
result.g = getValue(${a});
}
${a[r-2]} = ${a[r-2]} + 1;
if (${a[r-2]} < ${n[r-2]}) {
result.a = getValue(${a});
}
${a[r-1]} = ${a[r-1]} - 1;
if (${a[r-2]} < ${n[r-2]} &&
${a[r-1]} < ${n[r-1]}) {
result.b = getValue(${a});
}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function Tm(e,t,n){let r=e.indexOf(t);return e.map((a,o)=>o===r?`${a} - ${n}`:a).join()}function Nm(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return rr({inputs:{x:s.complexTensorInfos.imag},backend:n})}var wZ={kernelName:ah,backendName:"webgl",kernelFunc:Nm};function Ru(e,t,n){let r=e[0].dtype;if(r==="complex64"){let u=e.map(m=>Wd({inputs:{input:m},backend:n})),d=e.map(m=>Nm({inputs:{input:m},backend:n})),p=Ru(u,t,n),h=Ru(d,t,n),f=Ta({inputs:{real:p,imag:h},backend:n});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),d.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}let s=n.shouldExecuteOnCPU(e);if(r==="string"&&(s=!0),s){let u=e.map(b=>{let v=w.sizeFromShape(b.shape.slice(t));return be({inputs:{x:b},backend:n,attrs:{shape:[-1,v]}})}),d=u.map(b=>({vals:n.readSync(b.dataId),shape:b.shape})),p=E.computeOutShape(u.map(b=>b.shape),1),h=u[0].shape[0]===1,f=p7(d,p,r,h),m=E.computeOutShape(e.map(b=>b.shape),t),g=n.makeTensorInfo(m,r,f);return u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g}if(e.length>J().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(e.length/2),d=Ru(e.slice(0,u),t,n),p=Ru(e.slice(u),t,n),h=Ru([d,p],t,n);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),h}if(J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let u=new xZ(e.map(d=>d.shape),t);return n.runWebGLProgram(u,e,r)}let{tensors2D:a,outShape:o}=kZ(e,t,n),i=new vZ(a.map(u=>u.shape)),c=n.runWebGLProgram(i,a,r);a.forEach(u=>n.disposeIntermediateTensorInfo(u));let l=be({inputs:{x:c},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(c),l}function kZ(e,t,n){let r=E.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>be({inputs:{x:a},attrs:{shape:[-1,w.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:r}}function MN(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=E.computeOutShape(t.map(l=>l.shape),a);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(l=>w.sizeFromShape(l.shape)>0);if(i.length===1)return rr({inputs:{x:i[0]},backend:n});let c=i.map(l=>l.shape);return E.assertParamsConsistent(c,a),Ru(i,a,n)}var IZ={kernelName:oc,backendName:"webgl",kernelFunc:MN},LN=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,c=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,b=m?2:3,v=m?3:1,y="",x="";n&&(r?y=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords();
${n}
2021-10-28 19:58:21 +02:00
}`:s?y=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getLeakyreluAlphaAtOutCoords();
${n}
2021-10-28 19:58:21 +02:00
}`:y=`
2021-09-11 17:11:38 +02:00
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=`
2021-10-28 19:58:21 +02:00
${y}
2021-09-11 17:11:38 +02:00
const ivec2 strides = ivec2(${i}, ${c});
const ivec2 pads = ivec2(${a}, ${o});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int batch = coords[0];
2021-10-28 19:58:21 +02:00
int d2 = coords[${v}];
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner =
ivec2(coords[${g}], coords[${b}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${d}; wR++) {
2021-10-22 15:06:43 +02:00
int xR = xRCorner + wR * ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p}; wC++) {
2021-10-22 15:06:43 +02:00
int xC = xCCorner + wC * ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
if (${f===1}) {
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
dotProd +=
getX(batch, xR, xC, ${h}) *
getW(wR, wC, ${h}, d2);
} else {
dotProd +=
getX(batch, ${h}, xR, xC) *
getW(wR, wC, ${h}, d2);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
} else if (${f===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
} else if (${f===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2),
getW(wR, wC, ${h} + 2, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1),
getX(batch, xR, xC, ${h} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC),
getX(batch, ${h} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd;
${k}
${x}
setOutput(result);
}
2021-10-28 19:58:21 +02:00
`}},SZ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec3 strides = ivec3(${s}, ${a}, ${o});
const ivec3 pads = ivec3(${t}, ${n}, ${r});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
2021-10-22 15:06:43 +02:00
for (int wF = 0; wF < ${u}; wF++) {
2021-09-11 17:11:38 +02:00
int xF = xFCorner + wF * ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${d}; wR++) {
int xR = xRCorner + wR * ${c};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p}; wC++) {
2021-10-22 15:06:43 +02:00
int xC = xCCorner + wC * ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${f===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${h}) *
getW(wF, wR, wC, ${h}, d2);
} else if (${f===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${h}),
getX(batch, xF, xR, xC, ${h} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${h}, d2),
getW(wF, wR, wC, ${h} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${f===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${h}),
getX(batch, xF, xR, xC, ${h} + 1),
getX(batch, xF, xR, xC, ${h} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${h}, d2),
getW(wF, wR, wC, ${h} + 1, d2),
getW(wF, wR, wC, ${h} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},CZ=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=fr(this.outputShape.length);let{dataFormat:n}=t,r=Tn(),s=n==="channelsLast",a=s?0:1,o=s?1:2,i=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`,c="";for(let l=0;l<=1;l++)for(let u=0;u<=1;u++)c+=`
2021-10-22 15:06:43 +02:00
blockIndex = rc.y + ${u};
pos = rc.x + ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${i}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(d0 < inputShape[${a}] && d0 >= 0) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
inChannels);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(d1 < inputShape[${o}] && d1 >= 0) {
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
ch = imod(pos, inChannels);
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
if (${s}) {
innerDims = vec2(d1, ch);
2021-10-22 15:06:43 +02:00
result[${l*2+u}] = getChannel(
2021-09-11 17:11:38 +02:00
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
2021-10-22 15:06:43 +02:00
result[${l*2+u}] = getChannel(
2021-09-11 17:11:38 +02:00
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
2021-04-30 18:01:04 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec2 rc = getOutputCoords();
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0);
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
2021-04-30 18:01:04 +02:00
2021-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-10-28 19:58:21 +02:00
`}};function BN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let c=e.shape,l=r.texData.get(e.dataId),u=n.inChannels,d=c[0]*c[1]*c[2],p=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,b=[];if(!((d===1||p===1)&&u>_N)&&l.isPacked&&h&&l.texture!=null&&c[2]%2!=0&&w.arraysEqual(l.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=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,w.assert(Md(l.shape,k.shape),()=>`packed reshape ${l.shape} to ${k.shape} isn't free`);let N=be({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(N);let D=Sm({a:k,b:N,backend:r,transposeA:f,transposeB:m,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),F=r.texData.get(D.dataId);w.assert(F.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=C,F.shape=n.outShape,g=rr({inputs:{x:D},backend:r}),g.shape=n.outShape,b.push(D)}else{let x=h?c[0]*c[1]*c[2]:c[0]*c[2]*c[3],k=be({inputs:{x:e},backend:r,attrs:{shape:[1,x,n.inChannels]}}),C=be({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),N=Sm({a:k,b:C,transposeA:f,transposeB:m,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=be({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 zN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:c,filterHeight:l,inChannels:u,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=c*l*u,g=p*d,b=[m,g],v=!0,y=!1,x=[],k=be({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),C=be({inputs:{x:t},backend:r,attrs:{shape:[1,m,w.sizeFromShape(t.shape)/m]}});x.push(k),x.push(C);let N=new CZ(b,n),D=[k.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],F=r.runWebGLProgram(N,[k],"float32",D),O=be({inputs:{x:F},backend:r,attrs:{shape:[1,b[0],b[1]]}});x.push(F),x.push(O);let $=s!=null,P=a!=null,T=i==="leakyrelu",L=i?wm(i,!0):null,G=new IN(O.shape,C.shape,[1,g,n.outChannels],v,y,$,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=be({inputs:{x:q},backend:r,attrs:{shape:K}});x.push(q);for(let te of x)r.disposeIntermediateTensorInfo(te);return ee}function TZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:c,dilations:l,dimRoundingMode:u}=r,d=E.convertConv2DDataFormat(c),p=E.computeConv2DInfo(s.shape,a.shape,o,l,i,u,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=BN({x:s,filter:a,convInfo:p,backend:n});else if(J().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)h=zN({x:s,filter:a,convInfo:p,backend:n});else{let m=new LN(p);h=n.runWebGLProgram(m,[s,a],"float32")}let f=be({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var NZ={kernelName:ja,backendName:"webgl",kernelFunc:TZ},_Z=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${r};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${s};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${a}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput(dotProd);
}
2021-10-28 19:58:21 +02:00
`}},EZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,c=a?1:2,l=a?2:3,u=a?3:1;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${o}, ${i});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
2021-10-22 15:06:43 +02:00
int d1 = coords[${u}];
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
ivec2 dyCorner = ivec2(coords[${c}], coords[${l}]) - pads;
2021-09-11 17:11:38 +02:00
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
int idyR = int(dyR);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = ${t} - 1 - wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
int idyC = int(dyC);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = ${n} - 1 - wC;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${a}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},AZ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${s};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${n} - ${a};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${r} - ${o};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},DZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,c=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`
2021-10-22 15:06:43 +02:00
const ivec3 pads = ivec3(${i}, ${c}, ${l});
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${s}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${n} - 1 - wR;
for (int wC = 0; wC < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${r} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function FZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:c,dimRoundingMode:l,filterShape:u}=r,d=E.convertConv2DDataFormat(c),p=E.computeConv2DInfo(s.shape,u,o,1,i,l,!1,d),h=new _Z(p);return n.runWebGLProgram(h,[s,a],"float32")}var $Z={kernelName:jp,backendName:"webgl",kernelFunc:FZ};function RZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:c,dataFormat:l,dimRoundingMode:u}=r,d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(o,a.shape,i,1,c,u,!1,d),h=new EZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var PZ={kernelName:qa,backendName:"webgl",kernelFunc:RZ};function OZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,l=E.computeConv3DInfo(s.shape,a.shape,o,c,i),u=new SZ(l);return n.runWebGLProgram(u,[s,a],"float32")}var MZ={kernelName:Il,backendName:"webgl",kernelFunc:OZ};function LZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:c}=r,l=E.computeConv3DInfo(s.shape,c,o,1,i),u=new AZ(l);return n.runWebGLProgram(u,[s,a],"float32")}var BZ={kernelName:qp,backendName:"webgl",kernelFunc:LZ};function zZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:c}=r,l=E.computeConv3DInfo(c,a.shape,i,1,o),u=new DZ(l);return n.runWebGLProgram(u,[s,a],"float32")}var WZ={kernelName:Kp,backendName:"webgl",kernelFunc:zZ},VZ=kN+`
2021-09-11 17:11:38 +02:00
return cos(x);
2021-10-28 19:58:21 +02:00
`,UZ=Xe({opSnippet:VZ}),GZ={kernelName:Ka,backendName:"webgl",kernelFunc:UZ},HZ=`
2021-09-11 17:11:38 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2021-10-28 19:58:21 +02:00
`,jZ=Xe({opSnippet:HZ}),qZ={kernelName:Xa,backendName:"webgl",kernelFunc:jZ},KZ=class{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,c]=e,[l]=t,[u,d]=n;this.outputShape=[l,u,d,c];let p=r==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,b]=u>1?[`${(o-1)/(u-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[v,y,x]=d>1?[`${(i-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`
2021-09-11 17:11:38 +02:00
const float height_ratio = float(${m});
2021-10-28 19:58:21 +02:00
const float width_ratio = float(${v});
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${a}) {
return;
2021-04-01 19:39:54 +02:00
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float height_scale = ${g};
2021-10-28 19:58:21 +02:00
float width_scale = ${y};
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-10-28 19:58:21 +02:00
`}},XZ=e=>{let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:c,extrapolationValue:l}=r,u=new KZ(s.shape,a.shape,i,c,l);return n.runWebGLProgram(u,[s,a,o],"float32")},YZ={kernelName:ic,backendName:"webgl",kernelFunc:XZ},WN=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(${VN(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-16 14:30:50 +02:00
${ht(r)} coords = getOutputCoords();
2021-10-28 19:58:21 +02:00
int end = ${UN(r,"coords")};
2021-09-11 17:11:38 +02:00
float val = ${s};
int pow2 = int(pow(2.0, index));
if (${o}) {
int idx = ${i};
2021-10-28 19:58:21 +02:00
${UN(r,"coords")} = idx;
val += getX(${VN(r,"coords")});
2021-09-11 17:11:38 +02:00
}
setOutput(val);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function VN(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 UN(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 ZZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,c=s.shape.length,l=E.getAxesPermutation([a],c),u=s;l!=null&&(u=_n({inputs:{x:s},backend:n,attrs:{perm:l}}));let d=E.getInnerMostAxes(1,c)[0];if(d!==c-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${s.shape.length-1} but got axis=${a}`);let p=u.shape[d],h=rr({inputs:{x:u},backend:n});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new WN(u.shape,!1,i),g=[[f]],b=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(b)}if(o){let f=new WN(u.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(l!=null){let f=E.getUndoAxesPermutation(l),m=_n({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),m}return h}var JZ={kernelName:Ya,backendName:"webgl",kernelFunc:ZZ};function QZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let c=n.readSync(s.dataId),l=n.readSync(a.dataId),u=iN(c,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}else if(s.shape.length===2){let c=n.bufferSync(s),l=n.bufferSync(a),u=l7(c,l,o,i);return n.makeTensorInfo(u.shape,a.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}var eJ={kernelName:Xp,backendName:"webgl",kernelFunc:QZ},tJ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +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 nJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r,i=s.shape[0],c=o==="NHWC"?s.shape[1]:s.shape[2],l=o==="NHWC"?s.shape[2]:s.shape[3],u=o==="NHWC"?s.shape[3]:s.shape[1],d=c*a,p=l*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=new tJ(f,a,o);return n.runWebGLProgram(m,[s],s.dtype)}var rJ={kernelName:cc,backendName:"webgl",kernelFunc:nJ},GN=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=fr(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,c="",l="";n&&(r?c=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?c=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}`:c=`
float activation(float x) {
${n}
}
2021-10-22 15:06:43 +02:00
`,l="result = activation(result);");let u=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
2021-09-11 17:11:38 +02:00
${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;
${u}
2021-10-22 15:06:43 +02:00
${l}
2021-09-11 17:11:38 +02:00
setOutput(result);
}
2021-10-28 19:58:21 +02:00
`}},HN=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=fr(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,c=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,d=u,p=`
2021-09-11 17:11:38 +02:00
int xR; int xC; int xCOffset;
2021-10-22 15:06:43 +02:00
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<u;g++)p+=`
2021-09-11 17:11:38 +02:00
vec4 xTexelC${g*2};
int xTexelC${g*2}Ready;
vec4 xTexelC${g*2+1};
int xTexelC${g*2+1}Ready;
2021-10-22 15:06:43 +02:00
vec4 xC${g};`;p+=`
for (int r = 0; r < ${l}; r++) {
`;for(let g=0;g<u;g++)p+=`
xTexelC${g*2} = vec4(0.0);
xTexelC${g*2}Ready = 0;
xTexelC${g*2+1} = vec4(0.0);
xTexelC${g*2+1}Ready = 0;
xC${g} = vec4(0.0);`;p+=`
xR = xRCorner + r * dilations[0];
2021-09-11 17:11:38 +02:00
if (xR >=0 && xR < inDims[0]) {
2021-10-22 15:06:43 +02:00
`;for(let g=0;g<(d+1)/2;g++){let b=g*2;if(p+=`
xC = xCCorner + ${b*c};
`,i===1){if(b<u&&(o%2==1?(p+=`
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1;
2021-10-22 15:06:43 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b}.zw = vec2(0.0);
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b}Ready = 1;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
`,c===1&&b>0?p+=`
xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
2021-09-11 17:11:38 +02:00
`:p+=`
xCOffset = xC + 1 - 2;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
2021-07-29 15:05:49 +02:00
2021-10-22 15:06:43 +02:00
xC${b} = vec4(previous.zw, xTexelC${b}.xy);
2021-04-01 19:39:54 +02:00
} else {
2021-10-22 15:06:43 +02:00
xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
2021-09-11 17:11:38 +02:00
}
`):p+=`
2021-10-22 15:06:43 +02:00
if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
2021-09-11 17:11:38 +02:00
if (xC + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b}.zw = vec2(0.0);
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b}Ready = 1;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xC${b} = xTexelC${b};
2021-10-28 19:58:21 +02:00
`,b+1<u)){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};
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b+1}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b+1}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`,c>1&&(p+=`
xCOffset -= 2;
2021-10-22 15:06:43 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
xTexelC${b}Ready = 1;
2021-09-11 17:11:38 +02:00
}
`),p+=`
2021-10-22 15:06:43 +02:00
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
2021-10-28 19:58:21 +02:00
`):v===1?p+=`
2021-10-22 15:06:43 +02:00
xC${b+1} = xTexelC${b};
2021-09-11 17:11:38 +02:00
`:p+=`
2021-10-28 19:58:21 +02:00
xCOffset = xC + ${v};
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
2021-09-11 17:11:38 +02:00
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b+1}.zw = vec2(0.0);
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b+1}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
xC${b+1} = xTexelC${b+1};
`}}else b<u&&(o%2==1?(p+=`
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1 - strides[1];
2021-10-22 15:06:43 +02:00
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xC + 1, d1);
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b+1}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b+1}Ready = 1;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
`,b+1<u&&(p+=`
2021-09-11 17:11:38 +02:00
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
2021-10-22 15:06:43 +02:00
xC${b+1} = vec4(xTexelC${b+1}.xy, final.xy);
2021-09-11 17:11:38 +02:00
`)):(p+=`
2021-10-22 15:06:43 +02:00
if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
2021-09-11 17:11:38 +02:00
if (xC + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xCOffset = xC + strides[1];
2021-10-22 15:06:43 +02:00
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
2021-09-11 17:11:38 +02:00
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b+1}.zw = vec2(0.);
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b+1}Ready = 1;
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
2021-10-22 15:06:43 +02:00
xC${b} = vec4(
xTexelC${b}.xy, xTexelC${b+1}.xy);
`,b+1<u&&(p+=`
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
`)));b<u&&(p+=`
wTexel = getW(r, ${b}, d1, q);
dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
`,b+1<u&&(p+=`
wTexel = getW(r, ${b+1}, d1, q);
dotProd += xC${b+1} * vec4(wTexel.xz, wTexel.xz);
2021-09-11 17:11:38 +02:00
`))}p+=`
2021-10-22 15:06:43 +02:00
}
`,p+=`
}
`;let h="",f="";n&&(r?h=`vec4 activation(vec4 a) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?h=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${n}
}`:h=`vec4 activation(vec4 x) {
${n}
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${h}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${a};
int q = d2 - d1 * ${a};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${p}
vec4 result = dotProd - vec4(0.000000000000001);
${m}
${f}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function sJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c,dimRoundingMode:l}=r,u=c;u==null&&(u=[1,1]),w.assert(E.eitherStridesOrDilationsAreOne(o,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let d=E.computeConv2DInfo(s.shape,a.shape,o,u,i,l,!0),p;J().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels==1?p=new HN(d):p=new GN(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 aJ={kernelName:Za,backendName:"webgl",kernelFunc:sJ},oJ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${a} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${r};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${s};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},iJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${a}, ${o});
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
int batch = coords[0];
2021-09-11 17:11:38 +02:00
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${r}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = ${t} - 1 - wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = ${n} - 1 - wC;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${i}; dm++) {
int d2 = d1 * ${i} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
2021-10-28 19:58:21 +02:00
`}};function cJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,filterShape:u}=r,d=E.computeConv2DInfo(s.shape,u,o,i,c,l,!0),p=new oJ(d);return n.runWebGLProgram(p,[s,a],"float32")}var uJ={kernelName:Yp,backendName:"webgl",kernelFunc:cJ};function lJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,inputShape:u}=r,d=E.computeConv2DInfo(u,a.shape,o,i,c,l,!0),p=new iJ(d);return n.runWebGLProgram(p,[s,a],"float32")}var dJ={kernelName:Zp,backendName:"webgl",kernelFunc:lJ},pJ=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
2021-10-28 19:58:21 +02:00
`}};function hJ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=w.sizeFromShape(r.shape),o=be({inputs:{x:r},backend:n,attrs:{shape:[a]}}),i=new pJ(a),c=n.runWebGLProgram(i,[o],o.dtype),l=be({inputs:{x:c},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),l}var fJ={kernelName:Jp,backendName:"webgl",kernelFunc:hJ},mJ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:c,dilationWidth:l}=e,{top:u,left:d}=r;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 strides = ivec2(${s}, ${a});
2021-10-22 15:06:43 +02:00
const ivec2 pads = ivec2(${u}, ${d});
2021-09-11 17:11:38 +02:00
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++) {
2021-10-22 15:06:43 +02:00
int wIn = wBeg + w * ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (wIn >= 0 && wIn < ${n}) {
float xVal = getX(batch, hIn, wIn, d1);
float wVal = getW(h, w, d1);
float val = xVal + wVal;
if (val > curVal) {
curVal = val;
}
}
}
}
2021-07-29 15:05:49 +02:00
}
2021-09-11 17:11:38 +02:00
float result = curVal;
setOutput(result);
2021-07-29 15:05:49 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function gJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,l=E.computeDilation2DInfo(s.shape,a.shape,o,i,"NHWC",c),u,d=new mJ(l);u=n.runWebGLProgram(d,[s,a],"float32");let p=be({inputs:{x:u},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(u),p}var bJ={kernelName:Sl,backendName:"webgl",kernelFunc:gJ};function yJ(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:c}=E.decodeEinsumEquation(s,a.length);E.checkEinsumDimSizes(o.length,c,a);let{path:l,steps:u}=E.getEinsumComputePath(i,c),d=u.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:b,expandDims:v}=E.getEinsumPermutation(h,c[g]),y;E.isIdentityPermutation(b)?y=a[g]:(y=_n({inputs:{x:a[g]},backend:n,attrs:{perm:b}}),f.push(y));let x=y.shape.slice();for(let k=0;k<v.length;++k)x.splice(v[k],0,1);w.arraysEqual(y.shape,x)||(y=be({inputs:{x:y},backend:n,attrs:{shape:x}}),f.push(y)),p===null?p=y:(p=Gw({inputs:{a:y,b:p},backend:n}),f.push(p))}m<d-1&&(l[m]>=0&&(p=Im({inputs:{x:p},backend:n,attrs:{axis:l[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var vJ={kernelName:th,backendName:"webgl",kernelFunc:yJ},xJ="return (x >= 0.0) ? x : (exp(x) - 1.0);",wJ=`
2021-09-11 17:11:38 +02:00
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
2021-10-28 19:58:21 +02:00
`,kJ=Xe({opSnippet:xJ,packedOpSnippet:wJ}),IJ={kernelName:Qa,backendName:"webgl",kernelFunc:kJ},SJ="return (b >= 1.0) ? a : a * (b + 1.0);",CJ=`
2021-09-11 17:11:38 +02:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
2021-10-28 19:58:21 +02:00
`,TJ=e=>{let{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(CJ,r.shape,s.shape):new Fu(SJ,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)},NJ={kernelName:nh,backendName:"webgl",kernelFunc:TJ},_J=`
2021-09-11 17:11:38 +02:00
return vec4(equal(a, b));
2021-10-28 19:58:21 +02:00
`,EJ="return float(a == b);",AJ=dn({opSnippet:EJ,packedOpSnippet:_J,dtype:"bool",cpuKernelImpl:h7}),DJ={kernelName:lc,backendName:"webgl",kernelFunc:AJ},FJ=`
2021-09-11 17:11:38 +02:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2021-10-28 19:58:21 +02:00
float p = ${E.ERF_P};
float a1 = ${E.ERF_A1};
float a2 = ${E.ERF_A2};
float a3 = ${E.ERF_A3};
float a4 = ${E.ERF_A4};
float a5 = ${E.ERF_A5};
2021-09-11 17:11:38 +02:00
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
2021-10-28 19:58:21 +02:00
`,$J=Xe({opSnippet:FJ}),RJ={kernelName:uc,backendName:"webgl",kernelFunc:$J},jN="return exp(x);",qN=Xe({opSnippet:jN,packedOpSnippet:jN,cpuKernelImpl:f7,dtype:"float32"}),PJ={kernelName:eo,backendName:"webgl",kernelFunc:qN};function Kw(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),be({inputs:{x:a},backend:r,attrs:{shape:i}})}var OJ={kernelName:dc,backendName:"webgl",kernelFunc:Kw},KN="return exp(x) - 1.0;",MJ=Xe({opSnippet:KN,packedOpSnippet:KN,cpuKernelImpl:m7}),LJ={kernelName:pc,backendName:"webgl",kernelFunc:MJ},XN=class{constructor(e,t,n){this.variableNames=["real","imag"];let r=t[1];this.outputShape=t;let s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${r}.0`:"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
2021-09-11 17:11:38 +02:00
const float exponentMultiplier = ${s};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${o}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${r});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${r}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${a};
}
return result;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function YN(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=be({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),c=i.shape,l=new XN("real",c,t),u=new XN("imag",c,t),d=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:c},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:c}],p=n.runWebGLProgram(l,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=Ta({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);let m=be({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function BJ(e){let{inputs:t,backend:n}=e,{input:r}=t;return YN(r,!1,n)}var zJ={kernelName:rh,backendName:"webgl",kernelFunc:BJ},WJ=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
// Input can be obtained from uniform value.
setOutput(value);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function Vd(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 WJ(r,s),i=[[s]];return t.runWebGLProgram(o,[],a,i)}}var VJ={kernelName:Cl,backendName:"webgl",kernelFunc:Vd},UJ=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x - 1;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
2021-10-28 19:58:21 +02:00
`}},GJ={kernelName:hc,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new UJ(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},ZN="return floor(x);",HJ=Xe({opSnippet:ZN,packedOpSnippet:ZN,cpuKernelImpl:g7}),jJ={kernelName:to,backendName:"webgl",kernelFunc:HJ},qJ=`
2021-09-11 17:11:38 +02:00
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
2021-04-30 18:01:04 +02:00
}
2021-10-28 19:58:21 +02:00
`,KJ=`
2021-09-11 17:11:38 +02:00
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
2021-04-30 18:01:04 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return vec4(result);
2021-10-28 19:58:21 +02:00
`,XJ=dn({opSnippet:qJ,packedOpSnippet:KJ,dtype:"int32"}),YJ={kernelName:no,backendName:"webgl",kernelFunc:XJ},ZJ=class{constructor(e){this.variableNames=["A"];let t=Tn(),[n,r]=e;this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
2021-03-31 13:01:22 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(floor(value * 255.0 + 0.5));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},JJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Tn(),[n,r]=e;this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
2021-03-31 13:01:22 +02:00
}
2021-09-11 17:11:38 +02:00
${t.output} = result;
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},QJ={kernelName:Sh,backendName:"webgl",kernelFunc:eQ},Pu;function eQ(e){let{inputs:t,backend:n,attrs:r}=e,{pixels:s}=t,{numChannels:a}=r,o=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,[c,l]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],u=[l,c],d=[l,c,a];(i||o)&&(Pu==null&&(Pu=document.createElement("canvas").getContext("2d")),Pu.canvas.width=c,Pu.canvas.height=l,Pu.drawImage(s,0,0,c,l),s=Pu.canvas);let p=n.makeTensorInfo(u,"int32");n.texData.get(p.dataId).usage=pr.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),s);let h=J().getBool("WEBGL_PACK")?new JJ(d):new ZJ(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function tQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=E.convertConv2DDataFormat(u),g=E.computeConv2DInfo(s.shape,a.shape,c,d,l,p,!1,m),b,v=[];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=BN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(J().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)b=zN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let x=o!=null,k=i!=null,C=h==="leakyrelu",N=h?wm(h,!1):null,D=new LN(g,x,N,k,C),F=[s,a];if(o&&F.push(o),i&&F.push(i),C){let O=n.makeTensorInfo([],"float32",w.createScalarValue(f,"float32"));F.push(O),v.push(O)}b=n.runWebGLProgram(D,F,"float32")}let y=be({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return v.push(b),v.forEach(x=>n.disposeIntermediateTensorInfo(x)),y}var nQ={kernelName:Lo,backendName:"webgl",kernelFunc:tQ};function rQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=r,f=[],m=u;m==null&&(m=[1,1]),w.assert(E.eitherStridesOrDilationsAreOne(c,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${c} and dilations '${m}'`);let g=E.computeConv2DInfo(s.shape,a.shape,c,m,l,d,!0),b=J().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,v=p?wm(p,b):null,y=[s,a],x=o!=null,k=i!=null,C=p==="leakyrelu";if(x&&y.push(o),k&&y.push(i),C){let O=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));y.push(O),f.push(O)}let N;b?N=new HN(g,x,v,k,C):N=new GN(g,x,v,k,C);let D=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],F=n.runWebGLProgram(N,y,"float32",D);return f.forEach(O=>n.disposeIntermediateTensorInfo(O)),F}var sQ={kernelName:Bo,backendName:"webgl",kernelFunc:rQ},aQ=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let r=ht(t.length),s=ht(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2021-09-11 17:11:38 +02:00
${r} strides = ${r}(${this.strides});
void main() {
${s} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${a};
}
setOutput(getX(flattenIndex, coords[1]));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function oQ(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,l,u,d]=E.prepareAndValidate(r,s),p=be({inputs:{x:s},backend:n,attrs:{shape:[l,o]}}),h=be({inputs:{x:r},backend:n,attrs:{shape:[w.sizeFromShape(r.shape)/u,u]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.readSync(s.dataId),v=n.bufferSync(r),y=b7(b,v,r.dtype,l,o,u,d,r.shape,i);return n.makeTensorInfo(c,r.dtype,y.values)}let f=new aQ(o,d,[l,u]),m=n.runWebGLProgram(f,[h,p],h.dtype),g=be({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var iQ={kernelName:mc,backendName:"webgl",kernelFunc:oQ},cQ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=ht(this.rank),r=uQ(e,2);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${r}));
}
2021-10-28 19:58:21 +02:00
`}};function uQ(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 JN(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],l=n.readSync(a.dataId),u=s.shape[c];for(let x=0;x<l.length;++x){let k=l[x];w.assert(k<=u-1&&k>=0,()=>`GatherV2: the index value ${k} is not in [0, ${u-1}]`)}let d=E.segment_util.collectGatherOpShapeInfo(s,a,c,i),p=w.sizeFromShape(a.shape),h=[],f=be({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=be({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}});h.push(f),h.push(m);let g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize];if(n.shouldExecuteOnCPU([s,a])||s.dtype==="string"){let x=n.bufferSync(m),k=n.bufferSync(f),C=y7(k,x,g);return h.forEach(N=>n.disposeIntermediateTensorInfo(N)),n.makeTensorInfo(d.outputShape,C.dtype,C.values)}let b=new cQ(f.shape,g),v=n.runWebGLProgram(b,[f,m],f.dtype);h.push(v);let y=be({inputs:{x:v},backend:n,attrs:{shape:d.outputShape}});return h.forEach(x=>n.disposeIntermediateTensorInfo(x)),y}var lQ={kernelName:fc,backendName:"webgl",kernelFunc:JN},dQ="return float(a > b);",pQ=`
2021-09-11 17:11:38 +02:00
return vec4(greaterThan(a, b));
2021-10-28 19:58:21 +02:00
`,hQ=dn({opSnippet:dQ,packedOpSnippet:pQ,cpuKernelImpl:v7,dtype:"bool"}),fQ={kernelName:gc,backendName:"webgl",kernelFunc:hQ},mQ="return float(a >= b);",gQ=`
2021-09-11 17:11:38 +02:00
return vec4(greaterThanEqual(a, b));
2021-10-28 19:58:21 +02:00
`,bQ=dn({opSnippet:mQ,packedOpSnippet:gQ,dtype:"bool",cpuKernelImpl:x7}),yQ={kernelName:so,backendName:"webgl",kernelFunc:bQ};function vQ(e){let{inputs:t,backend:n}=e,{input:r}=t;return YN(r,!0,n)}var xQ={kernelName:sh,backendName:"webgl",kernelFunc:vQ},wQ="return float(!isnan(x) && !isinf(x));",kQ=Xe({opSnippet:wQ,dtype:"bool"}),IQ={kernelName:bc,backendName:"webgl",kernelFunc:kQ},SQ="return float(isinf(x));",CQ=Xe({opSnippet:SQ,dtype:"bool"}),TQ={kernelName:yc,backendName:"webgl",kernelFunc:CQ},NQ="return float(isnan(x));",_Q=Xe({opSnippet:NQ,dtype:"bool"}),EQ={kernelName:vc,backendName:"webgl",kernelFunc:_Q},AQ="return float(a < b);",DQ=`
2021-09-11 17:11:38 +02:00
return vec4(lessThan(a, b));
2021-10-28 19:58:21 +02:00
`,FQ=dn({opSnippet:AQ,packedOpSnippet:DQ,cpuKernelImpl:w7,dtype:"bool"}),$Q={kernelName:xc,backendName:"webgl",kernelFunc:FQ},RQ="return float(a <= b);",PQ=`
2021-09-11 17:11:38 +02:00
return vec4(lessThanEqual(a, b));
2021-10-28 19:58:21 +02:00
`,OQ=dn({opSnippet:RQ,packedOpSnippet:PQ,cpuKernelImpl:k7,dtype:"bool"}),MQ={kernelName:wc,backendName:"webgl",kernelFunc:OQ};function LQ(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=I7(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var BQ={kernelName:oh,backendName:"webgl",kernelFunc:LQ},zQ=`if (x < 0.0) return NAN;
return log(x);`,WQ=`
2021-09-11 17:11:38 +02:00
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
2021-10-28 19:58:21 +02:00
`,VQ=Xe({opSnippet:zQ,packedOpSnippet:WQ,cpuKernelImpl:S7}),UQ={kernelName:io,backendName:"webgl",kernelFunc:VQ},GQ="return log(1.0 + x);",HQ=Xe({opSnippet:GQ}),jQ={kernelName:kc,backendName:"webgl",kernelFunc:HQ},qQ="return float(a >= 1.0 && b >= 1.0);",KQ=`
2021-09-11 17:11:38 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2021-10-28 19:58:21 +02:00
`,XQ=dn({opSnippet:qQ,packedOpSnippet:KQ,dtype:"bool"}),YQ={kernelName:Ic,backendName:"webgl",kernelFunc:XQ},ZQ="return float(!(x >= 1.0));",JQ=Xe({opSnippet:ZQ}),QQ={kernelName:Tl,backendName:"webgl",kernelFunc:JQ},eee="return float(a >= 1.0 || b >= 1.0);",tee=`
2021-09-11 17:11:38 +02:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
2021-10-28 19:58:21 +02:00
`,nee=dn({opSnippet:eee,packedOpSnippet:tee,dtype:"bool"}),ree={kernelName:Nl,backendName:"webgl",kernelFunc:nee},see=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,c=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${c})`:s===1?i=`1.0/(${c})`:i=`exp(log(${c}) * float(-${s}));`,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${a}; j <= ${a}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${o}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
float val = x * ${i};
setOutput(val);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},aee=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,o=e[3]-1;this.outputShape=e;let i,c=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${c})`:s===1?i=`1.0/(${c})`:i=`exp(log(${c}) * float(-${s}));`,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${a};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${a}; j <= ${a}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
vec4 result = xAtOutputCoords * ${i};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},oee=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:c}=r,l=J().getBool("WEBGL_PACK_NORMALIZATION")?new aee(s.shape,a,o,i,c):new see(s.shape,a,o,i,c);return n.runWebGLProgram(l,[s],s.dtype)},iee={kernelName:_l,backendName:"webgl",kernelFunc:oee},cee=class{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${r}) * norm + float(${n});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${r})
* float(${s})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ 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-10-28 19:58:21 +02:00
`}},uee=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:c,alpha:l,beta:u}=r,d=new cee(s.shape,i,c,l,u);return n.runWebGLProgram(d,[s,a,o],s.dtype)},lee={kernelName:ih,backendName:"webgl",kernelFunc:uee};function dee(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=be({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=vi(i,e.dtype,"max",r),l=be({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),l}function QN(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),l=c,u=E.getAxesPermutation(l,i),d=u!=null,p=n.shouldExecuteOnCPU([s]),h=s;if(d){if(p){let y=n.texData.get(h.dataId).values,x=new Array(i);for(let N=0;N<x.length;N++)x[N]=s.shape[u[N]];let k=Uw(y,s.shape,s.dtype,u,x);h=n.makeTensorInfo(x,s.dtype);let C=n.texData.get(h.dataId);C.values=k}else h=km(s,u,n);l=E.getInnerMostAxes(l.length,i)}E.assertAxesAreInnerMostDims("max",l,i);let[f,m]=E.computeOutAndReduceShapes(h.shape,l),g=f;o&&(g=E.expandShapeToKeepDim(f,c));let b;if(p){let y=n.texData.get(h.dataId).values,x=C7(y,w.sizeFromShape(m),g,s.dtype);b=n.makeTensorInfo(g,s.dtype);let k=n.texData.get(b.dataId);k.values=x}else b=dee(h,m,g,n);return d&&n.disposeIntermediateTensorInfo(h),b}var pee={kernelName:co,backendName:"webgl",kernelFunc:QN},hee=bN+`
2021-09-11 17:11:38 +02:00
return max(a, b);
2021-10-28 19:58:21 +02:00
`,fee=`
2021-09-11 17:11:38 +02:00
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2021-10-28 19:58:21 +02:00
`+xm+`
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,mee=dn({opSnippet:hee,packedOpSnippet:fee,cpuKernelImpl:T7}),gee={kernelName:uo,backendName:"webgl",kernelFunc:mee};function bee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Tu(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;w.assert(E.eitherStridesOrDilationsAreOne(o,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let u=E.computePool2DInfo(s.shape,a,o,l,i,c);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return rr({inputs:{x:s},backend:n});let d=new zd(u,"max",!1);return n.runWebGLProgram(d,[s],s.dtype)}var yee={kernelName:lo,backendName:"webgl",kernelFunc:bee};function vee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dataFormat:c,dimRoundingMode:l}=r,u=[1,1,1],d=E.computePool3DInfo(s.shape,a,o,u,i,l,c),p=new Hw(d,"max",!1);return n.runWebGLProgram(p,[s],s.dtype)}var xee={kernelName:El,backendName:"webgl",kernelFunc:vee},wee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=s-1-e.padInfo.top,i=a-1-e.padInfo.left,c=s*a-1;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${o}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${s};
wR += ${r}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${a}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
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-10-28 19:58:21 +02:00
`}},kee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,c=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=i-1-e.padInfo.front,d=c-1-e.padInfo.top,p=l-1-e.padInfo.left,h=i*c*l-1;this.userCode=`
2021-10-22 15:06:43 +02:00
const ivec3 pads = ivec3(${u}, ${d}, ${p});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${i};
wD += ${s}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
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);
2021-10-22 15:06:43 +02:00
for (int wC = 0; wC < ${l};
2021-09-11 17:11:38 +02:00
wC += ${o}) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${h} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
2021-10-22 15:06:43 +02:00
wD * ${c} * ${l} +
wR * ${l} + wC;
2021-09-11 17:11:38 +02:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function Iee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:l,dimRoundingMode:u}=r,d=[1,1,1],p=E.computePool3DInfo(o.shape,i,c,d,l,u),h=new Hw(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new kee(p),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var See={kernelName:uh,backendName:"webgl",kernelFunc:Iee};function Cee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Tu([a,o],"maxPoolGrad");let{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=r,p=E.computePool2DInfo(i.shape,c,l,1,u,d),h=!0,f=new zd(p,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new wee(p),b=n.runWebGLProgram(g,[s,m],i.dtype);return n.disposeIntermediateTensorInfo(m),b}var Tee={kernelName:ch,backendName:"webgl",kernelFunc:Cee};function Nee(e,t,n,r){let s=new zd(n,"max",!1),a=r.runWebGLProgram(s,[e],"float32");s=new zd(n,"max",!0,!0,t);let o=r.runWebGLProgram(s,[e],"float32");return[a,o]}var _ee={kernelName:lh,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 l=[1,1];w.assert(E.eitherStridesOrDilationsAreOne(a,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${l}'`);let u=E.computePool2DInfo(r.shape,s,a,l,o),[d,p]=Nee(r,i,u,c);return[d,p]}};function Eee(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=be({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=vi(i,"float32","mean",r),l=be({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),l}var Aee={kernelName:po,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),l=c,u=E.getAxesPermutation(l,i),d=u!=null,p=o.shouldExecuteOnCPU([r]),h=[],f=r;if(d){if(p){let x=o.texData.get(f.dataId).values,k=new Array(i);for(let D=0;D<k.length;D++)k[D]=r.shape[u[D]];let C=Uw(x,r.shape,r.dtype,u,k);f=o.makeTensorInfo(k,r.dtype);let N=o.texData.get(f.dataId);N.values=C}else f=km(r,u,o);h.push(f),l=E.getInnerMostAxes(l.length,i)}E.assertAxesAreInnerMostDims("sum",l,i);let[m,g]=E.computeOutAndReduceShapes(f.shape,l),b=m;s&&(b=E.expandShapeToKeepDim(m,c));let v=Eee(f,g,b,o);for(let y of h)o.disposeIntermediateTensorInfo(y);return v}};function Dee(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),l=c,u=E.getAxesPermutation(l,i),d=s;u!=null&&(d=_n({inputs:{x:s},backend:n,attrs:{perm:u}}),l=E.getInnerMostAxes(l.length,s.shape.length)),E.assertAxesAreInnerMostDims("min",l,i);let[p,h]=E.computeOutAndReduceShapes(d.shape,l),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=vi(m,m.dtype,"min",n),b;if(o){let v=E.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:v}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var Fee={kernelName:ho,backendName:"webgl",kernelFunc:Dee},$ee=bN+`
2021-09-11 17:11:38 +02:00
return min(a, b);
2021-10-28 19:58:21 +02:00
`,Ree=`
2021-09-11 17:11:38 +02:00
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2021-10-28 19:58:21 +02:00
`+xm+`
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,Pee=dn({opSnippet:$ee,packedOpSnippet:Ree,cpuKernelImpl:N7}),Oee={kernelName:fo,backendName:"webgl",kernelFunc:Pee},Mee=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let r=e.length,s=ht(r),a=t.map(l=>l[0]).join(","),o=t.map((l,u)=>l[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),c=n==="reflect"?0:1;if(r===1){this.userCode=`
2021-09-11 17:11:38 +02:00
int start = ${a};
int end = ${o};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start) {
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}));
}
2021-10-28 19:58:21 +02:00
`}},Lee=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=ht(r),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=Nn("rc",r),c=Nn("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,u=r===1?"source":`vec2(${c.slice(-2).join()})`,d=n==="reflect"?0:1,p="";if(r===1){let h=`
2021-09-11 17:11:38 +02:00
${s} source = rc;
if (source < start) {
source = start * 2 - source - ${d};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${d};
}
source -= start;
`;p=`
${s} rc = outputLoc;
${h}
2021-10-22 15:06:43 +02:00
result[0] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {
2021-09-11 17:11:38 +02:00
${h}
2021-10-22 15:06:43 +02:00
result[1] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
}
`}else{let h=`
${s} source = rc;
${s} lt = ${s}(lessThan(source, start));
${s} gte = ${s}(greaterThanEqual(source, end));
${s} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${d}) +
gte * ((end - 1) * 2 - source + ${d});
source -= start;
`;p=`
${s} rc = outputLoc;
${h}
2021-10-22 15:06:43 +02:00
result[0] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {
2021-09-11 17:11:38 +02:00
${h}
2021-10-22 15:06:43 +02:00
result[1] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
}
rc = outputLoc;
${i[r-2]} += 1;
if(${i[r-2]} < ${this.outputShape[r-2]}) {
${h}
2021-10-22 15:06:43 +02:00
result[2] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {
2021-09-11 17:11:38 +02:00
${h}
2021-10-22 15:06:43 +02:00
result[3] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
}
}
`}this.userCode=`
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${o});
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${p}
setOutput(result);
2020-12-15 14:15:43 +01:00
}
2021-10-28 19:58:21 +02:00
`}},Bee=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{paddings:s,mode:a}=n,o=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Lee(r.shape,s,a):new Mee(r.shape,s,a);return t.runWebGLProgram(o,[r],r.dtype)},zee={kernelName:mo,backendName:"webgl",kernelFunc:Bee},Wee=`if (b == 0.0) return NAN;
return mod(a, b);`,Vee=`
2021-09-11 17:11:38 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2021-10-28 19:58:21 +02:00
`+xm+`
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,Uee=dn({opSnippet:Wee,packedOpSnippet:Vee}),Gee={kernelName:Sc,backendName:"webgl",kernelFunc:Uee},Hee=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t-1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// If no other event happened, last event happened.
setOutput(float(${t-1}));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},jee=`
2021-09-11 17:11:38 +02:00
if (a == b) {
return 1.0;
};
2021-10-28 19:58:21 +02:00
return a / b;`,qee=`
2021-09-11 17:11:38 +02:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.y == b.y) {
result.y = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.z == b.z) {
result.z = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.w == b.w) {
result.w = 1.;
2021-04-01 19:39:54 +02:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,e_=dn({opSnippet:jee,packedOpSnippet:qee,checkOutOfBounds:!0}),Kee={kernelName:Ja,backendName:"webgl",kernelFunc:e_},t_="return a - b;",n_=dn({opSnippet:t_,packedOpSnippet:t_,supportsComplex:!0,cpuKernelImpl:U7}),Xee={kernelName:$o,backendName:"webgl",kernelFunc:n_};function r_(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=w.parseAxisParam([a],s.shape),i=QN({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=E.expandShapeToKeepDim(i.shape,o),l=be({inputs:{x:i},backend:n,attrs:{shape:c}}),u=n_({inputs:{a:s,b:l},backend:n}),d=qN({inputs:{x:u},backend:n}),p=Im({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=be({inputs:{x:p},backend:n,attrs:{shape:c}}),f=e_({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}var Yee={kernelName:Do,backendName:"webgl",kernelFunc:r_};function Zee(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r,c=i?s:r_({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),l=c.shape[0],u=c.shape[1],d=new Hee(l,u,a),p=[[o]],h=n.runWebGLProgram(d,[c],"int32",p);return i||n.disposeIntermediateTensorInfo(c),h}var Jee={kernelName:dh,backendName:"webgl",kernelFunc:Zee},s_="return -x;";function Qee(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.texData.get(r.dataId),[o,i]=E7(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s;return J().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Du(r.shape,s_):s=new Ca(r.shape,s_),n.runWebGLProgram(s,[r],r.dtype)}var ete={kernelName:Cc,backendName:"webgl",kernelFunc:Qee},tte=is.nonMaxSuppressionV3Impl;function nte(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c}=r,l=n.readSync(s.dataId),u=n.readSync(a.dataId),{selectedIndices:d}=tte(l,u,o,i,c);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var rte={kernelName:Nc,backendName:"webgl",kernelFunc:nte},ste=is.nonMaxSuppressionV4Impl;function ate(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,padToMaxOutputSize:l}=r,u=n.readSync(s.dataId),d=n.readSync(a.dataId),{selectedIndices:p,validOutputs:h}=ste(u,d,o,i,c,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var ote={kernelName:_c,backendName:"webgl",kernelFunc:ate},ite=is.nonMaxSuppressionV5Impl;function cte(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,softNmsSigma:l}=r,u=n.readSync(s.dataId),d=n.readSync(a.dataId),p=o,h=i,f=c,m=l,{selectedIndices:g,selectedScores:b}=ite(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var ute={kernelName:Ec,backendName:"webgl",kernelFunc:cte},lte=class{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${r}), float(${n}),
float(index == coords.y)));
2021-03-26 15:26:02 +01:00
}
2021-10-28 19:58:21 +02:00
`}},dte=e=>{let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,c=w.sizeFromShape(s.shape),l=new lte(c,a,o,i),u=be({inputs:{x:s},backend:n,attrs:{shape:[c]}}),d=n.runWebGLProgram(l,[u],s.dtype);n.disposeIntermediateTensorInfo(u);let p=[...s.shape,a],h=be({inputs:{x:d},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(d),h},pte={kernelName:bo,backendName:"webgl",kernelFunc:dte};function _m(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=Wd({inputs:{input:r},backend:n}),a=_m({inputs:{x:s},backend:n}),o=Nm({inputs:{input:r},backend:n}),i=_m({inputs:{x:o},backend:n}),c=Ta({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Vd({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var hte={kernelName:Kc,backendName:"webgl",kernelFunc:_m};function a_(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=Wd({inputs:{input:r},backend:n}),a=a_({inputs:{x:s},backend:n}),o=Nm({inputs:{input:r},backend:n}),i=_m({inputs:{x:o},backend:n}),c=Ta({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Vd({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var fte={kernelName:Ac,backendName:"webgl",kernelFunc:a_};function mte(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return Kw({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(u=>{let d=Kw({inputs:{input:u},backend:n,attrs:{dim:s}});return i.push(d),d}),l=MN({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),l}var gte={kernelName:Dc,backendName:"webgl",kernelFunc:mte},bte=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((c,l)=>c[0]+e[l]+c[1]);let r=e.length,s=ht(r),a=t.map(c=>c[0]).join(","),o=t.map((c,l)=>c[0]+e[l]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=`
2021-09-11 17:11:38 +02:00
int start = ${a};
int end = ${o};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${s} start = ${s}(${a});
${s} end = ${s}(${o});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${s} coords = outC - start;
setOutput(getX(${i}));
}
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},yte=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=ht(r),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=Nn("rc",r),c=Nn("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,u=r===1?"source":`vec2(${c.slice(-2).join()})`,d=[`${s} rc = outputLoc;`,`${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {
2021-09-11 17:11:38 +02:00
`,r===1?"":`}
rc = outputLoc;
${i[r-2]} += 1;
if(${i[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":` ${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {`],p=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=r===1?2:4;f<m;f++)h+=`
2021-09-11 17:11:38 +02:00
${d[f]}
if (${p}) {
result[${f}] = float(value);
} else {
${s} source = rc - start;
2021-10-22 15:06:43 +02:00
result[${f}] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
}
`;h+=r===1?"} ":"}}",this.userCode=`
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${o});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${h}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},o_=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(w.sizeFromShape(s.shape)===0){let l=a.map((u,d)=>u[0]+s.shape[d]+u[1]);return Vd({backend:n,attrs:{shape:l,value:o,dtype:s.dtype}})}let i=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new yte(s.shape,a,o):new bte(s.shape,a,o),c=[[o]];return n.runWebGLProgram(i,[s],s.dtype,c)},vte={kernelName:yo,backendName:"webgl",kernelFunc:o_},xte=`
2021-09-11 17:11:38 +02:00
if(a < 0.0 && floor(b) < b){
return NAN;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (b == 0.0) {
return 1.0;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
2021-10-28 19:58:21 +02:00
`,wte=`
2021-09-11 17:11:38 +02:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
2021-10-28 19:58:21 +02:00
`+xm+`
2021-09-11 17:11:38 +02:00
return result;
2021-10-28 19:58:21 +02:00
`,kte=dn({opSnippet:xte,packedOpSnippet:wte}),Ite={kernelName:vo,backendName:"webgl",kernelFunc:kte};function Ste(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=[],l=w.parseAxisParam(a,s.shape),u=l,d=E.getAxesPermutation(u,i),p=s;d!=null&&(p=_n({inputs:{x:s},backend:n,attrs:{perm:d}}),u=E.getInnerMostAxes(u.length,i),c.push(p)),E.assertAxesAreInnerMostDims("prod",u,i);let h;if(n.shouldExecuteOnCPU([p])){let f=n.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:b}=D7(p.shape,p.dtype,f,u);h=n.makeTensorInfo(g,b,m)}else{let[f,m]=E.computeOutAndReduceShapes(p.shape,u),g=w.sizeFromShape(m),b=be({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),v=Dh(s.dtype),y=vi(b,v,"prod",n);h=be({inputs:{x:y},backend:n,attrs:{shape:f}}),c.push(b),c.push(y)}if(o){c.push(h);let f=E.expandShapeToKeepDim(h.shape,l);h=be({inputs:{x:h},backend:n,attrs:{shape:f}})}return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var Cte={kernelName:Fc,backendName:"webgl",kernelFunc:Ste},i_=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=F7(r,s,a,o);return t.makeTensorInfo([i.length],o,i)},Tte={kernelName:Al,backendName:"webgl",kernelFunc:i_},Nte="return 1.0 / x;",_te=Xe({opSnippet:Nte}),Ete={kernelName:$c,backendName:"webgl",kernelFunc:_te},Ate=jr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : x;
2021-10-28 19:58:21 +02:00
`,Dte=`
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2021-10-28 19:58:21 +02:00
`,Fte=Xe({opSnippet:Ate,packedOpSnippet:Dte}),$te={kernelName:wo,backendName:"webgl",kernelFunc:Fte},Rte=jr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2021-10-28 19:58:21 +02:00
`,Pte=`
2021-09-11 17:11:38 +02:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2021-10-28 19:58:21 +02:00
`,Ote=Xe({opSnippet:Rte,packedOpSnippet:Pte}),Mte={kernelName:Io,backendName:"webgl",kernelFunc:Ote},Lte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2021-10-22 15:06:43 +02:00
${l[0]/u[0]},
${l[1]/u[1]});
2021-09-11 17:11:38 +02:00
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec2 sourceFracIndexRC = ${d};
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},Bte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
2021-10-22 15:06:43 +02:00
${l[0]/u[0]},
${l[1]/u[1]},
${l[1]/u[1]});
2021-09-11 17:11:38 +02:00
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec3 sourceFracIndexRC = ${d};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
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);
}
2021-10-28 19:58:21 +02:00
`}};function zte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,l]=i,u=J().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Bte(s.shape,c,l,a,o):new Lte(s.shape,c,l,a,o);return n.runWebGLProgram(u,[s],"float32")}var Wte={kernelName:ko,backendName:"webgl",kernelFunc:zte},Vte=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],l=i[0]/c[0],u=i[1]/c[1],d=1/l,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float accumulator = 0.0;
2020-10-11 18:41:17 +02:00
2021-10-22 15:06:43 +02:00
const float heightScale = float(${l});
const float widthScale = float(${u});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
const float invHeightScale = float(${d});
const float invWidthScale = float(${p});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
const int winHeight = int(${h});
const int winWidth = int(${f});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
2021-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-10-28 19:58:21 +02:00
`}};function Ute(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Vte(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Gte={kernelName:fh,backendName:"webgl",kernelFunc:Ute},Hte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2021-10-22 15:06:43 +02:00
${l[0]/u[0]},
${l[1]/u[1]});
2021-09-11 17:11:38 +02:00
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec2 sourceFracIndexRC = ${p};
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}},jte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
2021-10-22 15:06:43 +02:00
${l[0]/u[0]},
${l[1]/u[1]},
${l[1]/u[1]});
2021-09-11 17:11:38 +02:00
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec3 sourceFracIndexRC = ${p};
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
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);
}
2021-10-28 19:58:21 +02:00
`}};function qte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,l]=i,u=J().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new jte(s.shape,c,l,a,o):new Hte(s.shape,c,l,a,o);return n.runWebGLProgram(u,[s],s.dtype)}var Kte={kernelName:Dl,backendName:"webgl",kernelFunc:qte},Xte=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],l=i[0]/c[0],u=i[1]/c[1],d=1/l,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float accumulator = 0.0;
2020-12-15 14:15:43 +01:00
2021-10-22 15:06:43 +02:00
const float heightScale = float(${l});
const float widthScale = float(${u});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const float invHeightScale = float(${d});
const float invWidthScale = float(${p});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const int winHeight = int(${h});
const int winWidth = int(${f});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracRow =
float(${i[0]}) *
(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);
}
2021-10-28 19:58:21 +02:00
`}};function Yte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Xte(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Zte={kernelName:hh,backendName:"webgl",kernelFunc:Yte},Jte=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
2021-09-16 14:30:50 +02:00
`;return}let r=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,s=e.map((o,i)=>r(i)).join(","),a=ht(n);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${s}));
}
2021-10-28 19:58:21 +02:00
`}},Qte=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=Nn("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=ht(n);n===1?this.userCode=`
2021-09-11 17:11:38 +02:00
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${s}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${i(r.slice())};
if(${s}){
result.g = ${c(r.slice())};
}
if(${a}) {
2021-10-22 15:06:43 +02:00
result.b = ${l(r.slice())};
2021-09-11 17:11:38 +02:00
if(${s}) {
2021-10-22 15:06:43 +02:00
result.a = ${u(r.slice())};
2021-09-11 17:11:38 +02:00
}
}
setOutput(result);
}
2021-10-28 19:58:21 +02:00
`;function i(h){return d(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function l(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function u(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let f=e.map((b,v)=>p(v,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 ene(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 rr({inputs:{x:s},backend:n});let c=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Qte(s.shape,i):new Jte(s.shape,i);return n.runWebGLProgram(c,[s],s.dtype)}var tne={kernelName:So,backendName:"webgl",kernelFunc:ene},nne=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],r=e[2];this.outputShape=e;let s="";typeof t=="number"?s=`float outputValue = ${t.toFixed(2)};`:s=`
2021-09-11 17:11:38 +02:00
vec3 fill = vec3(${t.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - params[0]) * params[3] -
(float(y) - params[1]) * params[2];
float coordYFloat = (float(x) - params[0]) * params[2] +
(float(y) - params[1]) * params[3];
int coordX = int(round(coordXFloat + params[0]));
int coordY = int(round(coordYFloat + params[1]));
${s}
if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
2021-10-28 19:58:21 +02:00
`}},rne={kernelName:Xc,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,c=new nne(r.shape,a),[l,u]=E.getImageCenter(o,r.shape[1],r.shape[2]),d=[[l,u,Math.sin(s),Math.cos(s)]];return i.runWebGLProgram(c,[r],r.dtype,d)}},sne=`
2021-09-11 17:11:38 +02:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
2021-04-01 19:39:54 +02:00
}
}
2021-10-28 19:58:21 +02:00
`,ane=Xe({opSnippet:sne}),one={kernelName:Co,backendName:"webgl",kernelFunc:ane},ine="return inversesqrt(x);",cne=Xe({opSnippet:ine,cpuKernelImpl:$7}),une={kernelName:To,backendName:"webgl",kernelFunc:cne},c_=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=ht(s.length),c=ht(a.length),l="";n===1?l="i":n===2&&(l="i, j");let u=`getIndices(${l})`,d="";r===1?d="i":r===2&&(d="i, coords[1]");let p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=`
2021-09-11 17:11:38 +02:00
${i} strides = ${i}(${s});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${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++) {
2021-10-22 15:06:43 +02:00
int index = round(${u});
2021-09-11 17:11:38 +02:00
flattenedIndex += index * ${h};
}
if (flattenedIndex == coords[0]) {
sum += ${p};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
2021-10-28 19:58:21 +02:00
`}};function lne(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=E.calculateShapes(a,s,o),p=[d/l,l];if(d===0)return n.makeTensorInfo(o,s.dtype);let h=be({inputs:{x:s},backend:n,attrs:{shape:[c,i]}}),f=be({inputs:{x:a},backend:n,attrs:{shape:[c,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new c_(c,i,h.shape.length,f.shape.length,u,p),b=n.runWebGLProgram(g,[f,h,m],f.dtype),v=be({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(m),v}var dne={kernelName:Pc,backendName:"webgl",kernelFunc:lne},pne=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let r,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",r="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],c=[];for(let l=0;l<t.length;l++)c.push(`${o[l]}`),l<e&&i.push(`${o[l]}`);r=i.join(),s=c.join()}let a=ht(n);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${a} resRC = getOutputCoords();
float cVal = getC(${r});
if (cVal >= 1.0) {
setOutput(getA(${s}));
} else {
setOutput(getB(${s}));
}
2021-03-26 15:26:02 +01:00
}
2021-10-28 19:58:21 +02:00
`}};function hne(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new pne(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(o,[r,s,a],wr(s.dtype,a.dtype))}var fne={kernelName:Oc,backendName:"webgl",kernelFunc:hne},mne=`
2021-09-11 17:11:38 +02:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2021-10-28 19:58:21 +02:00
float scaleAlpha = ${E.SELU_SCALEALPHA};
float scale = ${E.SELU_SCALE};
2021-09-11 17:11:38 +02:00
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2021-10-28 19:58:21 +02:00
`,gne=Xe({opSnippet:mne}),bne={kernelName:Mc,backendName:"webgl",kernelFunc:gne},u_="return 1.0 / (1.0 + exp(-1.0 * x));",yne=Xe({opSnippet:u_,packedOpSnippet:u_,cpuKernelImpl:R7}),vne={kernelName:_o,backendName:"webgl",kernelFunc:yne},xne=`
2021-09-11 17:11:38 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2021-10-28 19:58:21 +02:00
`,wne=Xe({opSnippet:xne}),kne={kernelName:zc,backendName:"webgl",kernelFunc:wne},Ine=kN+`
2021-09-11 17:11:38 +02:00
return sin(x);
2021-10-28 19:58:21 +02:00
`,Sne=Xe({opSnippet:Ine}),Cne={kernelName:No,backendName:"webgl",kernelFunc:Sne},Tne=`
2021-09-11 17:11:38 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2021-10-28 19:58:21 +02:00
`,Nne=Xe({opSnippet:Tne}),_ne={kernelName:Bc,backendName:"webgl",kernelFunc:Nne},Ene=`
2021-09-11 17:11:38 +02:00
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;
2021-10-28 19:58:21 +02:00
`,Ane=Xe({opSnippet:Ene}),Dne={kernelName:Wc,backendName:"webgl",kernelFunc:Ane},Fne=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,v)=>b*v),c=[[0,0]];c.push(...o);for(let b=1+a.length;b<s.shape.length;++b)c.push([0,0]);let l=[],u=o_({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),d=E.getReshaped(u.shape,a,i,!1),p=E.getPermuted(d.length,a.length,!1),h=E.getReshapedPermuted(u.shape,a,i,!1),f=be({inputs:{x:u},backend:n,attrs:{shape:d}}),m=_n({inputs:{x:f},backend:n,attrs:{perm:p}}),g=be({inputs:{x:m},backend:n,attrs:{shape:h}});return l.push(u),l.push(f),l.push(m),l.forEach(b=>n.disposeIntermediateTensorInfo(b)),g},$ne={kernelName:Vc,backendName:"webgl",kernelFunc:Fne};function Rne(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
2021-09-11 17:11:38 +02:00
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
2021-10-28 19:58:21 +02:00
${o.shape}`);let i=n.readSync(r.dataId),c=n.readSync(s.dataId),l=n.readSync(a.dataId),u=n.readSync(o.dataId)[0],[d,p,h,f,m]=O7(i,r.shape,r.dtype,c,s.dtype,l,u);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var Pne={kernelName:mh,backendName:"webgl",kernelFunc:Rne};function One(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.readSync(s.dataId)),i=n.readSync(r.dataId),c=Array.from(n.readSync(a.dataId)),[l,u,d]=M7(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(u,r.dtype,l),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var Mne={kernelName:gh,backendName:"webgl",kernelFunc:One};function Lne(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2021-10-28 19:58:21 +02:00
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[l,u]=uN(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(u,r.dtype,l)}var Bne={kernelName:bh,backendName:"webgl",kernelFunc:Lne};function zne(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2021-10-28 19:58:21 +02:00
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[l,u]=uN(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(u,r.dtype,l)}var Wne={kernelName:yh,backendName:"webgl",kernelFunc:zne};function Vne(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:l,strides:u,outputSize:d}=E.calculateShapes(a,s,i),p=!1,h=new c_(l,c,s.shape.length,a.shape.length,u,[d,1],p),f=n.runWebGLProgram(h,[a,s,o],a.dtype),m=be({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var Une={kernelName:vh,backendName:"webgl",kernelFunc:Vne};function Gne(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=E.prepareSplitSize(s,a,i),l=s.shape.length,u=new Array(l).fill(0),d=s.shape.slice();return c.map(p=>{let h=[...d];h[i]=p;let f=$u({inputs:{x:s},backend:n,attrs:{begin:u,size:h}});return u[i]+=p,f})}var Hne={kernelName:Uc,backendName:"webgl",kernelFunc:Gne},l_="return sqrt(x);",jne=Xe({opSnippet:l_,packedOpSnippet:l_,cpuKernelImpl:L7}),qne={kernelName:Eo,backendName:"webgl",kernelFunc:jne},Kne="return x * x;",Xne=Xe({opSnippet:Kne}),Yne={kernelName:Fl,backendName:"webgl",kernelFunc:Xne},d_="return (a - b) * (a - b);",Zne=dn({opSnippet:d_,packedOpSnippet:d_}),Jne={kernelName:Fo,backendName:"webgl",kernelFunc:Zne};function Qne({inputs:e,attrs:t,backend:n}){let{x:r}=e,s=jr+`
2021-09-11 17:11:38 +02:00
return x > 0.0 ? 1.0 : float(${t.alpha});
2021-10-28 19:58:21 +02:00
`,a=new Ca(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}var ere={kernelName:na,backendName:"webgl",kernelFunc:Qne},tre=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let r=n.length,s=ht(n.length),a=ht(n.length),o="";if(r===1)o="coords * strides + begin";else{let i=0;o=n.map((c,l)=>(i++,n.length===1?`coords * strides[${l}] + begin[${l}]`:`coords[${i-1}] * strides[${l}] + begin[${l}]`)).join(",")}this.userCode=`
2021-09-11 17:11:38 +02:00
${s} begin = ${s}(${e});
${s} strides = ${s}(${t});
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${o}));
2021-04-01 19:39:54 +02:00
}
2021-10-28 19:58:21 +02:00
`}};function nre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:v,end:y,strides:x}=Gt.sliceInfo(s.shape,a,o,i,c,l,u,d,p),k;if(m)k=be({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||b){w.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let N=Gt.computeOutShape(v,y,x),D=$u({inputs:{x:s},backend:n,attrs:{begin:v,size:N}});k=be({inputs:{x:D},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(D)}else if(n.shouldExecuteOnCPU([s])){let D=n.readSync(s.dataId),F=ze(s.shape,s.dtype,D),O=B7(h,F,x,v);k=n.makeTensorInfo(f,s.dtype,O.values)}else{let D=new tre(v,x,h);k=n.runWebGLProgram(D,[s],s.dtype)}let C=be({inputs:{x:k},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(k),C}var rre={kernelName:Gc,backendName:"webgl",kernelFunc:nre};function sre(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:l}=r,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=z7(p,h,s,a,o,i,c,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var are={kernelName:xh,backendName:"webgl",kernelFunc:sre};function ore(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),c=n.readSync(o.dataId)[0],[l,u,d]=W7(i,c,s),p=u.length;return[n.makeTensorInfo([p,2],"int32",l),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var ire={kernelName:wh,backendName:"webgl",kernelFunc:ore};function cre(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=V7(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var ure={kernelName:kh,backendName:"webgl",kernelFunc:cre},lre="return tan(x);",dre=Xe({opSnippet:lre}),pre={kernelName:Ro,backendName:"webgl",kernelFunc:dre},hre=`
2021-09-11 17:11:38 +02:00
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
2021-10-28 19:58:21 +02:00
`,fre=Xe({opSnippet:hre}),mre={kernelName:Po,backendName:"webgl",kernelFunc:fre},gre=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=ht(this.rank),s=bre(e);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} resRC = getOutputCoords();
setOutput(getA(${s}));
}
2021-10-28 19:58:21 +02:00
`}};function bre(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 p_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if(s.dtype==="string"||s.shape.length>5){let c=n.readSync(s.dataId),l=s.dtype==="string"?c.map(p=>w.decodeString(p)):c,u=ze(s.shape,s.dtype,l),d=G7(u,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new gre(s.shape,a);return n.runWebGLProgram(o,[s],s.dtype)}var yre={kernelName:ta,backendName:"webgl",kernelFunc:p_},vre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
int i = isFirstInPair ? elemIdx : elemIdx - inc;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod(elemIdx, 2 * dir) >= dir;
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) { // Elements in opposite order of direction
int iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutput(float(i0));
} else {
setOutput(float(i1));
}
}
2021-10-28 19:58:21 +02:00
`}},xre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float x0 = getX(batch, i0);
float x1 = i1 < n ? getX(batch, i1) : x0;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput(x0 >= x1 ? float(i0) : float(i1));
}
2021-10-28 19:58:21 +02:00
`}};function xi(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function h_(e){let t=1;for(;t<e;)t*=2;return t}function wre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r,i=J().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),c=J().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=s.shape,u=l[l.length-1];if(n.shouldExecuteOnCPU([s])||u<i||a>c){let O=n.readSync(s.dataId),[$,P]=H7(O,l,s.dtype,a,o);return[n.makeTensorInfo($.shape,$.dtype,$.values),n.makeTensorInfo(P.shape,P.dtype,P.values)]}if(a===0)return l[l.length-1]=0,[n.makeTensorInfo(l,s.dtype,[]),n.makeTensorInfo(l,"int32",[])];if(u===1)return[s,Vd({attrs:{shape:l,dtype:"int32",value:0},backend:n})];let d=n.texData.get(s.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(s):s,m=w.sizeFromShape(l)/u,g=be({inputs:{x:h},attrs:{shape:[m,u]},backend:n});p&&xi(n,h);let b=h_(a),v=h_(u),y=null,x=()=>y===null?[g,g]:[g,y],k=(O,$,P)=>{let T=x(),L=new vre(P),j=[[u],[y===null?1:0],[Number.NEGATIVE_INFINITY],[O],[$]],q=y;y=n.runWebGLProgram(L,T,"int32",j),xi(n,q)};for(let O=1;O<b;O*=2){let $=O*2;for(let P=O;P>=1;P/=2)k($,P,[m,v])}for(let O=v;O>b;O/=2){let $=x(),P=new xre([m,O/2]),L=[[u],[y===null?1:0],[b]],G=y;y=n.runWebGLProgram(P,$,"int32",L),xi(n,G);let j=b/2,q=j*2;for(let K=j;K>=1;K/=2)k(q,K,y.shape)}let C=y;y=$u({inputs:{x:y},backend:n,attrs:{begin:0,size:[m,a]}}),xi(n,C);let N=JN({inputs:{x:g,indices:y},backend:n,attrs:{axis:1,batchDims:1}});xi(n,g);let D=l.slice(0,-1);D.push(a),C=y,y=be({inputs:{x:y},attrs:{shape:D},backend:n}),xi(n,C);let F=N;return N=be({inputs:{x:N},attrs:{shape:D},backend:n}),xi(n,F),[N,y]}var kre={kernelName:Hc,backendName:"webgl",kernelFunc:wre},Ire=class{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(r){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode=`
2021-09-11 17:11:38 +02:00
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${i} == 2) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
if (inCoord < sz2) {
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
inCoord;
}
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
inCoord -= sz2 * float(int(float(inCoord / sz2)));
if (inCoord >= len) {
inCoord = sz2 - inCoord - 1.0;
}
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${i} == 3) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord -= len * float(int(float(inCoord / sz)));
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${i} == 4) {
return clamp(outCoord, 0.0, len - 1.0);
} else {
return outCoord;
}
}
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float readWithFillValue(int batch, int coordY, int coordX,
int channel) {
float outputValue;
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = float(${s});
}
return outputValue;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
float outputValue;
int batch = coords[0];
int x = coords[2];
int y = coords[1];
int channel = coords[3];
float xf = float(x);
float yf = float(y);
float a1 = getTransforms(batch, 0);
float a2 = getTransforms(batch, 1);
float a3 = getTransforms(batch, 2);
float b1 = getTransforms(batch, 3);
float b2 = getTransforms(batch, 4);
float b3 = getTransforms(batch, 5);
float c1 = getTransforms(batch, 6);
float c2 = getTransforms(batch, 7);
float projection = c1 * xf + c2 * yf + 1.0;
if (projection == 0.0) {
outputValue = float(${s});
} else {
float inX = (a1 * xf + a2 * yf + a3) / projection;
float inY = (b1 * xf + b2 * yf + b3) / projection;
float mapX = mapCoord(inX, float(${t}));
float mapY = mapCoord(inY, float(${e}));
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
if (${o} == 1) {
int coordY = int(round(mapY));
int coordX = int(round(mapX));
outputValue = readWithFillValue(batch, coordY, coordX,
channel);
} else {
float yFloor = floor(mapY);
float xFloor = floor(mapX);
float yCeil = yFloor + 1.0;
float xCeil = xFloor + 1.0;
float valueYFloor = (xCeil - mapX) *
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
float valueYCeil = (xCeil - mapX) *
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
outputValue = (yCeil - mapY) * valueYFloor +
(mapY - yFloor) * valueYCeil;
}
}
setOutput(outputValue);
}
2021-10-28 19:58:21 +02:00
`}};function Sre(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:c,outputShape:l}=r,[u,d,p,h]=s.shape,[f,m]=l!=null?l:[d,p],g=[u,f,m,h],b=new Ire(d,p,o,i,c,g);return n.runWebGLProgram(b,[s,a],"float32")}var Cre={kernelName:jc,backendName:"webgl",kernelFunc:Sre};function Tre(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Tu(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=r.readSync(a.dataId),{outputValues:i,outputShape:c,indices:l}=j7(o,s,a.shape,a.dtype);return[r.makeTensorInfo(c,a.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}var Nre={kernelName:Ih,backendName:"webgl",kernelFunc:Tre};function _re(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s,i=o.shape.length,c=s.shape[a],l=new Array(i-1),u=0;for(let m=0;m<i;m++)m!==a&&(l[u++]=o.shape[m]);let d=[],p=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(c);for(let m=0;m<f.length;m++){p[a]=m;let g=$u({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),b=be({inputs:{x:g},backend:n,attrs:{shape:l}});f[m]=b,d.push(g)}return d.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var Ere={kernelName:qc,backendName:"webgl",kernelFunc:_re},Are=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,o=a*Math.ceil(s/n);this.outputShape=[r,o];let i="0.0",c="sumValue",l=Math.floor(n/4)*4,u=n%4,d=`
2021-09-11 17:11:38 +02:00
sumValue += dot(values, segFilter);
`,p="";s%n>0&&(p=`
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`);let h="";s%n>0&&(h=`
if (inIdx < 0 || inIdx >= ${s}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${i};
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float getValue(int batch, int inIdx) {
${p}
return getX(batch, inIdx);
2021-03-26 15:26:02 +01:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float getSegmentIdAtIndex(int inIdx) {
${h}
return getSegmentIds(inIdx);
2021-03-31 13:01:22 +02:00
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${a})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${a})));
2021-03-09 23:32:33 +01:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0;
2021-03-09 23:32:33 +01:00
2021-10-22 15:06:43 +02:00
for (int i = 0; i < ${l}; i += 4) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2020-12-15 14:15:43 +01:00
}
2020-10-29 05:16:50 +01:00
2021-10-22 15:06:43 +02:00
int inIdx = inOffset + ${l};
if (${u===1}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
${d}
2021-10-22 15:06:43 +02:00
} else if (${u===2}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2021-10-22 15:06:43 +02:00
} else if (${u===3}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
${d}
}
setOutput(${c});
}
2021-10-28 19:58:21 +02:00
`}};function Dre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r,i=s.shape.length,c=[],l=0,u=E.getAxesPermutation([l],i),d=s;u!=null&&(d=_n({inputs:{x:s},backend:n,attrs:{perm:u}}),c.push(d),l=E.getInnerMostAxes(1,i)[0]);let p=E.segment_util.computeOutShape(d.shape,l,o),h=w.sizeFromShape([d.shape[l]]),f=be({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});c.push(f);let m=Dh(s.dtype),g=(x,k,C,N,D)=>{let F=x.shape[0],O=x.shape[1],$=E.segment_util.segOpComputeOptimalWindowSize(O,D),P={windowSize:$,inSize:O,batchSize:F,numSegments:D},T=new Are(P,k),L=n.compileAndRun(T,[x,C],N);if(c.push(L),L.shape[1]===D)return L;let G=i_({backend:n,attrs:{start:0,stop:D,step:1,dtype:"float32"}}),j=p_({inputs:{x:G},backend:n,attrs:{reps:[O/$]}});return c.push(G),c.push(j),g(L,k,j,N,D)},b=g(f,"unsortedSegmentSum",a,m,o),v=be({inputs:{x:b},backend:n,attrs:{shape:p}}),y=v;if(u!=null){c.push(v);let x=E.getUndoAxesPermutation(u);y=_n({inputs:{x:y},backend:n,attrs:{perm:x}})}return c.forEach(x=>n.disposeIntermediateTensorInfo(x)),y}var Fre={kernelName:$l,backendName:"webgl",kernelFunc:Dre},$re=[iee,lee,H9,q9,Y9,Q9,tY,sY,oY,cY,pY,fY,bY,xY,NY,IY,AY,RY,FY,LY,zY,VY,jY,QY,tZ,rZ,uZ,dZ,mZ,yZ,T9,IZ,$Z,PZ,NZ,BZ,WZ,MZ,GZ,qZ,YZ,JZ,eJ,rJ,uJ,dJ,aJ,fJ,bJ,vJ,IJ,NJ,DJ,RJ,PJ,OJ,LJ,zJ,VJ,GJ,jJ,YJ,QJ,nQ,sQ,iQ,lQ,fQ,yQ,C9,xQ,wZ,IQ,TQ,EQ,_9,$Q,MQ,BQ,jQ,UQ,YQ,QQ,ree,pee,xee,yee,See,Tee,_ee,gee,Aee,Fee,Oee,zee,Gee,Jee,$9,ete,rte,ote,ute,aZ,pte,fte,gte,vte,Ite,A9,Cte,Tte,oZ,Kee,Ete,Mte,$te,P9,Wte,Gte,Kte,Zte,tne,rne,one,une,dne,fne,bne,vne,kne,Cne,_ne,ZY,Yee,Dne,$ne,Pne,Mne,Bne,Wne,Une,Hne,qne,Yne,Jne,ere,rre,are,ire,ure,Xee,V9,pre,mre,yre,kre,Cre,U9,Nre,Ere,Fre,hte];for(let e of $re)Pl(e);var Wt;(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"})(Wt||(Wt={}));var Ud;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(Ud||(Ud={}));var f_;function Rre(e){f_=e.wasm.cwrap(Mo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Pre(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=r,p=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let D=n.dataIdMap.get(o.dataId);if(D.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${D.shape.length}.`);f=D.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=Ud[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let b=c?s.shape[2]:s.shape[1],v=l?a.shape[1]:a.shape[2],y=s.shape[0],x=n.makeOutput([y,b,v],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 f_(p,C,s.shape.length,h,N,a.shape.length,c,l,g,f,m,d||0,k),x}var Ore={kernelName:Mo,backendName:"wasm",setupFunc:Rre,kernelFunc:Pre};function pn(e,t){let n;function r(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function s(a){let{backend:o,inputs:{x:i}}=a,c=o.dataIdMap.get(i.dataId).id,l=o.makeOutput(i.shape,t||i.dtype),u=o.dataIdMap.get(l.dataId).id;return w.sizeFromShape(l.shape)===0||n(c,Wt[i.dtype],u),l}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var Mre=pn(Xi);function En(e,t,n){let r;function s(o){r=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:c}=o,{a:l,b:u}=c,d=i.dataIdMap.get(l.dataId).id,p=i.dataIdMap.get(u.dataId).id,h=n!=null?n:l.dtype,f=E.assertAndGetBroadcastShape(l.shape,u.shape),m=i.makeOutput(f,h);if(w.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(l.shape).buffer),b=new Uint8Array(new Int32Array(u.shape).buffer),v=i.dataIdMap.get
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. */