face-api/dist/face-api.js

4879 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
*/
2022-02-07 15:43:35 +01:00
var faceapi=(()=>{var Hb=Object.defineProperty;var cD=Object.getOwnPropertyDescriptor;var uD=Object.getOwnPropertyNames;var lD=Object.prototype.hasOwnProperty;var dD=e=>Hb(e,"__esModule",{value:!0});var pD=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var Gp=(e,t)=>{for(var n in t)Hb(e,n,{get:t[n],enumerable:!0})},hD=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of uD(t))!lD.call(e,s)&&(n||s!=="default")&&Hb(e,s,{get:()=>t[s],enumerable:!(r=cD(t,s))||r.enumerable});return e};var fD=(e=>(t,n)=>e&&e.get(t)||(n=hD(dD({}),t,1),e&&e.set(t,n),n))(typeof WeakMap!="undefined"?new WeakMap:0);var Yue={};Gp(Yue,{AgeGenderNet:()=>eg,BoundingBox:()=>Vu,Box:()=>lt,ComposableTask:()=>Or,ComputeAllFaceDescriptorsTask:()=>Aa,ComputeFaceDescriptorsTaskBase:()=>cg,ComputeSingleFaceDescriptorTask:()=>Da,DetectAllFaceLandmarksTask:()=>lg,DetectAllFacesTask:()=>mp,DetectFaceLandmarksTaskBase:()=>ug,DetectFacesTaskBase:()=>pg,DetectSingleFaceLandmarksTask:()=>dg,DetectSingleFaceTask:()=>hg,Dimensions:()=>_n,FACE_EXPRESSION_LABELS:()=>M0,FaceDetection:()=>wt,FaceDetectionNet:()=>eA,FaceExpressionNet:()=>Zm,FaceExpressions:()=>Ea,FaceLandmark68Net:()=>Zu,FaceLandmark68TinyNet:()=>tg,FaceLandmarkNet:()=>VE,FaceLandmarks:()=>xr,FaceLandmarks5:()=>NE,FaceLandmarks68:()=>Gu,FaceMatch:()=>rp,FaceMatcher:()=>mg,FaceRecognitionNet:()=>Ju,Gender:()=>Qm,LabeledBox:()=>sp,LabeledFaceDescriptors:()=>Os,NetInput:()=>Ms,NeuralNetwork:()=>dn,ObjectDetection:()=>Na,Point:()=>Oe,PredictedBox:()=>_E,Rect:()=>Uu,SsdMobilenetv1:()=>Di,SsdMobilenetv1Options:()=>Pr,TinyFaceDetector:()=>rl,TinyFaceDetectorOptions:()=>ig,TinyYolov2:()=>tl,TinyYolov2Options:()=>bs,allFaces:()=>que,allFacesSsdMobilenetv1:()=>mA,allFacesTinyYolov2:()=>jue,awaitMediaLoaded:()=>D0,bufferToImage:()=>$0,computeFaceDescriptor:()=>$ue,createCanvas:()=>Ni,createCanvasFromMedia:()=>cp,createFaceDetectionNet:()=>Tue,createFaceRecognitionNet:()=>fue,createSsdMobilenetv1:()=>QE,createTinyFaceDetector:()=>Kue,createTinyYolov2:()=>_ue,detectAllFaces:()=>fg,detectFaceLandmarks:()=>hA,detectFaceLandmarksTiny:()=>Due,detectLandmarks:()=>Gue,detectSingleFace:()=>Hue,draw:()=>W0,env:()=>nt,euclideanDistance:()=>Z0,extendWithAge:()=>sg,extendWithFaceDescriptor:()=>rg,extendWithFaceDetection:()=>Si,extendWithFaceExpressions:()=>Jm,extendWithFaceLandmarks:()=>Yu,extendWithGender:()=>ag,extractFaceTensors:()=>ju,extractFaces:()=>Hu,fetchImage:()=>eue,fetchJson:()=>P0,fetchNetWeights:()=>tue,fetchOrThrow:()=>Ls,fetchVideo:()=>nue,getContext2dOrThrow:()=>Gn,getMediaDimensions:()=>Ci,imageTensorToCanvas:()=>F0,imageToSquare:()=>R0,inverseSigmoid:()=>qce,iou:()=>x0,isMediaElement:()=>Vm,isMediaLoaded:()=>ip,isWithAge:()=>mue,isWithFaceDetection:()=>gs,isWithFaceExpressions:()=>L0,isWithFaceLandmarks:()=>Ei,isWithGender:()=>gue,loadAgeGenderModel:()=>Wue,loadFaceDetectionModel:()=>Vue,loadFaceExpressionModel:()=>zue,loadFaceLandmarkModel:()=>Mue,loadFaceLandmarkTinyModel:()=>Lue,loadFaceRecognitionModel:()=>Bue,loadSsdMobilenetv1Model:()=>fA,loadTinyFaceDetectorModel:()=>Pue,loadTinyYolov2Model:()=>Oue,loadWeightMap:()=>O0,locateFaces:()=>Uue,matchDimensions:()=>rue,minBbox:()=>w0,nets:()=>rt,nonMaxSuppression:()=>k0,normalize:()=>Qr,padToSquare:()=>I0,predictAgeAndGender:()=>Rue,recognizeFaceExpressions:()=>Fue,resizeResults:()=>gA,resolveInput:()=>Ti,shuffleArray:()=>jce,sigmoid:()=>np,ssdMobilenetv1:()=>pA,tf:()=>Pe,tinyFaceDetector:()=>Eue,tinyYolov2:()=>Aue,toNetInput:()=>yt,utils:()=>v0,validateConfig:()=>q0,version:()=>Xue});var Pe={};Gp(Pe,{Abs:()=>vc,Acos:()=>xc,Acosh:()=>wc,AdadeltaOptimizer:()=>rm,AdagradOptimizer:()=>sm,AdamOptimizer:()=>am,AdamaxOptimizer:()=>om,Add:()=>ma,AddN:()=>go,All:()=>kc,Any:()=>Ic,ArgMax:()=>bo,ArgMin:()=>rd,Asin:()=>Sc,Asinh:()=>Tc,Atan:()=>Cc,Atan2:()=>_c,Atanh:()=>Nc,AvgPool:()=>yo,AvgPool3D:()=>sd,AvgPool3DGrad:()=>
2021-12-06 12:34:50 +01:00
`)),c.join(`
2022-02-07 15:43:35 +01:00
`)}function A$(e,t,n,r){let s=xt(t),a=r[r.length-1],o=new Array(a).fill(0),i=t.length,c=n==="complex64"?Cl(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],Tl(c[u+d],0,n).length)}return o}function Tl(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(qb))} + ${parseFloat(e[1].toFixed(qb))}j`:Js(e)?r=`'${e}'`:n==="bool"?r=oI(e):r=parseFloat(e.toFixed(qb)).toString(),Ol(r,t)}function oI(e){return e===0?"false":"true"}function rh(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=Cl(e);return[Tl(m[0],0,n)]}return n==="bool"?[oI(e[0])]:[e[0].toString()]}if(c===1){if(i>f1){let g=wl*o,b=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-wl)*o,i*o));return n==="complex64"&&(b=Cl(b),y=Cl(y)),["["+b.map((v,x)=>Tl(v,s[x],n)).join(", ")+", ..., "+y.map((v,x)=>Tl(v,s[i-wl+x],n)).join(", ")+"]"]}let m=n==="complex64"?Cl(e):Array.from(e);return["["+m.map((g,b)=>Tl(g,s[b],n)).join(", ")+"]"]}let l=t.slice(1),u=r.slice(1),d=r[0]*o,p=[];if(i>f1){for(let m=0;m<wl;m++){let g=m*d,b=g+d;p.push(...rh(e.slice(g,b),l,n,u,s,!1))}p.push("...");for(let m=i-wl;m<i;m++){let g=m*d,b=g+d;p.push(...rh(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(...rh(e.slice(g,b),l,n,u,s,m===i-1))}let h=c===2?",":"";p[0]="["+p[0]+h;for(let m=1;m<p.length-1;m++)p[m]=" "+p[m]+h;let f=`,
2021-12-06 12:34:50 +01:00
`;for(let m=2;m<c;m++)f+=`
2022-02-07 15:43:35 +01:00
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function Cl(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Ht=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=xt(e),n!=null){let r=n.length;O(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||jk(t,this.size),this.strides=yc(e)}set(e,...t){t.length===0&&(t=[0]),O(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 Mr().makeTensor(this.values,this.shape,this.dtype)}},Mr=null,Yi=null,D$=null;function $$(e){Mr=e}function F$(e){Yi=e}function R$(e){D$=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=xt(e),this.strides=yc(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 Yi.buffer(this.shape,this.dtype,e)}bufferSync(){return Yi.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=Mr().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>kh(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Mr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Mr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>kh(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 Mr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Mr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Yi.print(this,e)}clone(){return this.throwIfDisposed(),Yi.clone(this)}toString(e=!1){let t=this.dataSync();return E$(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Yi.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Mr().makeVariable(this,e,t,n)}};Object.defineProperty(Ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function ee(){return uv("Tensor",()=>Ee)}ee();var aa=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(!fa(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Mr().disposeTensor(this),this.dataId=e.dataId,Mr().incRef(this,null)}dispose(){Mr().disposeVariable(this),this.isDisposedInternal=!0}};Ob
Manifest JSON has weights with names: ${i.join(", ")}.`)}let c=s.reduce((h,f,m)=>(f&&h.push(m),h),[]),l=[];c.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;l.push(m)})});let u=await e(l),d={},p=0;return c.forEach(h=>{let f=t[h].paths.length,m=0;for(let x=0;x<f;x++)m+=u[p+x].byteLength;let g=new ArrayBuffer(m),b=new Uint8Array(g),y=0;for(let x=0;x<f;x++){let w=new Uint8Array(u[p+x]);b.set(w,y),y+=w.byteLength}a[h].forEach(x=>{let w=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),T=hI(w,[x.manifestEntry]);for(let N in T)d[N]=T[N]}),p+=f}),d}}var DF="application/octet-stream",$F="application/json",mv=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?(O(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,O(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&O(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=fI(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:DF}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Sd(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 fv(t,s=>this.loadWeights(s))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=FF(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 II(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,hv(c)]}};mv.URL_SCHEME_REGEX=/^https?:\/\//;function FF(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}function vy(e){return e.match(mv.URL_SCHEME_REGEX)!=null}var TI=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>vy(r)):n=vy(e),n)return gv(e,t)}return null};Ft.registerSaveRouter(TI);Ft.registerLoadRouter(TI);function gv(e,t){return new mv(e,t)}function RF(e,t){return gv(e,t)}var Yb=class{
2021-09-11 17:11:38 +02:00
Actual: ${s}.
2021-12-06 12:34:50 +01:00
Expected: ${a}.`);for(let o=0;o<a.length;++o){let i=s[o],c=a[o];if(!n(i,c))throw new Error(`Arrays differ: actual[${o}] = ${i}, expected[${o}] = ${c}.
2021-09-11 17:11:38 +02:00
Actual: ${s}.
2022-02-07 15:43:35 +01:00
Expected: ${a}.`)}}function iR(e,t){e().then(()=>t.fail(),()=>t())}function cR(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Js(e)||Js(e[0])||Js(t)||Js(t[0])?wy(e,n,(r,s)=>r==s):wy(e,t,(r,s)=>kv(r,s,0))}function uR(e,t,n){if(n==null&&(n=wv()),!kv(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function kv(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function lR(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 dR(e,t){let n=new Float32Array(e),r=new Float32Array(t);if(n.length!==r.length)throw new Error(`Expected ArrayBuffer to be of length ${r.length}, but it was ${n.length}`);for(let s=0;s<r.length;s++)if(n[s]!==r[s])throw new Error(`Expected ArrayBuffer value at ${s} to be ${r[s]} but got ${n[s]} instead`)}function UI(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?UI(n):e[t]=kd(n)}return e}var pR="3.13.0";function hR(){J().set("PROD",!0)}function fR(){J().set("DEBUG",!0)}function mR(){J().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Iv(e){J().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}R$(Iv);function gR(){z.disposeVariables()}function ns(){return z}function Sh(){return z.memory()}function bR(e){return z.profile(e)}function M(e,t){return z.tidy(e,t)}function De(e){dv(e).forEach(n=>n.dispose())}function Jt(e){return z.keep(e)}function yR(e){return z.time(e)}function vR(e){return z.setBackend(e)}function xR(){return z.ready()}function wR(){return z.backendName}function kR(e){z.removeBackend(e)}function IR(e){return z.findBackend(e)}function SR(e){return z.findBackendFactory(e)}function _f(e,t,n=1){return z.registerBackend(e,t,n)}function GI(){return z.backend}function TR(e,t){J().setPlatform(e,t)}function CR(e,t){let n=A(e,"a","add"),r=A(t,"b","add");[n,r]=Dt(n,r);let s={a:n,b:r};return z.runKernel(ma,s)}var Y=W({add_:CR});function NR(e,t){let n=A(e,"a","floorDiv"),r=A(t,"b","floorDiv");[n,r]=Dt(n,r);let s={a:n,b:r};return z.runKernel($o,s)}var Ef=W({floorDiv_:NR});function _R(e,t){let n=A(e,"a","div"),r=A(t,"b","div");if([n,r]=Dt(n,r),n.dtype==="int32"&&r.dtype==="int32")return Ef(n,r);let s={a:n,b:r},a={};return z.runKernel(_o,s,a)}var ge=W({div_:_R});function ER(e,t){let n=A(e,"a","mul"),r=A(t,"b","mul");[n,r]=Dt(n,r);let s={a:n,b:r};return z.runKernel(Ho,s)}var V=W({mul_:ER});function AR(e){let t=A(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return z.runKernel(ad,n)}else{let n={x:t};return z.runKernel(vc,n)}}var Bt=W({abs_:AR});function DR(e){let n={x:A(e,"x","acos")};return z.runKernel(xc,n)}var Sv=W({acos_:DR});function $R(e){let n={x:A(e,"x","acosh")};return z.runKernel(wc,n)}var Tv=W({acosh_:$R});function FR(e){O(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),O(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(!fa(s.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=t;return z.runKernel(go,r)}var HI=W({addN_:FR});function RR(e,t=null,n=!1){let s={x:A(e,"x","all","bool")},a={axis:t,keepDims:n};return z.runKernel(kc,s,a)}var Af=W({all_:RR});function PR(e,t=null,n=!1){let s={x:A(e,"x","any","bool")},a={axis:t,keepDims:n};return z.runKernel(Ic,s,a)}var Hl=W({any_:PR});function OR(e,t=0){let r={x:A(e,"x","argMax")},s={axis:t};return z.runKernel(bo,r,s)}var no=W({argMax_:OR});function MR(e,t=0){let r={x:A(e,"x","argMin")},s={axis:t};return z.runKernel(rd,r,s)}var Cv=W({argMin_:MR});function LR(e){let n={x:A(e,"x","asin")};return z.runKernel(Sc,n)}var Nv=W({asin_:LR});function BR(e){let n={x:A(e,"x","asinh")};return z.runKernel(Tc,n)}var _v=W({asinh_:BR});function
with dtype ${a.dtype}. `)}),n.length===1)return Ns(n[0]);let r=n,s={axis:t};return z.runKernel(Ac,r,s)}var tt=W({concat_:JR});function QR(e){let n={x:A(e,"x","sigmoid","float32")};return z.runKernel(ri,n)}var fr=W({sigmoid_:QR});function eP(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(cu,s,a)}var ze=W({slice_:eP});function tP(e){let n={x:A(e,"x","tanh","float32")};return z.runKernel(li,n)}var ro=W({tanh_:tP});function nP(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=tt([l,d],1),h=Ae(p,i),f=Y(h,c),m=f.shape[0],g=f.shape[1]/4,b=[m,g],y=ze(f,[0,0],b),v=ze(f,[0,g],b),x=ze(f,[0,g*2],b),w=ze(f,[0,g*3],b),T=Y(V(fr(y),ro(v)),V(u,fr(Y(o,x)))),N=V(ro(T),fr(w));return[T,N]}var rP=W({basicLSTMCell_:nP});function sP(e,t,n){let r=A(e,"x","batchToSpaceND"),s=t.reduce((i,c)=>i*c);O(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),O(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),O(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(Ec,a,o)}var Cd=W({batchToSpaceND_:sP});function aP(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 oP(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")),O(i.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),O(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),O(l==null||i.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:aP(o),scale:l,offset:u,mean:i,variance:c},h={varianceEpsilon:a},f=z.runKernel(Fo,p,h);return U(f,o.shape)}var Es=W({batchNorm_:oP});function iP(e,t,n,r,s,a){let o=A(e,"x","batchNorm"),i=A(t,"mean","batchNorm"),c=A(n,"variance","batchNorm"),l;s!=null&&(l=A(s,"scale","batchNorm"));let u;return r!=null&&(u=A(r,"offset","batchNorm")),O(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),O(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),O(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),l!=null&&O(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&O(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),Es(o,i,c,u,l,a)}var XI=W({batchNorm2d_:iP});function cP(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")),O(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),O(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),O(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),l!=null&&O(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&O(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),Es(o,i,c,u,l,a)}var YI=W({batchNorm3d_:cP});function uP(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
2022-01-14 16:04:13 +01:00
${r.shape}`),O(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
2022-02-07 15:43:35 +01:00
${r.shape}`),O(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($c,i,c)}var Lv=W({depthToSpace_:AP});function DP(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]])),O(l.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`),O(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),O(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]}.`),Sn("depthwiseConv2d",r,o);let d={x:l,filter:c},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},h=z.runKernel(No,d,p);return u?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var wa=W({depthwiseConv2d_:DP});function $P(e){let n={x:A(e,"x","diag")};return z.runKernel(sf,n)}var FP=W({diag_:$P});function RP(e,t,n,r,s=[1,1],a="NHWC"){let o=A(e,"x","dilation2d"),i=A(t,"filter","dilation2d");O(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),O(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),O(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(id,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Bv=W({dilation2d_:RP});function PP(e,t){let n=A(e,"a","equal","string_or_numeric"),r=A(t,"b","equal","string_or_numeric");[n,r]=Dt(n,r),ht(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(Rc,s)}var tr=W({equal_:PP});function OP(e,t,n){let r=A(t,"a","where"),s=A(n,"b","where"),a=A(e,"condition","where","bool"),o=ht(ht(a.shape,r.shape),s.shape),i=nc(a,o),c=nc(r,o),l=nc(s,o),u={condition:i,t:c,e:l};return z.runKernel(ou,u)}var mn=W({where_:OP});function MP(e){let n={x:A(e,"x","zerosLike")};return z.runKernel(vu,n)}var je=W({zerosLike_:MP});function LP(e,t){let n=A(e,"a","div"),r=A(t,"b","div");[n,r]=Dt(n,r);let s=ge(n,r),a=je(s),o=tr(r,a);return mn(o,a,s)}var zv=W({divNoNan_:LP});function BP(e,t){let n=A(e,"t1","dot"),r=A(t,"t2","dot");O((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(O(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 oS=W({dot_:BP});function zP(e,...t){let n=t.map((s,a)=>A(s,`tensors${a}`,"einsum")),r={equation:e};return z.runKernel(af,n,r)}var iS=W({einsum_:zP});function WP(e){let n={x:A(e,"x","elu","float32")};return z.runKernel(Eo,n)}var ku=W({elu_:WP});function VP(e){let t=A(e,"x","erf");O(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ce(t,"float32"));let n={x:t};return z.runKernel(Fc,n)}var Wv=W({erf_:VP});function UP(e){let n={x:A(e,"x","exp")};return z.runKernel(Ao,n)}var gn=W({exp_:UP});function GP(e,t=0){let n=A(e,"x","expandDims","string_or_numeric");O(t<=n.rank,()=>"Axis must be <= rank of the tensor");let r={input:n},s={dim:t};return z.runKernel(Pc,r,s)}var fn=W({expandDims_:GP});function HP(e){let n={x:A(e,"x","expm1")};return z.runKernel(Oc,n)}var Vv=W({expm1_:HP});function jP(e,t){let n=A(e,"x","tile","string_or_numeric");O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let r={x:n},s={reps
rank ${a.rank}.`),O(sc(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(dd,c,l);return i?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var Hv=W({localResponseNormalization_:aO});function oO(e){let n={x:A(e,"x","log","float32")};return z.runKernel(Mo,n)}var nr=W({log_:oO});function iO(e){let n={x:A(e,"x","log1p")};return z.runKernel(jc,n)}var Ed=W({log1p_:iO});function cO(e){return O(sa(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&&In(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Mf(o),o[0]})}}function uO(e){return O(sa(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{O(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&&In(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Mf(o),o})}}function lO(e){return O(sa(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{O(t instanceof Ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),O(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 Mf(r),{grad:r[0],value:s}}}function dO(e){return O(sa(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{O(Array.isArray(t)&&t.every(s=>s instanceof Ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),O(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&&In(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Mf(r.grads),r}}function dS(e,t){O(sa(e),()=>"The f passed in variableGrads(f) must be a function"),O(t==null||Array.isArray(t)&&t.every(l=>l instanceof aa),()=>"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),O(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);O(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()."),O(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 cs(e){return z.customGrad(e)}function Mf(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 pO(e){let n={x:A(e,"x","neg")};return z.runKernel(Xc,n)}var Ct=W({neg_:pO});function hO(e){let n={x:A(e,"x","softplus")};return z.runKernel(du,n)}var hi=W({softplus_:hO});function fO(e){let t=A(e,"x","logSigmoid");return cs(r=>({value:Ct(hi(Ct(r))),gradFunc:o=>V(o,fr(Ct(r)))}))(t)}var pS=W({logSigmoid_:fO});function mO(e,t=null,n=!1){let s={x:A(e,"x","max")},a={reductionIndices:t,keepDims:n};return z.runKernel(Lo,s,a)}var _r=W({max_:mO});function gO(e,t){let n=A(e,"a","sub"),r=A(t,"b","sub");[n,r]=Dt(n,r);let s={a:n,b:r};return z.runKernel(ci,s)}var fe=W({sub_:gO});function bO(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(ai,s,a)}var xe=W({sum_:bO});function yO(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 cs((s,a)=>{let i=_r(s,t,!0),c=fe(s,i),l=fe(ce(c,"float32"),nr(xe(gn(c),t,!0)));return a([l]),{value:l,gradFunc:(d,p)=>{let[h]=p,f=!0,m=gn(h);return fe(d,V(xe(d,t,f),m))}}})(n)}var Lf=W({logSoftmax_:yO});function jv(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function hS(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 fS(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 ao(e,t){let n=t.map(r=>1);return hS(e,n,t)}function vO(e,t,n){O(jv(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function mS(e,t){if(jv(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 qv(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function xO(e,t){let n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function wO(e,t=null,n=!1){let r=A(e,"x","logSumExp"),s=Dr(t,r.shape),a=_r(r,s,!0),o=fe(r,a),i=gn(o),c=xe(i,s),l=nr(c),u=Y(U(a,l.shape),l);if(n){let d=ao(u.shape,s);return U(u,d)}return u}var Kv=W({logSumExp_:wO});function kO(e,t){let n=A(e,"a","logicalAnd","bool"),r=A(t,"b","logicalAnd","bool");ht(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(qc,s)}var Ar=W({logicalAnd_:kO});function IO(e){let n={x:A(e,"x","logicalNot","bool")};return z.runKernel(ud,n)}var Ad=W({logicalNot_:IO});function SO(e,t){let n=A(e,"a","logicalOr","bool"),r=A(t,"b","logicalOr","bool");ht(n.shape,r.shape);let s={a:n,b:r};return z.runKernel(ld,s)}var Bf=W({logicalOr_:SO});function TO(e,t){let n=A(e,"a","logicalXor","bool"),r=A(t,"b","logicalXor","bool");return ht(n.shape,r.shape),Ar(Bf(e,t),Ad(Ar(e,t)))}var gS=W({logicalXor_:TO});function CO(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]])),O(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),O(ds(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),Sn("maxPool",r,s);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s},d=z.runKernel(zo,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Mt=W({maxPool_:CO});function NO(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]])),O(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),Sn("maxPool3d",r,s);let l={x:i},u={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},d=z.runKernel(pd,l,u);return c?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Xv=W({maxPool3d_:NO});function _O(e,t,n,r,s=!1){let o={x:A(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},c=z.runKernel(mf,o,i);return{result:c[0],indexes:c[1]}}var bS=W({maxPoolWithArgmax_:_O});funct
${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(md,c);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}var zL=W({sparseFillEmptyRows_:BL});function WL(e,t,n){let r=A(e,"inputIndices","sparseReshape","int32"),s=A(t,"inputShape","sparseReshape","int32"),a=A(n,"newShape","sparseReshape","int32");if(r.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
${r.shape}`);if(s.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:r,inputShape:s,newShape:a},i=z.runKernel(fu,o);return{outputIndices:i[0],outputShape:i[1]}}var VL=W({sparseReshape_:WL});function UL(e,t,n){let r=A(e,"data","sparseSegmentMean"),s=A(t,"indices","sparseSegmentMean","int32"),a=A(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
2022-02-07 15:43:35 +01:00
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return z.runKernel(gd,o)}var GL=W({sparseSegmentMean_:UL});function HL(e,t,n){let r=A(e,"data","sparseSegmentSum"),s=A(t,"indices","sparseSegmentSum","int32"),a=A(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
2022-02-07 15:43:35 +01:00
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return z.runKernel(bd,o)}var jL=W({sparseSegmentSum_:HL});function qL(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(wf,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var KL=W({stringNGrams_:qL});function XL(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(kf,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var YL=W({stringSplit_:XL});function ZL(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(If,s,r)}var JL=W({stringToHashBucketFast_:ZL}),QL={fft:Fd,ifft:uc,rfft:Rd,irfft:Xf},eB={hammingWindow:AM,hannWindow:DS,frame:$S,stft:RM},Qn={flipLeftRight:LM,grayscaleToRGB:zM,resizeNearestNeighbor:MS,resizeBilinear:OS,rotateWithOffset:VM,cropAndResize:OM,nonMaxSuppression:GM,nonMaxSuppressionAsync:JM,nonMaxSuppressionWithScore:eL,nonMaxSuppressionWithScoreAsync:nL,nonMaxSuppressionPadded:sL,nonMaxSuppressionPaddedAsync:oL,threshold:dL,transform:hL},LS={bandPart:mL,gramSchmidt:bL,qr:vL},tB={absoluteDifference:kL,computeWeightedLoss:Ds,cosineDistance:SL,hingeLoss:CL,huberLoss:_L,logLoss:AL,meanSquaredError:$L,sigmoidCrossEntropy:PL,softmaxCrossEntropy:LL},Nl={sparseFillEmptyRows:zL,sparseReshape:VL,sparseSegmentMean:GL,sparseSegmentSum:jL},ah={stringNGrams:KL,stringSplit:YL,stringToHashBucketFast:JL},$s=class extends zI{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 dS(e,t)}dispose(){this.iterations_!=null&&De(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ie(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty($s,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var rm=class extends $s{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(()=>je(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:M(()=>je(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(ut(o),1-this.rho)),u=V(ge(cn(Y(c,this.epsilon)),cn(Y(i,this.epsilon))),o),d=Y(V(c,this.rho),V(ut(u),1-this.rho));i.assign(l),c.assign(d);let p=Y(V(u,-this.learningRate),s);s.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpda
indices.shape[0] = ${e}`}function PB(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function OB(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function MB(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function LB(e,t){return`size ${e} must be non-negative, not ${t}`}function BB(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function zB(e,t){let n=xt(e),r=xt(t);return`Input to reshape is a SparseTensor with ${n}
dense values, but the requested shape requires a multiple of ${r}. inputShape=${e} outputShape= ${t}`}function WB(e,t){let n=xt(e),r=xt(t);return`Input to reshape is a tensor with ${n} dense values, but the requested shape has ${r}. inputShape=${e} outputShape=${t}`}function VB(){return"segment ids must be >= 0"}function UB(){return"segment ids are not increasing"}function GB(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function HB(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}var VS={};$e(VS,{collectGatherOpShapeInfo:()=>KB,computeOutShape:()=>qB,segOpComputeOptimalWindowSize:()=>jB});function jB(e,t){let n=!1,r;for(e<=px?(r=e,n=!0):r=gh(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=gh(e,r+1);return r}function qB(e,t,n){let r=[],s=e.length;for(let a=0;a<s;a++)a!==t?r.push(e[a]):r.push(n);return r}function KB(e,t,n,r){let s=t.shape.length,a=e.shape.length;if(r!==0&&(r<-s||r>s))throw new Error(`Expect batchDims in the range of [-${s}, ${s}], but got ${r}`);if(r<0&&(r+=s),r>a)throw new Error(`batchDims (${r}) must be less than rank(x) (
${a}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let d=0;d<r;++d)if(e.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${e.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);let o=e.shape[n],i=[],c=1,l=1,u=1;for(let d=0;d<r;++d)i.push(e.shape[d]),c*=e.shape[d];for(let d=r;d<n;d++)i.push(e.shape[d]),l*=e.shape[d];for(let d=r;d<s;d++)i.push(t.shape[d]);for(let d=n+1;d<a;d++)i.push(e.shape[d]),u*=e.shape[d];return{batchSize:c,sliceSize:u,outerSize:l,dimSize:o,outputShape:i}}function XB(e){try{return e.map(t=>kh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function YB(e){return e.map(t=>kd(t))}var hs={};$e(hs,{nonMaxSuppressionV3Impl:()=>FS,nonMaxSuppressionV4Impl:()=>RS,nonMaxSuppressionV5Impl:()=>PS,whereImpl:()=>IS});var US={kernelName:vc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,Nu(ce(n,"float32"),-1))}}},ZB={kernelName:xc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=ut(ce(n,"float32")),s=cn(fe(Ie(1),r));return Ct(ge(e,s))}}}},JB={kernelName:wc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=cn(fe(ut(ce(n,"float32")),1));return ge(e,r)}}}},QB={kernelName:ma,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=ht(n.shape,r.shape);return{a:()=>{let i=e,c=Wt(n.shape,s);return c.length>0&&(i=xe(i,c)),U(i,n.shape)},b:()=>{let i=e,c=Wt(r.shape,s);return c.length>0&&(i=xe(i,c)),U(i,r.shape)}}}},ez={kernelName:go,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((r,s)=>{n[s]=()=>e.clone()}),n}},tz={kernelName:bo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>je(n)}}},nz={kernelName:rd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>je(n)}}},rz={kernelName:Sc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,cn(fe(Ie(1),ut(ce(n,"float32")))))}}},sz={kernelName:Tc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=cn(Y(Ie(1),ut(ce(n,"float32"))));return ge(e,r)}}}},az={kernelName:_c,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=ht(n.shape,r.shape);return{a:()=>{let i=Y(ut(n),ut(r)),c=V(e,ge(r,i)),l=Wt(n.shape,s);return l.length>0&&(c=xe(c,l)),U(c,n.shape)},b:()=>{let i=Y(ut(n),ut(r)),c=Ct(V(e,ge(n,i))),l=Wt(r.shape,s);return l.length>0&&(c=xe(c,l)),U(c,r.shape)}}}},oz={kernelName:Cc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Y(ut(ce(n,"float32")),1))}}},iz={kernelName:Nc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,fe(Ie(1),ut(ce(n,"float32"))))}}};function cz(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]])),O(c.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),O(l.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`),Sn("avgPool3dGrad",s,a);let d={dy:c,input:l},p={filterSize:n,strides:r,pad:s,dimRoundingMode:a},h=z.runKernel(Kh,d,p);return u?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var uz=W({avgPool3dGrad_:cz}),lz={kernelName:sd,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>uz(e,r,s,a,o,i)}}};function dz(e,t,n,r,s){let a=A(e,"dy","avgPoolGrad"),o=A(t,"input","avgPoolGrad");O(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]])),O(c.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${c.rank}.`),O(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(qh,u,d);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var pz=W({avgPoolGrad_:dz}),hz={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o}=n;return{x:()=>pz(e,r,s,a,o)}}},fz={kernelName:vo,i
2021-09-11 17:11:38 +02:00
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{let a=e;if(a.className==null||a.config==null)throw new H(`${r}: Improper config format: ${JSON.stringify(a)}.
2022-02-07 15:43:35 +01: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.
2022-02-07 15:43:35 +01:00
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(c!=null){let l={};for(let h of Object.keys(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];Iy(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 J4(e,t){return e<t?-1:e>t?1:0}function jp(e,t){return-1*J4(e,t)}function na(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function Q4(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 mi(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 fx(e,t,n=0,r=1/0){return rs(n>=0),rs(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(s=>typeof s===t)}function Qt(e,t){Array.isArray(e)?(k.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,r)=>Qt(n,`element ${r+1} of ${t}`))):k.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${qS(e)}.`)}function qS(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>qS(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function eW(e,t,n){let r=n!=null?n():k.now(),s;return(...o)=>{let i=n!=null?n():k.now();return i-r<t||(r=i,s=e(...o)),s}}function KS(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function mx(e,t){return M(()=>cn(xe(V(e,e),t,!0)))}var Md=class extends ie.Serializable{getConfig(){return{}}},gx=class extends Md{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=mx(e,this.axis),n=en(t,0,this.maxValue);return V(e,ge(n,Y(Gt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};gx.className="MaxNorm";ie.registerClass(gx);var bx=class extends Md{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return M(()=>ge(e,Y(Gt(),mx(e,this.axis))))}getConfig(){return{axis:this.axis}}};bx.className="UnitNorm";ie.registerClass(bx);var yx=class extends Md{apply(e){return Ke(e)}};yx.className="NonNeg";ie.registerClass(yx);var vx=class extends Md{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=mx(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(Gt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};vx.className="MinMaxNorm";ie.registerClass(vx);var F1={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function qt(e){return hx(e)}function R1(e,t={}){return Od(e,ie.SerializationMap.getMap().classNameMap,t,"constraint")}function Kt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in F1?F1[e]:e,config:{}};return R1(n)}else return e instanceof Md?e:R1(e)}function tW(e){return new gx(e)}function nW(e){return new bx(e)}function rW(){return new yx}function sW(e){return new vx(e)}var XS={};$e(XS,{constant:()=>NW,glorotNormal:()=>RW,glorotUniform:()=>FW,heNormal:()=>PW,heUniform:()=>OW,identity:()=>DW,leCunNormal:()=>MW,leCunUniform:()=>LW,ones:()=>CW,orthogonal:()=>BW,randomNormal:()=>EW,randomUniform:()=>_W,truncatedNormal:()=>AW,varianceScaling:()=>$W,zeros:()=>TW});var aW=["channelsFirst","channelsLast"],oW=["nearest","bilinear"],iW=["valid","same","causal"],cW=["max","avg"],uW=["sum","mul","concat","ave"],qi=new Map;function Lt(e){mi(aW,"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,Jt(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,r)=>this.write(n,t[r]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let r=0;r<this.size();r++)e.push(r)}if(e.length===0)return er([],[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 er([],[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})`),tt(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,ft(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,r=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
2021-09-11 17:11:38 +02:00
tensor.shape[0], but sum of lengths is
2022-02-07 15:43:35 +01:00
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let s=n===0?0:t.size/n,a=[];M(()=>{t=U(t,[1,n,s]);for(let i=0;i<e.length;++i){let c=i===0?0:r[i-1],l=[0,c,0],u=[1,e[i],s];a[i]=U(ze(t,l,u),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},qd=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: "),Jt(s)}),this.idTensor=Ie(0),this.maxNumElements=r,Jt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new qd([...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=Il(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=Il(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.");Jt(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);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=Il(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: "),Jt(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=Il(this.elementShape,this.tensors,n);return e.length===0?er([],[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=Il(this.elementShape,this.tensors,t);return this.size()===0?er([],[0].concat(n)):M(()=>{let r=this.tensors.map(s=>U(s,n));return tt(r,0)})}};function uH(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
2022-02-07 15:43:35 +01:00
${r}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=Uy(a,n),i=r===0?0:e.size/r,c=M(()=>{let u=[];e=U(e,[1,r,i]);for(let d=0;d<t.length;++d){let p=d===0?0:s[d-1],h=[0,p,0],f=[1,t[d],i];u[d]=U(ze(e,h,f),o)}return e.dispose(),u}),l=new qd([],n,e.dtype,t.length);for(let u=0;u<c.length;u++)l.setItem(u,c[u]);return l}var hH=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[Ss(r)]}case"Switch":{let r=I("pred",e,t,n),s=I("data",e,t,n);return s.kept||(s=Ss(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{let r=e.inputNames.find(s=>xn(s,t,n)!==void 0);if(r){let s=xn(r,t,n);return[Ss(s)]}return}case"Enter":{let r=I("frameName",e,t,n),s=I("tensor",e,t,n);return n.enterFrame(r),[Ss(s)]}case"Exit":{let r=I("tensor",e,t,n);return n.exitFrame(),[Ss(r)]}case"NextIteration":{let r=I("tensor",e,t,n);return n.nextIteration(),[Ss(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 cH(l,s,r,a,c,o,i);return n.addTensorArray(u),[u.idTensor,Ie(1)]}case"TensorArrayWriteV3":{let r=I("tensorArrayId",e,t,n),s=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(s,a),[o.idTensor]}case"TensorArrayReadV3":{let r=I("tensorArrayId",e,t,n),s=I("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{let r=I("tensorArrayId",e,t,n),s=I("indices",e,t,n),a=I("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{let r=I("tensorArrayId",e,t,n),s=I("indices",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(s,a),[o.idTensor]}case"TensorArrayConcatV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=I("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{let r=I("tensorArrayId",e,t,n),s=I("tensor",e,t,n),a=I("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(a,s),[o.idTensor]}case"TensorArraySizeV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return[Ie(s.size(),"int32")]}case"TensorArrayCloseV3":{let r=I("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{let r=I("tensorListId",e,t,n),s=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(s,a),[o.idTensor]}case"TensorListGetItem":{let r=I("tensorListId",e,t,n),s=I("index",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let r=I("indices",e,t,n),s=I("tensor",e,t,n),a=I("elementShape",e,t,n),o=I("numElements",e,t,n),i=dH(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=lH(r,s,o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{let r=I("tensorListId",e,t,n),s=I("indices",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensor
${e}`);let r;return this.size===1/0||this.size==null?r=this.size:t?r=Math.ceil(this.size/e):r=Math.floor(this.size/e),Xn(async()=>(await n.iterator()).columnMajorBatch(e,t,p6),r)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,Xn(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,Xn(async()=>(await t.iterator()).filter(r=>M(()=>e(r))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return Xn(async()=>(await t.iterator()).map(n=>M(()=>e(n))),this.size)}mapAsync(e){let t=this;return Xn(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let t=this;return Xn(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,Xn(async()=>{let r=Ww(async()=>({value:await t.iterator(),done:!1}));return YH(r.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,Xn(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let r=this,s=VH.alea(t||k.now().toString());return Xn(async()=>{let a=s.int32();return n&&(a+=s.int32()),(await r.iterator()).shuffle(e,a.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,Xn(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};Du.MAX_BUFFER_SIZE=1e4;function Xn(e,t=null){return new class extends Du{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function l6(e){return Xn(async()=>PC(e),e.length)}function d6(e){if(!hc(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=t==null?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(let n in e)t=t==null?e[n].size:Math.min(t,e[n].size);return Xn(async()=>{let n=await FC(e,r=>{if(r instanceof Du)return{value:r.iterator(),recurse:!1};if(hc(r))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return ZH(n,ea.SHORTEST)},t)}function p6(e){if(e===null)return null;let t=e[0];return jH(t)?{value:h6(e),recurse:!1}:{value:null,recurse:!0}}function h6(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ee?Ot(e):er(e)}var LC=class extends Du{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))}},Zp='"',Sl=Symbol("out"),uk=Symbol("field"),Jp=Symbol("quote"),sy=Symbol("quoteafterquote"),lk=Symbol("quoteinquote"),BC=class extends Du{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 LC(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(k.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&k.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((r,s)=>(r[s]=r[s]+1||1,r),{}),n=Object.keys(t).filter(r=>t[r]>1);if(k.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let r of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(r)===-1)throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],o=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!o)){let i=t[s],c=null;if(i==="")if(o&&o.default!==void 0)c=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);c=void 0}else{let l=Number(i);if(isNaN(l))o&&o.dtype==="bool"?c=this.getBoolean(i):c=i;else if(!o||!o.dtype)c=l;else switch(o.dtype){case"float32":c=l;break;case"int32":c=Math.floor(l);break;case"bool":c=this.getBoolean(i);break;default:c=l}}o&&o.isLabel?r[a]=c:n[a]=c}}return Object.keys(r).length===0?n:{xs:n,ys:r}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],r=0,s=e.length,a=Sl;for(let o=0;o<s;o++)switch(a){case Sl:switch(e.charAt(o)){case Zp:r=o+1,a=Jp;break;case this.delimiter:if(r=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=Sl;break;default:a=uk,r=o;break}break;case uk:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o)),a=Sl,r=o+1;break;default:}break;case Jp:switch(e.charAt(o)){case Zp:a=sy;break;default:}break;case sy:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o-1)),a=Sl,r=o+1;break;case Zp:a=Jp;break;default:a=lk;break}break;case lk:switch(e.charAt(o)){case Zp:a=Jp;break;default:}break;default:}if(a===sy?n.push(e.substring(r,s-1)):n.push(e.substring(r)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}},zC=class extends tn{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSi
2021-09-11 17:11:38 +02:00
============================
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.
2022-02-07 15:43:35 +01:00
============================`));let r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&k.isString(n[0])){let s=n.map(a=>k.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return _.mergeRealAndImagArrays(r,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(r=>k.decodeString(r))}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,n)}makeOutput(e,t,n){let r=this.write(e,t,n);return ns().makeTensorFromDataId(r,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=k.now();return e(),{kernelMs:k.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){ke([e],"where");let t=this.readSync(e.dataId);return N6(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Uw.nextDataId=0;var KC={};$e(KC,{addImpl:()=>YC,bincountImpl:()=>Hw,bincountReduceImpl:()=>ZC,ceilImpl:()=>JC,concatImpl:()=>jw,equalImpl:()=>QC,expImpl:()=>t2,expm1Impl:()=>r2,floorImpl:()=>s2,gatherNdImpl:()=>a2,gatherV2Impl:()=>o2,greaterEqualImpl:()=>c2,greaterImpl:()=>i2,lessEqualImpl:()=>l2,lessImpl:()=>u2,linSpaceImpl:()=>d2,logImpl:()=>p2,maxImpl:()=>h2,maximumImpl:()=>f2,minimumImpl:()=>m2,multiplyImpl:()=>qw,negImpl:()=>g2,notEqualImpl:()=>b2,prodImpl:()=>y2,rangeImpl:()=>Xw,rsqrtImpl:()=>v2,sigmoidImpl:()=>m5,simpleAbsImpl:()=>XC,sliceImpl:()=>Mh,sparseFillEmptyRowsImpl:()=>w2,sparseReshapeImpl:()=>k2,sparseSegmentReductionImpl:()=>Yw,sqrtImpl:()=>y5,squaredDifferenceImpl:()=>I2,stridedSliceImpl:()=>S2,stringNGramsImpl:()=>T2,stringSplitImpl:()=>C2,stringToHashBucketFastImpl:()=>N2,subImpl:()=>_2,tileImpl:()=>E2,topKImpl:()=>D2,transposeImpl:()=>Kw,uniqueImpl:()=>$2});function XC(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var _6=e=>{let{x:t}=e.inputs,n=e.backend;ke(t,"abs");let r=new Float32Array(k.sizeFromShape(t.shape)),s=n.data.get(t.dataId).values;return r=XC(s),n.makeOutput(r,t.shape,t.dtype)},E6={kernelName:vc,backendName:"cpu",kernelFunc:_6};function Vt(e){return(t,n,r,s,a)=>{let o=_.assertAndGetBroadcastShape(t,n),i=o.length,c=k.computeStrides(o),l=k.sizeFromShape(o),u=k.getTypedArrayFromDType(a,l),d=t.length,p=n.length,h=k.computeStrides(t),f=k.computeStrides(n),m=_.getBroadcastDims(t,o),g=_.getBroadcastDims(n,o);if(m.length+g.length===0)for(let b=0;b<u.length;++b)u[b]=e(r[b%r.length],s[b%s.length]);else for(let b=0;b<u.length;++b){let y=k.indexToLoc(b,i,c),v=y.slice(-d);m.forEach(N=>v[N]=0);let x=k.locToIndex(v,d,h),w=y.slice(-p);g.forEach(N=>w[N]=0);let T=k.locToIndex(w,p,f);u[b]=e(r[x],s[T])}return[u,o]}}function Zn(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 A6={kernelName:Zh,backendName:"cpu",kernelFunc:Zn};function Oh(e,t,n="float32"){if(n==="complex64"){let s=Oh(e,t,"float32"),a=Oh(e,t,"float32")
2021-09-11 17:11:38 +02:00
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
2022-02-07 15:43:35 +01:00
${o.shape}`);let i=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,u=n.data.get(o.dataId).values[0],[d,p,h,f,m]=w2(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 BK={kernelName:md,backendName:"cpu",kernelFunc:LK};function zK(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
2022-02-07 15:43:35 +01:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.data.get(s.dataId).values),i=n.data.get(r.dataId).values,c=Array.from(n.data.get(a.dataId).values),[l,u,d]=k2(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(u,r.dtype,l),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var WK={kernelName:fu,backendName:"cpu",kernelFunc:zK};function VK(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2022-02-07 15:43:35 +01:00
${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[l,u]=Yw(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(u,r.dtype,l)}var UK={kernelName:gd,backendName:"cpu",kernelFunc:VK};function GK(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
2022-02-07 15:43:35 +01:00
${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[l,u]=Yw(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(u,r.dtype,l)}var HK={kernelName:bd,backendName:"cpu",kernelFunc:GK};function jK(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:p}=_.calculateShapes(a,s,i),h=!1,f=n.bufferSync(s),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],b=X2(f,m,i,p,u,l,c,d,g,h);return n.makeTensorInfo(i,b.dtype,b.values)}var qK={kernelName:xf,backendName:"cpu",kernelFunc:jK};function KK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=k.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=new Array(s.shape.length).fill(0),u=s.shape.slice();return c.map(d=>{let p=[...u];p[i]=d;let h=uo({inputs:{x:s},backend:n,attrs:{begin:l,size:p}});return l[i]+=d,h})}var XK={kernelName:hu,backendName:"cpu",kernelFunc:KK},YK={kernelName:yd,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,r=t;ke(n,"square");let s=r.data.get(n.dataId).values,a=new Float32Array(s.length);for(let i=0;i<s.length;++i){let c=s[i];a[i]=c*c}return{dataId:r.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},ZK=it(ya,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),JK={kernelName:ya,backendName:"cpu",kernelFunc:ZK};function QK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r;ke(s,"stridedSlice");let{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=jt.sliceInfo(s.shape,a,o,i,c,l,u,d,p),w;if(m)w=_t({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||b){k.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let T=jt.computeOutShape(y,v,x),N=uo({inputs:{x:s},backend:n,attrs:{begin:y,size:T}});w=_t({inputs:{x:N},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(N)}else{let T=n.bufferSync(s),N=S2(h,T,x,y);w=n.makeTensorInfo(f,N.dtype,N.values)}return w}var eX={kernelName:mu,backendName:"cpu",kernelFunc:QK};function tX(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]=T2(p,h,s,a,o,i,c,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var nX={kernelName:wf,backendName:"cpu",kernelFunc:tX};function rX(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]=C2(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 sX={kernelName:kf,backendName:"cpu",kernelFunc:rX};function aX(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=N2(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var oX={kernelName:If,backendName:"cpu",kernelFunc:aX},iX=it(ui,e=>Math.tan(e)),cX={kernelName:ui,backendName:"cpu",kernelFunc:iX},uX=it(li,e=>Math.tanh(e)),lX={kernelName:li,backendName:"cpu",kernelFunc:uX};function dX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;ke(s,"tile");let o=E2(n.bufferSync(s),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var pX={kernelName:ba,backendName:"cpu",kernelFunc:dX};function hX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r;ke(s,"topk
2021-12-09 20:22:22 +01:00
`),a=s.length.toString().length+2,o=s.map((d,p)=>k.rightPad((p+1).toString(),a)+d),i=0;for(let d=0;d<o.length;d++)i=Math.max(o[d].length,i);let c=o.slice(0,r-1),l=o.slice(r-1,r),u=o.slice(r);console.log(c.join(`
2021-09-11 17:11:38 +02:00
`)),console.log(t.split(`
2021-12-09 20:22:22 +01:00
`)[0]),console.log(`%c ${k.rightPad(l[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
2022-02-07 15:43:35 +01:00
`))}function nN(e){return Fs(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function rN(e,t){if(be(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function ih(e,t){if(be(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function sN(e,t){let n=Fs(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return be(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),be(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function aN(e,t){let n=Fs(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return be(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),be(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function BX(){return J().getNumber("WEBGL_VERSION")===2?1:4}function oN(e){return Fs(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function iN(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 cN(e){return Fs(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function qy(e,t,n,r,s,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(be(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),be(e,()=>e.vertexAttribPointer(i,s,e.FLOAT,!1,a,o)),be(e,()=>e.enableVertexAttribArray(i)),!0)}function uN(e,t,n){fN(e,n),be(e,()=>e.activeTexture(e.TEXTURE0+n)),be(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function zX(e,t){fN(e,t),be(e,()=>e.activeTexture(e.TEXTURE0+t)),be(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function lN(e,t,n){return Fs(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function dN(e,t,n){return e.getUniformLocation(t,n)}function pN(e,t,n,r){be(e,()=>uN(e,t,r)),be(e,()=>e.uniform1i(n,r))}function WX(e){be(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),be(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),be(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function ch(e,t,n){be(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),be(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Ky(e,t){be(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),be(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Fl(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+hN(e,t))}function hN(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 Fs(e,t,n){let r=be(e,()=>t());if(r==null)throw new Error(n);return r}function fN(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 lo(e,t=2){return k.sizeFromShape(e.slice(0,e.length-t))}function po(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 uh(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[lo(e),...po(e)]),t}function mN(e,t=!1){let n=J().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((s,a)=>a>=e.length-2?k.nearestLargerEven(e[a]):e[a]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=k.squeezeShape(e).newShape);let r=k.sizeFromShape(e);if(e.length<=1&&r<=n)return[1,r];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]
2021-09-11 17:11:38 +02:00
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
#define isnan(value) isnan_custom(value)
2021-12-06 12:34:50 +01:00
`,c="",l=`
2021-09-11 17:11:38 +02:00
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
`):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",o="",i=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
2021-06-04 14:54:48 +02:00
}
2021-12-06 12:34:50 +01:00
`,c=`
2021-09-11 17:11:38 +02:00
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
2021-06-04 14:54:48 +02:00
}
2021-10-22 15:06:43 +02:00
`,l=`
2021-09-11 17:11:38 +02:00
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2022-02-07 15:43:35 +01:00
`),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:c,defineRound:l}}function yi(e,t,n="index"){let r=k.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / ${s}`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${s}`:`index -= ${e[a]} * ${s}`;return`${o}; ${i};`}).join("")}function Am(e,t,n="index"){let r=k.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / outShapeStrides[${a}]`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`;return`${o}; ${i};`}).join("")}function HX(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 jX(e,t,n="index"){let r=e.map((a,o)=>o),s=HX(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 r0(e){let t=k.computeStrides(e).map(n=>n.toString());return`
2021-09-11 17:11:38 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
2022-02-07 15:43:35 +01:00
`}function s0(){return`
2021-09-11 17:11:38 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
2022-02-07 15:43:35 +01:00
`}var kN=`
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;
}
2022-02-07 15:43:35 +01:00
`,{getBroadcastDims:IN}=_;function qX(e,t,n){let r=[];if(e.forEach(h=>{let f=k.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?r.push(`uniform float ${h.name}${f>1?`[${f}]`:""};`):(r.push(`uniform sampler2D ${h.name};`),r.push(`uniform int offset${h.name};`)),n.enableShapeUniforms){let{uniformShape:m}=a0(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(`
2022-01-14 16:04:13 +01:00
`),a=e.map(h=>KX(h,t,n.packedInputs,n.enableShapeUniforms)).join(`
2022-02-07 15:43:35 +01:00
`),o=t.texShape,i=Cn(),c=ZX(i),l,u,d=e7(i);return t.isPacked?(l=XX(t.logicalShape,o,n.enableShapeUniforms),u=QX(i)):(l=YX(t.logicalShape,o,n.enableShapeUniforms),u=JX(i)),n.packedInputs&&(d+=s7),[d,c,u,s,l,a,n.userCode].join(`
`)}function Pu(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return g7(e,t);case 1:return y7(e,t);case 2:return x7(e,t);case 3:return k7(e,t);case 4:return S7(e,t);case 5:return T7(e);case 6:return C7(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function SN(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return m7(e);case 1:return b7(e,t);case 2:return v7(e,t);case 3:return w7(e,t);default:return I7(e,t)}}function KX(e,t,n=!1,r){let s="";n?s+=SN(e,r):s+=Pu(e,r);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?s+=N7(e,t):s+=_7(e,t)),s}function XX(e,t,n){switch(e.length){case 0:return TN();case 1:return a7(e,t,n);case 2:return h7(e,t,n);case 3:return i7(e,t,n);default:return u7(e,t,n)}}function YX(e,t,n){switch(e.length){case 0:return TN();case 1:return o7(e,t,n);case 2:return f7(e,t,n);case 3:return c7(e,t,n);case 4:return l7(e,t,n);case 5:return d7(e,t);case 6:return p7(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function ZX(e){return`
2021-09-11 17:11:38 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
2021-05-18 14:11:17 +02:00
}
2022-01-14 16:04:13 +01:00
`}function JX(e){return`
2021-09-11 17:11:38 +02:00
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
2021-05-18 14:11:17 +02:00
}
2022-01-14 16:04:13 +01:00
`}function QX(e){return`
2021-09-11 17:11:38 +02:00
void setOutput(vec4 val) {
${e.output} = val;
2021-05-18 14:11:17 +02:00
}
2022-01-14 16:04:13 +01:00
`}function e7(e){return`${e.version}
2021-09-11 17:11:38 +02:00
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
2021-12-09 20:22:22 +01:00
${t7}
2022-01-14 16:04:13 +01:00
${n7}
${r7}
`}var t7=`
2021-09-11 17:11:38 +02:00
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2022-01-14 16:04:13 +01:00
`,n7=`
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2022-01-14 16:04:13 +01:00
`,r7=`
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2022-01-14 16:04:13 +01:00
`,s7=`
2021-09-11 17:11:38 +02:00
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
2022-02-07 15:43:35 +01:00
`;function TN(){return`
2021-09-11 17:11:38 +02:00
int getOutputCoords() {
return 0;
2021-05-18 14:11:17 +02:00
}
2022-01-14 16:04:13 +01:00
`}function a7(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
}
2022-01-14 16:04:13 +01:00
`}function o7(e,t,n){return t[0]===1?n?`
2021-09-11 17:11:38 +02:00
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
`:`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?n?`
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
`:`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:n?`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
return resTexRC.x * outTexShape[1] + resTexRC.y;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
2021-05-18 14:11:17 +02:00
}
2022-01-14 16:04:13 +01:00
`}function i7(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
}
2022-01-14 16:04:13 +01:00
`}function c7(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
2022-02-07 15:43:35 +01:00
${Am(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2022-02-07 15:43:35 +01:00
`;let r=yi(["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
}
2022-01-14 16:04:13 +01:00
`}function u7(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
int texelsInBatchN = texelsInBatch * outShape[1];
int b2 = index / texelsInBatchN;
index -= b2 * texelsInBatchN;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec4(b2, b, r, c);
2021-05-18 14:11:17 +02:00
}
2021-12-06 12:34:50 +01:00
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2),o=a,i="",c="b, r, c";for(let l=2;l<e.length-1;l++)o*=e[e.length-l-1],i=`
2021-10-22 15:06:43 +02:00
int b${l} = index / ${o};
index -= b${l} * ${o};
2021-12-06 12:34:50 +01:00
`+i,c=`b${l}, `+c;return`
2021-09-11 17:11:38 +02:00
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
int index = resTexRC.x * ${r[1]} + resTexRC.y;
${i}
int b = index / ${a};
index -= b * ${a};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
2021-12-06 12:34:50 +01:00
return ivec${e.length}(${c});
2021-05-18 14:11:17 +02:00
}
2022-01-14 16:04:13 +01:00
`}function l7(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
2022-02-07 15:43:35 +01:00
${Am(["r","c","d","d2"],e)}
2021-09-11 17:11:38 +02:00
return ivec4(r, c, d, d2);
2021-05-18 14:11:17 +02:00
}
2022-02-07 15:43:35 +01:00
`;let r=yi(["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
}
2022-02-07 15:43:35 +01:00
`}function d7(e,t){let n=yi(["r","c","d","d2","d3"],e);return`
2021-09-11 17:11:38 +02:00
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
2021-05-18 14:11:17 +02:00
}
2022-02-07 15:43:35 +01:00
`}function p7(e,t){let n=yi(["r","c","d","d2","d3","d4"],e);return`
2021-09-11 17:11:38 +02:00
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
2021-05-18 14:11:17 +02:00
}
2022-01-14 16:04:13 +01:00
`}function h7(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(k.arraysEqual(e,t))return n?`
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));
}
`;let s=Math.ceil(e[1]/2);return n?`
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec2(r, c);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int index = resTexRC.x * ${r[1]} + resTexRC.y;
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return ivec2(r, c);
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}function f7(e,t,n){return k.arraysEqual(e,t)?n?`
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:e[1]===1?n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:e[0]===1?n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
int r = index / outShape[1];
int c = index - r * outShape[1];
return ivec2(r, c);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}function vi(e){return`offset${e}`}function m7(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=Cn();return`
2021-09-11 17:11:38 +02:00
vec4 ${n}() {
return ${r.texture2D}(${t}, halfCR);
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}function g7(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);
}
2022-02-07 15:43:35 +01:00
`;let o=vi(n);if(t)return`
2021-09-11 17:11:38 +02:00
float ${r}() {
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
`;let[i,c]=e.shapeInfo.texShape;return`
2021-09-11 17:11:38 +02:00
float ${r}() {
2021-12-06 12:34:50 +01:00
vec2 uv = uvFromFlat(${i}, ${c}, ${o});
2021-09-11 17:11:38 +02:00
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}function b7(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=Cn();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);
}
2022-01-14 16:04:13 +01:00
`}function y7(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) {
2022-02-07 15:43:35 +01:00
${Ou(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);
}
2022-02-07 15:43:35 +01:00
`;let i=vi(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);
}
2022-02-07 15:43:35 +01:00
`}function v7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=a[0],i=a[1],c=Cn();if(a!=null&&k.arraysEqual(n,a))return t?`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
2021-12-06 12:34:50 +01:00
return ${c.texture2D}(${r}, uv);
2021-09-11 17:11:38 +02:00
}
`:`
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);
2021-12-06 12:34:50 +01:00
return ${c.texture2D}(${r}, uv);
2021-09-11 17:11:38 +02:00
}
`;if(t)return`
vec4 ${s}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
2021-12-06 12:34:50 +01:00
return ${c.texture2D}(${r}, uv);
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
`;let l=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],u=Math.ceil(n[1]/2);return`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int row, int col) {
2021-12-06 12:34:50 +01:00
vec2 uv = packedUVfrom2D(${u}, ${l[0]}, ${l[1]}, row, col);
return ${c.texture2D}(${r}, uv);
2021-09-11 17:11:38 +02:00
}
2022-01-14 16:04:13 +01:00
`}function x7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(a!=null&&k.arraysEqual(n,a)){if(t)return`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`;let p=a[0],h=a[1];return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
2022-02-07 15:43:35 +01:00
`}let{newShape:o,keptDims:i}=k.squeezeShape(n),c=o;if(c.length<n.length){let p=Mu(e,c),h=["row","col"];return`
${Pu(p,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
2022-02-07 15:43:35 +01:00
return ${s}(${Lu(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)));
2022-02-07 15:43:35 +01:00
${Ou(e)}
2021-09-11 17:11:38 +02:00
}
2022-02-07 15:43:35 +01:00
`;let l=a[0],u=a[1],d=vi(r);return u===1?t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${r}Shape[1], 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
2021-10-22 15:06:43 +02:00
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
2021-09-11 17:11:38 +02:00
return sampleTexture(${r}, uv);
}
2021-10-22 15:06:43 +02:00
`:l===1?t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${r}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
2021-12-06 12:34:50 +01:00
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
2021-09-11 17:11:38 +02:00
return sampleTexture(${r}, uv);
}
`:t?`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${r}Shape[1] + col + ${d};
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${n[1]} + col + ${d};
2021-12-06 12:34:50 +01:00
vec2 uv = uvFromFlat(${l}, ${u}, index);
2021-09-11 17:11:38 +02:00
return sampleTexture(${r}, uv);
}
2022-02-07 15:43:35 +01:00
`}function w7(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=Mu(e,p),m=["b","row","col"];return`
${SN(f,t)}
2021-09-11 17:11:38 +02:00
vec4 ${s}(int b, int row, int col) {
2022-02-07 15:43:35 +01:00
return ${s}(${Lu(m,h)});
2021-09-11 17:11:38 +02:00
}
2022-02-07 15:43:35 +01:00
`}let i=Cn();if(t)return`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${i.texture2D}(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
`;let c=o[0],l=o[1],u=Math.ceil(n[2]/2),d=u*Math.ceil(n[1]/2);return`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
2021-12-06 12:34:50 +01:00
${c}, ${l}, ${d}, ${u}, b, row, col);
2021-09-11 17:11:38 +02:00
return ${i.texture2D}(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}function k7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],o=n[2],{newShape:i,keptDims:c}=k.squeezeShape(n),l=i;if(l.length<n.length){let m=Mu(e,l),g=["row","col","depth"];return`
${Pu(m,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth) {
2022-02-07 15:43:35 +01:00
return ${s}(${Lu(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)));
2022-02-07 15:43:35 +01:00
${Ou(e)}
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
`;let u=e.shapeInfo.texShape,d=u[0],p=u[1],h=e.shapeInfo.flatOffset;if(p===a&&h==null)return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth) {
int stride1 = ${r}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${p}.0, ${d}.0);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;if(p===o&&h==null)return t?`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${n[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${d}.0);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`;let f=vi(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);
}
2022-02-07 15:43:35 +01:00
`}function I7(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=Cn();if(t)return`
2021-09-11 17:11:38 +02:00
vec4 ${r}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${n}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${s.texture2D}(${n}, uv);
}
2021-12-06 12:34:50 +01:00
`;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=c[0],u=c[1],d=Math.ceil(a[o-1]/2),p=d*Math.ceil(a[o-2]/2),h="int b, int row, int col",f=`b * ${p} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<o-1;m++)h=`int b${m}, `+h,p*=a[o-m-1],f=`b${m} * ${p} + `+f;return`
2021-09-11 17:11:38 +02:00
vec4 ${r}(${h}) {
int index = ${f};
2021-12-06 12:34:50 +01:00
int texR = index / ${u};
int texC = index - texR * ${u};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${l});
2021-09-11 17:11:38 +02:00
return ${s.texture2D}(${n}, uv);
}
2022-02-07 15:43:35 +01:00
`}function S7(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:c,keptDims:l}=k.squeezeShape(n);if(c.length<n.length){let y=Mu(e,c),v=["row","col","depth","depth2"];return`
${Pu(y,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2022-02-07 15:43:35 +01:00
return ${s}(${Lu(v,l)});
2021-09-11 17:11:38 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${i}, ${o}, ${a}, 1)));
2022-02-07 15:43:35 +01:00
${Ou(e)}
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(h===i&&u==null)return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
${f}
${m}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${o}, ${a}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
2021-12-06 12:34:50 +01:00
`;if(h===a&&u==null)return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${n[1]*n[2]}, ${n[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
2022-02-07 15:43:35 +01:00
`;let b=vi(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);
}
2022-02-07 15:43:35 +01:00
`}function T7(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,o=t[2]*a,i=t[1]*o,{newShape:c,keptDims:l}=k.squeezeShape(t);if(c.length<t.length){let m=Mu(e,c),g=["row","col","depth","depth2","depth3"];return`
${Pu(m)}
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
2022-02-07 15:43:35 +01:00
return ${r}(${Lu(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;
2022-02-07 15:43:35 +01:00
${Ou(e)}
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&u==null)return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${o}, ${a}, ${s}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
2021-12-06 12:34:50 +01:00
`;if(h===s&&u==null)return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
2022-02-07 15:43:35 +01:00
`;let f=vi(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);
}
2022-02-07 15:43:35 +01:00
`}function C7(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=k.squeezeShape(t);if(s.length<t.length){let g=Mu(e,s),b=["row","col","depth","depth2","depth3","depth4"];return`
${Pu(g)}
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
2022-02-07 15:43:35 +01:00
return ${r}(${Lu(b,a)});
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
`}let o=t[5],i=t[4]*o,c=t[3]*i,l=t[2]*c,u=t[1]*l;if(e.shapeInfo.isUniform)return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
2021-12-06 12:34:50 +01:00
vec4(${u}, ${l}, ${c}, ${i})) +
2021-09-11 17:11:38 +02:00
dot(
vec2(depth3, depth4),
vec2(${o}, 1)));
2022-02-07 15:43:35 +01:00
${Ou(e)}
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
`;let d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===u&&d==null)return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
2021-12-06 12:34:50 +01:00
vec4(${l}, ${c}, ${i}, ${o})) +
2021-09-11 17:11:38 +02:00
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
`;if(f===o&&d==null)return`
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
2022-02-07 15:43:35 +01:00
`;let m=vi(n);return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
2021-12-06 12:34:50 +01:00
int index = row * ${u} + col * ${l} + depth * ${c} +
2021-09-11 17:11:38 +02:00
depth2 * ${i} + depth3 * ${o} + depth4 + ${m};
vec2 uv = uvFromFlat(${h}, ${f}, index);
return sampleTexture(${n}, uv);
}
2022-02-07 15:43:35 +01:00
`}function Ou(e){let t=e.name,n=k.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
2022-02-07 15:43:35 +01:00
`}function N7(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=IN(e.shapeInfo.logicalShape,t.logicalShape),c=mt(o),l=o-a,u,d=["x","y","z","w","u","v"];a===0?u="":o<2&&i.length>=1?u="coords = 0;":u=i.map(y=>`coords.${d[y+l]} = 0;`).join(`
2021-12-09 20:22:22 +01:00
`);let p="";o<2&&a>0?p="coords":p=e.shapeInfo.logicalShape.map((y,v)=>`coords.${d[v+l]}`).join(", ");let h="return outputValue;",m=k.sizeFromShape(e.shapeInfo.logicalShape)===1,b=k.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!b)h=`
2021-09-11 17:11:38 +02:00
return vec4(outputValue.xy, outputValue.xy);
`;else if(m&&!b)o===1?h=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:h=`
return vec4(outputValue.x);
2021-12-09 20:22:22 +01:00
`;else if(i.length){let y=a-2,v=a-1;i.indexOf(y)>-1&&i.indexOf(v)>-1?h="return vec4(outputValue.x);":i.indexOf(y)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(v)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
2021-09-11 17:11:38 +02:00
vec4 ${s}() {
2021-12-06 12:34:50 +01:00
${c} coords = getOutputCoords();
${u}
2021-09-11 17:11:38 +02:00
vec4 outputValue = get${r}(${p});
${h}
}
2022-01-14 16:04:13 +01:00
`}function _7(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===c&&e.shapeInfo.flatOffset==null&&k.arraysEqual(o,a))return`
2021-09-11 17:11:38 +02:00
float ${s}() {
return sampleTexture(${n}, resultUV);
}
2022-02-07 15:43:35 +01:00
`;let l=mt(c),u=IN(e.shapeInfo.logicalShape,t.logicalShape),d=c-i,p,h=["x","y","z","w","u","v"];i===0?p="":c<2&&u.length>=1?p="coords = 0;":p=u.map(m=>`coords.${h[m+d]} = 0;`).join(`
2021-12-06 12:34:50 +01:00
`);let f="";return c<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+d]}`).join(", "),`
2021-09-11 17:11:38 +02:00
float ${s}() {
2021-10-22 15:06:43 +02:00
${l} coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
${p}
return get${r}(${f});
}
2022-02-07 15:43:35 +01:00
`}function mt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function a0(e,t,n){let{newShape:r,keptDims:s}=k.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):r,c=!e&&a>1&&!k.arraysEqual(t,n)&&r.length<a||o;return{useSqueezeShape:c,uniformShape:c?i:t,keptDims:s}}function Mu(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Lu(e,t){return t.map(n=>e[n]).join(", ")}function E7(e,t,n,r){let s=n.map((x,w)=>{let T={logicalShape:x.shape,texShape:x.isUniform?null:x.texData.texShape,isUniform:x.isUniform,isPacked:x.isUniform?!1:x.texData.isPacked,flatOffset:null};return x.texData!=null&&x.texData.slice!=null&&x.texData.slice.flatOffset>0&&(T.flatOffset=x.texData.slice.flatOffset),{name:t.variableNames[w],shapeInfo:T}}),a=s.map(x=>x.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=qX(s,o,t),c=tN(e.gl,i),l=e.createProgram(c),u=null,d=e.getUniformLocation(l,"NAN",!1);J().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(l,"INFINITY",!1));let p=!1,h={},f={},m={};for(let x=0;x<t.variableNames.length;x++){let w=t.variableNames[x];h[w]=e.getUniformLocation(l,w,p),h[`offset${w}`]=e.getUniformLocation(l,`offset${w}`,p),t.enableShapeUniforms&&(f[`${w}Shape`]=e.getUniformLocation(l,`${w}Shape`,p),m[`${w}TexShape`]=e.getUniformLocation(l,`${w}TexShape`,p))}let g,b,y;t.enableShapeUniforms&&(g=e.getUniformLocation(l,"outShape",p),y=e.getUniformLocation(l,"outShapeStrides",p),b=e.getUniformLocation(l,"outTexShape",p));let v=[];return t.customUniforms&&t.customUniforms.forEach((x,w)=>{v[w]=e.getUniformLocation(l,x.name,p)}),{program:t,fragmentShader:c,source:i,webGLProgram:l,uniformLocations:h,customUniformLocations:v,inShapeInfos:a,outShapeInfo:o,infLoc:u,nanLoc:d,inShapesLocations:f,inTexShapesLocations:m,outShapeLocation:g,outShapeStridesLocation:y,outTexShapeLocation:b}}function hk(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,r)=>{let s=n.logicalShape,a=t[r],o=a.shape;if(!k.arraysEqual(s,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${o} must match`);if(n.isUniform&&a.isUniform)return;let i=n.texShape,c=a.isUniform?null:a.texData.texShape;if(!k.arraysEqual(i,c))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${c} must match`)})}function A7(e,t,n,r,s){t.program.enableShapeUniforms||(hk(t.inShapeInfos,n),hk([t.outShapeInfo],[r]));let a=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,o[0],o[1]):e.setOutputMatrixTexture(a.texture,o[0],o[1]),e.setProgram(t.webGLProgram),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}=a0(t.program.packedInputs,c.shape,c.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,c.texData.texShape[0],c.texData.texShape[1]),d!=null){if(c.isUniform){if(k.sizeFromShape(c.shape)<2)e.gl.uniform1f(d,c.uniformValues[0]);else{let m=c.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(d,m)}return}c.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,c.texData.slice.flatOffset),e.setInputMatrixTexture(c.texData.texture.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.s
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2022-02-07 15:43:35 +01:00
${this.enableShapeUniforms?Am(["r","c","d"],e):yi(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${t.output} = result;
}
2022-02-07 15:43:35 +01:00
`}},F7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Jl.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Cn();this.outputShape=e,this.enableShapeUniforms=Un(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2022-02-07 15:43:35 +01:00
${this.enableShapeUniforms?Am(["r","c","d"],e):yi(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
${t.output} = result;
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}},R7=class{constructor(e){this.variableNames=["A"],this.outTexUsage=pr.DOWNLOAD;let t=Cn();this.outputShape=e,this.userCode=`
${kN}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
2022-02-07 15:43:35 +01:00
`}},P7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=pr.DOWNLOAD;let t=Cn();this.outputShape=e,this.userCode=`
${kN}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
2022-02-07 15:43:35 +01:00
`}},O7=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Cn();this.outputShape=e,this.enableShapeUniforms=Un(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode=`
${this.enableShapeUniforms?s0():r0(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.);
}
2022-02-07 15:43:35 +01:00
`}},M7=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Cn();this.outputShape=e,this.enableShapeUniforms=Un(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=`
2022-02-07 15:43:35 +01:00
${this.enableShapeUniforms?s0():r0(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
}
2022-02-07 15:43:35 +01:00
`}},CN={};$e(CN,{bindVertexProgramAttributeStreams:()=>PN,createBufferFromOutputTexture:()=>LN,createFloat16MatrixTexture:()=>DN,createFloat16PackedMatrixTexture:()=>RN,createFloat32MatrixTexture:()=>AN,createIndexBuffer:()=>EN,createPackedMatrixTexture:()=>FN,createUnsignedBytesMatrixTexture:()=>$N,createVertexBuffer:()=>_N,createVertexShader:()=>NN,downloadByteEncodedFloatMatrixFromOutputTexture:()=>zN,downloadFloat32MatrixFromBuffer:()=>BN,downloadMatrixFromPackedOutputTexture:()=>VN,downloadPackedMatrixFromBuffer:()=>WN,getInternalFormatForFloat16MatrixTexture:()=>i0,getInternalFormatForFloat16PackedMatrixTexture:()=>l0,getInternalFormatForFloat32MatrixTexture:()=>o0,getInternalFormatForPackedMatrixTexture:()=>u0,getInternalFormatForUnsignedBytesMatrixTexture:()=>c0,uploadDenseMatrixToTexture:()=>ON,uploadPixelDataToTexture:()=>MN});function NN(e){let t=Cn(),n=`${t.version}
2021-09-11 17:11:38 +02:00
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
2022-02-07 15:43:35 +01:00
}`;return eN(e,n)}function _N(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 sN(e,t)}function EN(e){let t=new Uint16Array([0,1,2,2,1,3]);return aN(e,t)}function Zd(e,t,n,r,s,a){iN(t,n);let o=oN(e),i=e.TEXTURE_2D;return be(e,()=>e.bindTexture(i,o)),be(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),be(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),be(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),be(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),J().getNumber("WEBGL_VERSION")===1?be(e,()=>e.texImage2D(i,0,r,t,n,0,s,a,null)):be(e,()=>e.texStorage2D(i,1,r,t,n)),be(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:o,texShape:[n,t]}}function o0(e){return e.internalFormatFloat}function AN(e,t,n,r){let[s,a]=Yd(t,n);return Zd(e,s,a,o0(r),r.textureFormatFloat,e.FLOAT)}function i0(e){return e.internalFormatHalfFloat}function DN(e,t,n,r){let[s,a]=Yd(t,n);return Zd(e,s,a,i0(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function c0(e){return e.downloadTextureFormat}function $N(e,t,n,r){let[s,a]=Yd(t,n);return Zd(e,s,a,c0(r),e.RGBA,e.UNSIGNED_BYTE)}function u0(e){return e.internalFormatPackedFloat}function FN(e,t,n,r){let[s,a]=Fu(t,n);return Zd(e,s,a,u0(r),e.RGBA,e.FLOAT)}function l0(e){return e.internalFormatPackedHalfFloat}function RN(e,t,n,r){let[s,a]=Fu(t,n);return Zd(e,s,a,l0(r),e.RGBA,r.textureTypeHalfFloat)}function PN(e,t,n){return be(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),qy(e,t,"clipSpacePos",n,3,20,0)&&qy(e,t,"uv",n,2,20,12)}function ON(e,t,n,r,s,a){be(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,i,c;s instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,c=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,c=a.internalFormatPackedFloat),o.set(s),J().getNumber("WEBGL_VERSION")===2?be(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o)):be(e,()=>e.texImage2D(e.TEXTURE_2D,0,c,n,r,0,e.RGBA,i,o)),be(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function MN(e,t,n){be(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?J().getNumber("WEBGL_VERSION")===2?be(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):be(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):J().getNumber("WEBGL_VERSION")===2?be(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):be(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),be(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function LN(e,t,n,r){let s=e.createBuffer();be(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));let i=4*4*t*n;return be(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),be(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),be(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function BN(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 zN(e,t,n,r){let[s,a]=Yd(t,n),o=4,i=new Uint8Array($X(t*n,o));return be(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function WN(e,t,n,r,s,a,o,i){let c=e,l=new Float32Array(FX(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 VN(e,t,n){let r=new Float32Array(t*n*4);return be(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}var ph=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,Z2(t,e)):this.gl=Kr(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=$l(this.gl,s),hr(this.gl,a))this.textureHalfFloatExtension=$l(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=
2021-09-11 17:11:38 +02:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2022-02-07 15:43:35 +01:00
`;else{let t=wn("rc",this.rank),n=mt(this.rank),r=this.getOutOfBoundsCondition(t),s=this.getSetup(t),a=this.getOutput(t);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
2021-12-09 20:22:22 +01:00
${n} rc = getOutputCoords();
2021-04-01 19:39:54 +02:00
2021-12-09 20:22:22 +01:00
if(${r}) {
2021-09-11 17:11:38 +02:00
setOutput(vec4(0));
} else {
2021-12-09 20:22:22 +01:00
${s}
2021-04-01 19:39:54 +02:00
2021-12-09 20:22:22 +01:00
setOutput(vec4(${a}));
2021-04-01 19:39:54 +02:00
}
}
2021-12-09 20:22:22 +01:00
`}}getSourceCoordsArr(e){let t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let s=`${n===0?"r":"rp1"}, ${r===0?"c":"cp1"}`;for(let a=2;a<this.rank;a++)s=`${e[e.length-1-a]},`+s;t.push(s)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],r=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
int r = ${t[0]};
int c = ${t[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${n};
bool rEdge = rp1 >= ${r};
2022-01-14 16:04:13 +01:00
`}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
2021-12-09 20:22:22 +01:00
cEdge ? 0. : getA(${t[1]}),
rEdge ? 0. : getA(${t[2]}),
2022-02-07 15:43:35 +01:00
rEdge || cEdge ? 0. : getA(${t[3]})`}},qN=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Un(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=`
2022-01-14 16:04:13 +01:00
${T9(t,this.enableShapeUniforms)}
2022-02-07 15:43:35 +01:00
${this.enableShapeUniforms?s0():r0(e)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 rc = getOutputCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 thisRC;
int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${n}
2021-04-01 19:39:54 +02:00
setOutput(result);
}
2022-01-14 16:04:13 +01:00
`}};function T9(e,t){return`
2021-09-11 17:11:38 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
2022-02-07 15:43:35 +01:00
${t?jX(["r","c","d"],"inputShape"):yi(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}var C9=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=mk(t,n),s=gk(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=fk(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let i=this.freeTextures[s].shift();return this.usedTextures[s].push(i),i}let o;return r===on.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===on.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===on.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===on.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===on.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(e,t,n,r){if(this.freeTextures==null)return;let s=mk(n,r),a=gk(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);let o=fk(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.texture),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.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function N9(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function fk(e,t,n,r,s){let a=_9(t,r),o;if(s){let[c,l]=Fu(e[0],e[1]);o=c*l}else{let[c,l]=Yd(e[0],e[1]);o=c*l}let i=N9(n,a);return o*i}function _9(e,t){switch(e){case on.PACKED_2X2_FLOAT32:return u0(t);case on.PACKED_2X2_FLOAT16:return l0(t);case on.UNPACKED_FLOAT32:return o0(t);case on.UNPACKED_FLOAT16:return i0(t);case on.PACKED_4X1_UNSIGNED_BYTE:return c0(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function E9(e){return J().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?on.PACKED_2X2_FLOAT32:on.UNPACKED_FLOAT32:e?on.PACKED_2X2_FLOAT16:on.UNPACKED_FLOAT16}function mk(e,t){if(e===pr.UPLOAD)return on.PACKED_2X2_FLOAT32;if(e===pr.RENDER||e==null)return E9(t);if(e===pr.DOWNLOAD||e===pr.PIXELS)return on.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function gk(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var Cs=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Un(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);
}
2022-02-07 15:43:35 +01:00
`}},Fr="if (isnan(x)) return x;",A9="return x;",bk="return abs(x);",D9="return (x >= 0.0) ? x : (exp(x) - 1.0);",$9=Fr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : x;
2022-01-14 16:04:13 +01:00
`,F9=Fr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2022-02-07 15:43:35 +01:00
`,Ki="return x;",R9="return 1.0 / (1.0 + exp(-1.0 * x));",P9="return x;",O9=`
2021-09-11 17:11:38 +02:00
vec4 result;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2022-01-14 16:04:13 +01:00
`,M9=`
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2022-01-14 16:04:13 +01:00
`,L9=`
2021-09-11 17:11:38 +02:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2022-02-07 15:43:35 +01:00
`,B9="return 1.0 / (1.0 + exp(-1.0 * x));",ja=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Un(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
vec4 unaryOperation(vec4 x) {
${t}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}},z9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=Un(this.outputShape.length);let t=e.length,n=wn("rc",t),r=mt(t),s=I9(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
}
2022-02-07 15:43:35 +01:00
`}},W9=hs.whereImpl,V9=1e-7,U9=1e-4,th={};function G9(e){return e in th||(th[e]={}),th[e]}var H9=J().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),j9=600;function q9(){return J().global.screen==null?1024:J().global.screen.height*J().global.screen.width*window.devicePixelRatio*j9/1024/1024}var Dm=class extends nd{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");let t;if(e!=null){if(e instanceof ph)t=e;else{let n=Kr(J().getNumber("WEBGL_VERSION"),e);t=new ph(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Kr(J().getNumber("WEBGL_VERSION"));t=new ph(n),this.binaryCache=G9(J().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new C9(this.gpgpu),this.numMBBeforeWarning=q9(),this.texData=new Gh(this,ns())}nextDataId(){return Dm.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 ja(o,Ki):d=new Cs(o,Ki);let p=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:r}],r),h=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return n;let c=this.activeTimers!=null,l;c&&(l=k.now());let u;if(r==="complex64"){let d=this.readSync(s.real.dataId),p=this.readSync(s.imag.dataId);u=_.mergeRealAndImagArrays(d,p)}else u=this.getValuesFromTexture(e);return c&&(this.downloadWaitMs+=k.now()-l),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(s!=null){let h;i?h=new ja(r,Ki):h=new Cs(r,Ki);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("DEBUG")&&!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.texture,...Qp(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];u=_.mergeRealAndImagArrays(f,m)}else if(c==null)u=this.getValuesFromTexture(e);else{let h=k.sizeFromShape(r);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,h)}if(l!=null&&this.disposeIntermediateTensorInfo(l),c!=null){let h=this.gpgpu.gl;be(h,()=>h.deleteBuffer(c))}let d=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(h=
2021-09-11 17:11:38 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2022-02-07 15:43:35 +01:00
`,gc=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=Un(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
float binaryOperation(float a, float b) {
${e}
2021-04-01 19:39:54 +02:00
}
void main() {
2021-09-11 17:11:38 +02:00
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
2022-02-07 15:43:35 +01:00
`}},$m=`
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;
2022-02-07 15:43:35 +01:00
`,Jd=class{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length;this.enableShapeUniforms=Un(s);let a="";if(r)if(s===0||k.sizeFromShape(this.outputShape)===1)a=`
2021-09-11 17:11:38 +02:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else if(a=`
2022-02-07 15:43:35 +01:00
${mt(s)} coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
`,s===1)this.enableShapeUniforms?a+=`
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`:a+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
2022-02-07 15:43:35 +01:00
`;else{let i=wn("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);
}
2022-02-07 15:43:35 +01:00
`}};function ar(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 Z9={kernelName:Po,backendName:"webgl",kernelFunc:ar};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=ar({inputs:{x:r},backend:n}),c=ar({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:c},a}var J9={kernelName:Zh,backendName:"webgl",kernelFunc:Ta},YN="return (a < 0.) ? b * a : a;",ZN=`
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2022-02-07 15:43:35 +01:00
`;function Q9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=n.makeTensorInfo([],"float32",k.createScalarValue(a,"float32")),i=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Jd(ZN,s.shape,o.shape):new gc(YN,s.shape,o.shape),c=n.runWebGLProgram(i,[s,o],"float32");return n.disposeIntermediateTensorInfo(o),c}var eY={kernelName:Oo,backendName:"webgl",kernelFunc:Q9},JN="return (a < 0.) ? b * a : a;",QN=`
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2022-02-07 15:43:35 +01:00
`;function tY(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Jd(QN,r.shape,s.shape):new gc(JN,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}var nY={kernelName:Xo,backendName:"webgl",kernelFunc:tY},Bu="if (isnan(x)) return x;",rY=`
2021-09-11 17:11:38 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2022-01-14 16:04:13 +01:00
`,sY=`
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;
2022-02-07 15:43:35 +01:00
`;function Ye({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{let{x:o}=s,i=a,c=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let 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 ja(o.shape,t):u=new Cs(o.shape,e),i.runWebGLProgram(u,[o],c)}}function un({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:o,backend:i})=>{let{a:c,b:l}=o,u=i;if(r&&c.dtype==="complex64"){let f=u.texData.get(c.dataId),m=u.texData.get(l.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(v=>{let[x,w]=v,T={dataId:x.dataId,dtype:x.dtype,shape:c.shape},N={dataId:w.dataId,dtype:w.dtype,shape:l.shape},$=new gc(e,c.shape,l.shape);return u.runWebGLProgram($,[T,N],Er(x.dtype,w.dtype))}),y=Ta({inputs:{real:g,imag:b},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(b),y}let d=a||Er(c.dtype,l.dtype);if((c.dtype==="string"||l.dtype==="string"||u.shouldExecuteOnCPU([c,l]))&&s!=null){let f=u.texData.get(c.dataId).values,m=u.texData.get(l.dataId).values,g=c.dtype==="string"?_.fromUint8ToStringArray(f):f,b=c.dtype==="string"?_.fromUint8ToStringArray(m):m,[y,v]=s(c.shape,l.shape,g,b,d),x=u.makeTensorInfo(v,d),w=u.texData.get(x.dataId);return w.values=y,x}let p=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new Jd(t,c.shape,l.shape,n):h=new gc(e,c.shape,l.shape),u.runWebGLProgram(h,[c,l],d)}}function Fm(e,t=!1){if(e==="linear")return t?P9:A9;if(e==="relu")return t?M9:$9;if(e==="elu")return t?O9:D9;if(e==="relu6")return t?L9:F9;if(e==="prelu")return t?QN:JN;if(e==="leakyrelu")return t?ZN:YN;if(e==="sigmoid")return t?B9:R9;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var e_=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=Un(this.outputShape.length);let l=r?e[1]:e[2],u=Math.ceil(l/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=s?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m=`vec4 activation(vec4 a) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
2021-12-06 12:34:50 +01:00
}`:c?m=`vec4 activation(vec4 a) {
2021-09-11 17:11:38 +02:00
vec4 b = getLeakyreluAlphaAtOutCoords();
${o}
}`:m=`vec4 activation(vec4 x) {
${o}
2021-12-09 20:22:22 +01:00
}`,g="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let y="rc.x",v="rc.x";e[0]<t[0]?y=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(v=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
2021-09-11 17:11:38 +02:00
${m}
// Don't use uniform for sharedDimensionPacked for performance.
2021-12-06 12:34:50 +01:00
const float sharedDimension = ${u}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
2021-12-06 12:34:50 +01:00
for (int i = 0; i < ${u}; i++) {
2021-12-09 20:22:22 +01:00
int batchA = ${y};
int batchB = ${v};
2021-09-11 17:11:38 +02:00
vec4 a = getMatrixA(batchA, ${d});
vec4 b = getMatrixB(batchB, ${p});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${h[0]} * ${f[0]});
result += (${h[1]} * ${f[1]});
}
return result;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${b}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${g}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(result);
}
2022-02-07 15:43:35 +01:00
`}},yk={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},vk=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode=`
2021-09-11 17:11:38 +02:00
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
2022-02-07 15:43:35 +01:00
`}},xk="return a * b;";function p0(e){let{inputs:t,backend:n}=e,{a:r,b:s}=t,a=_.upcastType(r.dtype,s.dtype);if(r.dtype==="complex64"){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),l=new vk(yk.REAL,r.shape,s.shape),u=new vk(yk.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]=s9(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 Jd(xk,r.shape,s.shape):o=new gc(xk,r.shape,s.shape),n.runWebGLProgram(o,[r,s],a)}var aY={kernelName:Ho,backendName:"webgl",kernelFunc:p0};function oY(e,t,n){let r=[lo(e.shape),...po(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[lo(t),...po(t)],o=new qN(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 me(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=n,i=k.sizeFromShape(s.shape),c=k.inferFromImplicitShape(a,i),l=k.sizeFromShape(c);k.assert(i===l,()=>`The new shape (${c}) has ${l} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let u=o.texData.get(s.dataId);return u.isPacked&&!Ql(s.shape,c)&&!(u.texture!==null&&Ql(u.shape,c))?oY(s,c,o):(o.incRef(s.dataId),{dataId:s.dataId,shape:c,dtype:s.dtype})}var iY={kernelName:su,backendName:"webgl",kernelFunc:me},wk=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o=Math.floor(n/4)*4,i=n%4,c="sumValue += dot(values, ones);";if(t!=null){let u=1/t;c=`sumValue += dot(values * ${k.isInt(u)?u.toPrecision(2):u}, ones);`}let l="";s%n>0&&(l=`
2021-09-11 17:11:38 +02:00
if (inIdx < 0 || inIdx >= ${s}) {
return 0.0;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
2021-10-22 15:06:43 +02:00
${l}
2021-09-11 17:11:38 +02:00
return getX(batch, inIdx);
2021-04-01 19:39:54 +02:00
}
void main() {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
int batch = coords[0];
2021-09-11 17:11:38 +02:00
int outIdx = coords[1];
int inOffset = outIdx * ${n};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${o}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
${c}
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + ${o};
if (${i===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
${c}
2021-09-11 17:11:38 +02:00
} else if (${i===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
${c}
2021-09-11 17:11:38 +02:00
} else if (${i===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
2021-04-01 19:39:54 +02:00
2021-12-06 12:34:50 +01:00
${c}
2021-09-11 17:11:38 +02:00
}
setOutput(sumValue);
}
2022-01-14 16:04:13 +01:00
`}},cY=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let c=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?c="sumValue":t==="prod"?c="prodValue":t==="all"?c="allValue":t==="any"&&(c="anyValue");let l=Math.floor(n/4)*4,u=n%4,d=`
2021-09-11 17:11:38 +02:00
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${i}(values, minMaxValue);
if (${t==="min"} || ${t==="max"}) {
minMaxValue = ${i}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
`,p="vec4";t==="all"?(o="1.0",d=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,p="bvec4"):t==="any"&&(o="0.0",d=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,p="bvec4");let h="";s%n>0&&(h=`
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${o};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${h}
return getX(batch, inIdx);
2021-04-01 19:39:54 +02:00
}
void main() {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
vec4 minMaxValue = vec4(${o});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
2021-10-22 15:06:43 +02:00
for (int i = 0; i < ${l}; i += 4) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i;
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
}
2021-04-01 19:39:54 +02:00
2021-10-22 15:06:43 +02:00
int inIdx = inOffset + ${l};
2021-12-06 12:34:50 +01:00
if (${u===1}) {
2021-09-11 17:11:38 +02:00
${p} values = ${p}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2021-12-06 12:34:50 +01:00
} else if (${u===2}) {
2021-09-11 17:11:38 +02:00
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2021-12-06 12:34:50 +01:00
} else if (${u===3}) {
2021-09-11 17:11:38 +02:00
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
}
2021-12-06 12:34:50 +01:00
setOutput(${c});
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function uY(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],r=_.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}function xi(e,t,n,r){let s=uY(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 wk({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l},i):new wk({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:l}):u=new cY({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 lY=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];this.outputShape=n,this.rank=n.length;let r=mt(this.rank),s=dY(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
}
2022-02-07 15:43:35 +01:00
`}};function dY(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 pY=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let l=0;l<n.length;l++)n[l]=e[t[l]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let r=mt(this.rank),s=jN("rc",this.rank),a=new Array(this.rank);for(let l=0;l<t.length;l++)a[t[l]]=s[l];let o=`vec2(${a.slice(-2).join()})`,i=`++${s[this.rank-1]} < ${n[this.rank-1]}`,c=`getChannel(getA(${a.join()}), ${o})`;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} rc = getOutputCoords();
vec4 result = vec4(0.);
2021-12-06 12:34:50 +01:00
result[0] = ${c};
2021-09-11 17:11:38 +02:00
if(${i}) {
2021-12-06 12:34:50 +01:00
result[1] = ${c};
}
2021-09-11 17:11:38 +02:00
--${s[this.rank-1]};
if(++${s[this.rank-2]} < ${n[this.rank-2]}) {
2021-12-06 12:34:50 +01:00
result[2] = ${c};
2021-09-11 17:11:38 +02:00
if(${i}) {
2021-12-06 12:34:50 +01:00
result[3] = ${c};
}
}
2021-09-11 17:11:38 +02:00
setOutput(result);
}
2022-02-07 15:43:35 +01:00
`}};function Rm(e,t,n){let r=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new pY(e.shape,t):new lY(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function hY(e,t,n,r){let s=t,a=e.shape.length,o=k.parseAxisParam(s,e.shape),i=o,c=_.getAxesPermutation(i,a),l=c!=null,u=e;l&&(u=Rm(e,c,r),i=_.getInnerMostAxes(i.length,a)),_.assertAxesAreInnerMostDims("sum",i,a);let[d,p]=_.computeOutAndReduceShapes(u.shape,i),h=d;n&&(h=_.expandShapeToKeepDim(d,o));let f=k.sizeFromShape(p),g=k.sizeFromShape(e.shape)/f,b=me({inputs:{x:u},attrs:{shape:[g,f]},backend:r}),y=Cf(e.dtype),v=xi(b,y,"sum",r),x=me({inputs:{x:v},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(v),l&&r.disposeIntermediateTensorInfo(u),x}function Pm(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return hY(s,a,o,n)}var fY={kernelName:ai,backendName:"webgl",kernelFunc:Pm};function kn(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=d0(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=Rm(s,a,o);return l}var mY={kernelName:di,backendName:"webgl",kernelFunc:kn},t_=1e3;function zh({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:c=null}){let l=e.shape.length,u=t.shape.length,d=n?e.shape[l-2]:e.shape[l-1],p=r?t.shape[u-1]:t.shape[u-2],h=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=k.sizeFromShape(m),y=k.sizeFromShape(g),x=wu.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);k.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`);let w=n?[b,d,h]:[b,h,d],T=r?[y,f,p]:[y,p,f],N=me({inputs:{x:e},backend:s,attrs:{shape:w}}),$=me({inputs:{x:t},backend:s,attrs:{shape:T}}),D=[N,$],P=Math.max(b,y),F=n?N.shape[1]:N.shape[2],R=a!=null,C=o!=null,L=c==="leakyrelu",G=c!=null?Fm(c,!0):null,j=R||C||L||G!=null,K;if((h===1||f===1)&&F>t_&&j===!1){let Z=N,te=$;n&&(Z=kn({inputs:{x:N},backend:s,attrs:{perm:[0,2,1]}}),D.push(Z)),r&&(te=kn({inputs:{x:$},backend:s,attrs:{perm:[0,2,1]}}),D.push(te));let se=f!==1,oe=f===1,re=Z;se&&(re=me({inputs:{x:Z},backend:s,attrs:{shape:[P,F,1]}}),D.push(re));let ue=f===1?2:1,ne=te;oe&&(ne=me({inputs:{x:te},backend:s,attrs:{shape:[P,1,F]}}),D.push(ne));let he=p0({inputs:{a:re,b:ne},backend:s});K=Pm({inputs:{x:he},backend:s,attrs:{axis:ue,keepDims:!0}}),D.push(he)}else{let Z=Er(e.dtype,t.dtype),te=new e_(w,T,[P,h,f],n,r,R,G,C,L),se=[N,$];if(a!=null&&se.push(a),C&&se.push(o),L){let oe=s.makeTensorInfo([],"float32",k.createScalarValue(i,"float32"));se.push(oe),D.push(oe)}K=s.runWebGLProgram(te,se,Z)}let q=me({inputs:{x:K},backend:s,attrs:{shape:x}});D.push(K);for(let Z of D)s.disposeIntermediateTensorInfo(Z);return q}function gY(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 zh({a:s,b:a,transposeA:c,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var bY={kernelName:Za,backendName:"webgl",kernelFunc:gY},kk="return abs(x);";function yY(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=GN(a.values);return n.makeTensorInfo(r.shape,r.dtype,o)}let s;return J().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new ja(r.shape,kk):s=new Cs(r.shape,kk),n.runWebGLProgram(s,[r],r.dtype)}var vY={kernelName:vc,backendName:"webgl",kernelFunc:yY},xY=Fr+`
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);
2022-02-07 15:43:35 +01:00
`,wY=Ye({opSnippet:xY}),kY={kernelName:xc,backendName:"webgl",kernelFunc:wY},IY=Fr+`
2021-09-11 17:11:38 +02:00
if (x < 1.0) return NAN;
2022-02-07 15:43:35 +01:00
return log(x + sqrt(x * x - 1.0));`,SY=Ye({opSnippet:IY}),TY={kernelName:wc,backendName:"webgl",kernelFunc:SY},Ik="return a + b;",CY=un({opSnippet:Ik,packedOpSnippet:Ik,supportsComplex:!0,cpuKernelImpl:B7}),NY={kernelName:ma,backendName:"webgl",kernelFunc:CY},_Y=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
}
2022-01-14 16:04:13 +01:00
`}},EY=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
}
2022-02-07 15:43:35 +01:00
`}};function hh(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return ar({inputs:{x:r[0]},backend:n});if(r.length>J().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),l=hh({inputs:r.slice(0,c),backend:n}),u=hh({inputs:r.slice(c),backend:n});return hh({inputs:[l,u],backend:n})}let s=r.map(c=>c.dtype).reduce((c,l)=>Er(c,l)),a=r.map(c=>c.shape),i=J().getBool("WEBGL_PACK")?new EY(r[0].shape,a):new _Y(r[0].shape,a);return n.runWebGLProgram(i,r,s)}var AY={kernelName:go,backendName:"webgl",kernelFunc:hh};function DY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=k.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=kn({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,i)),_.assertAxesAreInnerMostDims("all",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=k.sizeFromShape(h),m=me({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=xi(m,m.dtype,"all",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=me({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=me({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var $Y={kernelName:kc,backendName:"webgl",kernelFunc:DY};function FY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=k.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=kn({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,i)),_.assertAxesAreInnerMostDims("any",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=k.sizeFromShape(h),m=me({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=xi(m,m.dtype,"any",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=me({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=me({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var RY={kernelName:Ic,backendName:"webgl",kernelFunc:FY},PY=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
}
2022-02-07 15:43:35 +01:00
`}},OY=class{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,c=mt(i),l=wn("coords",i),u,d;if(a===1){d=i+1;let N=mt(d);u=`
2022-01-14 16:04:13 +01:00
${N} sourceLocR = ${N}(${l.join()}, 0);
2021-10-22 15:06:43 +02:00
++${l[i-1]};
2022-01-14 16:04:13 +01:00
${N} sourceLocG = ${N}(${l.join()}, 0);
2021-10-22 15:06:43 +02:00
++${l[i-2]};
2022-01-14 16:04:13 +01:00
${N} sourceLocA = ${N}(${l.join()}, 0);
2021-10-22 15:06:43 +02:00
--${l[i-1]};
2022-01-14 16:04:13 +01:00
${N} sourceLocB = ${N}(${l.join()}, 0);
2021-12-06 12:34:50 +01:00
--${l[i-2]};`}else d=i,u=`
${c} sourceLocR = coords;
2021-10-22 15:06:43 +02:00
++${l[i-1]};
2021-12-06 12:34:50 +01:00
${c} sourceLocG = coords;
2021-10-22 15:06:43 +02:00
++${l[i-2]};
2021-12-06 12:34:50 +01:00
${c} sourceLocA = coords;
2021-10-22 15:06:43 +02:00
--${l[i-1]};
2021-12-06 12:34:50 +01:00
${c} sourceLocB = coords;
2022-02-07 15:43:35 +01: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=wn("sourceLocR",d-1).concat("inIdx.r"),g=wn("sourceLocG",d-1).concat("inIdx.g"),b=wn("sourceLocB",d-1).concat("inIdx.b"),y=wn("sourceLocA",d-1).concat("inIdx.a"),v=n==="max"?"greaterThan":"lessThan",x=r?"":`
2021-09-11 17:11:38 +02:00
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${b.join()}),
2021-12-09 20:22:22 +01:00
getBestIndicesAChannel(${y.join()})));`,w=`vec4(
2021-09-11 17:11:38 +02:00
getAChannel(${m.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${b.join()}) : 0.,
2021-12-09 20:22:22 +01:00
hasNextRow && hasNextCol ? getAChannel(${y.join()}) : 0.)`,T=r?"":`
2021-09-11 17:11:38 +02:00
float getBestIndicesAChannel(${f.join()}) {
return getChannel(getBestIndicesA(${p.join()}),
vec2(${p.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${f.join()}) {
return getChannel(getA(${p.join()}),
vec2(${p.slice(-2).join()}));
}
2021-12-09 20:22:22 +01:00
${T}
2021-04-01 19:39:54 +02:00
void main() {
2021-12-06 12:34:50 +01:00
${c} coords = getOutputCoords();
2021-10-22 15:06:43 +02:00
bool hasNextCol = ${l[i-1]} < ${o[i-1]-1};
bool hasNextRow = ${l[i-2]} < ${o[i-2]-1};
2021-12-06 12:34:50 +01:00
${u}
2021-09-11 17:11:38 +02:00
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
sourceLocB${h}, sourceLocA${h}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
2021-12-09 20:22:22 +01:00
vec4 bestValue = ${w};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${x}
2021-12-09 20:22:22 +01:00
vec4 candidate = ${w};
2021-09-11 17:11:38 +02:00
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
2021-12-09 20:22:22 +01:00
vec4(${v}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2021-09-11 17:11:38 +02:00
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(bestIndex);
}
2022-02-07 15:43:35 +01:00
`}};function n_(e,t,n,r=null){let s=t.shape[0],a=t.shape[1];r!=null&&(s=r.shape[0],a=r.shape[1]);let o=_.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:s,outSize:Math.ceil(a/o)},c=new PY(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=n_(e,t,n,u);return e.disposeIntermediateTensorInfo(u),d}function r_(e,t,n,r=null){let s=r!=null?r.shape:t.shape,a=s[s.length-1],o=_.computeOptimalWindowSize(a),i=new OY(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=r_(e,t,n,l);return e.disposeIntermediateTensorInfo(l),u}return l}function s_(e,t,n,r){let s=[n];if(_.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]=_.computeOutAndReduceShapes(c.shape,s),d=k.sizeFromShape(u),p=me({inputs:{x:c},backend:e,attrs:{shape:[-1,d]}});a.push(p);let h=n_(e,p,r);a.push(h);let f=me({inputs:{x:h},backend:e,attrs:{shape:l}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return r_(e,t,r)}function MY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=k.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=kn({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMax",[o[0]],c.shape.length);let u=s_(n,c,o[0],"max");return l.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var LY={kernelName:bo,backendName:"webgl",kernelFunc:MY};function BY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=k.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,l=[];i!=null&&(c=kn({inputs:{x:s},backend:n,attrs:{perm:i}}),l.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);let u=s_(n,c,o[0],"min");return l.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var zY={kernelName:rd,backendName:"webgl",kernelFunc:BY},WY=Fr+`
2021-09-11 17:11:38 +02:00
if (abs(x) > 1.) {
2021-04-01 19:39:54 +02:00
return NAN;
}
2021-09-11 17:11:38 +02:00
return asin(x);
2022-02-07 15:43:35 +01:00
`,VY=Ye({opSnippet:WY}),UY={kernelName:Sc,backendName:"webgl",kernelFunc:VY},GY=Fr+"return log(x + sqrt(x * x + 1.0));",HY=Ye({opSnippet:GY}),jY={kernelName:Tc,backendName:"webgl",kernelFunc:HY},qY=Fr+`
2021-09-11 17:11:38 +02:00
return atan(x);
2022-02-07 15:43:35 +01:00
`,KY=Ye({opSnippet:qY}),XY={kernelName:Cc,backendName:"webgl",kernelFunc:KY},YY=rY+`
2021-09-11 17:11:38 +02:00
return atan(a, b);
2022-01-14 16:04:13 +01:00
`,ZY=`
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));
2022-01-14 16:04:13 +01:00
`+sY+`
2021-09-11 17:11:38 +02:00
return result;
2022-02-07 15:43:35 +01:00
`,JY=un({opSnippet:YY,packedOpSnippet:ZY}),QY={kernelName:_c,backendName:"webgl",kernelFunc:JY},eZ=Fr+`
2021-09-11 17:11:38 +02:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2022-02-07 15:43:35 +01:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,tZ=Ye({opSnippet:eZ}),nZ={kernelName:Nc,backendName:"webgl",kernelFunc:tZ},ed=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-12-06 12:34:50 +01:00
for (int wR = 0; wR < ${u};
wR += ${c}) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${d};
2021-10-22 15:06:43 +02:00
wC += ${l}) {
2021-09-11 17:11:38 +02:00
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
2022-01-14 16:04:13 +01:00
if (value ${N} currMinMaxValue) {
2021-09-11 17:11:38 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${r?s?m:g:`wR * ${d} + wC`};
}
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(float(minMaxPosition));
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
`;return}let y="max",v=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(v="avgValue / count");let x=Math.floor(a/4)*4,w=a%4,T=`
2021-09-11 17:11:38 +02:00
if (${f}) {
avgValue += dot(values, ones);
2021-04-01 19:39:54 +02:00
} else {
2021-12-09 20:22:22 +01:00
minMaxValue = ${y}(values, minMaxValue);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;this.userCode=`
const ivec2 strides = ivec2(${o}, ${i});
const ivec2 pads = ivec2(${p}, ${h});
const float initializationValue = ${b};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int batch = coords[0];
2021-04-01 19:39:54 +02:00
int d = coords[3];
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${b});
float avgValue = 0.0;
count = 0.0;
2021-12-06 12:34:50 +01:00
for (int wR = 0; wR < ${u};
wR += ${c}) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${x}; wC += 4) {
2021-10-22 15:06:43 +02:00
int xC = xCCorner + wC * ${l};
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2021-10-22 15:06:43 +02:00
getValue(batch, xR, xC + ${l}, d),
getValue(batch, xR, xC + 2 * ${l}, d),
getValue(batch, xR, xC + 3 * ${l}, d)
2021-09-11 17:11:38 +02:00
);
2021-12-09 20:22:22 +01:00
${T}
2021-09-11 17:11:38 +02:00
}
int xC = xCCorner + ${x};
2021-12-09 20:22:22 +01:00
if (${w===1}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
2021-12-09 20:22:22 +01:00
${T}
} else if (${w===2}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2021-10-22 15:06:43 +02:00
getValue(batch, xR, xC + ${l}, d),
2021-09-11 17:11:38 +02:00
initializationValue,
initializationValue
);
2021-12-09 20:22:22 +01:00
${T}
} else if (${w===3}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2021-10-22 15:06:43 +02:00
getValue(batch, xR, xC + ${l}, d),
getValue(batch, xR, xC + 2 * ${l}, d),
2021-09-11 17:11:38 +02:00
initializationValue
);
2021-12-09 20:22:22 +01:00
${T}
2021-04-01 19:39:54 +02:00
}
}
2021-12-09 20:22:22 +01:00
setOutput(${v});
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}},h0=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,c=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",v="0.0";if(y||(v="-1.0 / 1e-20"),n){let D=">=";this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec3 strides =
2021-12-06 12:34:50 +01:00
ivec3(${o}, ${i}, ${c});
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3(${m}, ${g}, ${b});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wD = 0; wD < ${p};
2021-10-22 15:06:43 +02:00
wD += ${l}) {
2021-09-11 17:11:38 +02:00
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${h};
2021-12-06 12:34:50 +01:00
wR += ${u}) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${f};
wC += ${d}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
2022-01-14 16:04:13 +01:00
if (value ${D} 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
}
2022-01-14 16:04:13 +01:00
`;return}let x="max",w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(w="avgValue / count");let T=Math.floor(a/4)*4,N=a%4,$=`
2021-12-09 20:22:22 +01:00
if (${y}) {
2021-09-11 17:11:38 +02:00
avgValue += dot(values, ones);
} else {
minMaxValue = ${x}(values, minMaxValue);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;this.userCode=`
const ivec3 strides =
2021-12-06 12:34:50 +01:00
ivec3(${o}, ${i}, ${c});
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3(${m}, ${g}, ${b});
2021-12-09 20:22:22 +01:00
const float initializationValue = ${v};
2021-09-11 17:11:38 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2021-12-09 20:22:22 +01:00
vec4 minMaxValue = vec4(${v});
2021-09-11 17:11:38 +02:00
float avgValue = 0.0;
count = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wD = 0; wD < ${p};
2021-10-22 15:06:43 +02:00
wD += ${l}) {
2021-09-11 17:11:38 +02:00
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${h};
2021-12-06 12:34:50 +01:00
wR += ${u}) {
2021-09-11 17:11:38 +02:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
2021-12-09 20:22:22 +01:00
for (int wC = 0; wC < ${T}; wC += 4) {
2021-09-11 17:11:38 +02:00
int xC = xCCorner + wC * ${d};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
getValue(batch, xD, xR, xC + 3 * ${d}, ch)
);
2022-01-14 16:04:13 +01:00
${$}
2021-04-01 19:39:54 +02:00
}
2021-12-09 20:22:22 +01:00
int xC = xCCorner + ${T};
2022-01-14 16:04:13 +01:00
if (${N===1}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
2022-01-14 16:04:13 +01:00
${$}
} else if (${N===2}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
initializationValue,
initializationValue
);
2022-01-14 16:04:13 +01:00
${$}
} else if (${N===3}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
initializationValue
);
2021-04-01 19:39:54 +02:00
2022-01-14 16:04:13 +01:00
${$}
2021-04-01 19:39:54 +02:00
}
}
2021-12-09 20:22:22 +01:00
setOutput(${w});
2021-04-01 19:39:54 +02:00
}
}
2022-02-07 15:43:35 +01:00
`}};function rZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Ru(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;k.assert(_.eitherStridesOrDilationsAreOne(o,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let u=_.computePool2DInfo(s.shape,a,o,l,i,c);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return ar({inputs:{x:s},backend:n});let d=new ed(u,"avg",!1);return n.runWebGLProgram(d,[s],"float32")}var sZ={kernelName:yo,backendName:"webgl",kernelFunc:rZ};function aZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:l}=r,u=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,u,i,c,l),p=new h0(d,"avg",!1);return n.runWebGLProgram(p,[s],"float32")}var oZ={kernelName:sd,backendName:"webgl",kernelFunc:aZ},iZ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,c=e.effectiveFilterWidth,l=i-1-e.padInfo.top,u=c-1-e.padInfo.left,d=1/(t*n);this.userCode=`
2021-12-06 12:34:50 +01:00
const ivec2 pads = ivec2(${l}, ${u});
2021-09-11 17:11:38 +02:00
const float avgMultiplier = float(${d});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${i};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${r}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
int idyR = int(dyR);
2021-12-06 12:34:50 +01:00
for (int wC = 0; wC < ${c};
2021-09-11 17:11:38 +02:00
wC+= ${o}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier;
2021-04-01 19:39:54 +02:00
}
}
setOutput(dotProd);
}
2022-01-14 16:04:13 +01:00
`}},cZ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=u-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3(${h}, ${f}, ${m});
const float avgMultiplier = float(${g});
2021-04-01 19:39:54 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2021-09-11 17:11:38 +02:00
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
2021-04-01 19:39:54 +02:00
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2021-12-06 12:34:50 +01:00
for (int wD = 0; wD < ${u};
2021-09-11 17:11:38 +02:00
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
int idyD = int(dyD);
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${d};
2021-12-06 12:34:50 +01:00
wR += ${c}) {
2021-09-11 17:11:38 +02:00
float dyR = float(dyRCorner + wR) / ${a}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p};
2021-10-22 15:06:43 +02:00
wC += ${l}) {
2021-09-11 17:11:38 +02:00
float dyC = float(dyCCorner + wC) / ${o}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier;
2021-04-01 19:39:54 +02:00
}
}
}
setOutput(dotProd);
}
2022-02-07 15:43:35 +01:00
`}};function uZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:l,dimRoundingMode:u}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,l,u),h=new cZ(p);return n.runWebGLProgram(h,[s],o.dtype)}var lZ={kernelName:Kh,backendName:"webgl",kernelFunc:uZ};function dZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Ru([s,a],"avgPoolGrad");let{filterSize:i,strides:c,pad:l}=r,u=_.computePool2DInfo(o.shape,i,c,1,l),d=new iZ(u);return n.runWebGLProgram(d,[s],o.dtype)}var pZ={kernelName:qh,backendName:"webgl",kernelFunc:dZ};function hZ(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return zh({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var fZ={kernelName:vo,backendName:"webgl",kernelFunc:hZ},mZ=class{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let o="0.0";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";s!=null&&(_.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${o};
float scale = ${i};
float inv = scale * inversesqrt(variance + float(${a}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}},gZ=class{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";s!=null&&(_.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
vec4 offset = ${o};
vec4 scale = ${i};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput((x - mean) * inv + offset);
}
2022-02-07 15:43:35 +01:00
`}},bZ=({inputs:e,backend:t,attrs:n})=>{let{x:r,mean:s,variance:a,offset:o,scale:i}=e;k.assert(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k.assert(o==null||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k.assert(i==null||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:c}=n;c==null&&(c=.001);let l=[r,s,a],u=null;o!=null&&(u=o.shape,l.push(o));let d=null;i!=null&&(d=i.shape,l.push(i));let p=J().getBool("WEBGL_PACK_NORMALIZATION")?new gZ(r.shape,s.shape,a.shape,u,d,c):new mZ(r.shape,s.shape,a.shape,u,d,c);return t.runWebGLProgram(p,l,l[0].dtype)},yZ={kernelName:Fo,backendName:"webgl",kernelFunc:bZ},vZ=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=mt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=xZ(this.rank),r,s=e.map((a,o)=>`sourceLoc.${Zy[o]} = start[${o}] + coords.${Zy[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}));
}
2022-02-07 15:43:35 +01:00
`}},Zy=["x","y","z","w","u","v"];function xZ(e){if(e===1)return"sourceLoc";if(e<=6)return Zy.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var wZ=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=mt(this.rank),n=wn("coords",this.rank),r=wn("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,o=`
2021-09-11 17:11:38 +02:00
result.x = ${a};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${r[this.rank-1]};
result.y = ${a};
--${r[this.rank-1]};
}
`,i=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
++${r[this.rank-2]};
result.z = ${a};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${r[this.rank-1]};
result.w = ${a};
}
}
2021-12-06 12:34:50 +01:00
`,c=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((l,u)=>`start[${u}]`).join()});`:e.map((l,u)=>`${r[u]} = ${n[u]} + start[${u}];`).join(`
2021-09-11 17:11:38 +02:00
`);this.userCode=`
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
2021-12-06 12:34:50 +01:00
${c}
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
${o}
${i}
setOutput(result);
}
2022-02-07 15:43:35 +01:00
`}};function kZ(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=jt.computeFlatOffset(t,k.computeStrides(e.shape));s.slice&&(i+=s.slice.flatOffset),o.slice={flatOffset:i,origDataId:s.slice&&s.slice.origDataId||e.dataId};let c=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,c+1),a}function zu(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,c]=jt.parseSliceParams(s,a,o);if(jt.assertParamsValid(s,i,c),k.sizeFromShape(c)===0)return n.makeTensorInfo(c,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||s.dtype==="string"){let d=n.texData.get(s.dataId),p=d9(d.values,i,c,s.shape,s.dtype);return n.makeTensorInfo(c,s.dtype,p)}let{isPacked:l}=n.texData.get(s.dataId),u=jt.isSliceContinous(s.shape,i,c);if(l||!u){let d=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new wZ(c):new vZ(c),p=[i];return n.runWebGLProgram(d,[s],s.dtype,p)}return n.uploadToGPU(s.dataId),kZ(s,i,c,n)}var IZ={kernelName:cu,backendName:"webgl",kernelFunc:zu},SZ=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;k.assert(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,v)=>y*v),c=_.getReshaped(s.shape,a,i),l=_.getPermuted(c.length,a.length),u=_.getReshapedPermuted(s.shape,a,i),d=_.getSliceBeginCoords(o,a.length),p=_.getSliceSize(u,o,a.length),h=[],f=me({inputs:{x:s},backend:n,attrs:{shape:c}}),m=kn({inputs:{x:f},backend:n,attrs:{perm:l}}),g=me({inputs:{x:m},backend:n,attrs:{shape:u}}),b=zu({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach(y=>n.disposeIntermediateTensorInfo(y)),b},TZ={kernelName:Ec,backendName:"webgl",kernelFunc:SZ};function CZ(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=UN(i,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,l)}var NZ={kernelName:Xh,backendName:"webgl",kernelFunc:CZ};function _Z(e){let{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),o=n.readSync(s.dataId),i=_.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var EZ={kernelName:Yh,backendName:"webgl",kernelFunc:_Z},AZ="return float(a != b);",a_=un({opSnippet:AZ,cpuKernelImpl:o9,dtype:"bool"}),DZ={kernelName:Yc,backendName:"webgl",kernelFunc:a_};function Qd(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return ar({inputs:{x:s.complexTensorInfos.real},backend:n})}var $Z={kernelName:bf,backendName:"webgl",kernelFunc:Qd},FZ="return float(int(x));";function RZ(e,t){let n=new Cs(e.shape,FZ),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function Jy(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return ar({inputs:{x:s},backend:n});let o=St(s.shape),i=Jy({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=Qd({inputs:{input:s},backend:n}),i=Jy({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!k.hasEncodingLoss(s.dtype,a)){let o=ar({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return RZ(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",k.getTypedArrayFromDType("bool",1)),c=a_({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 PZ={kernelName:xo,backendName:"webgl",kernelFunc:Jy},Sk="return ceil(x);",OZ=Ye({opSnippet:Sk,packedOpSnippet:Sk,cpuKernelImpl:W7}),MZ={kernelName:wo,backendName:"webgl",kernelFunc:OZ},LZ=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));
}
2022-01-14 16:04:13 +01:00
`}},BZ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
vec4 value = getAAtOutCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (any(isnan(value))) {
setOutput(value);
return;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
2022-02-07 15:43:35 +01:00
`}};function zZ(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 BZ(s.shape):i=new LZ(s.shape);let c=[[a],[o]];return n.runWebGLProgram(i,[s],s.dtype,c)}var WZ={kernelName:ga,backendName:"webgl",kernelFunc:zZ},VZ=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
2022-02-07 15:43:35 +01:00
`}};function Tk(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function UZ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new VZ(r.shape),o=[Tk(r,s.complexTensorInfos.real),Tk(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var GZ={kernelName:ad,backendName:"webgl",kernelFunc:UZ},HZ=class{constructor(e){this.outputShape=[],this.outputShape=_.computeOutShape(e,1),this.variableNames=e.map((a,o)=>`T${o}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let o=t[a-1];n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${o}));`)}let r=t.length,s=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${s}));`),this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${n.join(`
`)}
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}},jZ=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.computeOutShape(e,t);let n=this.outputShape,r=n.length,s=mt(r),a=wn("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((f,m)=>`T${m}`);let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let c=o[t],l=o.slice(-2),u=o.join(),d=`if (${c} < ${i[0]}) {
2021-09-11 17:11:38 +02:00
return getChannel(
2021-12-06 12:34:50 +01:00
getT0(${u}), vec2(${l.join()}));
2021-09-11 17:11:38 +02:00
}`;for(let f=1;f<i.length;f++){let m=i[f-1];d+=`
2021-12-06 12:34:50 +01:00
if (${c} < ${i[f]} && ${c} >= ${i[f-1]}) {
2021-09-11 17:11:38 +02:00
return getChannel(
2022-02-07 15:43:35 +01:00
getT${f}(${nh(o,c,m)}),
vec2(${nh(l,c,m)}));
2021-09-11 17:11:38 +02:00
}`}let p=i.length,h=i[i.length-1];d+=`
return getChannel(
2022-02-07 15:43:35 +01:00
getT${p}(${nh(o,c,h)}),
vec2(${nh(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
}
2022-02-07 15:43:35 +01:00
`}};function nh(e,t,n){let r=e.indexOf(t);return e.map((a,o)=>o===r?`${a} - ${n}`:a).join()}function Om(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return ar({inputs:{x:s.complexTensorInfos.imag},backend:n})}var qZ={kernelName:lf,backendName:"webgl",kernelFunc:Om};function Ji(e,t,n){let r=e[0].dtype;if(r==="complex64"){let u=e.map(m=>Qd({inputs:{input:m},backend:n})),d=e.map(m=>Om({inputs:{input:m},backend:n})),p=Ji(u,t,n),h=Ji(d,t,n),f=Ta({inputs:{real:p,imag:h},backend:n});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),d.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}let s=n.shouldExecuteOnCPU(e);if(r==="string"&&(s=!0),s){let u=e.map(b=>{let y=k.sizeFromShape(b.shape.slice(t));return me({inputs:{x:b},backend:n,attrs:{shape:[-1,y]}})}),d=u.map(b=>({vals:n.readSync(b.dataId),shape:b.shape})),p=_.computeOutShape(u.map(b=>b.shape),1),h=u[0].shape[0]===1,f=V7(d,p,r,h),m=_.computeOutShape(e.map(b=>b.shape),t),g=n.makeTensorInfo(m,r,f);return u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g}if(e.length>J().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(e.length/2),d=Ji(e.slice(0,u),t,n),p=Ji(e.slice(u),t,n),h=Ji([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 jZ(e.map(d=>d.shape),t);return n.runWebGLProgram(u,e,r)}let{tensors2D:a,outShape:o}=KZ(e,t,n),i=new HZ(a.map(u=>u.shape)),c=n.runWebGLProgram(i,a,r);a.forEach(u=>n.disposeIntermediateTensorInfo(u));let l=me({inputs:{x:c},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(c),l}function KZ(e,t,n){let r=_.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>me({inputs:{x:a},attrs:{shape:[-1,k.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:r}}function o_(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=k.parseAxisParam(s,t[0].shape)[0],o=_.computeOutShape(t.map(l=>l.shape),a);if(k.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(l=>k.sizeFromShape(l.shape)>0);if(i.length===1)return ar({inputs:{x:i[0]},backend:n});let c=i.map(l=>l.shape);return _.assertParamsConsistent(c,a),Ji(i,a,n)}var XZ={kernelName:Ac,backendName:"webgl",kernelFunc:o_},i_=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,c=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,b=m?2:3,y=m?3:1,v="",x="";n&&(r?v=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords();
${n}
2021-12-09 20:22:22 +01:00
}`:s?v=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getLeakyreluAlphaAtOutCoords();
${n}
2021-12-09 20:22:22 +01:00
}`:v=`
2021-09-11 17:11:38 +02:00
float activation(float x) {
${n}
}
2021-12-09 20:22:22 +01:00
`,x="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${v}
2021-09-11 17:11:38 +02:00
2021-12-06 12:34:50 +01:00
const ivec2 strides = ivec2(${i}, ${c});
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${a}, ${o});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int batch = coords[0];
2021-12-09 20:22:22 +01:00
int d2 = coords[${y}];
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner =
ivec2(coords[${g}], coords[${b}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${d}; wR++) {
2021-10-22 15:06:43 +02:00
int xR = xRCorner + wR * ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p}; wC++) {
2021-12-06 12:34:50 +01:00
int xC = xCCorner + wC * ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
if (${f===1}) {
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
dotProd +=
getX(batch, xR, xC, ${h}) *
getW(wR, wC, ${h}, d2);
} else {
dotProd +=
getX(batch, ${h}, xR, xC) *
getW(wR, wC, ${h}, d2);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
} else if (${f===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
} else if (${f===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2),
getW(wR, wC, ${h} + 2, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1),
getX(batch, xR, xC, ${h} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC),
getX(batch, ${h} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd;
2021-12-09 20:22:22 +01:00
${w}
2021-09-11 17:11:38 +02:00
${x}
setOutput(result);
}
2022-01-14 16:04:13 +01:00
`}},YZ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,l=e.dilationWidth,u=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec3 strides = ivec3(${s}, ${a}, ${o});
const ivec3 pads = ivec3(${t}, ${n}, ${r});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
2021-12-06 12:34:50 +01:00
for (int wF = 0; wF < ${u}; wF++) {
2021-09-11 17:11:38 +02:00
int xF = xFCorner + wF * ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${d}; wR++) {
2021-12-06 12:34:50 +01:00
int xR = xRCorner + wR * ${c};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p}; wC++) {
2021-10-22 15:06:43 +02:00
int xC = xCCorner + wC * ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${f===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${h}) *
getW(wF, wR, wC, ${h}, d2);
} else if (${f===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${h}),
getX(batch, xF, xR, xC, ${h} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${h}, d2),
getW(wF, wR, wC, ${h} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${f===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${h}),
getX(batch, xF, xR, xC, ${h} + 1),
getX(batch, xF, xR, xC, ${h} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${h}, d2),
getW(wF, wR, wC, ${h} + 1, d2),
getW(wF, wR, wC, ${h} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}},ZZ=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=Un(this.outputShape.length);let{dataFormat:n}=t,r=Cn(),s=n==="channelsLast",a=s?0:1,o=s?1:2,i=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`,c="";for(let l=0;l<=1;l++)for(let u=0;u<=1;u++)c+=`
2021-12-06 12:34:50 +01:00
blockIndex = rc.y + ${u};
2021-10-22 15:06:43 +02:00
pos = rc.x + ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${i}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(d0 < inputShape[${a}] && d0 >= 0) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
inChannels);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(d1 < inputShape[${o}] && d1 >= 0) {
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
ch = imod(pos, inChannels);
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
if (${s}) {
innerDims = vec2(d1, ch);
2021-12-06 12:34:50 +01:00
result[${l*2+u}] = getChannel(
2021-09-11 17:11:38 +02:00
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
2021-12-06 12:34:50 +01:00
result[${l*2+u}] = getChannel(
2021-09-11 17:11:38 +02:00
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
2021-04-30 18:01:04 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec2 rc = getOutputCoords();
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0);
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
2021-04-30 18:01:04 +02:00
2021-12-06 12:34:50 +01:00
${c}
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
${r.output} = result;
2021-04-30 18:01:04 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function c_({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>t_)&&l.isPacked&&h&&l.texture!=null&&c[2]%2!==0&&k.arraysEqual(l.shape.slice(-3),c.slice(-3))){let x=c[0]*c[1]*(c[2]+1),w={dataId:e.dataId,shape:[1,x,n.inChannels],dtype:e.dtype},T=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,k.assert(Ql(l.shape,w.shape),()=>`packed reshape ${l.shape} to ${w.shape} isn't free`);let N=me({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(N);let $=zh({a:w,b:N,backend:r,transposeA:f,transposeB:m,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),D=r.texData.get($.dataId);k.assert(D.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=T,D.shape=n.outShape,g=ar({inputs:{x:$},backend:r}),g.shape=n.outShape,b.push($)}else{let x=h?c[0]*c[1]*c[2]:c[0]*c[2]*c[3],w=me({inputs:{x:e},backend:r,attrs:{shape:[1,x,n.inChannels]}}),T=me({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),N=zh({a:w,b:T,transposeA:f,transposeB:m,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=me({inputs:{x:N},backend:r,attrs:{shape:n.outShape}}),b.push(w),b.push(T),b.push(N)}for(let x of b)r.disposeIntermediateTensorInfo(x);return g}function u_({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:c,filterHeight:l,inChannels:u,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=c*l*u,g=p*d,b=[m,g],y=!0,v=!1,x=[],w=me({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),T=me({inputs:{x:t},backend:r,attrs:{shape:[1,m,k.sizeFromShape(t.shape)/m]}});x.push(w),x.push(T);let N=new ZZ(b,n),$=[w.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],D=r.runWebGLProgram(N,[w],"float32",$),P=me({inputs:{x:D},backend:r,attrs:{shape:[1,b[0],b[1]]}});x.push(D),x.push(P);let F=s!=null,R=a!=null,C=i==="leakyrelu",L=i?Fm(i,!0):null,G=new e_(P.shape,T.shape,[1,g,n.outChannels],y,v,F,L,R,C),j=[P,T];if(s&&j.push(s),R&&j.push(a),C){let te=r.makeTensorInfo([],"float32",k.createScalarValue(o,"float32"));j.push(te),x.push(te)}let K=r.runWebGLProgram(G,j,"float32"),q=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],Z=me({inputs:{x:K},backend:r,attrs:{shape:q}});x.push(K);for(let te of x)r.disposeIntermediateTensorInfo(te);return Z}function JZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:c,dilations:l,dimRoundingMode:u}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,a.shape,o,l,i,u,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=c_({x:s,filter:a,convInfo:p,backend:n});else if(J().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)h=u_({x:s,filter:a,convInfo:p,backend:n});else{let m=new i_(p);h=n.runWebGLProgram(m,[s,a],"float32")}let f=me({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var QZ={kernelName:ko,backendName:"webgl",kernelFunc:JZ},eJ=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);
}
2022-01-14 16:04:13 +01:00
`}},tJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,c=a?1:2,l=a?2:3,u=a?3:1;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${o}, ${i});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
2021-12-06 12:34:50 +01:00
int d1 = coords[${u}];
2021-09-11 17:11:38 +02:00
2021-12-06 12:34:50 +01:00
ivec2 dyCorner = ivec2(coords[${c}], coords[${l}]) - pads;
2021-09-11 17:11:38 +02:00
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
int idyR = int(dyR);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = ${t} - 1 - wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
int idyC = int(dyC);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = ${n} - 1 - wC;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${a}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}},nJ=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
}
2022-01-14 16:04:13 +01:00
`}},rJ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,c=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`
2021-12-06 12:34:50 +01:00
const ivec3 pads = ivec3(${i}, ${c}, ${l});
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${s}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${n} - 1 - wR;
for (int wC = 0; wC < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${r} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function sJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:c,dimRoundingMode:l,filterShape:u}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,u,o,1,i,l,!1,d),h=new eJ(p);return n.runWebGLProgram(h,[s,a],"float32")}var aJ={kernelName:Jh,backendName:"webgl",kernelFunc:sJ};function oJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:c,dataFormat:l,dimRoundingMode:u}=r,d=_.convertConv2DDataFormat(l),p=_.computeConv2DInfo(o,a.shape,i,1,c,u,!1,d),h=new tJ(p);return n.runWebGLProgram(h,[s,a],"float32")}var iJ={kernelName:Io,backendName:"webgl",kernelFunc:oJ};function cJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,l=_.computeConv3DInfo(s.shape,a.shape,o,c,i),u=new YZ(l);return n.runWebGLProgram(u,[s,a],"float32")}var uJ={kernelName:od,backendName:"webgl",kernelFunc:cJ};function lJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:c}=r,l=_.computeConv3DInfo(s.shape,c,o,1,i),u=new nJ(l);return n.runWebGLProgram(u,[s,a],"float32")}var dJ={kernelName:Qh,backendName:"webgl",kernelFunc:lJ};function pJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:c}=r,l=_.computeConv3DInfo(c,a.shape,i,1,o),u=new rJ(l);return n.runWebGLProgram(u,[s,a],"float32")}var hJ={kernelName:ef,backendName:"webgl",kernelFunc:pJ},fJ=Bu+`
2021-09-11 17:11:38 +02:00
return cos(x);
2022-02-07 15:43:35 +01:00
`,mJ=Ye({opSnippet:fJ}),gJ={kernelName:So,backendName:"webgl",kernelFunc:mJ},bJ=`
2021-09-11 17:11:38 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2022-02-07 15:43:35 +01:00
`,yJ=Ye({opSnippet:bJ}),vJ={kernelName:To,backendName:"webgl",kernelFunc:yJ},xJ=class{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,c]=e,[l]=t,[u,d]=n;this.outputShape=[l,u,d,c];let p=r==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,b]=u>1?[`${(o-1)/(u-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[y,v,x]=d>1?[`${(i-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`
2021-09-11 17:11:38 +02:00
const float height_ratio = float(${m});
2021-12-09 20:22:22 +01:00
const float width_ratio = float(${y});
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${a}) {
return;
2021-04-01 19:39:54 +02:00
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float height_scale = ${g};
2021-12-09 20:22:22 +01:00
float width_scale = ${v};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float in_y = ${b};
if( in_y < 0.0 || in_y > ${h} ) {
setOutput(float(${s}));
return;
}
float in_x = ${x};
if( in_x < 0.0 || in_x > ${f} ) {
setOutput(float(${s}));
return;
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${p} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}},wJ=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 xJ(s.shape,a.shape,i,c,l);return n.runWebGLProgram(u,[s,a,o],"float32")},kJ={kernelName:Dc,backendName:"webgl",kernelFunc:wJ},Ck=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(${Nk(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() {
2022-02-07 15:43:35 +01:00
${mt(r)} coords = getOutputCoords();
int end = ${_k(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};
2022-02-07 15:43:35 +01:00
${_k(r,"coords")} = idx;
val += getX(${Nk(r,"coords")});
2021-09-11 17:11:38 +02:00
}
setOutput(val);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function Nk(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 _k(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 IJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,c=s.shape.length,l=_.getAxesPermutation([a],c),u=s;l!=null&&(u=kn({inputs:{x:s},backend:n,attrs:{perm:l}}));let d=_.getInnerMostAxes(1,c)[0];if(d!==c-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${s.shape.length-1} but got axis=${a}`);let p=u.shape[d],h=ar({inputs:{x:u},backend:n});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new Ck(u.shape,!1,i),g=[[f]],b=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(b)}if(o){let f=new Ck(u.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(l!=null){let f=_.getUndoAxesPermutation(l),m=kn({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),m}return h}var SJ={kernelName:Co,backendName:"webgl",kernelFunc:IJ};function TJ(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=UN(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=z7(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 CJ={kernelName:tf,backendName:"webgl",kernelFunc:TJ},NJ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function _J(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 NJ(f,a,o);return n.runWebGLProgram(m,[s],s.dtype)}var EJ={kernelName:$c,backendName:"webgl",kernelFunc:_J},l_=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=Un(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,c="",l="";n&&(r?c=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords();
${n}
2021-12-06 12:34:50 +01:00
}`:s?c=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getLeakyreluAlphaAtOutCoords();
${n}
2021-12-06 12:34:50 +01:00
}`:c=`
2021-09-11 17:11:38 +02:00
float activation(float x) {
${n}
}
2021-12-06 12:34:50 +01:00
`,l="result = activation(result);");let u=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${c}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${i};
int q = d2 - d1 * ${i};
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${a}; wR++) {
int xR = xRCorner + wR * dilations[0];
if (xR < 0 || xR >= inDims[0]) {
continue;
}
for (int wC = 0; wC < ${o}; wC++) {
int xC = xCCorner + wC * dilations[1];
if (xC < 0 || xC >= inDims[1]) {
continue;
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd;
2021-12-06 12:34:50 +01:00
${u}
2021-10-22 15:06:43 +02:00
${l}
2021-09-11 17:11:38 +02:00
setOutput(result);
}
2022-02-07 15:43:35 +01:00
`}},d_=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=Un(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,c=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,d=u,p=`
2021-09-11 17:11:38 +02:00
int xR; int xC; int xCOffset;
2021-12-06 12:34:50 +01:00
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<u;g++)p+=`
2021-09-11 17:11:38 +02:00
vec4 xTexelC${g*2};
int xTexelC${g*2}Ready;
vec4 xTexelC${g*2+1};
int xTexelC${g*2+1}Ready;
2021-10-22 15:06:43 +02:00
vec4 xC${g};`;p+=`
for (int r = 0; r < ${l}; r++) {
2021-12-06 12:34:50 +01:00
`;for(let g=0;g<u;g++)p+=`
2021-10-22 15:06:43 +02:00
xTexelC${g*2} = vec4(0.0);
xTexelC${g*2}Ready = 0;
xTexelC${g*2+1} = vec4(0.0);
xTexelC${g*2+1}Ready = 0;
xC${g} = vec4(0.0);`;p+=`
xR = xRCorner + r * dilations[0];
2021-09-11 17:11:38 +02:00
if (xR >=0 && xR < inDims[0]) {
2021-10-22 15:06:43 +02:00
`;for(let g=0;g<(d+1)/2;g++){let b=g*2;if(p+=`
2021-12-06 12:34:50 +01:00
xC = xCCorner + ${b*c};
2022-01-14 16:04:13 +01:00
`,i===1){if(b<u&&(o%2===1?(p+=`
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1;
2021-10-22 15:06:43 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b}.zw = vec2(0.0);
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b}Ready = 1;
2021-09-11 17:11:38 +02:00
}
2021-12-06 12:34:50 +01:00
`,c===1&&b>0?p+=`
2021-10-22 15:06:43 +02:00
xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
2021-09-11 17:11:38 +02:00
`:p+=`
xCOffset = xC + 1 - 2;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
2021-07-29 15:05:49 +02:00
2021-10-22 15:06:43 +02:00
xC${b} = vec4(previous.zw, xTexelC${b}.xy);
2021-04-01 19:39:54 +02:00
} else {
2021-10-22 15:06:43 +02:00
xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
2021-09-11 17:11:38 +02:00
}
`):p+=`
2021-10-22 15:06:43 +02:00
if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
2021-09-11 17:11:38 +02:00
if (xC + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b}.zw = vec2(0.0);
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b}Ready = 1;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xC${b} = xTexelC${b};
2022-01-14 16:04:13 +01:00
`,b+1<u)){let y=o%2===0?k.nearestLargerEven(c):c;c%2===0&&o%2===1||c%2!==0&&o%2!==1?(p+=`
2021-12-09 20:22:22 +01:00
xCOffset = xC + imod(pads[1], 2) + ${y};
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b+1}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b+1}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-12-06 12:34:50 +01:00
`,c>1&&(p+=`
2021-09-11 17:11:38 +02:00
xCOffset -= 2;
2021-10-22 15:06:43 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
xTexelC${b}Ready = 1;
2021-09-11 17:11:38 +02:00
}
`),p+=`
2021-10-22 15:06:43 +02:00
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
2021-12-09 20:22:22 +01:00
`):y===1?p+=`
2021-10-22 15:06:43 +02:00
xC${b+1} = xTexelC${b};
2021-09-11 17:11:38 +02:00
`:p+=`
2021-12-09 20:22:22 +01:00
xCOffset = xC + ${y};
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
2021-09-11 17:11:38 +02:00
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b+1}.zw = vec2(0.0);
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b+1}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
xC${b+1} = xTexelC${b+1};
2022-01-14 16:04:13 +01:00
`}}else b<u&&(o%2===1?(p+=`
2021-09-11 17:11:38 +02:00
xCOffset = xC + 1 - strides[1];
2021-10-22 15:06:43 +02:00
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xCOffset, d1);
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-10-22 15:06:43 +02:00
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xC + 1, d1);
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b+1}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b+1}Ready = 1;
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
2021-12-06 12:34:50 +01:00
`,b+1<u&&(p+=`
2021-09-11 17:11:38 +02:00
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
2021-10-22 15:06:43 +02:00
xC${b+1} = vec4(xTexelC${b+1}.xy, final.xy);
2021-09-11 17:11:38 +02:00
`)):(p+=`
2021-10-22 15:06:43 +02:00
if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
xTexelC${b} = getX(batch, xR, xC, d1);
2021-09-11 17:11:38 +02:00
if (xC + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xCOffset = xC + strides[1];
2021-10-22 15:06:43 +02:00
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
2021-09-11 17:11:38 +02:00
if (xCOffset + 1 >= inDims[1]) {
2021-10-22 15:06:43 +02:00
xTexelC${b+1}.zw = vec2(0.);
2021-09-11 17:11:38 +02:00
}
2021-10-22 15:06:43 +02:00
xTexelC${b+1}Ready = 1;
2021-09-11 17:11:38 +02:00
}
2021-04-01 19:39:54 +02:00
2021-10-22 15:06:43 +02:00
xC${b} = vec4(
xTexelC${b}.xy, xTexelC${b+1}.xy);
2021-12-06 12:34:50 +01:00
`,b+1<u&&(p+=`
2021-10-22 15:06:43 +02:00
xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
2021-12-06 12:34:50 +01:00
`)));b<u&&(p+=`
2021-10-22 15:06:43 +02:00
wTexel = getW(r, ${b}, d1, q);
dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
2021-12-06 12:34:50 +01:00
`,b+1<u&&(p+=`
2021-10-22 15:06:43 +02:00
wTexel = getW(r, ${b+1}, d1, q);
dotProd += xC${b+1} * vec4(wTexel.xz, wTexel.xz);
2021-09-11 17:11:38 +02:00
`))}p+=`
2021-10-22 15:06:43 +02:00
}
`,p+=`
}
`;let h="",f="";n&&(r?h=`vec4 activation(vec4 a) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?h=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${n}
}`:h=`vec4 activation(vec4 x) {
${n}
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${h}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${a};
int q = d2 - d1 * ${a};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${p}
vec4 result = dotProd - vec4(0.000000000000001);
${m}
${f}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function AJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c,dimRoundingMode:l}=r,u=c;u==null&&(u=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(o,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let d=_.computeConv2DInfo(s.shape,a.shape,o,u,i,l,!0),p;J().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels===1?p=new d_(d):p=new l_(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 DJ={kernelName:No,backendName:"webgl",kernelFunc:AJ},$J=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
}
2022-01-14 16:04:13 +01:00
`}},FJ=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);
}
2022-02-07 15:43:35 +01:00
`}};function RJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,filterShape:u}=r,d=_.computeConv2DInfo(s.shape,u,o,i,c,l,!0),p=new $J(d);return n.runWebGLProgram(p,[s,a],"float32")}var PJ={kernelName:nf,backendName:"webgl",kernelFunc:RJ};function OJ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:l,inputShape:u}=r,d=_.computeConv2DInfo(u,a.shape,o,i,c,l,!0),p=new FJ(d);return n.runWebGLProgram(p,[s,a],"float32")}var MJ={kernelName:rf,backendName:"webgl",kernelFunc:OJ},LJ=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
2022-02-07 15:43:35 +01:00
`}};function BJ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=k.sizeFromShape(r.shape),o=me({inputs:{x:r},backend:n,attrs:{shape:[a]}}),i=new LJ(a),c=n.runWebGLProgram(i,[o],o.dtype),l=me({inputs:{x:c},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),l}var zJ={kernelName:sf,backendName:"webgl",kernelFunc:BJ},WJ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:c,dilationWidth:l}=e,{top:u,left:d}=r;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 strides = ivec2(${s}, ${a});
2021-12-06 12:34:50 +01:00
const ivec2 pads = ivec2(${u}, ${d});
2021-09-11 17:11:38 +02:00
const float neg_infinity = -3.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++) {
2021-12-06 12:34:50 +01:00
int hIn = hBeg + h * ${c};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if (hIn >= 0 && hIn < ${t}) {
for (int w = 0; w < ${i}; w++) {
2021-10-22 15:06:43 +02:00
int wIn = wBeg + w * ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (wIn >= 0 && wIn < ${n}) {
float xVal = getX(batch, hIn, wIn, d1);
float wVal = getW(h, w, d1);
float val = xVal + wVal;
if (val > curVal) {
curVal = val;
}
}
}
}
2021-07-29 15:05:49 +02:00
}
2021-09-11 17:11:38 +02:00
float result = curVal;
setOutput(result);
2021-07-29 15:05:49 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function VJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,l=_.computeDilation2DInfo(s.shape,a.shape,o,i,"NHWC",c),u,d=new WJ(l);u=n.runWebGLProgram(d,[s,a],"float32");let p=me({inputs:{x:u},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(u),p}var UJ={kernelName:id,backendName:"webgl",kernelFunc:VJ};function GJ(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:c}=_.decodeEinsumEquation(s,a.length);_.checkEinsumDimSizes(o.length,c,a);let{path:l,steps:u}=_.getEinsumComputePath(i,c),d=u.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:b,expandDims:y}=_.getEinsumPermutation(h,c[g]),v;_.isIdentityPermutation(b)?v=a[g]:(v=kn({inputs:{x:a[g]},backend:n,attrs:{perm:b}}),f.push(v));let x=v.shape.slice();for(let w=0;w<y.length;++w)x.splice(y[w],0,1);k.arraysEqual(v.shape,x)||(v=me({inputs:{x:v},backend:n,attrs:{shape:x}}),f.push(v)),p===null?p=v:(p=p0({inputs:{a:v,b:p},backend:n}),f.push(p))}m<d-1&&(l[m]>=0&&(p=Pm({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 HJ={kernelName:af,backendName:"webgl",kernelFunc:GJ},jJ="return (x >= 0.0) ? x : (exp(x) - 1.0);",qJ=`
2021-09-11 17:11:38 +02:00
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
2022-02-07 15:43:35 +01:00
`,KJ=Ye({opSnippet:jJ,packedOpSnippet:qJ}),XJ={kernelName:Eo,backendName:"webgl",kernelFunc:KJ},YJ="return (b >= 1.0) ? a : a * (b + 1.0);",ZJ=`
2021-09-11 17:11:38 +02:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
2022-02-07 15:43:35 +01:00
`,JJ=e=>{let{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=J().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Jd(ZJ,r.shape,s.shape):new gc(YJ,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)},QJ={kernelName:of,backendName:"webgl",kernelFunc:JJ},eQ=`
2021-09-11 17:11:38 +02:00
return vec4(equal(a, b));
2022-02-07 15:43:35 +01:00
`,tQ="return float(a == b);",nQ=un({opSnippet:tQ,packedOpSnippet:eQ,dtype:"bool",cpuKernelImpl:U7}),rQ={kernelName:Rc,backendName:"webgl",kernelFunc:nQ},sQ=`
2021-09-11 17:11:38 +02:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2021-12-09 20:22:22 +01:00
float p = ${_.ERF_P};
float a1 = ${_.ERF_A1};
float a2 = ${_.ERF_A2};
float a3 = ${_.ERF_A3};
float a4 = ${_.ERF_A4};
float a5 = ${_.ERF_A5};
2021-09-11 17:11:38 +02:00
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
2022-02-07 15:43:35 +01:00
`,aQ=Ye({opSnippet:sQ}),oQ={kernelName:Fc,backendName:"webgl",kernelFunc:aQ},iQ=Bu+`
2022-01-14 16:04:13 +01:00
return exp(x);
`,cQ=`
vec4 result = exp(x);
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2022-02-07 15:43:35 +01:00
`,p_=Ye({opSnippet:iQ,packedOpSnippet:cQ,cpuKernelImpl:G7,dtype:"float32"}),uQ={kernelName:Ao,backendName:"webgl",kernelFunc:p_};function Qy(e){let{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),c=s;return s<0&&(k.assert(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),c=o+s+1),i.splice(c,0,1),me({inputs:{x:a},backend:r,attrs:{shape:i}})}var lQ={kernelName:Pc,backendName:"webgl",kernelFunc:Qy},Ek="return exp(x) - 1.0;",dQ=Ye({opSnippet:Ek,packedOpSnippet:Ek,cpuKernelImpl:H7}),pQ={kernelName:Oc,backendName:"webgl",kernelFunc:dQ},Ak=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
}
2022-02-07 15:43:35 +01:00
`}};function h_(e,t,n){let r=n.texData.get(e.dataId),s=k.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=s/a,i=me({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),c=i.shape,l=new Ak("real",c,t),u=new Ak("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=me({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function hQ(e){let{inputs:t,backend:n}=e,{input:r}=t;return h_(r,!1,n)}var fQ={kernelName:cf,backendName:"webgl",kernelFunc:hQ},mQ=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
// Input can be obtained from uniform value.
setOutput(value);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function ep(e){let{backend:t,attrs:n}=e,{shape:r,value:s}=n,{dtype:a}=n;if(a=a||k.inferDtype(s),a==="string"){let o=k.getArrayFromDType(a,k.sizeFromShape(r));return o.fill(s),t.makeTensorInfo(r,a,o)}else{let o=new mQ(r,s),i=[[s]];return t.runWebGLProgram(o,[],a,i)}}var gQ={kernelName:cd,backendName:"webgl",kernelFunc:ep},bQ=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x - 1;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
2022-02-07 15:43:35 +01:00
`}},yQ={kernelName:Mc,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new bQ(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},Dk="return floor(x);",vQ=Ye({opSnippet:Dk,packedOpSnippet:Dk,cpuKernelImpl:j7}),xQ={kernelName:Do,backendName:"webgl",kernelFunc:vQ},wQ=`
2021-09-11 17:11:38 +02:00
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
2021-04-30 18:01:04 +02:00
}
2022-01-14 16:04:13 +01:00
`,kQ=`
2021-09-11 17:11:38 +02:00
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
2021-04-30 18:01:04 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return vec4(result);
2022-02-07 15:43:35 +01:00
`,IQ=un({opSnippet:wQ,packedOpSnippet:kQ,dtype:"int32"}),SQ={kernelName:$o,backendName:"webgl",kernelFunc:IQ},TQ=class{constructor(e){this.variableNames=["A"];let t=Cn(),[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
}
2022-02-07 15:43:35 +01:00
`}},CQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Cn(),[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
}
2022-02-07 15:43:35 +01:00
`}},NQ={kernelName:vh,backendName:"webgl",kernelFunc:_Q},Xi;function _Q(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)&&(Xi==null&&(Xi=document.createElement("canvas").getContext("2d")),Xi.canvas.width=c,Xi.canvas.height=l,Xi.drawImage(s,0,0,c,l),s=Xi.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 CQ(d):new TQ(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function EQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=_.convertConv2DDataFormat(u),g=_.computeConv2DInfo(s.shape,a.shape,c,d,l,p,!1,m),b,y=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))b=c_({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=u_({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let x=o!=null,w=i!=null,T=h==="leakyrelu",N=h?Fm(h,!1):null,$=new i_(g,x,N,w,T),D=[s,a];if(o&&D.push(o),i&&D.push(i),T){let P=n.makeTensorInfo([],"float32",k.createScalarValue(f,"float32"));D.push(P),y.push(P)}b=n.runWebGLProgram($,D,"float32")}let v=me({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return y.push(b),y.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var AQ={kernelName:Ja,backendName:"webgl",kernelFunc:EQ};function DQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:l,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=r,f=[],m=u;m==null&&(m=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(c,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${c} and dilations '${m}'`);let g=_.computeConv2DInfo(s.shape,a.shape,c,m,l,d,!0),b=J().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,y=p?Fm(p,b):null,v=[s,a],x=o!=null,w=i!=null,T=p==="leakyrelu";if(x&&v.push(o),w&&v.push(i),T){let P=n.makeTensorInfo([],"float32",k.createScalarValue(h,"float32"));v.push(P),f.push(P)}let N;b?N=new d_(g,x,y,w,T):N=new l_(g,x,y,w,T);let $=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],D=n.runWebGLProgram(N,v,"float32",$);return f.forEach(P=>n.disposeIntermediateTensorInfo(P)),D}var $Q={kernelName:Qa,backendName:"webgl",kernelFunc:DQ},FQ=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let r=mt(t.length),s=mt(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2021-09-11 17:11:38 +02:00
${r} strides = ${r}(${this.strides});
void main() {
${s} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${a};
}
setOutput(getX(flattenIndex, coords[1]));
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function RQ(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,o=a[a.length-1],i=k.sizeFromShape(r.shape),[c,l,u,d]=_.prepareAndValidate(r,s),p=me({inputs:{x:s},backend:n,attrs:{shape:[l,o]}}),h=me({inputs:{x:r},backend:n,attrs:{shape:[k.sizeFromShape(r.shape)/u,u]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.readSync(s.dataId),y=n.bufferSync(r),v=q7(b,y,r.dtype,l,o,u,d,r.shape,i);return n.makeTensorInfo(c,r.dtype,v.values)}let f=new FQ(o,d,[l,u]),m=n.runWebGLProgram(f,[h,p],h.dtype),g=me({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var PQ={kernelName:Bc,backendName:"webgl",kernelFunc:RQ},OQ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=mt(this.rank),r=MQ(e,2);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${n} resRC = getOutputCoords();
2022-01-14 16:04:13 +01:00
int index = int(getIndices(resRC.x, resRC.z));
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
setOutput(inBounds * getA(${r}));
2021-09-11 17:11:38 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function MQ(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let s=0;s<e.length;s++)s===2?r.push("index"):r.push(`${n[s]}`);return r.join()}function f_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,c=k.parseAxisParam(o,s.shape)[0];if(J().get("DEBUG")){let y=n.readSync(a.dataId),v=s.shape[c];for(let x=0;x<y.length;++x){let w=y[x];k.assert(w<=v-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${v-1}]`)}}let l=_.segment_util.collectGatherOpShapeInfo(s,a,c,i),u=k.sizeFromShape(a.shape),d=[],p=me({inputs:{x:s},backend:n,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),h=me({inputs:{x:a},backend:n,attrs:{shape:[l.batchSize,u/l.batchSize]}});d.push(p),d.push(h);let f=[l.batchSize,l.outerSize,u/l.batchSize,l.sliceSize];if(n.shouldExecuteOnCPU([s,a])||s.dtype==="string"){let y=n.bufferSync(h),v=n.bufferSync(p),x=K7(v,y,f);return d.forEach(w=>n.disposeIntermediateTensorInfo(w)),n.makeTensorInfo(l.outputShape,x.dtype,x.values)}let m=new OQ(p.shape,f),g=n.runWebGLProgram(m,[p,h],p.dtype);d.push(g);let b=me({inputs:{x:g},backend:n,attrs:{shape:l.outputShape}});return d.forEach(y=>n.disposeIntermediateTensorInfo(y)),b}var LQ={kernelName:Lc,backendName:"webgl",kernelFunc:f_},BQ="return float(a > b);",zQ=`
2021-09-11 17:11:38 +02:00
return vec4(greaterThan(a, b));
2022-02-07 15:43:35 +01:00
`,WQ=un({opSnippet:BQ,packedOpSnippet:zQ,cpuKernelImpl:X7,dtype:"bool"}),VQ={kernelName:zc,backendName:"webgl",kernelFunc:WQ},UQ="return float(a >= b);",GQ=`
2021-09-11 17:11:38 +02:00
return vec4(greaterThanEqual(a, b));
2022-02-07 15:43:35 +01:00
`,HQ=un({opSnippet:UQ,packedOpSnippet:GQ,dtype:"bool",cpuKernelImpl:Y7}),jQ={kernelName:Ro,backendName:"webgl",kernelFunc:HQ};function qQ(e){let{inputs:t,backend:n}=e,{input:r}=t;return h_(r,!0,n)}var KQ={kernelName:uf,backendName:"webgl",kernelFunc:qQ},XQ="return float(!isnan(x) && !isinf(x));",YQ=Ye({opSnippet:XQ,dtype:"bool"}),ZQ={kernelName:Wc,backendName:"webgl",kernelFunc:YQ},JQ="return float(isinf(x));",QQ=Ye({opSnippet:JQ,dtype:"bool"}),eee={kernelName:Vc,backendName:"webgl",kernelFunc:QQ},tee="return float(isnan(x));",nee=Ye({opSnippet:tee,dtype:"bool"}),ree={kernelName:Uc,backendName:"webgl",kernelFunc:nee},see="return float(a < b);",aee=`
2021-09-11 17:11:38 +02:00
return vec4(lessThan(a, b));
2022-02-07 15:43:35 +01:00
`,oee=un({opSnippet:see,packedOpSnippet:aee,cpuKernelImpl:Z7,dtype:"bool"}),iee={kernelName:Gc,backendName:"webgl",kernelFunc:oee},cee="return float(a <= b);",uee=`
2021-09-11 17:11:38 +02:00
return vec4(lessThanEqual(a, b));
2022-02-07 15:43:35 +01:00
`,lee=un({opSnippet:cee,packedOpSnippet:uee,cpuKernelImpl:J7,dtype:"bool"}),dee={kernelName:Hc,backendName:"webgl",kernelFunc:lee};function pee(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=Q7(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var hee={kernelName:df,backendName:"webgl",kernelFunc:pee},fee=Bu+`
2022-01-14 16:04:13 +01:00
return x < 0.0 ? 0./0. : log(x);
`,mee=`
2021-09-11 17:11:38 +02:00
vec4 result = log(x);
2022-01-14 16:04:13 +01:00
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
2021-09-11 17:11:38 +02:00
return result;
2022-02-07 15:43:35 +01:00
`,gee=Ye({opSnippet:fee,packedOpSnippet:mee,cpuKernelImpl:e9}),bee={kernelName:Mo,backendName:"webgl",kernelFunc:gee},yee=Bu+`
2022-01-14 16:04:13 +01:00
return log(1.0 + x);
2022-02-07 15:43:35 +01:00
`,vee=Ye({opSnippet:yee}),xee={kernelName:jc,backendName:"webgl",kernelFunc:vee},wee="return float(a >= 1.0 && b >= 1.0);",kee=`
2021-09-11 17:11:38 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2022-02-07 15:43:35 +01:00
`,Iee=un({opSnippet:wee,packedOpSnippet:kee,dtype:"bool"}),See={kernelName:qc,backendName:"webgl",kernelFunc:Iee},Tee="return float(!(x >= 1.0));",Cee=Ye({opSnippet:Tee}),Nee={kernelName:ud,backendName:"webgl",kernelFunc:Cee},_ee="return float(a >= 1.0 || b >= 1.0);",Eee=`
2021-09-11 17:11:38 +02:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
2022-02-07 15:43:35 +01:00
`,Aee=un({opSnippet:_ee,packedOpSnippet:Eee,dtype:"bool"}),Dee={kernelName:ld,backendName:"webgl",kernelFunc:Aee},$ee=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,c=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${c})`:s===1?i=`1.0/(${c})`:i=`exp(log(${c}) * float(-${s}));`,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${a}; j <= ${a}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${o}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
float val = x * ${i};
setOutput(val);
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}},Fee=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
}
2022-02-07 15:43:35 +01:00
`}},Ree=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 Fee(s.shape,a,o,i,c):new $ee(s.shape,a,o,i,c);return n.runWebGLProgram(l,[s],s.dtype)},Pee={kernelName:dd,backendName:"webgl",kernelFunc:Ree},Oee=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
}
2022-02-07 15:43:35 +01:00
`}},Mee=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 Oee(s.shape,i,c,l,u);return n.runWebGLProgram(d,[s,a,o],s.dtype)},Lee={kernelName:pf,backendName:"webgl",kernelFunc:Mee};function Bee(e,t,n,r){let s=k.sizeFromShape(t),o=k.sizeFromShape(e.shape)/s,i=me({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=xi(i,e.dtype,"max",r),l=me({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),l}function m_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=s.shape.length,c=k.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=u!=null,p=n.shouldExecuteOnCPU([s]),h=s;if(d){if(p){let v=n.texData.get(h.dataId).values,x=new Array(i);for(let N=0;N<x.length;N++)x[N]=s.shape[u[N]];let w=d0(v,s.shape,s.dtype,u,x);h=n.makeTensorInfo(x,s.dtype);let T=n.texData.get(h.dataId);T.values=w}else h=Rm(s,u,n);l=_.getInnerMostAxes(l.length,i)}_.assertAxesAreInnerMostDims("max",l,i);let[f,m]=_.computeOutAndReduceShapes(h.shape,l),g=f;o&&(g=_.expandShapeToKeepDim(f,c));let b;if(p){let v=n.texData.get(h.dataId).values,x=t9(v,k.sizeFromShape(m),g,s.dtype);b=n.makeTensorInfo(g,s.dtype);let w=n.texData.get(b.dataId);w.values=x}else b=Bee(h,m,g,n);return d&&n.disposeIntermediateTensorInfo(h),b}var zee={kernelName:Lo,backendName:"webgl",kernelFunc:m_},Wee=XN+`
2021-09-11 17:11:38 +02:00
return max(a, b);
2022-01-14 16:04:13 +01:00
`,Vee=`
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));
2022-02-07 15:43:35 +01:00
`+$m+`
2021-09-11 17:11:38 +02:00
return result;
2022-02-07 15:43:35 +01:00
`,Uee=un({opSnippet:Wee,packedOpSnippet:Vee,cpuKernelImpl:n9}),Gee={kernelName:Bo,backendName:"webgl",kernelFunc:Uee};function Hee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Ru(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,l=1;k.assert(_.eitherStridesOrDilationsAreOne(o,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let u=_.computePool2DInfo(s.shape,a,o,l,i,c);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return ar({inputs:{x:s},backend:n});let d=new ed(u,"max",!1);return n.runWebGLProgram(d,[s],s.dtype)}var jee={kernelName:zo,backendName:"webgl",kernelFunc:Hee};function qee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dataFormat:c,dimRoundingMode:l}=r,u=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,u,i,l,c),p=new h0(d,"max",!1);return n.runWebGLProgram(p,[s],s.dtype)}var Kee={kernelName:pd,backendName:"webgl",kernelFunc:qee},Xee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=s-1-e.padInfo.top,i=a-1-e.padInfo.left,c=s*a-1;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${o}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${s};
wR += ${r}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${a}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
2021-12-06 12:34:50 +01:00
int maxPosValue = ${c} - int(getMaxPos(b, idyR, idyC, d));
2021-09-11 17:11:38 +02:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${a} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}},Yee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,c=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=i-1-e.padInfo.front,d=c-1-e.padInfo.top,p=l-1-e.padInfo.left,h=i*c*l-1;this.userCode=`
2021-12-06 12:34:50 +01:00
const ivec3 pads = ivec3(${u}, ${d}, ${p});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${i};
wD += ${s}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
2021-12-06 12:34:50 +01:00
for (int wR = 0; wR < ${c};
2021-09-11 17:11:38 +02:00
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-10-22 15:06:43 +02:00
for (int wC = 0; wC < ${l};
2021-09-11 17:11:38 +02:00
wC += ${o}) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${h} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
2021-12-06 12:34:50 +01:00
wD * ${c} * ${l} +
2021-10-22 15:06:43 +02:00
wR * ${l} + wC;
2021-09-11 17:11:38 +02:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function Zee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:l,dimRoundingMode:u}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,l,u),h=new h0(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new Yee(p),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var Jee={kernelName:ff,backendName:"webgl",kernelFunc:Zee};function Qee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Ru([a,o],"maxPoolGrad");let{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=r,p=_.computePool2DInfo(i.shape,c,l,1,u,d),h=!0,f=new ed(p,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new Xee(p),b=n.runWebGLProgram(g,[s,m],i.dtype);return n.disposeIntermediateTensorInfo(m),b}var ete={kernelName:hf,backendName:"webgl",kernelFunc:Qee};function tte(e,t,n,r){let s=new ed(n,"max",!1),a=r.runWebGLProgram(s,[e],"float32");s=new ed(n,"max",!0,!0,t);let o=r.runWebGLProgram(s,[e],"float32");return[a,o]}var nte={kernelName:mf,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,c=n;k.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let l=[1,1];k.assert(_.eitherStridesOrDilationsAreOne(a,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${l}'`);let u=_.computePool2DInfo(r.shape,s,a,l,o),[d,p]=tte(r,i,u,c);return[d,p]}};function rte(e,t,n,r){let s=k.sizeFromShape(t),o=k.sizeFromShape(e.shape)/s,i=me({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=xi(i,"float32","mean",r),l=me({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),l}var ste={kernelName:Wo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{keepDims:s,axis:a}=t,o=n,i=r.shape.length,c=k.parseAxisParam(a,r.shape),l=c,u=_.getAxesPermutation(l,i),d=u!=null,p=o.shouldExecuteOnCPU([r]),h=[],f=r;if(d){if(p){let x=o.texData.get(f.dataId).values,w=new Array(i);for(let $=0;$<w.length;$++)w[$]=r.shape[u[$]];let T=d0(x,r.shape,r.dtype,u,w);f=o.makeTensorInfo(w,r.dtype);let N=o.texData.get(f.dataId);N.values=T}else f=Rm(r,u,o);h.push(f),l=_.getInnerMostAxes(l.length,i)}_.assertAxesAreInnerMostDims("sum",l,i);let[m,g]=_.computeOutAndReduceShapes(f.shape,l),b=m;s&&(b=_.expandShapeToKeepDim(m,c));let y=rte(f,g,b,o);for(let v of h)o.disposeIntermediateTensorInfo(v);return y}};function ate(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=k.parseAxisParam(a,s.shape),l=c,u=_.getAxesPermutation(l,i),d=s;u!=null&&(d=kn({inputs:{x:s},backend:n,attrs:{perm:u}}),l=_.getInnerMostAxes(l.length,s.shape.length)),_.assertAxesAreInnerMostDims("min",l,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,l),f=k.sizeFromShape(h),m=me({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=xi(m,m.dtype,"min",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=me({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=me({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),b}var ote={kernelName:Vo,backendName:"webgl",kernelFunc:ate},ite=XN+`
2021-09-11 17:11:38 +02:00
return min(a, b);
2022-01-14 16:04:13 +01:00
`,cte=`
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));
2022-02-07 15:43:35 +01:00
`+$m+`
2021-09-11 17:11:38 +02:00
return result;
2022-02-07 15:43:35 +01:00
`,ute=un({opSnippet:ite,packedOpSnippet:cte,cpuKernelImpl:r9}),lte={kernelName:Uo,backendName:"webgl",kernelFunc:ute},dte=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let r=e.length,s=mt(r),a=t.map(l=>l[0]).join(","),o=t.map((l,u)=>l[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),c=n==="reflect"?0:1;if(r===1){this.userCode=`
2021-09-11 17:11:38 +02:00
int start = ${a};
int end = ${o};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start) {
2021-12-06 12:34:50 +01:00
outC = start * 2 - outC - ${c};
2021-09-11 17:11:38 +02:00
} else if(outC >= end) {
2021-12-06 12:34:50 +01:00
outC = (end - 1) * 2 - outC + ${c};
2021-09-11 17:11:38 +02:00
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${s} start = ${s}(${a});
${s} end = ${s}(${o});
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outC = getOutputCoords();
for (int i = 0; i < ${r}; i++) {
if (outC[i] < start[i]) {
2021-12-06 12:34:50 +01:00
outC[i] = start[i] * 2 - outC[i] - ${c};
2021-09-11 17:11:38 +02:00
} else if(outC[i] >= end[i]) {
2021-12-06 12:34:50 +01:00
outC[i] = (end[i] - 1) * 2 - outC[i] + ${c};
2021-09-11 17:11:38 +02:00
}
}
${s} coords = outC - start;
setOutput(getX(${i}));
}
2022-02-07 15:43:35 +01:00
`}},pte=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let r=e.length,s=mt(r),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=wn("rc",r),c=wn("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,u=r===1?"source":`vec2(${c.slice(-2).join()})`,d=n==="reflect"?0:1,p="";if(r===1){let h=`
2021-09-11 17:11:38 +02:00
${s} source = rc;
if (source < start) {
source = start * 2 - source - ${d};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${d};
}
source -= start;
`;p=`
${s} rc = outputLoc;
${h}
2021-12-06 12:34:50 +01:00
result[0] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {
2021-09-11 17:11:38 +02:00
${h}
2021-12-06 12:34:50 +01:00
result[1] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
}
`}else{let h=`
${s} source = rc;
${s} lt = ${s}(lessThan(source, start));
${s} gte = ${s}(greaterThanEqual(source, end));
${s} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${d}) +
gte * ((end - 1) * 2 - source + ${d});
source -= start;
`;p=`
${s} rc = outputLoc;
${h}
2021-12-06 12:34:50 +01:00
result[0] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {
2021-09-11 17:11:38 +02:00
${h}
2021-12-06 12:34:50 +01:00
result[1] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
}
rc = outputLoc;
${i[r-2]} += 1;
if(${i[r-2]} < ${this.outputShape[r-2]}) {
${h}
2021-12-06 12:34:50 +01:00
result[2] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {
2021-09-11 17:11:38 +02:00
${h}
2021-12-06 12:34:50 +01:00
result[3] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
}
}
`}this.userCode=`
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${o});
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${p}
setOutput(result);
2020-12-15 14:15:43 +01:00
}
2022-02-07 15:43:35 +01:00
`}},hte=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{paddings:s,mode:a}=n,o=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new pte(r.shape,s,a):new dte(r.shape,s,a);return t.runWebGLProgram(o,[r],r.dtype)},fte={kernelName:Go,backendName:"webgl",kernelFunc:hte},mte=`if (b == 0.0) return NAN;
2022-01-14 16:04:13 +01:00
return mod(a, b);`,gte=`
2021-09-11 17:11:38 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2022-02-07 15:43:35 +01:00
`+$m+`
2021-09-11 17:11:38 +02:00
return result;
2022-02-07 15:43:35 +01:00
`,bte=un({opSnippet:mte,packedOpSnippet:gte}),yte={kernelName:Kc,backendName:"webgl",kernelFunc:bte},vte=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t-1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// If no other event happened, last event happened.
setOutput(float(${t-1}));
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}},xte=`
2021-09-11 17:11:38 +02:00
if (a == b) {
return 1.0;
};
2022-01-14 16:04:13 +01:00
return a / b;`,wte=`
2021-09-11 17:11:38 +02:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.y == b.y) {
result.y = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.z == b.z) {
result.z = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.w == b.w) {
result.w = 1.;
2021-04-01 19:39:54 +02:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
return result;
2022-02-07 15:43:35 +01:00
`,g_=un({opSnippet:xte,packedOpSnippet:wte,checkOutOfBounds:!0}),kte={kernelName:_o,backendName:"webgl",kernelFunc:g_},$k="return a - b;",b_=un({opSnippet:$k,packedOpSnippet:$k,supportsComplex:!0,cpuKernelImpl:v9}),Ite={kernelName:ci,backendName:"webgl",kernelFunc:b_};function y_(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=k.parseAxisParam([a],s.shape),i=m_({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=_.expandShapeToKeepDim(i.shape,o),l=me({inputs:{x:i},backend:n,attrs:{shape:c}}),u=b_({inputs:{a:s,b:l},backend:n}),d=p_({inputs:{x:u},backend:n}),p=Pm({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=me({inputs:{x:p},backend:n,attrs:{shape:c}}),f=g_({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 Ste={kernelName:oi,backendName:"webgl",kernelFunc:y_};function Tte(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r,c=i?s:y_({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),l=c.shape[0],u=c.shape[1],d=new vte(l,u,a),p=[[o]],h=n.runWebGLProgram(d,[c],"int32",p);return i||n.disposeIntermediateTensorInfo(c),h}var Cte={kernelName:gf,backendName:"webgl",kernelFunc:Tte},Nte=Fr+`
2022-01-14 16:04:13 +01:00
return -x;
`,_te=`
vec4 result = -x;
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2022-02-07 15:43:35 +01:00
`;function Ete(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.texData.get(r.dataId),[o,i]=a9(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s;return J().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new ja(r.shape,_te):s=new Cs(r.shape,Nte),n.runWebGLProgram(s,[r],r.dtype)}var Ate={kernelName:Xc,backendName:"webgl",kernelFunc:Ete},Dte=hs.nonMaxSuppressionV3Impl;function $te(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}=Dte(l,u,o,i,c);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var Fte={kernelName:Zc,backendName:"webgl",kernelFunc:$te},Rte=hs.nonMaxSuppressionV4Impl;function Pte(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}=Rte(u,d,o,i,c,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Ote={kernelName:Jc,backendName:"webgl",kernelFunc:Pte},Mte=hs.nonMaxSuppressionV5Impl;function Lte(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}=Mte(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var Bte={kernelName:Qc,backendName:"webgl",kernelFunc:Lte},zte=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
}
2022-02-07 15:43:35 +01:00
`}},Wte=e=>{let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,c=k.sizeFromShape(s.shape),l=new zte(c,a,o,i),u=me({inputs:{x:s},backend:n,attrs:{shape:[c]}}),d=n.runWebGLProgram(l,[u],s.dtype);n.disposeIntermediateTensorInfo(u);let p=[...s.shape,a],h=me({inputs:{x:d},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(d),h},Vte={kernelName:jo,backendName:"webgl",kernelFunc:Wte};function Wh(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=Qd({inputs:{input:r},backend:n}),a=Wh({inputs:{x:s},backend:n}),o=Om({inputs:{input:r},backend:n}),i=Wh({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 ep({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var Ute={kernelName:vu,backendName:"webgl",kernelFunc:Wh};function v_(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=Qd({inputs:{input:r},backend:n}),a=v_({inputs:{x:s},backend:n}),o=Om({inputs:{input:r},backend:n}),i=Wh({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 ep({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var Gte={kernelName:eu,backendName:"webgl",kernelFunc:v_};function Hte(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return Qy({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{k.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),k.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(u=>{let d=Qy({inputs:{input:u},backend:n,attrs:{dim:s}});return i.push(d),d}),l=o_({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),l}var jte={kernelName:tu,backendName:"webgl",kernelFunc:Hte},qte=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((c,l)=>c[0]+e[l]+c[1]);let r=e.length,s=mt(r),a=t.map(c=>c[0]).join(","),o=t.map((c,l)=>c[0]+e[l]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=`
2021-09-11 17:11:38 +02:00
int start = ${a};
int end = ${o};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${s} start = ${s}(${a});
${s} end = ${s}(${o});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${s} coords = outC - start;
setOutput(getX(${i}));
}
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}},Kte=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let r=e.length,s=mt(r),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=wn("rc",r),c=wn("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,u=r===1?"source":`vec2(${c.slice(-2).join()})`,d=[`${s} rc = outputLoc;`,`${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {
2021-09-11 17:11:38 +02:00
`,r===1?"":`}
rc = outputLoc;
${i[r-2]} += 1;
if(${i[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":` ${i[r-1]} += 1;
2021-10-22 15:06:43 +02:00
if(${l}) {`],p=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=r===1?2:4;f<m;f++)h+=`
2021-09-11 17:11:38 +02:00
${d[f]}
if (${p}) {
result[${f}] = float(value);
} else {
${s} source = rc - start;
2021-12-06 12:34:50 +01:00
result[${f}] = getChannel(getX(${c.join()}), ${u});
2021-09-11 17:11:38 +02:00
}
`;h+=r===1?"} ":"}}",this.userCode=`
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${o});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${h}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}},x_=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(k.sizeFromShape(s.shape)===0){let l=a.map((u,d)=>u[0]+s.shape[d]+u[1]);return ep({backend:n,attrs:{shape:l,value:o,dtype:s.dtype}})}let i=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Kte(s.shape,a,o):new qte(s.shape,a,o),c=[[o]];return n.runWebGLProgram(i,[s],s.dtype,c)},Xte={kernelName:qo,backendName:"webgl",kernelFunc:x_},Yte=`
2021-09-11 17:11:38 +02:00
if(a < 0.0 && floor(b) < b){
return NAN;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (b == 0.0) {
return 1.0;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
2022-01-14 16:04:13 +01:00
`,Zte=`
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));
2022-02-07 15:43:35 +01:00
`+$m+`
2021-09-11 17:11:38 +02:00
return result;
2022-02-07 15:43:35 +01:00
`,Jte=un({opSnippet:Yte,packedOpSnippet:Zte}),Qte={kernelName:Ko,backendName:"webgl",kernelFunc:Jte};function ene(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=[],l=k.parseAxisParam(a,s.shape),u=l,d=_.getAxesPermutation(u,i),p=s;d!=null&&(p=kn({inputs:{x:s},backend:n,attrs:{perm:d}}),u=_.getInnerMostAxes(u.length,i),c.push(p)),_.assertAxesAreInnerMostDims("prod",u,i);let h;if(n.shouldExecuteOnCPU([p])){let f=n.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:b}=i9(p.shape,p.dtype,f,u);h=n.makeTensorInfo(g,b,m)}else{let[f,m]=_.computeOutAndReduceShapes(p.shape,u),g=k.sizeFromShape(m),b=me({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),y=Cf(s.dtype),v=xi(b,y,"prod",n);h=me({inputs:{x:v},backend:n,attrs:{shape:f}}),c.push(b),c.push(v)}if(o){c.push(h);let f=_.expandShapeToKeepDim(h.shape,l);h=me({inputs:{x:h},backend:n,attrs:{shape:f}})}return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var tne={kernelName:nu,backendName:"webgl",kernelFunc:ene},w_=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=c9(r,s,a,o);return t.makeTensorInfo([i.length],o,i)},nne={kernelName:hd,backendName:"webgl",kernelFunc:w_},rne="return 1.0 / x;",sne=Ye({opSnippet:rne}),ane={kernelName:ru,backendName:"webgl",kernelFunc:sne},one=Fr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : x;
2022-01-14 16:04:13 +01:00
`,ine=`
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2022-02-07 15:43:35 +01:00
`,cne=Ye({opSnippet:one,packedOpSnippet:ine}),une={kernelName:Yo,backendName:"webgl",kernelFunc:cne},lne=Fr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2022-01-14 16:04:13 +01:00
`,dne=`
2021-09-11 17:11:38 +02:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2022-02-07 15:43:35 +01:00
`,pne=Ye({opSnippet:lne,packedOpSnippet:dne}),hne={kernelName:Jo,backendName:"webgl",kernelFunc:pne},fne=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2021-12-06 12:34:50 +01:00
${l[0]/u[0]},
${l[1]/u[1]});
2021-09-11 17:11:38 +02:00
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec2 sourceFracIndexRC = ${d};
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}},mne=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
2021-12-06 12:34:50 +01:00
${l[0]/u[0]},
${l[1]/u[1]},
${l[1]/u[1]});
2021-09-11 17:11:38 +02:00
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec3 sourceFracIndexRC = ${d};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
2021-12-06 12:34:50 +01:00
bool hasNextCol = d < ${c-1};
2021-09-11 17:11:38 +02:00
bool hasNextRow = coords.z < ${n-1};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
setOutput(newValue);
}
2022-02-07 15:43:35 +01:00
`}};function gne(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 mne(s.shape,c,l,a,o):new fne(s.shape,c,l,a,o);return n.runWebGLProgram(u,[s],"float32")}var bne={kernelName:Zo,backendName:"webgl",kernelFunc:gne},yne=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],l=i[0]/c[0],u=i[1]/c[1],d=1/l,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float accumulator = 0.0;
2020-10-11 18:41:17 +02:00
2021-10-22 15:06:43 +02:00
const float heightScale = float(${l});
2021-12-06 12:34:50 +01:00
const float widthScale = float(${u});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
const float invHeightScale = float(${d});
const float invWidthScale = float(${p});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
const int winHeight = int(${h});
const int winWidth = int(${f});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
2021-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
}
2022-02-07 15:43:35 +01:00
`}};function vne(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new yne(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var xne={kernelName:vf,backendName:"webgl",kernelFunc:vne},wne=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2021-12-06 12:34:50 +01:00
${l[0]/u[0]},
${l[1]/u[1]});
2021-09-11 17:11:38 +02:00
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec2 sourceFracIndexRC = ${p};
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
2021-04-01 19:39:54 +02:00
}
2022-01-14 16:04:13 +01:00
`}},kne=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let l=[r&&t>1?o-1:o,r&&n>1?i-1:i],u=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
2021-12-06 12:34:50 +01:00
${l[0]/u[0]},
${l[1]/u[1]},
${l[1]/u[1]});
2021-09-11 17:11:38 +02:00
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec3 sourceFracIndexRC = ${p};
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
2021-12-06 12:34:50 +01:00
bool hasNextCol = d < ${c-1};
2021-09-11 17:11:38 +02:00
bool hasNextRow = coords.z < ${n-1};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 newValue = vec4(
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput(newValue);
}
2022-02-07 15:43:35 +01:00
`}};function Ine(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 kne(s.shape,c,l,a,o):new wne(s.shape,c,l,a,o);return n.runWebGLProgram(u,[s],s.dtype)}var Sne={kernelName:fd,backendName:"webgl",kernelFunc:Ine},Tne=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],l=i[0]/c[0],u=i[1]/c[1],d=1/l,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float accumulator = 0.0;
2020-12-15 14:15:43 +01:00
2021-10-22 15:06:43 +02:00
const float heightScale = float(${l});
2021-12-06 12:34:50 +01:00
const float widthScale = float(${u});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const float invHeightScale = float(${d});
const float invWidthScale = float(${p});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const int winHeight = int(${h});
const int winWidth = int(${f});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracRow =
float(${i[0]}) *
2021-12-06 12:34:50 +01:00
(float(dyR) / float(${c[0]}));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracCol =
float(${i[1]}) *
2021-12-06 12:34:50 +01:00
(float(dyC) / float(${c[1]}));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int sourceNearestRow = int(min(
float(int(${r}) - 1),
${n} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
int sourceNearestCol = int(min(
float(int(${s}) - 1),
${n} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
setOutput(accumulator);
}
2022-02-07 15:43:35 +01:00
`}};function Cne(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Tne(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Nne={kernelName:yf,backendName:"webgl",kernelFunc:Cne},_ne=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
2022-02-07 15:43:35 +01:00
`;return}let r=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,s=e.map((o,i)=>r(i)).join(","),a=mt(n);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${s}));
}
2022-02-07 15:43:35 +01:00
`}},Ene=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=wn("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=mt(n);n===1?this.userCode=`
2021-09-11 17:11:38 +02:00
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${s}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${i(r.slice())};
if(${s}){
2021-12-06 12:34:50 +01:00
result.g = ${c(r.slice())};
2021-09-11 17:11:38 +02:00
}
if(${a}) {
2021-10-22 15:06:43 +02:00
result.b = ${l(r.slice())};
2021-09-11 17:11:38 +02:00
if(${s}) {
2021-12-06 12:34:50 +01:00
result.a = ${u(r.slice())};
2021-09-11 17:11:38 +02:00
}
}
setOutput(result);
}
2022-02-07 15:43:35 +01:00
`;function i(h){return d(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function l(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function u(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let f=e.map((b,y)=>p(y,h)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function p(h,f){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${f[h]} - 1`:`${f[h]}`}}};function Ane(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=s.shape.length,i=k.parseAxisParam(a,s.shape);if(o===0)return ar({inputs:{x:s},backend:n});let c=J().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ene(s.shape,i):new _ne(s.shape,i);return n.runWebGLProgram(c,[s],s.dtype)}var Dne={kernelName:Qo,backendName:"webgl",kernelFunc:Ane},$ne=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);
}
2022-02-07 15:43:35 +01:00
`}},Fne={kernelName:xu,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,c=new $ne(r.shape,a),[l,u]=_.getImageCenter(o,r.shape[1],r.shape[2]),d=[[l,u,Math.sin(s),Math.cos(s)]];return i.runWebGLProgram(c,[r],r.dtype,d)}},Rne=`
2021-09-11 17:11:38 +02:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
2021-04-01 19:39:54 +02:00
}
}
2022-02-07 15:43:35 +01:00
`,Pne=Ye({opSnippet:Rne}),One={kernelName:ei,backendName:"webgl",kernelFunc:Pne},Mne="return inversesqrt(x);",Lne=Ye({opSnippet:Mne,cpuKernelImpl:u9}),Bne={kernelName:ti,backendName:"webgl",kernelFunc:Lne},k_=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=mt(s.length),c=mt(a.length),l="";n===1?l="i":n===2&&(l="i, j");let u=`getIndices(${l})`,d="";r===1?d="i":r===2&&(d="i, coords[1]");let p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=`
2021-09-11 17:11:38 +02:00
${i} strides = ${i}(${s});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
2021-12-06 12:34:50 +01:00
${c} coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
2021-12-06 12:34:50 +01:00
int index = round(${u});
2021-09-11 17:11:38 +02:00
flattenedIndex += index * ${h};
}
if (flattenedIndex == coords[0]) {
sum += ${p};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
2022-02-07 15:43:35 +01:00
`}};function zne(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=_.calculateShapes(a,s,o),p=[d/l,l];if(d===0)return n.makeTensorInfo(o,s.dtype);let h=me({inputs:{x:s},backend:n,attrs:{shape:[c,i]}}),f=me({inputs:{x:a},backend:n,attrs:{shape:[c,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new k_(c,i,h.shape.length,f.shape.length,u,p),b=n.runWebGLProgram(g,[f,h,m],f.dtype),y=me({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(m),y}var Wne={kernelName:au,backendName:"webgl",kernelFunc:zne},Vne=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let r,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",r="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],c=[];for(let l=0;l<t.length;l++)c.push(`${o[l]}`),l<e&&i.push(`${o[l]}`);r=i.join(),s=c.join()}let a=mt(n);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${a} resRC = getOutputCoords();
float cVal = getC(${r});
if (cVal >= 1.0) {
setOutput(getA(${s}));
} else {
setOutput(getB(${s}));
}
2021-03-26 15:26:02 +01:00
}
2022-02-07 15:43:35 +01:00
`}};function Une(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new Vne(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(o,[r,s,a],Er(s.dtype,a.dtype))}var Gne={kernelName:ou,backendName:"webgl",kernelFunc:Une},Hne=`
2021-09-11 17:11:38 +02:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2021-12-09 20:22:22 +01:00
float scaleAlpha = ${_.SELU_SCALEALPHA};
float scale = ${_.SELU_SCALE};
2021-09-11 17:11:38 +02:00
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2022-02-07 15:43:35 +01:00
`,jne=Ye({opSnippet:Hne}),qne={kernelName:iu,backendName:"webgl",kernelFunc:jne},Kne=Bu+`
2022-01-14 16:04:13 +01:00
return 1.0 / (1.0 + exp(-1.0 * x));
`,Xne=`
vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2022-02-07 15:43:35 +01:00
`,Yne=Ye({opSnippet:Kne,packedOpSnippet:Xne,cpuKernelImpl:l9}),Zne={kernelName:ri,backendName:"webgl",kernelFunc:Yne},Jne=`
2021-09-11 17:11:38 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2022-02-07 15:43:35 +01:00
`,Qne=Ye({opSnippet:Jne}),ere={kernelName:lu,backendName:"webgl",kernelFunc:Qne},tre=Bu+`
2021-09-11 17:11:38 +02:00
return sin(x);
2022-02-07 15:43:35 +01:00
`,nre=Ye({opSnippet:tre}),rre={kernelName:ni,backendName:"webgl",kernelFunc:nre},sre=`
2021-09-11 17:11:38 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2022-02-07 15:43:35 +01:00
`,are=Ye({opSnippet:sre}),ore={kernelName:uu,backendName:"webgl",kernelFunc:are},ire=`
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;
2022-02-07 15:43:35 +01:00
`,cre=Ye({opSnippet:ire}),ure={kernelName:du,backendName:"webgl",kernelFunc:cre},lre=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;k.assert(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((b,y)=>b*y),c=[[0,0]];c.push(...o);for(let b=1+a.length;b<s.shape.length;++b)c.push([0,0]);let l=[],u=x_({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),d=_.getReshaped(u.shape,a,i,!1),p=_.getPermuted(d.length,a.length,!1),h=_.getReshapedPermuted(u.shape,a,i,!1),f=me({inputs:{x:u},backend:n,attrs:{shape:d}}),m=kn({inputs:{x:f},backend:n,attrs:{perm:p}}),g=me({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},dre={kernelName:pu,backendName:"webgl",kernelFunc:lre};function pre(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:
2022-02-07 15:43:35 +01:00
${o.shape}`);let i=n.readSync(r.dataId),c=n.readSync(s.dataId),l=n.readSync(a.dataId),u=n.readSync(o.dataId)[0],[d,p,h,f,m]=p9(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 hre={kernelName:md,backendName:"webgl",kernelFunc:pre};function fre(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]=h9(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(u,r.dtype,l),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var mre={kernelName:fu,backendName:"webgl",kernelFunc:fre};function gre(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
2022-02-07 15:43:35 +01:00
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[l,u]=HN(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(u,r.dtype,l)}var bre={kernelName:gd,backendName:"webgl",kernelFunc:gre};function yre(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
2022-02-07 15:43:35 +01:00
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[l,u]=HN(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(u,r.dtype,l)}var vre={kernelName:bd,backendName:"webgl",kernelFunc:yre};function xre(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:l,strides:u,outputSize:d}=_.calculateShapes(a,s,i),p=!1,h=new k_(l,c,s.shape.length,a.shape.length,u,[d,1],p),f=n.runWebGLProgram(h,[a,s,o],a.dtype),m=me({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var wre={kernelName:xf,backendName:"webgl",kernelFunc:xre};function kre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=k.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=s.shape.length,u=new Array(l).fill(0),d=s.shape.slice();return c.map(p=>{let h=[...d];h[i]=p;let f=zu({inputs:{x:s},backend:n,attrs:{begin:u,size:h}});return u[i]+=p,f})}var Ire={kernelName:hu,backendName:"webgl",kernelFunc:kre},Fk="return sqrt(x);",Sre=Ye({opSnippet:Fk,packedOpSnippet:Fk,cpuKernelImpl:f9}),Tre={kernelName:si,backendName:"webgl",kernelFunc:Sre},Cre="return x * x;",Nre=Ye({opSnippet:Cre}),_re={kernelName:yd,backendName:"webgl",kernelFunc:Nre},Rk="return (a - b) * (a - b);",Ere=un({opSnippet:Rk,packedOpSnippet:Rk}),Are={kernelName:ii,backendName:"webgl",kernelFunc:Ere};function Dre({inputs:e,attrs:t,backend:n}){let{x:r}=e,s=Fr+`
2021-09-11 17:11:38 +02:00
return x > 0.0 ? 1.0 : float(${t.alpha});
2022-02-07 15:43:35 +01:00
`,a=new Cs(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}var $re={kernelName:ya,backendName:"webgl",kernelFunc:Dre},Fre=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let r=n.length,s=mt(n.length),a=mt(n.length),o="";if(r===1)o="coords * strides + begin";else{let i=0;o=n.map((c,l)=>(i++,n.length===1?`coords * strides[${l}] + begin[${l}]`:`coords[${i-1}] * strides[${l}] + begin[${l}]`)).join(",")}this.userCode=`
2021-09-11 17:11:38 +02:00
${s} begin = ${s}(${e});
${s} strides = ${s}(${t});
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${o}));
2021-04-01 19:39:54 +02:00
}
2022-02-07 15:43:35 +01:00
`}};function Rre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=jt.sliceInfo(s.shape,a,o,i,c,l,u,d,p),w;if(m)w=me({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||b){k.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let N=jt.computeOutShape(y,v,x),$=zu({inputs:{x:s},backend:n,attrs:{begin:y,size:N}});w=me({inputs:{x:$},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo($)}else if(n.shouldExecuteOnCPU([s])){let $=n.readSync(s.dataId),D=We(s.shape,s.dtype,$),P=m9(h,D,x,y);w=n.makeTensorInfo(f,s.dtype,P.values)}else{let $=new Fre(y,x,h);w=n.runWebGLProgram($,[s],s.dtype)}let T=me({inputs:{x:w},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(w),T}var Pre={kernelName:mu,backendName:"webgl",kernelFunc:Rre};function Ore(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]=g9(p,h,s,a,o,i,c,l);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var Mre={kernelName:wf,backendName:"webgl",kernelFunc:Ore};function Lre(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]=b9(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 Bre={kernelName:kf,backendName:"webgl",kernelFunc:Lre};function zre(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=y9(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var Wre={kernelName:If,backendName:"webgl",kernelFunc:zre},Vre="return tan(x);",Ure=Ye({opSnippet:Vre}),Gre={kernelName:ui,backendName:"webgl",kernelFunc:Ure},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);
2022-02-07 15:43:35 +01:00
`,jre=Ye({opSnippet:Hre}),qre={kernelName:li,backendName:"webgl",kernelFunc:jre},Kre=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[a]*t[a];this.outputShape=n,this.rank=n.length;let r=mt(this.rank),s=Xre(e);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} resRC = getOutputCoords();
setOutput(getA(${s}));
}
2022-02-07 15:43:35 +01:00
`}};function Xre(e){let t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let s=0;s<e.length;s++)r.push(`imod(${n[s]}, ${e[s]})`);return r.join()}function I_(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if(s.dtype==="string"||s.shape.length>5){let c=n.readSync(s.dataId),l=s.dtype==="string"?c.map(p=>k.decodeString(p)):c,u=We(s.shape,s.dtype,l),d=x9(u,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new Kre(s.shape,a);return n.runWebGLProgram(o,[s],s.dtype)}var Yre={kernelName:ba,backendName:"webgl",kernelFunc:I_},Zre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
int i = isFirstInPair ? elemIdx : elemIdx - inc;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod(elemIdx, 2 * dir) >= dir;
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) { // Elements in opposite order of direction
int iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutput(float(i0));
} else {
setOutput(float(i1));
}
}
2022-01-14 16:04:13 +01:00
`}},Jre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float x0 = getX(batch, i0);
float x1 = i1 < n ? getX(batch, i1) : x0;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput(x0 >= x1 ? float(i0) : float(i1));
}
2022-02-07 15:43:35 +01:00
`}};function Ma(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function Pk(e){let t=1;for(;t<e;)t*=2;return t}function Qre(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 P=n.readSync(s.dataId),[F,R]=w9(P,l,s.dtype,a,o);return[n.makeTensorInfo(F.shape,F.dtype,F.values),n.makeTensorInfo(R.shape,R.dtype,R.values)]}if(a===0)return l[l.length-1]=0,[n.makeTensorInfo(l,s.dtype,[]),n.makeTensorInfo(l,"int32",[])];if(u===1)return[s,ep({attrs:{shape:l,dtype:"int32",value:0},backend:n})];let d=n.texData.get(s.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(s):s,m=k.sizeFromShape(l)/u,g=me({inputs:{x:h},attrs:{shape:[m,u]},backend:n});p&&Ma(n,h);let b=Pk(a),y=Pk(u),v=null,x=()=>v===null?[g,g]:[g,v],w=(P,F,R)=>{let C=x(),L=new Zre(R),j=[[u],[v===null?1:0],[Number.NEGATIVE_INFINITY],[P],[F]],K=v;v=n.runWebGLProgram(L,C,"int32",j),Ma(n,K)};for(let P=1;P<b;P*=2){let F=P*2;for(let R=P;R>=1;R/=2)w(F,R,[m,y])}for(let P=y;P>b;P/=2){let F=x(),R=new Jre([m,P/2]),L=[[u],[v===null?1:0],[b]],G=v;v=n.runWebGLProgram(R,F,"int32",L),Ma(n,G);let j=b/2,K=j*2;for(let q=j;q>=1;q/=2)w(K,q,v.shape)}let T=v;v=zu({inputs:{x:v},backend:n,attrs:{begin:0,size:[m,a]}}),Ma(n,T);let N=f_({inputs:{x:g,indices:v},backend:n,attrs:{axis:1,batchDims:1}});Ma(n,g);let $=l.slice(0,-1);$.push(a),T=v,v=me({inputs:{x:v},attrs:{shape:$},backend:n}),Ma(n,T);let D=N;return N=me({inputs:{x:N},attrs:{shape:$},backend:n}),Ma(n,D),[N,v]}var ese={kernelName:gu,backendName:"webgl",kernelFunc:Qre},tse=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);
}
2022-02-07 15:43:35 +01:00
`}};function nse(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 tse(d,p,o,i,c,g);return n.runWebGLProgram(b,[s,a],"float32")}var rse={kernelName:bu,backendName:"webgl",kernelFunc:nse};function sse(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Ru(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}=k9(o,s,a.shape,a.dtype);return[r.makeTensorInfo(c,a.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}var ase={kernelName:Sf,backendName:"webgl",kernelFunc:sse};function ose(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=zu({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),b=me({inputs:{x:g},backend:n,attrs:{shape:l}});f[m]=b,d.push(g)}return d.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var ise={kernelName:yu,backendName:"webgl",kernelFunc:ose},cse=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,o=a*Math.ceil(s/n);this.outputShape=[r,o];let i="0.0",c="sumValue",l=Math.floor(n/4)*4,u=n%4,d=`
2021-09-11 17:11:38 +02:00
sumValue += dot(values, segFilter);
`,p="";s%n>0&&(p=`
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`);let h="";s%n>0&&(h=`
if (inIdx < 0 || inIdx >= ${s}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${i};
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float getValue(int batch, int inIdx) {
${p}
return getX(batch, inIdx);
2021-03-26 15:26:02 +01:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float getSegmentIdAtIndex(int inIdx) {
${h}
return getSegmentIds(inIdx);
2021-03-31 13:01:22 +02:00
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${a})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${a})));
2021-03-09 23:32:33 +01:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0;
2021-03-09 23:32:33 +01:00
2021-10-22 15:06:43 +02:00
for (int i = 0; i < ${l}; i += 4) {
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2020-12-15 14:15:43 +01:00
}
2020-10-29 05:16:50 +01:00
2021-10-22 15:06:43 +02:00
int inIdx = inOffset + ${l};
2021-12-06 12:34:50 +01:00
if (${u===1}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
${d}
2021-12-06 12:34:50 +01:00
} else if (${u===2}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2021-12-06 12:34:50 +01:00
} else if (${u===3}) {
2021-09-11 17:11:38 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
${d}
}
2021-12-06 12:34:50 +01:00
setOutput(${c});
2021-12-01 21:37:52 +01:00
}
2022-02-07 15:43:35 +01:00
`}};function use(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r,i=s.shape.length,c=[],l=0,u=_.getAxesPermutation([l],i),d=s;u!=null&&(d=kn({inputs:{x:s},backend:n,attrs:{perm:u}}),c.push(d),l=_.getInnerMostAxes(1,i)[0]);let p=_.segment_util.computeOutShape(d.shape,l,o),h=k.sizeFromShape([d.shape[l]]),f=me({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});c.push(f);let m=Cf(s.dtype),g=(x,w,T,N,$)=>{let D=x.shape[0],P=x.shape[1],F=_.segment_util.segOpComputeOptimalWindowSize(P,$),R={windowSize:F,inSize:P,batchSize:D,numSegments:$},C=new cse(R,w),L=n.compileAndRun(C,[x,T],N);if(c.push(L),L.shape[1]===$)return L;let G=w_({backend:n,attrs:{start:0,stop:$,step:1,dtype:"float32"}}),j=I_({inputs:{x:G},backend:n,attrs:{reps:[P/F]}});return c.push(G),c.push(j),g(L,w,j,N,$)},b=g(f,"unsortedSegmentSum",a,m,o),y=me({inputs:{x:b},backend:n,attrs:{shape:p}}),v=y;if(u!=null){c.push(y);let x=_.getUndoAxesPermutation(u);v=kn({inputs:{x:v},backend:n,attrs:{perm:x}})}return c.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var lse={kernelName:vd,backendName:"webgl",kernelFunc:use},dse=[bY,vY,kY,TY,NY,AY,$Y,RY,LY,zY,UY,jY,XY,QY,nZ,sZ,oZ,lZ,pZ,fZ,yZ,TZ,NZ,EZ,PZ,MZ,WZ,J9,GZ,XZ,QZ,aJ,iJ,uJ,dJ,hJ,gJ,vJ,kJ,SJ,CJ,EJ,DJ,PJ,MJ,zJ,UJ,HJ,XJ,QJ,rQ,oQ,uQ,lQ,pQ,fQ,gQ,yQ,xQ,SQ,NQ,AQ,$Q,PQ,LQ,VQ,jQ,Z9,KQ,qZ,ZQ,eee,ree,eY,iee,dee,hee,bee,xee,See,Nee,Dee,Pee,Lee,zee,Gee,jee,Kee,Jee,ete,nte,ste,ote,lte,fte,yte,Cte,aY,Ate,Fte,Ote,Bte,DZ,Vte,Gte,jte,Xte,Qte,nY,tne,nne,$Z,kte,ane,une,hne,iY,bne,xne,Sne,Nne,Dne,Fne,One,Bne,Wne,Gne,qne,Zne,ere,rre,ore,IZ,Ste,ure,dre,hre,mre,bre,vre,wre,Ire,Tre,_re,Are,$re,Pre,Mre,Bre,Wre,Ite,fY,Gre,qre,Yre,ese,rse,mY,ase,ise,lse,Ute];for(let e of dse)xd(e);var Rt;(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"})(Rt||(Rt={}));var td;(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"})(td||(td={}));var S_;function pse(e){S_=e.wasm.cwrap(Za,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function hse(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 $=n.dataIdMap.get(o.dataId);if($.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${$.shape.length}.`);f=$.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=td[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let b=c?s.shape[2]:s.shape[1],y=l?a.shape[1]:a.shape[2],v=wu.assertAndGetBroadcastShape(s.shape.slice(0,-2),a.shape.slice(0,-2)),x=n.makeOutput([...v,b,y],s.dtype),w=n.dataIdMap.get(x.dataId).id,T=new Uint8Array(new Int32Array(s.shape).buffer),N=new Uint8Array(new Int32Array(a.shape).buffer);return S_(p,T,s.shape.length,h,N,a.shape.length,c,l,g,f,m,d||0,w),x}var fse={kernelName:Za,backendName:"wasm",setupFunc:pse,kernelFunc:hse};function ln(e,t){let n;function r(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function s(a){let{backend:o,inputs:{x:i}}=a,c=o.dataIdMap.get(i.dataId).id,l=o.makeOutput(i.shape,t||i.dtype),u=o.dataIdMap.get(l.dataId).id;return k.sizeFromShape(l.shape)===0||n(c,Rt[i.dtype],u),l}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var mse=ln(vc);function Nn(e,t,n){let r;function s(o){r=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:c}=o,{a:l,b:u}=c,d=i.dataIdMap.get(l.dataId).id,p=i.dataIdMap.get(u.dataId).id,h=n!=null?n:l.dtype,f=_.assertAndGetBroadcastShape(l.shape,u.shape),m=i.makeOutput(f,h);if(k.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(l.shape).bu
2021-12-09 20:22:22 +01:00
${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
2022-02-07 15:43:35 +01:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=t.dataIdMap.get(r.dataId).id,i=t.dataIdMap.get(s.dataId).id,c=t.dataIdMap.get(a.dataId).id,l=r.shape[0],u=k.sizeFromShape(a.shape),d=t.makeOutput([l,u],r.dtype),p=t.dataIdMap.get(d.dataId).id,h=t.makeOutput([u],a.dtype),f=t.dataIdMap.get(h.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;mE(o,i,c,l,p,f,g);let b=t.readSync(m.dataId),y;switch(b[0]){case 0:{y=_.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(b[1],b[2]);break}case 1:{y=_.getSparseReshapeNegativeOutputDimErrorMessage(b[1],b[2]);break}case 2:y=_.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let v=Array.from(t.readSync(s.dataId)),x=Array.from(t.readSync(h.dataId));y=_.getSparseReshapeInputOutputMultipleErrorMessage(v,x);break}case 4:{let v=Array.from(t.readSync(s.dataId)),x=Array.from(t.readSync(h.dataId));y=_.getSparseReshapeInputOutputMismatchErrorMessage(v,x);break}default:y=""}if(t.disposeData(m.dataId),y)throw t.disposeData(d.dataId),t.disposeData(h.dataId),new Error(y);return[d,h]}var zie={kernelName:fu,backendName:"wasm",setupFunc:Lie,kernelFunc:Bie},gE;function bE(e){gE=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function yE(e,t){let{backend:n,inputs:r}=e,{data:s,indices:a,segmentIds:o}=r,i=a.shape[0],c=n.readSync(o.dataId,i-1,i)[0],u=i>0?c+1:0;if(u<0)throw new Error(_.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=s.shape.slice();d[0]=u;let p=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=n.dataIdMap.get(o.dataId).id,m=n.makeOutput(d,s.dtype),g=n.dataIdMap.get(m.dataId).id,b=n.makeOutput([4],"int32"),y=n.dataIdMap.get(b.dataId).id;gE(p,Rt[s.dtype],s.shape[0],h,f,g,y,t,0);let v=n.readSync(b.dataId),x;switch(v[0]){case 0:{x=_.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=_.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=_.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(v[1],v[2]);break;case 3:x=_.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(v[1],v[2],v[3]);break;default:x=""}if(n.disposeData(b.dataId),x)throw n.disposeData(m.dataId),new Error(x);return m}function Wie(e){return yE(e,!0)}var Vie={kernelName:gd,backendName:"wasm",setupFunc:bE,kernelFunc:Wie};function Uie(e){return yE(e,!1)}var Gie={kernelName:bd,backendName:"wasm",setupFunc:bE,kernelFunc:Uie};function Hie(e){let{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=n,i=k.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),l=new Array(s.shape.length).fill(0),u=s.shape.slice();return c.map(d=>{let p=[...u];p[i]=d;let h=ho({inputs:{x:s},attrs:{begin:l,size:p},backend:r});return l[i]+=d,h})}var jie={kernelName:hu,backendName:"wasm",kernelFunc:Hie},qie=ln(si),Kie=ln(yd),Xie=!0,Yie=Nn(ii,Xie),vE;function Zie(e){vE=e.wasm.cwrap(ya,null,["number","number","number","number"])}function Jie(e){let{backend:t,inputs:n,attrs:r}=e,{alpha:s}=r,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),c=t.dataIdMap.get(i.dataId).id;return vE(o,s,Rt[a.dtype],c),i}var Qie={kernelName:ya,backendName:"wasm",setupFunc:Zie,kernelFunc:Jie},xE;function ece(e){xE=e.wasm.cwrap(mu,null,["number","array","number","array","array","array","array","array","number","number"])}function tce(e){let{backend:t,inputs:n,attrs:r}=e,{x:s}=n,{begin:a,end:o,strides:i,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:y,end:v,strides:x}=jt.sliceInfo(s.shape,a,o,i,c,l,u,d,p),w;if(m)w=Bn({inputs:{x:s},backend:t,attrs:{shape:f}});else if(g||b){k.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let T=jt.computeOutShape(y,v,x),N=ho({inputs:{x:s},backend:t,attrs:{begin:y,size:T}});w=Bn({inputs:{x:N},backend:t,attrs:{shape:f}}),t.disposeData(N.dataId)}else{let T=t.makeOutput(h,"float32"),N=t.dataIdMap.get(
2021-12-01 21:37:52 +01:00
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
2022-01-14 16:04:13 +01:00
* 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 2022 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,
2021-12-01 21:37:52 +01:00
* 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. */