face-api/dist/face-api.js

4820 lines
1.2 MiB
JavaScript
Raw Normal View History

2021-09-08 19:51:28 +02:00
/*
Face-API
homepage: <https://github.com/vladmandic/face-api>
author: <https://github.com/vladmandic>'
2021-09-08 19:51:28 +02:00
*/
2021-09-29 15:32:30 +02:00
var faceapi=(()=>{var q0=Object.defineProperty;var WA=e=>q0(e,"__esModule",{value:!0});var Zr=(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 Ep=(e,t)=>{WA(e);for(var n in t)q0(e,n,{get:t[n],enumerable:!0})};var Wce={};Ep(Wce,{AgeGenderNet:()=>Um,BoundingBox:()=>Bu,Box:()=>ut,ComposableTask:()=>Dr,ComputeAllFaceDescriptorsTask:()=>Ea,ComputeFaceDescriptorsTaskBase:()=>Zm,ComputeSingleFaceDescriptorTask:()=>Aa,DetectAllFaceLandmarksTask:()=>Qm,DetectAllFacesTask:()=>op,DetectFaceLandmarksTaskBase:()=>Jm,DetectFacesTaskBase:()=>tg,DetectSingleFaceLandmarksTask:()=>eg,DetectSingleFaceTask:()=>ng,Dimensions:()=>Nn,FACE_EXPRESSION_LABELS:()=>x0,FaceDetection:()=>vt,FaceDetectionNet:()=>PE,FaceExpressionNet:()=>Wm,FaceExpressions:()=>_a,FaceLandmark68Net:()=>Ku,FaceLandmark68TinyNet:()=>Gm,FaceLandmarkNet:()=>IE,FaceLandmarks:()=>yr,FaceLandmarks5:()=>cE,FaceLandmarks68:()=>Wu,FaceMatch:()=>Xd,FaceMatcher:()=>sg,FaceRecognitionNet:()=>Xu,Gender:()=>Ws,LabeledBox:()=>Yd,LabeledFaceDescriptors:()=>Ls,NetInput:()=>Bs,NeuralNetwork:()=>ln,ObjectDetection:()=>Ta,Point:()=>Oe,PredictedBox:()=>uE,Rect:()=>zu,SsdMobilenetv1:()=>Ei,SsdMobilenetv1Options:()=>Ar,TinyFaceDetector:()=>el,TinyFaceDetectorOptions:()=>Ym,TinyYolov2:()=>Ju,TinyYolov2Options:()=>gs,allFaces:()=>Mce,allFacesSsdMobilenetv1:()=>YE,allFacesTinyYolov2:()=>Oce,awaitMediaLoaded:()=>f0,bufferToImage:()=>m0,computeFaceDescriptor:()=>kce,createCanvas:()=>Ci,createCanvasFromMedia:()=>Qd,createFaceDetectionNet:()=>mce,createFaceRecognitionNet:()=>sce,createSsdMobilenetv1:()=>RE,createTinyFaceDetector:()=>Lce,createTinyYolov2:()=>yce,detectAllFaces:()=>rg,detectFaceLandmarks:()=>KE,detectFaceLandmarksTiny:()=>wce,detectLandmarks:()=>Rce,detectSingleFace:()=>Pce,draw:()=>S0,env:()=>Je,euclideanDistance:()=>R0,extendWithAge:()=>qm,extendWithFaceDescriptor:()=>jm,extendWithFaceDetection:()=>ki,extendWithFaceExpressions:()=>Vm,extendWithFaceLandmarks:()=>qu,extendWithGender:()=>Km,extractFaceTensors:()=>Uu,extractFaces:()=>Vu,fetchImage:()=>Hie,fetchJson:()=>y0,fetchNetWeights:()=>jie,fetchOrThrow:()=>zs,fetchVideo:()=>qie,getContext2dOrThrow:()=>Wn,getMediaDimensions:()=>Si,imageTensorToCanvas:()=>g0,imageToSquare:()=>b0,inverseSigmoid:()=>Lie,iou:()=>r0,isMediaElement:()=>$m,isMediaLoaded:()=>Jd,isWithAge:()=>ace,isWithFaceDetection:()=>fs,isWithFaceExpressions:()=>w0,isWithFaceLandmarks:()=>Ni,isWithGender:()=>oce,loadAgeGenderModel:()=>Dce,loadFaceDetectionModel:()=>$ce,loadFaceExpressionModel:()=>Ace,loadFaceLandmarkModel:()=>Nce,loadFaceLandmarkTinyModel:()=>_ce,loadFaceRecognitionModel:()=>Ece,loadSsdMobilenetv1Model:()=>XE,loadTinyFaceDetectorModel:()=>Cce,loadTinyYolov2Model:()=>Tce,loadWeightMap:()=>v0,locateFaces:()=>Fce,matchDimensions:()=>Kie,minBbox:()=>s0,nets:()=>Qe,nonMaxSuppression:()=>a0,normalize:()=>qr,padToSquare:()=>o0,predictAgeAndGender:()=>Sce,recognizeFaceExpressions:()=>Ice,resizeResults:()=>ZE,resolveInput:()=>Ii,shuffleArray:()=>Mie,sigmoid:()=>Kd,ssdMobilenetv1:()=>qE,tf:()=>Jw,tinyFaceDetector:()=>vce,tinyYolov2:()=>xce,toNetInput:()=>mt,utils:()=>n0,validateConfig:()=>A0,version:()=>zce});var Jw={};Ep(Jw,{Abs:()=>Xi,Acos:()=>Yi,Acosh:()=>Zi,AdadeltaOptimizer:()=>lf,AdagradOptimizer:()=>df,AdamOptimizer:()=>pf,AdamaxOptimizer:()=>hf,Add:()=>Js,AddN:()=>La,All:()=>Ji,Any:()=>Qi,ArgMax:()=>Ba,ArgMin:()=>xl,Asin:()=>ec,Asinh:()=>tc,Atan:()=>nc,Atan2:()=>sc,Atanh:()=>rc,AvgPool:()=>za,AvgPool3D:()=>wl,AvgPool3DGrad:()=>Mp,AvgPoolGrad:()=>Op,BackendWasm:()=>oE,BatchMatMul:()=>Wa,BatchToSpaceND:()=>ac,Bincount:()=>Lp,BroadcastArgs:()=>Mb,BroadcastTo:()=>p1,Callback:()=>tC,CallbackList:()=>qI,Cast:()=>Va,Ceil:()=>Ua,ClipByValue:()=>Qs,Complex:()=>Bp,ComplexAbs:()=>kl,Concat:()=>oc,Conv2D:()=>Ga,Conv2DBackpropFilter:()=>zp,Conv2DBackpropInput:()=>Ha,Conv3D:()=>Il,Conv3DBackpropFilterV2:()=>Wp,Conv3DBackpropInputV2:()=>
2021-09-11 17:11:38 +02:00
`)),c.join(`
2021-09-29 15:32:30 +02:00
`)}function t$(e,t,n,r){let s=$t(t),a=r[r.length-1],o=new Array(a).fill(0),i=t.length,c=n==="complex64"?Wl(e):e;if(i>1)for(let u=0;u<s/a;u++){let l=u*a;for(let d=0;d<a;d++)o[d]=Math.max(o[d],zl(c[l+d],0,n).length)}return o}function zl(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(Wb))} + ${parseFloat(e[1].toFixed(Wb))}j`:Ys(e)?r=`'${e}'`:n==="bool"?r=x1(e):r=parseFloat(e.toFixed(Wb)).toString(),vl(r,t)}function x1(e){return e===0?"false":"true"}function Sh(e,t,n,r,s,a=!0){let o=n==="complex64"?2:1,i=t[0],c=t.length;if(c===0){if(n==="complex64"){let m=Wl(e);return[zl(m[0],0,n)]}return n==="bool"?[x1(e[0])]:[e[0].toString()]}if(c===1){if(i>v1){let g=Bl*o,b=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-Bl)*o,i*o));return n==="complex64"&&(b=Wl(b),y=Wl(y)),["["+b.map((v,x)=>zl(v,s[x],n)).join(", ")+", ..., "+y.map((v,x)=>zl(v,s[i-Bl+x],n)).join(", ")+"]"]}let m=n==="complex64"?Wl(e):Array.from(e);return["["+m.map((g,b)=>zl(g,s[b],n)).join(", ")+"]"]}let u=t.slice(1),l=r.slice(1),d=r[0]*o,p=[];if(i>v1){for(let m=0;m<Bl;m++){let g=m*d,b=g+d;p.push(...Sh(e.slice(g,b),u,n,l,s,!1))}p.push("...");for(let m=i-Bl;m<i;m++){let g=m*d,b=g+d;p.push(...Sh(e.slice(g,b),u,n,l,s,m===i-1))}}else for(let m=0;m<i;m++){let g=m*d,b=g+d;p.push(...Sh(e.slice(g,b),u,n,l,s,m===i-1))}let h=c===2?",":"";p[0]="["+p[0]+h;for(let m=1;m<p.length-1;m++)p[m]=" "+p[m]+h;let f=`,
2021-09-11 17:11:38 +02:00
`;for(let m=2;m<c;m++)f+=`
2021-09-29 15:32:30 +02:00
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function Wl(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var Wt=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=$t(e),n!=null){let r=n.length;F(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||n1(t,this.size),this.strides=qi(e)}set(e,...t){t.length===0&&(t=[0]),F(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let 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 Qr().makeTensor(this.values,this.shape,this.dtype)}},Qr=null,Zc=null,n$=null;function r$(e){Qr=e}function s$(e){Zc=e}function a$(e){n$=e}var Ee=class{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=$t(e),this.strides=qi(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Zc.buffer(this.shape,this.dtype,e)}bufferSync(){return Zc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Ki(this.shape,e,this.dtype==="complex64")}arraySync(){return Ki(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Qr().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>Ih(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=Qr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ih(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 Qr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Qr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Zc.print(this,e)}clone(){return this.throwIfDisposed(),Zc.clone(this)}toString(e=!1){let t=this.dataSync();return e$(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Zc.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Qr().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 Ob("Tensor",()=>Ee)}ee();var ra=class extends Ee{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ks(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Qr().disposeTensor(this),this.dataId=e.dataId,Qr().incRef(this,null)}dispose(){Qr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(ra,Symbol.hasInstance,{value:e=>e instanceof Ee&&e.as
Manifest JSON has weights with names: ${i.join(", ")}.`)}let c=s.reduce((h,f,m)=>(f&&h.push(m),h),[]),u=[];c.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;u.push(m)})});let l=await e(u),d={},p=0;return c.forEach(h=>{let f=t[h].paths.length,m=0;for(let x=0;x<f;x++)m+=l[p+x].byteLength;let g=new ArrayBuffer(m),b=new Uint8Array(g),y=0;for(let x=0;x<f;x++){let k=new Uint8Array(l[p+x]);b.set(k,y),y+=k.byteLength}a[h].forEach(x=>{let k=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),C=E1(k,[x.manifestEntry]);for(let N in C)d[N]=C[N]}),p+=f}),d}}var tF="application/octet-stream",nF="application/json",ry=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(F(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=Q().platform.fetch,F(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&F(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=$1(e,n);t.body.append("model.json",new Blob([JSON.stringify(r)],{type:nF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:tF}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Hl(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(s){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,r=t.weightsManifest;if(n==null&&r==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Jb(t,s=>this.loadWeights(s))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=rF(t),s=this.weightPathPrefix||n,a=[];for(let u of e)a.push(...u.weights);let o=[],i=[];for(let u of e)for(let l of u.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(l)):o.push(s+l+r);this.weightUrlConverter&&o.push(...await Promise.all(i));let c=await U1(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Zb(c)]}};ry.URL_SCHEME_REGEX=/^https?:\/\//;function rF(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}function sy(e){return e.match(ry.URL_SCHEME_REGEX)!=null}var H1=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>sy(r)):n=sy(e),n)return ay(e,t)}return null};Dt.registerSaveRouter(H1);Dt.registerLoadRouter(H1);function ay(e,t){return new ry(e,t)}function sF(e,t){return ay(e,t)}var oy=class{
2021-09-11 17:11:38 +02:00
Actual: ${s}.
Expected: ${a}.`);for(let o=0;o<a.length;++o){let i=s[o],c=a[o];if(!n(i,c))throw new Error(`Arrays differ: actual[${o}] = ${i}, expected[${o}] = ${c}.
Actual: ${s}.
2021-09-29 15:32:30 +02:00
Expected: ${a}.`)}}function TF(e,t){e().then(()=>t.fail(),()=>t())}function NF(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ys(e)||Ys(e[0])||Ys(t)||Ys(t[0])?py(e,n,(r,s)=>r==s):py(e,t,(r,s)=>hy(r,s,0))}function _F(e,t,n){if(n==null&&(n=dy()),!hy(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function hy(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function EF(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 AF(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function lk(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?lk(n):e[t]=Ll(n)}return e}var DF="3.9.0";function $F(){Q().set("PROD",!0)}function FF(){Q().set("DEBUG",!0)}function RF(){Q().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function fy(e){Q().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}a$(fy);function PF(){B.disposeVariables()}function Cs(){return B}function Ah(){return B.memory()}function OF(e){return B.profile(e)}function M(e,t){return B.tidy(e,t)}function $e(e){qb(e).forEach(n=>n.dispose())}function Yt(e){return B.keep(e)}function MF(e){return B.time(e)}function LF(e){return B.setBackend(e)}function BF(){return B.ready()}function zF(){return B.backendName}function WF(e){B.removeBackend(e)}function VF(e){return B.findBackend(e)}function UF(e){return B.findBackendFactory(e)}function Dh(e,t,n=1){return B.registerBackend(e,t,n)}function dk(){return B.backend}function GF(e,t){Q().setPlatform(e,t)}function HF(e,t){let n=E(e,"a","add"),r=E(t,"b","add");[n,r]=Nt(n,r);let s={a:n,b:r};return B.runKernel(Js,s)}var Y=W({add_:HF});function jF(e,t){let n=E(e,"a","floorDiv"),r=E(t,"b","floorDiv");[n,r]=Nt(n,r);let s={a:n,b:r};return B.runKernel(eo,s)}var $h=W({floorDiv_:jF});function qF(e,t){let n=E(e,"a","div"),r=E(t,"b","div");if([n,r]=Nt(n,r),n.dtype==="int32"&&r.dtype==="int32")return $h(n,r);let s={a:n,b:r},a={};return B.runKernel(Ya,s,a)}var ge=W({div_:qF});function KF(e,t){let n=E(e,"a","mul"),r=E(t,"b","mul");[n,r]=Nt(n,r);let s={a:n,b:r};return B.runKernel(fo,s)}var V=W({mul_:KF});function XF(e){let t=E(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return B.runKernel(kl,n)}else{let n={x:t};return B.runKernel(Xi,n)}}var Mt=W({abs_:XF});function YF(e){let n={x:E(e,"x","acos")};return B.runKernel(Yi,n)}var my=W({acos_:YF});function ZF(e){let n={x:E(e,"x","acosh")};return B.runKernel(Zi,n)}var gy=W({acosh_:ZF});function JF(e){F(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),F(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((s,a)=>E(s,`tensors${a}`,"addN")),n=t[0];t.forEach(s=>{if(s.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(s=>{if(!ks(s.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=t;return B.runKernel(La,r)}var pk=W({addN_:JF});function QF(e,t=null,n=!1){let s={x:E(e,"x","all","bool")},a={axis:t,keepDims:n};return B.runKernel(Ji,s,a)}var Fh=W({all_:QF});function eR(e,t=null,n=!1){let s={x:E(e,"x","any","bool")},a={axis:t,keepDims:n};return B.runKernel(Qi,s,a)}var jl=W({any_:eR});function tR(e,t=0){let r={x:E(e,"x","argMax")},s={axis:t};return B.runKernel(Ba,r,s)}var Ho=W({argMax_:tR});function nR(e,t=0){let r={x:E(e,"x","argMin")},s={axis:t};return B.runKernel(xl,r,s)}var by=W({argMin_:nR});function rR(e){let n={x:E(e,"x","asin")};return B.runKernel(ec,n)}var yy=W({asin_:rR});function sR(e){let n={x:E(e,"x","asinh")};return B.runKernel(tc,n)}var vy=W({asinh_:sR});function aR(e){let n={x:E(e,"x","atan")};return B.runKernel(nc,n)}var xy=W({atan_:aR});function oR(e,t){let n=E(e,"a","atan2"),r=E(t,"b","atan2");[n,r]=Nt(n,r);let s={a:n,b:r};return B.runKernel(sc,s)}var wy=W({atan2_:oR});function iR(e){let n={x:E(
with dtype ${a.dtype}. `)}),n.length===1)return Ss(n[0]);let r=n,s={axis:t};return B.runKernel(oc,r,s)}var Ze=W({concat_:bR});function yR(e){let n={x:E(e,"x","sigmoid")};return B.runKernel(To,n)}var lr=W({sigmoid_:yR});function vR(e,t,n){let r=E(e,"x","slice","string_or_numeric");if(r.rank===0)throw new Error("Slicing scalar is not possible");let s={x:r},a={begin:t,size:n};return B.runKernel(Lc,s,a)}var We=W({slice_:vR});function xR(e){let n={x:E(e,"x","tanh")};return B.runKernel(Fo,n)}var qo=W({tanh_:xR});function wR(e,t,n,r,s,a){let o=E(e,"forgetBias","basicLSTMCell"),i=E(t,"lstmKernel","basicLSTMCell"),c=E(n,"lstmBias","basicLSTMCell"),u=E(r,"data","basicLSTMCell"),l=E(s,"c","basicLSTMCell"),d=E(a,"h","basicLSTMCell"),p=Ze([u,d],1),h=De(p,i),f=Y(h,c),m=f.shape[0],g=f.shape[1]/4,b=[m,g],y=We(f,[0,0],b),v=We(f,[0,g],b),x=We(f,[0,g*2],b),k=We(f,[0,g*3],b),C=Y(V(lr(y),qo(v)),V(l,lr(Y(o,x)))),N=V(qo(C),lr(k));return[C,N]}var kR=W({basicLSTMCell_:wR});function IR(e,t,n){let r=E(e,"x","batchToSpaceND"),s=t.reduce((i,c)=>i*c);F(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),F(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),F(r.shape[0]%s==0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`);let a={x:r},o={blockShape:t,crops:n};return B.runKernel(ac,a,o)}var Kl=W({batchToSpaceND_:IR});function SR(e){let t;return e.rank===0||e.rank===1?t=U(e,[1,1,1,e.size]):e.rank===2?t=U(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function CR(e,t,n,r,s,a){a==null&&(a=.001);let o=E(e,"x","batchNorm"),i=E(t,"mean","batchNorm"),c=E(n,"variance","batchNorm"),u;s!=null&&(u=E(s,"scale","batchNorm"));let l;r!=null&&(l=E(r,"offset","batchNorm")),F(i.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),F(l==null||i.rank===l.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),F(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:SR(o),scale:u,offset:l,mean:i,variance:c},h={varianceEpsilon:a},f=B.runKernel(to,p,h);return U(f,o.shape)}var Ts=W({batchNorm_:CR});function TR(e,t,n,r,s,a){let o=E(e,"x","batchNorm"),i=E(t,"mean","batchNorm"),c=E(n,"variance","batchNorm"),u;s!=null&&(u=E(s,"scale","batchNorm"));let l;return r!=null&&(l=E(r,"offset","batchNorm")),F(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),F(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),F(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&F(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),l!=null&&F(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${l.rank}.`),Ts(o,i,c,l,u,a)}var gk=W({batchNorm2d_:TR});function NR(e,t,n,r,s,a){let o=E(e,"x","batchNorm"),i=E(t,"mean","batchNorm"),c=E(n,"variance","batchNorm"),u;s!=null&&(u=E(s,"scale","batchNorm"));let l;return r!=null&&(l=E(r,"offset","batchNorm")),F(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),F(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),F(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&F(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),l!=null&&F(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${l.rank}.`),Ts(o,i,c,l,u,a)}var bk=W({batchNorm3d_:NR});function _R(e,t,n,r,s,a){let o=E(e,"x","batchNorm"),i=E(t,"mean","batchNorm"),c=E(n,"variance","batchNorm"),u;s!=null&&(u=E(s,"scale","batchNorm"));let l;return r!=nul
2021-09-11 17:11:38 +02:00
${s} and ${t} for depthToSpace with input shape
2021-09-16 14:30:50 +02:00
${r.shape}`),F(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
2021-09-11 17:11:38 +02:00
${a} and ${t} for depthToSpace with input shape
2021-09-29 15:32:30 +02:00
${r.shape}`),F(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`);let i={x:r},c={blockSize:t,dataFormat:n};return B.runKernel(cc,i,c)}var Ay=W({depthToSpace_:XR});function YR(e,t,n,r,s="NHWC",a=[1,1],o){let i=E(e,"x","depthwiseConv2d"),c=E(t,"filter","depthwiseConv2d"),u=i,l=!1;i.rank===3&&(l=!0,u=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),F(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),F(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`),F(u.shape[3]===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),o!=null&&F(qt(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:u,filter:c},p={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},h=B.runKernel(Xa,d,p);return l?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var ua=W({depthwiseConv2d_:YR});function ZR(e){let n={x:E(e,"x","diag")};return B.runKernel(jp,n)}var JR=W({diag_:ZR});function QR(e,t,n,r,s=[1,1],a="NHWC"){let o=E(e,"x","dilation2d"),i=E(t,"filter","dilation2d");F(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),F(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),F(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let c=o,u=!1;o.rank===3&&(c=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),u=!0);let l={x:c,filter:i},d={strides:n,pad:r,dilations:s},p=B.runKernel(Sl,l,d);return u?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Dy=W({dilation2d_:QR});function eP(e,t){let n=e.length,r=[];for(let s=0;s<n;s++){let a=n-1-s,o=e[a]||1;(t[t.length-1-s]||1)>1&&o===1&&r.unshift(a)}return r}function Vt(e,t){let n=[];for(let r=0;r<t.length;r++){let s=e[e.length-r-1],a=t.length-r-1,o=t[a];(s==null||s===1&&o>1)&&n.unshift(a)}return n}function gt(e,t){let n=[],r=Math.max(e.length,t.length);for(let s=0;s<r;s++){let a=e[e.length-s-1];a==null&&(a=1);let o=t[t.length-s-1];if(o==null&&(o=1),a===1)n.unshift(o);else if(o===1)n.unshift(a);else if(a!==o){let i=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(i)}else n.unshift(a)}return n}function tP(e,t){let n=E(e,"a","equal","string_or_numeric"),r=E(t,"b","equal","string_or_numeric");[n,r]=Nt(n,r),gt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(lc,s)}var qn=W({equal_:tP});function nP(e,t,n){let r=E(t,"a","where"),s=E(n,"b","where"),a=E(e,"condition","where","bool"),o=gt(gt(a.shape,r.shape),s.shape),i=su(a,o),c=su(r,o),u=su(s,o),l={condition:i,t:c,e:u};return B.runKernel(Oc,l)}var pn=W({where_:nP});function rP(e){let n={x:E(e,"x","zerosLike")};return B.runKernel(Kc,n)}var Ge=W({zerosLike_:rP});function sP(e,t){let n=E(e,"a","div"),r=E(t,"b","div");[n,r]=Nt(n,r);let s=ge(n,r),a=Ge(s),o=qn(r,a);return pn(o,a,s)}var $y=W({divNoNan_:sP});function aP(e,t){let n=E(e,"t1","dot"),r=E(t,"t2","dot");F((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(F(s===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`),n.rank===1&&r.rank===1){let o=U(n,[1,-1]),i=U(r,[-1,1]),c=De(o,i);return U(c,[])}else if(n.rank===1&&r.rank===2){let o=U(n,[1,-1]),i=U(r,[r.shape[0],r.shape[1]]),c=De(o,i);return U(c,[c.size])}else if(n.rank===2&&r.rank===1){let o=U(r,[-1,1]),i=De(n,o);return U(i,[i.size])}else{let o=U(r,[r.shape[0],r.shape[1]]);return De(n,o)}}var Nk=W({dot_:aP});function oP(e,...t){let n=t.map((s,a)=>E(s,`tensors${a}`,"einsum")),r={equation:e};return B.runKernel(Xp,n,r)}var _k=W({einsum_:oP});function iP(e){let n={x:E(e,"x","elu")};return B.runKernel(Za,n)}var au=W({elu_:iP});function cP(e){let t=E(e,"x","erf");F(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be
rank ${a.rank}.`),F(qt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=U(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let c={x:o},u={depthRadius:t,bias:n,alpha:r,beta:s},l=B.runKernel(_l,c,u);return i?U(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var My=W({localResponseNormalization_:CP});function TP(e){let n={x:E(e,"x","log")};return B.runKernel(ao,n)}var Kn=W({log_:TP});function NP(e){let n={x:E(e,"x","log1p")};return B.runKernel(kc,n)}var Zl=W({log1p_:NP});function _P(e){return F(Zs(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let r=E(t,"x","tf.grad","string_or_numeric"),s=n!=null?E(n,"dy","tf.grad"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(r),[r],s);return s!=null&&bn(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Wh(o),o[0]})}}function EP(e){return F(Zs(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{F(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let r=Gl(t,"args","tf.grads","string_or_numeric"),s=n!=null?E(n,"dy","tf.grads"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(...r),r,s);return s!=null&&bn(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Wh(o),o})}}function AP(e){return F(Zs(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{F(t instanceof Ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),F(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:r,value:s}=B.gradients(()=>e(t),[t],n);return Wh(r),{grad:r[0],value:s}}}function DP(e){return F(Zs(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{F(Array.isArray(t)&&t.every(s=>s instanceof Ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),F(n==null||n instanceof Ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let r=B.gradients(()=>e(...t),t,n);return n!=null&&bn(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Wh(r.grads),r}}function $k(e,t){F(Zs(e),()=>"The f passed in variableGrads(f) must be a function"),F(t==null||Array.isArray(t)&&t.every(u=>u instanceof ra),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in B.registeredVariables)t.push(B.registeredVariables[u])}let r=n?t.filter(u=>!u.trainable):null,s=t.length;t=t.filter(u=>u.trainable),F(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);let a=!0,{value:o,grads:i}=B.gradients(e,t,null,a);F(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),F(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let c={};return t.forEach((u,l)=>{i[l]!=null&&(c[u.name]=i[l])}),r!=null&&r.forEach(u=>c[u.name]=null),{value:o,grads:c}}function ns(e){return B.customGrad(e)}function Wh(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 $P(e){let n={x:E(e,"x","neg")};return B.runKernel(Cc,n)}var kt=W({neg_:$P});function FP(e){let n={x:E(e,"x","softplus")};return B.runKernel(Wc,n)}var Xo=W({softplus_:FP});function RP(e){let t=E(e,"x","logSigmoid");return ns(r=>({value:kt(Xo(kt(r))),gradFunc:o=>V(o,lr(kt(r)))}))(t)}var Fk=W({logSigmoid_:RP});function PP(e,t=null,n=!1){let s={x:E(e,"x","max")},a={reductionIndices:t,keepDims:n};return B.runKernel(oo,s,a)}var Ir=W({max_:PP});function OP(e,t){let n=E(e,"a","sub"),r=E(t,"b","sub");[n,r]=Nt(n,r);let s={a:n,b:r};return B.runKernel(Do,s)}var fe=W({sub_:OP});function MP(e,t=null,n=!1){let r=E(e,"x","sum");r.dtype==="bool"&&(r=ce(r,"int32"));let s={x:r},a={axis:t,keepDims:n};return B.runKernel(_o,s,a)}var ve=W({sum_:MP});function LP(e,t=-1){let n=E(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return ns((s,a)=>{let o=!0,i=Ir(s,t,!0),c=fe(s,i),u=fe(ce(c,"float32"),Kn(ve(hn(c),t,o)));return a([u]),{value:u,gradFunc:(d,p)=>{let[h]=p,f=!0,m=hn(h);return fe(d,V(ve(d,t,f),m))}}})(n)}var Vh=W({logSoftmax_:LP});function Ly(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Rk(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 Pk(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 Yo(e,t){let n=t.map(r=>1);return Rk(e,n,t)}function BP(e,t,n){F(Ly(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Ok(e,t){if(Ly(e,t))return null;let n=[];for(let r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);return e.forEach(r=>n.push(r)),n}function By(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function zP(e,t){let n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function WP(e,t=null,n=!1){let r=E(e,"x","logSumExp"),s=wr(t,r.shape),a=Ir(r,s,!0),o=fe(r,a),i=hn(o),c=ve(i,s),u=Kn(c),l=Y(U(a,u.shape),u);if(n){let d=Yo(l.shape,s);return U(l,d)}return l}var zy=W({logSumExp_:WP});function VP(e,t){let n=E(e,"a","logicalAnd","bool"),r=E(t,"b","logicalAnd","bool");gt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(Ic,s)}var Sr=W({logicalAnd_:VP});function UP(e){let n={x:E(e,"x","logicalNot","bool")};return B.runKernel(Tl,n)}var Jl=W({logicalNot_:UP});function GP(e,t){let n=E(e,"a","logicalOr","bool"),r=E(t,"b","logicalOr","bool");gt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(Nl,s)}var Uh=W({logicalOr_:GP});function HP(e,t){let n=E(e,"a","logicalXor","bool"),r=E(t,"b","logicalXor","bool");return gt(n.shape,r.shape),Sr(Uh(e,t),Jl(Sr(e,t)))}var Mk=W({logicalXor_:HP});function jP(e,t,n,r,s){let a=E(e,"x","maxPool"),o=1,i=a,c=!1;a.rank===3&&(c=!0,i=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),F(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),F(ts(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),s!=null&&F(qt(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s},d=B.runKernel(co,u,l);return c?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Rt=W({maxPool_:jP});function qP(e,t=[1,1,1],n,r,s,a="NDHWC"){let o=E(e,"x","maxPool3d"),i=o,c=!1;o.rank===4&&(c=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),F(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),F(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),s!=null&&F(qt(r),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let u={x:i},l={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},d=B.runKernel(El,u,l);return c?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Wy=W({maxPool3d_:qP});function KP(e,
2021-09-16 14:30:50 +02:00
${s.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let c={indices:s,values:a,denseShape:o,defaultValue:i},u=B.runKernel(uh,c);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var oL=W({sparseFillEmptyRows_:aL});function iL(e,t,n){let r=E(e,"inputIndices","sparseReshape"),s=E(t,"inputShape","sparseReshape"),a=E(n,"newShape","sparseReshape");if(r.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
${r.shape}`);if(s.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:r,inputShape:s,newShape:a},i=B.runKernel(lh,o);return{outputIndices:i[0],outputShape:i[1]}}var cL=W({sparseReshape_:iL});function uL(e,t,n){let r=E(e,"data","sparseSegmentMean"),s=E(t,"indices","sparseSegmentMean"),a=E(n,"segmentIds","sparseSegmentMean");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
2021-09-16 14:30:50 +02:00
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return B.runKernel(dh,o)}var lL=W({sparseSegmentMean_:uL});function dL(e,t,n){let r=E(e,"data","sparseSegmentSum"),s=E(t,"indices","sparseSegmentSum"),a=E(n,"segmentIds","sparseSegmentSum");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
2021-09-29 15:32:30 +02:00
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return B.runKernel(ph,o)}var pL=W({sparseSegmentSum_:dL});function hL(e,t,n,r,s,a,o,i){let c=E(e,"data","stringNGrams","string");if(c.dtype!=="string")throw new Error("Data must be of datatype string");if(c.shape.length!==1)throw new Error(`Data must be a vector, saw: ${c.shape}`);let u=E(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let l={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:c,dataSplits:u},p=B.runKernel(fh,d,l);return{nGrams:p[0],nGramsSplits:p[1]}}var fL=W({stringNGrams_:hL});function mL(e,t,n=!0){let r=E(e,"input","stringSplit","string"),s=E(t,"delimiter","stringSplit","string");if(r.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(s.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);let a={skipEmpty:n},o={input:r,delimiter:s},i=B.runKernel(mh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var gL=W({stringSplit_:mL});function bL(e,t){let n=E(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let s={input:n};return B.runKernel(gh,s,r)}var yL=W({stringToHashBucketFast_:bL}),vL={fft:sd,ifft:du,rfft:ad,irfft:Qh},xL={hammingWindow:YO,hannWindow:Jk,frame:Qk,stft:eM},Jn={flipLeftRight:sM,grayscaleToRGB:oM,resizeNearestNeighbor:aI,resizeBilinear:sI,rotateWithOffset:cM,cropAndResize:nM,nonMaxSuppression:lM,nonMaxSuppressionAsync:yM,nonMaxSuppressionWithScore:xM,nonMaxSuppressionWithScoreAsync:kM,nonMaxSuppressionPadded:SM,nonMaxSuppressionPaddedAsync:TM,threshold:DM,transform:FM},iI={bandPart:PM,gramSchmidt:MM,qr:BM},wL={absoluteDifference:VM,computeWeightedLoss:_s,cosineDistance:GM,hingeLoss:jM,huberLoss:KM,logLoss:YM,meanSquaredError:JM,sigmoidCrossEntropy:tL,softmaxCrossEntropy:sL},od={sparseFillEmptyRows:oL,sparseReshape:cL,sparseSegmentMean:lL,sparseSegmentSum:pL},uf={stringNGrams:fL,stringSplit:gL,stringToHashBucketFast:yL},Es=class extends ik{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 $e(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 $k(e,t)}dispose(){this.iterations_!=null&&$e(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(Es,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var lf=class extends Es{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=B.registeredVariables[n],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:M(()=>Ge(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:M(()=>Ge(s).variable(a))});let o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[r].variable,c=this.accumulatedUpdates[r].variable;M(()=>{let u=Y(V(i,this.rho),V(ct(o),1-this.rho)),l=V(ge(an(Y(c,this.epsilon)),an(Y(i,this.epsilon))),o),d=Y(V(c,this.rho),V(ct(l),1-this.rho));i.assign(u),c.assign(d);let p=Y(V(l,-this.learningRate),s);s.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpda
${a}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let d=0;d<r;++d)if(e.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${e.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);let o=e.shape[n],i=[],c=1,u=1,l=1;for(let d=0;d<r;++d)i.push(e.shape[d]),c*=e.shape[d];for(let d=r;d<n;d++)i.push(e.shape[d]),u*=e.shape[d];for(let d=r;d<s;d++)i.push(t.shape[d]);for(let d=n+1;d<a;d++)i.push(e.shape[d]),l*=e.shape[d];return{batchSize:c,sliceSize:l,outerSize:u,dimSize:o,outputShape:i}}function rB(e){try{return e.map(t=>Ih(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function sB(e){return e.map(t=>Ll(t))}var as={};Re(as,{nonMaxSuppressionV3Impl:()=>eI,nonMaxSuppressionV4Impl:()=>tI,nonMaxSuppressionV5Impl:()=>nI,whereImpl:()=>Gk});var hI={kernelName:Xi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>V(e,pu(ce(n,"float32"),-1))}}},aB={kernelName:Yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=ct(ce(n,"float32")),s=an(fe(Ie(1),r));return kt(ge(e,s))}}}},oB={kernelName:Zi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=an(fe(ct(ce(n,"float32")),1));return ge(e,r)}}}},iB={kernelName:Js,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=e,c=Vt(n.shape,s);return c.length>0&&(i=ve(i,c)),U(i,n.shape)},b:()=>{let i=e,c=Vt(r.shape,s);return c.length>0&&(i=ve(i,c)),U(i,r.shape)}}}},cB={kernelName:La,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((r,s)=>{n[s]=()=>e.clone()}),n}},uB={kernelName:Ba,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},lB={kernelName:xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ge(n)}}},dB={kernelName:ec,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,an(fe(Ie(1),ct(ce(n,"float32")))))}}},pB={kernelName:tc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=an(Y(Ie(1),ct(ce(n,"float32"))));return ge(e,r)}}}},hB={kernelName:sc,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=gt(n.shape,r.shape);return{a:()=>{let i=Y(ct(n),ct(r)),c=V(e,ge(r,i)),u=Vt(n.shape,s);return u.length>0&&(c=ve(c,u)),U(c,n.shape)},b:()=>{let i=Y(ct(n),ct(r)),c=kt(V(e,ge(n,i))),u=Vt(r.shape,s);return u.length>0&&(c=ve(c,u)),U(c,r.shape)}}}},fB={kernelName:nc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Y(ct(ce(n,"float32")),1))}}},mB={kernelName:rc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,fe(Ie(1),ct(ce(n,"float32"))))}}};function gB(e,t,n,r,s,a){let o=E(e,"dy","avgPool3dGrad"),i=E(t,"input","avgPool3dGrad"),c=o,u=i,l=!1;i.rank===4&&(l=!0,c=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),u=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),F(c.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),F(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),a!=null&&F(qt(s),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let d={dy:c,input:u},p={filterSize:n,strides:r,pad:s,dimRoundingMode:a},h=B.runKernel(Mp,d,p);return l?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var bB=W({avgPool3dGrad_:gB}),yB={kernelName:wl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>bB(e,r,s,a,o,i)}}};function vB(e,t,n,r,s){let a=E(e,"dy","avgPoolGrad"),o=E(t,"input","avgPoolGrad");F(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,c=a,u=!1;o.rank===3&&(u=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),F(c.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${c.rank}.`),F(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let l={dy:c,input:i},d={filterSize:n,strides:r,pad:s},p=B.runKernel(Op,l,d);return u?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var xB=W({avgPoolGrad_:vB}),wB={kernelName:za,inputsToSave:["x"],gradFunc:(e,
2021-09-11 17:11:38 +02:00
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{let a=e;if(a.className==null||a.config==null)throw new H(`${r}: Improper config format: ${JSON.stringify(a)}.
2021-09-16 14:30:50 +02:00
'className' and 'config' must set.`);let o=a.className,i,c;if(o in n?[i,c]=n[o]:o in Cr?[i,c]=Cr.className:o in t&&([i,c]=t[o]),i==null)throw new H(`Unknown ${r}: ${o}. This may be due to one of the following reasons:
2021-09-11 17:11:38 +02:00
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2021-09-29 15:32:30 +02:00
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(c!=null){let u={};for(let h of Object.keys(Cr))u[h]=Cr[h];for(let h of Object.keys(n))u[h]=n[h];let l=a.config;l.customObjects=u;let d=Object.assign({},Cr);for(let h of Object.keys(n))Cr[h]=n[h];cv(a.config);let p=c(i,a.config,n,s);return Cr=Object.assign({},d),p}else{let u=Object.assign({},Cr);for(let d of Object.keys(n))Cr[d]=n[d];let l=new i(a.config);return Cr=Object.assign({},u),l}}}function o4(e,t){return e<t?-1:e>t?1:0}function bf(e,t){return-1*o4(e,t)}function ha(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function i4(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 ri(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 uv(e,t,n=0,r=1/0){return os(n>=0),os(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(s=>typeof s===t)}function Jt(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,r)=>Jt(n,`element ${r+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${SI(e)}.`)}function SI(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>SI(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function c4(e,t){let n=w.now(),r;return(...a)=>{let o=w.now();return o-n<t||(n=o,r=e(...a)),r}}function CI(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function lv(e,t){return M(()=>an(ve(V(e,e),t,!0)))}var ud=class extends oe.Serializable{getConfig(){return{}}},dv=class extends ud{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return M(()=>{let t=lv(e,this.axis),n=Zt(t,0,this.maxValue);return V(e,ge(n,Y(Ut(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};dv.className="MaxNorm";oe.registerClass(dv);var pv=class extends ud{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return M(()=>ge(e,Y(Ut(),lv(e,this.axis))))}getConfig(){return{axis:this.axis}}};pv.className="UnitNorm";oe.registerClass(pv);var hv=class extends ud{apply(e){return qe(e)}};hv.className="NonNeg";oe.registerClass(hv);var fv=class extends ud{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return M(()=>{let t=lv(e,this.axis),n=Y(V(this.rate,Zt(t,this.minValue,this.maxValue)),V(1-this.rate,t));return V(e,ge(n,Y(Ut(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};fv.className="MinMaxNorm";oe.registerClass(fv);var TI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Gt(e){return iv(e)}function NI(e,t={}){return cd(e,oe.SerializationMap.getMap().classNameMap,t,"constraint")}function Ht(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in TI?TI[e]:e,config:{}};return NI(n)}else return e instanceof ud?e:NI(e)}function u4(e){return new dv(e)}function l4(e){return new pv(e)}function d4(){return new hv}function p4(e){return new fv(e)}var _I={};Re(_I,{constant:()=>P4,glorotNormal:()=>V4,glorotUniform:()=>W4,heNormal:()=>U4,heUniform:()=>G4,identity:()=>B4,leCunNormal:()=>H4,leCunUniform:()=>j4,ones:()=>R4,orthogonal:()=>q4,randomNormal:()=>M4,randomUniform:()=>O4,truncatedNormal:()=>L4,varianceScaling:()=>z4,zeros:()=>F4});var h4=["channelsFirst","channelsLast"],f4=["nearest","bilinear"],m4=["valid","same","causal"],g4=["max","avg"],b4=["sum","mul","concat","ave"],fu=new Map;function Ot(e){ri(h4,"DataFormat",e)}function y4(e){ri
2021-09-16 14:30:50 +02:00
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),_r(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,Yt(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 jn([],[0].concat(this.elementShape));let n=this.readMany(e);return _r(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Pt(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return jn([],[0].concat(this.elementShape));let t=[];for(let r=0;r<this.size();r++)t.push(r);let n=this.readMany(t);return _r(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Ze(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,dt(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,r=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
2021-09-11 17:11:38 +02:00
tensor.shape[0], but sum of lengths is
2021-09-16 14:30:50 +02:00
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let s=n===0?0:t.size/n,a=[];M(()=>{t=U(t,[1,n,s]);for(let i=0;i<e.length;++i){let c=i===0?0:r[i-1],u=[0,c,0],l=[1,e[i],s];a[i]=U(We(t,u,l),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},Nd=class{constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(s=>{if(n!==s.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);_r(t,s.shape,"TensorList shape mismatch: "),Yt(s)}),this.idTensor=Ie(0),this.maxNumElements=r,Yt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Nd([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);_r(e,this.elementShape,"TensorList shape mismatch: ");let r=Td(this.elementShape,this.tensors,e);return M(()=>{let s=this.tensors.map(a=>U(a,r));return Pt(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Td(this.elementShape,this.tensors,e),r=this.tensors.pop();return _r(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(_r(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Yt(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.`);_r(this.tensors[e].shape,t,"TensorList shape mismatch: ");let r=Td(this.elementShape,this.tensors,t);return U(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);_r(this.elementShape,t.shape,"TensorList shape mismatch: "),Yt(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}`);_r(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let r=Td(this.elementShape,this.tensors,n);return e.length===0?jn([],[0].concat(r)):M(()=>{let s=e.map(a=>U(this.tensors[a],r));return Pt(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);_r(this.elementShape,t,"TensorList shape mismatch: ");let n=Td(this.elementShape,this.tensors,t);return this.size()===0?jn([],[0].concat(n)):M(()=>{let r=this.tensors.map(s=>U(s,n));return Ze(r,0)})}};function gG(e,t,n){let r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor m
2021-09-11 17:11:38 +02:00
tensor.shape[0], but sum of lengths is
2021-09-29 15:32:30 +02:00
${r}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=sw(a,n),i=r===0?0:e.size/r,c=M(()=>{let l=[];e=U(e,[1,r,i]);for(let d=0;d<t.length;++d){let p=d===0?0:s[d-1],h=[0,p,0],f=[1,t[d],i];l[d]=U(We(e,h,f),o)}return e.dispose(),l}),u=new Nd([],n,e.dtype,t.length);for(let l=0;l<c.length;l++)u.setItem(l,c[l]);return u}var xG=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let r=I("thenBranch",e,t,n),s=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let r=I("body",e,t,n),s=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(l=>l.id),c=await o[0].data();o.forEach(l=>{!l.kept&&i.indexOf(l.id)===-1&&l.dispose()});let u=a;for(;c[0];){let l=u;u=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let d=u.map(h=>h.id);l.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[s].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);c=await p[0].data(),p.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return u}case"LoopCond":{let r=I("pred",e,t,n);return[Rs(r)]}case"Switch":{let r=I("pred",e,t,n),s=I("data",e,t,n);return s.kept||(s=Rs(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{let r=e.inputNames.find(s=>kn(s,t,n)!==void 0);if(r){let s=kn(r,t,n);return[Rs(s)]}return}case"Enter":{let r=I("frameName",e,t,n),s=I("tensor",e,t,n);return n.enterFrame(r),[Rs(s)]}case"Exit":{let r=I("tensor",e,t,n);return n.exitFrame(),[Rs(r)]}case"NextIteration":{let r=I("tensor",e,t,n);return n.nextIteration(),[Rs(r)]}case"TensorArrayV3":{let r=I("size",e,t,n),s=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),c=I("identicalElementShapes",e,t,n),u=I("name",e,t,n),l=new mG(u,s,r,a,c,o,i);return n.addTensorArray(l),[l.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=yG(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=bG(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),er(async()=>(await n.iterator()).columnMajorBatch(e,t,vH),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,er(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,er(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 er(async()=>(await t.iterator()).map(n=>M(()=>e(n))),this.size)}mapAsync(e){let t=this;return er(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 er(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,er(async()=>{let r=cw(async()=>({value:await t.iterator(),done:!1}));return rH(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,er(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=XG.alea(t||w.now().toString());return er(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,er(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()}};ku.MAX_BUFFER_SIZE=1e4;function er(e,t=null){return new class extends ku{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function bH(e){return er(async()=>WC(e),e.length)}function yH(e){if(!wu(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 er(async()=>{let n=await BC(e,r=>{if(r instanceof ku)return{value:r.iterator(),recurse:!1};if(wu(r))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return sH(n,xa.SHORTEST)},t)}function vH(e){if(e===null)return null;let t=e[0];return QG(t)?{value:xH(e),recurse:!1}:{value:null,recurse:!0}}function xH(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ee?Pt(e):jn(e)}var HC=class extends ku{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))}},Jf='"',_d=Symbol("out"),jC=Symbol("field"),Qf=Symbol("quote"),lw=Symbol("quoteafterquote"),qC=Symbol("quoteinquote"),KC=class extends ku{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 HC(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(w.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((r,s)=>(r[s]=r[s]+1||1,r),{}),n=Object.keys(t).filter(r=>t[r]>1);if(w.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let r of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(r)===-1)throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],o=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!o)){let i=t[s],c=null;if(i==="")if(o&&o.default!==void 0)c=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);c=void 0}else{let u=Number(i);if(isNaN(u))o&&o.dtype==="bool"?c=this.getBoolean(i):c=i;else if(!o||!o.dtype)c=u;else switch(o.dtype){case"float32":c=u;break;case"int32":c=Math.floor(u);break;case"bool":c=this.getBoolean(i);break;default:c=u}}o&&o.isLabel?r[a]=c:n[a]=c}}return Object.keys(r).length===0?n:{xs:n,ys:r}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],r=0,s=e.length,a=_d;for(let o=0;o<s;o++)switch(a){case _d:switch(e.charAt(o)){case Jf:r=o+1,a=Qf;break;case this.delimiter:if(r=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=_d;break;default:a=jC,r=o;break}break;case jC:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o)),a=_d,r=o+1;break;default:}break;case Qf:switch(e.charAt(o)){case Jf:a=lw;break;default:}break;case lw:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o-1)),a=_d,r=o+1;break;case Jf:a=Qf;break;default:a=qC;break}break;case qC:switch(e.charAt(o)){case Jf:a=Qf;break;default:}break;default:}if(a===lw?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}},XC=class extends Qt{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSi
2021-09-11 17:11:38 +02:00
============================
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
2021-09-29 15:32:30 +02:00
============================`));let r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return _.mergeRealAndImagArrays(r,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(r=>w.decodeString(r))}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,n)}makeOutput(e,t,n){let r=this.write(e,t,n);return Cs().makeTensorFromDataId(r,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){ke([e],"where");let t=this.readSync(e.dataId);return RH(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};dw.nextDataId=0;var rT={};Re(rT,{addImpl:()=>aT,bincountImpl:()=>hw,bincountReduceImpl:()=>oT,ceilImpl:()=>iT,concatImpl:()=>fw,equalImpl:()=>cT,expImpl:()=>lT,expm1Impl:()=>pT,floorImpl:()=>hT,gatherNdImpl:()=>fT,gatherV2Impl:()=>mT,greaterEqualImpl:()=>bT,greaterImpl:()=>gT,lessEqualImpl:()=>vT,lessImpl:()=>yT,linSpaceImpl:()=>xT,logImpl:()=>wT,maxImpl:()=>kT,maximumImpl:()=>IT,minimumImpl:()=>ST,multiplyImpl:()=>mw,negImpl:()=>CT,notEqualImpl:()=>TT,prodImpl:()=>NT,rangeImpl:()=>bw,rsqrtImpl:()=>_T,sigmoidImpl:()=>k6,simpleAbsImpl:()=>sT,sliceImpl:()=>nm,sparseFillEmptyRowsImpl:()=>AT,sparseReshapeImpl:()=>DT,sparseSegmentReductionImpl:()=>yw,sqrtImpl:()=>C6,squaredDifferenceImpl:()=>$T,stridedSliceImpl:()=>FT,stringNGramsImpl:()=>RT,stringSplitImpl:()=>PT,stringToHashBucketFastImpl:()=>OT,subImpl:()=>MT,tileImpl:()=>LT,topKImpl:()=>zT,transposeImpl:()=>gw,uniqueImpl:()=>WT});function sT(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var PH=e=>{let{x:t}=e.inputs,n=e.backend;ke(t,"abs");let r=new Float32Array(w.sizeFromShape(t.shape)),s=n.data.get(t.dataId).values;return r=sT(s),n.makeOutput(r,t.shape,"float32")},OH={kernelName:Xi,backendName:"cpu",kernelFunc:PH};function Bt(e){return(t,n,r,s,a)=>{let o=_.assertAndGetBroadcastShape(t,n),i=o.length,c=w.computeStrides(o),u=w.sizeFromShape(o),l=w.getTypedArrayFromDType(a,u),d=t.length,p=n.length,h=w.computeStrides(t),f=w.computeStrides(n),m=_.getBroadcastDims(t,o),g=_.getBroadcastDims(n,o);if(m.length+g.length===0)for(let b=0;b<l.length;++b)l[b]=e(r[b%r.length],s[b%s.length]);else for(let b=0;b<l.length;++b){let y=w.indexToLoc(b,i,c),v=y.slice(-d);m.forEach(N=>v[N]=0);let x=w.locToIndex(v,d,h),k=y.slice(-p);g.forEach(N=>k[N]=0);let C=w.locToIndex(k,p,f);l[b]=e(r[x],s[C])}return[l,o]}}function tr(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 MH={kernelName:Bp,backendName:"cpu",kernelFunc:tr};function em(e,t,n="float32"){if(n==="complex64"){let s=em(e,t,"float32"),a=em(e,t,"float32
2021-09-16 14:30:50 +02:00
indices.shape[0] = ${i}`);let g=w.getArrayFromDType(n,0),b=w.getArrayFromDType(s,0);return[g,[0,d],b,u,l]}let p=!0,h=0,f=new Array(c).fill(0);for(let g=0;g<i;++g){let b=e[g*d];if(b<0)throw new Error(`indices(${g}, 0) is invalid: ${b} < 0`);if(b>=c)throw new Error(`indices(${g}, 0) is invalid: ${b} >= ${c}`);++f[b],p=p&&b>=h,h=b}let m=!0;for(let g=0;g<c;++g){let b=f[g]===0;u[g]=b,m=m&&!b,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&p){let g=e,b=r;for(let y=0;y<i;++y)l[y]=y;return[g,[i,d],b,u,l]}else{let g=f[c-1],b=w.getArrayFromDType(n,g*d),y=w.getArrayFromDType(s,g),v=new Array(c).fill(0);for(let x=0;x<i;++x){let k=e[x*d],C=v[k],N=(k===0?0:f[k-1])+C;v[k]++;for(let $=0;$<d;++$)b[N*d+$]=e[x*d+$];y[N]=r[x],l[x]=N}for(let x=0;x<c;++x)if(v[x]===0){let C=x===0?0:f[x-1];b[C*d+0]=x;for(let N=1;N<d;++N)b[C*d+N]=0;y[C]=o}return[b,[g,d],y,u,l]}}function DT(e,t,n,r,s){let a=w.sizeFromShape(r),o=t[0],i=s.length,c=[],u=1,l=-1;for(let g=0;g<i;++g){let b=s[g];if(b===-1){if(l!==-1)throw new Error(`only one output dimension may be -1, not both ${l} and ${g}`);l=g,c.push(1)}else{if(b<0)throw new Error(`size ${g} must be non-negative, not ${b}`);u*=b,c.push(b)}}if(l!==-1){if(u<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");let g=Math.trunc(a/u);if(u*g!==a)throw new Error(`Input to reshape is a SparseTensor with ${a}
2021-09-29 15:32:30 +02:00
dense values, but the requested shape requires a multiple of ${u}. inputShape=${r} outputShape= ${c}`);c[l]=g}let d=w.sizeFromShape(c);if(d!==a)throw new Error(`Input to reshape is a tensor with ${a} dense values, but the requested shape has ${d}. inputShape=${r} outputShape=${c}`);let p=r.length,h=[];if(p>0){h[p-1]=1;for(let g=p-2;g>=0;--g)h[g]=h[g+1]*r[g+1]}let f=[];if(i>0){f[i-1]=1;for(let g=i-2;g>=0;--g)f[g]=f[g+1]*c[g+1]}let m=w.getArrayFromDType(n,o*i);for(let g=0;g<o;++g){let b=0;for(let y=0;y<p;++y)b+=e[g*p+y]*h[y];for(let y=0;y<i;++y)m[g*i+y]=Math.trunc(b/f[y]),b%=f[y]}return[m,[o,i],c]}function yw(e,t,n,r,s,a=!1,o=0){let i=r.length;if(i!==s.length)throw new Error("segmentIds and indices should have same size.");let c=[t[0],e.length/t[0]],u=c[1],d=i>0?s[i-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let p=t.slice();p[0]=d;let h=p.reduce((v,x)=>v*x,1),f=w.getArrayFromDType(n,h);if(i===0)return d>0&&f.fill(o),[f,p];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,g=1,b=0,y=s[m];for(;;){let v=0;if(g<i){if(v=s[g],y===v){++g;continue}if(y>=v)throw new Error("segment ids are not increasing")}if(y<0||y>=d)throw new Error(`Segment id ${y} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);y>b&&f.fill(o,b*u,y*u);for(let x=m;x<g;++x){let k=r[x];if(k<0||k>=c[0])throw new Error(`Bad: indices[${x}] == ${r[x]} out of range [0, ${c[0]})`);for(let C=0;C<u;C++)f[y*u+C]+=e[k*u+C]}if(a)for(let x=0;x<u;x++)f[y*u+x]/=g-m;if(m=g,++g,b=y+1,y=v,g>i)break}return b<d&&f.fill(o,b*u,d*u),[f,p]}var C6=ka(e=>Math.sqrt(e)),T6=ot(No,e=>Math.sqrt(e)),N6={kernelName:No,backendName:"cpu",kernelFunc:T6},$T=Bt((e,t)=>{let n=e-t;return n*n}),_6=en(Ao,$T),E6={kernelName:Ao,backendName:"cpu",kernelFunc:_6};function FT(e,t,n,r){let s=ze(e,t.dtype);for(let a=0;a<s.size;a++){let o=s.indexToLoc(a),i=new Array(o.length);for(let c=0;c<i.length;c++)i[c]=o[c]*n[c]+r[c];s.set(t.get(...i),...o)}return s}var A6=class{constructor(e,t,n,r,s,a){this.separator=w.encodeString(e),this.nGramWidths=t,this.leftPad=w.encodeString(n),this.rightPad=w.encodeString(r),this.padWidth=s,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,s,a){for(let o=0;o<s;++o){let i=this.getPadWidth(a),c=Math.max(0,i-o),u=Math.max(0,i-(s-(o+1))),l=a-(c+u),d=t+(c>0?0:o-i),p=0;p+=c*this.leftPad.length;for(let b=0;b<l;++b)p+=e[d+b].length;p+=u*this.rightPad.length,p+=(c+u+l-1)*this.separator.length,n[r+o]=new Uint8Array(p);let f=n[r+o],m=0,g=b=>b.forEach(y=>f[m++]=y);for(let b=0;b<c;++b)g(this.leftPad),g(this.separator);for(let b=0;b<l-1;++b)g(e[d+b]),g(this.separator);if(l>0){g(e[d+l-1]);for(let b=0;b<u;++b)g(this.separator),g(this.rightPad)}else{for(let b=0;b<u-1;++b)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let n=e.length,r=t.length;if(r>0){let i=t[0];if(i!==0)throw new Error(`First split value must be 0, got ${i}`);for(let c=1;c<r;++c){let u=t[c]>=i;if(u=u&&t[c]<=n,!u)throw new Error(`Invalid split value ${t[c]}, must be in [${i}, ${n}]`);i=t[c]}if(i!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`)}let s=r-1,a=w.getArrayFromDType("int32",r);if(n===0||r===0){let i=new Array(n);for(let c=0;c<=s;++c)a[c]=0;return[i,a]}a[0]=0;for(let i=1;i<=s;++i){let c=t[i]-t[i-1],u=0;this.nGramWidths.forEach(l=>{u+=this.getNumNGrams(c,l)}),this.preserveShort&&c>0&&u===0&&(u=1),a[i]=a[i-1]+u}let o=new Array(a[s]);for(let i=0;i<s;++i){let c=t[i],u=a[i];if(this.nGramWidths.forEach(l=>{let d=t[i+1]-t[i],p=this.getNumNGrams(d,l);this.createNGrams(e,c,o,u,p,l),u+=p}),this.preserveShort&&u===a[i]){let l=t[i+1]-t[i];if(l===0)continue;let d=l+2*this.padWidth,p=1;this.createNGrams(e,c,o,u,p,d)}}return[o,a]}};function RT(e,t,n,r,s,a,o,i){return new A6(n,r,s,a,o,i).compute(e,t)}function D6(e,t,n,r){if(!e.length)return;if(t.length===0){for(let a=0;a<e.length;++a)r.push(e.subarray(a,a+1));return}if(t.length===1){let a=t[0],o=e.indexOf(a);for(;o!==-1;){let i=e.subarray(0,o);(!n|
2021-09-11 17:11:38 +02:00
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
2021-09-16 14:30:50 +02:00
${o.shape}`);let i=n.data.get(r.dataId).values,c=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values[0],[d,p,h,f,m]=AT(i,r.shape,r.dtype,c,s.dtype,u,l);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var j8={kernelName:uh,backendName:"cpu",kernelFunc:H8};function q8(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
2021-09-11 17:11:38 +02:00
${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
2021-09-16 14:30:50 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.data.get(s.dataId).values),i=n.data.get(r.dataId).values,c=Array.from(n.data.get(a.dataId).values),[u,l,d]=DT(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(l,r.dtype,u),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var K8={kernelName:lh,backendName:"cpu",kernelFunc:q8};function X8(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2021-09-16 14:30:50 +02:00
${a.shape}`);let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[u,l]=yw(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(l,r.dtype,u)}var Y8={kernelName:dh,backendName:"cpu",kernelFunc:X8};function Z8(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2021-09-29 15:32:30 +02:00
${a.shape}`);let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,[u,l]=yw(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(l,r.dtype,u)}var J8={kernelName:ph,backendName:"cpu",kernelFunc:Z8};function Q8(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:u,sliceSize:l,strides:d,outputSize:p}=_.calculateShapes(a,s,i),h=!1,f=n.bufferSync(s),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],b=s2(f,m,i,p,l,u,c,d,g,h);return n.makeTensorInfo(i,b.dtype,b.values)}var eK={kernelName:hh,backendName:"cpu",kernelFunc:Q8};function tK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),u=new Array(s.shape.length).fill(0),l=s.shape.slice();return c.map(d=>{let p=[...l];p[i]=d;let h=di({inputs:{x:s},backend:n,attrs:{begin:u,size:p}});return u[i]+=d,h})}var nK={kernelName:Uc,backendName:"cpu",kernelFunc:tK},rK={kernelName:$l,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}}},sK=ot(ta,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),aK={kernelName:ta,backendName:"cpu",kernelFunc:sK};function oK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:u,ellipsisMask:l,newAxisMask:d,shrinkAxisMask:p}=r;ke(s,"stridedSlice");let{nonStrided:h,$begin:f,$strides:m,size:g,newShape:b,outShape:y}=vn.sliceInfo(s.shape,a,o,i,c,u,l,d,p),v=yt({inputs:{x:s},backend:n,attrs:{shape:b}}),x;if(h){let C=di({inputs:{x:v},backend:n,attrs:{begin:f,size:g}});x=yt({inputs:{x:C},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(C)}else if(y.some(C=>C===0))x=n.makeTensorInfo(y,s.dtype,[]);else{let C=n.bufferSync(v),N=FT(y,C,m,f);x=n.makeTensorInfo(N.shape,N.dtype,N.values)}let k=yt({inputs:{x},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),k}var iK={kernelName:Gc,backendName:"cpu",kernelFunc:oK};function cK(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:u}=r,{data:l,dataSplits:d}=t,p=n.data.get(l.dataId).values,h=n.data.get(d.dataId).values,[f,m]=RT(p,h,s,a,o,i,c,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var uK={kernelName:fh,backendName:"cpu",kernelFunc:cK};function lK(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,c=n.data.get(o.dataId).values[0],[u,l,d]=PT(i,c,s),p=l.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",l),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var dK={kernelName:mh,backendName:"cpu",kernelFunc:lK};function pK(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=OT(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var hK={kernelName:gh,backendName:"cpu",kernelFunc:pK},fK=ot($o,e=>Math.tan(e)),mK={kernelName:$o,backendName:"cpu",kernelFunc:fK},gK=ot(Fo,e=>Math.tanh(e)),bK={kernelName:Fo,backendName:"cpu",kernelFunc:gK};function yK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;ke(s,"tile");let o=LT(n.bufferSync(s),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var vK={kernelName:ea,backendName:"cpu",kernelFunc:yK};function xK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r;ke(s,"topk");let i=n.data.get(s.dataId).values,[c,u]=zT(i,s.shape,s.dtype,a,o);return
2021-09-11 17:11:38 +02:00
`),a=s.length.toString().length+2,o=s.map((d,p)=>w.rightPad((p+1).toString(),a)+d),i=0;for(let d=0;d<o.length;d++)i=Math.max(o[d].length,i);let c=o.slice(0,r-1),u=o.slice(r-1,r),l=o.slice(r);console.log(c.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${w.rightPad(u[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(l.join(`
2021-09-29 15:32:30 +02:00
`))}function h2(e){return Ps(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function f2(e,t){if(xe(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function om(e,t){if(xe(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function m2(e,t){let n=Ps(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),xe(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function g2(e,t){let n=Ps(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return xe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),xe(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function jK(){return Q().getNumber("WEBGL_VERSION")===2?1:4}function b2(e){return Ps(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function y2(e,t){let n=Q().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let r=`[${e}x${t}]`;throw new Error("Requested texture size "+r+" is invalid.")}if(e>n||t>n){let r=`[${e}x${t}]`,s=`[${n}x${n}]`;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+s+".")}}function v2(e){return Ps(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function _w(e,t,n,r,s,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),xe(e,()=>e.vertexAttribPointer(i,s,e.FLOAT,!1,a,o)),xe(e,()=>e.enableVertexAttribArray(i)),!0)}function x2(e,t,n){C2(e,n),xe(e,()=>e.activeTexture(e.TEXTURE0+n)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function qK(e,t){C2(e,t),xe(e,()=>e.activeTexture(e.TEXTURE0+t)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function w2(e,t,n){return Ps(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function k2(e,t,n){return e.getUniformLocation(t,n)}function I2(e,t,n,r){xe(e,()=>x2(e,t,r)),xe(e,()=>e.uniform1i(n,r))}function KK(e){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),xe(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),xe(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function im(e,t,n){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),xe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Ew(e,t){xe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),xe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Od(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+S2(e,t))}function S2(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function Ps(e,t,n){let r=xe(e,()=>t());if(r==null)throw new Error(n);return r}function C2(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 hi(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function fi(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 cm(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[hi(e),...fi(e)]),t}function T2(e,t=!1){let n=Q().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((s,a)=>a>=e.length-2?w.nearestLargerEven(e[a]):e[a]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let r=w.sizeFromShape(e);if(e.length<=1&&r<=n)return[1,r];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]
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)
`,c="",u=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
`):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",o="",i=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
`,c=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
`,u=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2021-09-29 15:32:30 +02:00
`),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:c,defineRound:u}}function mi(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / ${s}`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${s}`:`index -= ${e[a]} * ${s}`;return`${o}; ${i};`}).join("")}function pm(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / outShapeStrides[${a}]`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`;return`${o}; ${i};`}).join("")}function JK(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 QK(e,t,n="index"){let r=e.map((a,o)=>o),s=JK(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 $w(e){let t=w.computeStrides(e).map(n=>n.toString());return`
2021-09-11 17:11:38 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
2021-09-16 14:30:50 +02:00
`}function Fw(){return`
2021-09-11 17:11:38 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
2021-09-16 14:30:50 +02:00
`}var F2=`
2021-09-11 17:11:38 +02:00
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
2021-06-04 14:54:48 +02:00
}
2021-09-11 17:11:38 +02:00
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
2021-09-16 14:30:50 +02:00
`,{getBroadcastDims:R2}=_;function eX(e,t,n){let r=[];if(e.forEach(h=>{let f=w.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?r.push(`uniform float ${h.name}${f>1?`[${f}]`:""};`):(r.push(`uniform sampler2D ${h.name};`),r.push(`uniform int offset${h.name};`)),n.enableShapeUniforms){let{uniformShape:m}=Rw(n.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(m.length){case 1:r.push(`uniform int ${h.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${h.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${h.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${h.name}Shape;`);break;default:break}r.push(`uniform ivec2 ${h.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;");break;default:break}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(h=>{r.push(`uniform ${h.type} ${h.name}${h.arrayIndex?`[${h.arrayIndex}]`:""};`)});let s=r.join(`
`),a=e.map(h=>tX(h,t,n.packedInputs,n.enableShapeUniforms)).join(`
`),o=t.texShape,i=In(),c=sX(i),u,l,d=iX(i);return t.isPacked?(u=nX(t.logicalShape,o,n.enableShapeUniforms),l=oX(i)):(u=rX(t.logicalShape,o,n.enableShapeUniforms),l=aX(i)),n.packedInputs&&(d+=dX),[d,c,l,s,u,a,n.userCode].join(`
`)}function _u(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return IX(e,t);case 1:return CX(e,t);case 2:return NX(e,t);case 3:return EX(e,t);case 4:return DX(e,t);case 5:return $X(e);case 6:return FX(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function P2(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return kX(e);case 1:return SX(e,t);case 2:return TX(e,t);case 3:return _X(e,t);default:return AX(e,t)}}function tX(e,t,n=!1,r){let s="";n?s+=P2(e,r):s+=_u(e,r);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?s+=RX(e,t):s+=PX(e,t)),s}function nX(e,t,n){switch(e.length){case 0:return O2();case 1:return pX(e,t,n);case 2:return xX(e,t,n);case 3:return fX(e,t,n);default:return gX(e,t,n)}}function rX(e,t,n){switch(e.length){case 0:return O2();case 1:return hX(e,t,n);case 2:return wX(e,t,n);case 3:return mX(e,t,n);case 4:return bX(e,t,n);case 5:return yX(e,t);case 6:return vX(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function sX(e){return`
2021-09-11 17:11:38 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function aX(e){return`
2021-09-11 17:11:38 +02:00
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function oX(e){return`
2021-09-11 17:11:38 +02:00
void setOutput(vec4 val) {
${e.output} = val;
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function iX(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-09-16 14:30:50 +02:00
${cX}
${uX}
${lX}
`}var cX=`
2021-09-11 17:11:38 +02:00
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2021-09-16 14:30:50 +02:00
`,uX=`
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2021-09-16 14:30:50 +02:00
`,lX=`
2021-09-11 17:11:38 +02:00
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2021-09-16 14:30:50 +02:00
`,dX=`
2021-09-11 17:11:38 +02:00
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
2021-09-16 14:30:50 +02:00
`;function O2(){return`
2021-09-11 17:11:38 +02:00
int getOutputCoords() {
return 0;
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function pX(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return r[0]===1?n?`
2021-09-11 17:11:38 +02:00
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.x * ${r[1]}.0);
}
`:r[1]===1?n?`
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.y * ${r[0]}.0);
}
`:n?`
int getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function hX(e,t,n){return t[0]===1?n?`
2021-09-11 17:11:38 +02:00
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
`:`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?n?`
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
`:`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:n?`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
return resTexRC.x * outTexShape[1] + resTexRC.y;
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function fX(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec3(b, r, c);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
int index = resTexRC.x * ${r[1]} + resTexRC.y;
int b = index / ${a};
index -= b * ${a};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec3(b, r, c);
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function mX(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
2021-09-16 14:30:50 +02:00
${pm(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2021-09-29 15:32:30 +02:00
`;let r=mi(["r","c","d"],e);return`
2021-09-11 17:11:38 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${r}
return ivec3(r, c, d);
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function gX(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-09-11 17:11:38 +02:00
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2),o=a,i="",c="b, r, c";for(let u=2;u<e.length-1;u++)o*=e[e.length-u-1],i=`
int b${u} = index / ${o};
index -= b${u} * ${o};
`+i,c=`b${u}, `+c;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
int index = resTexRC.x * ${r[1]} + resTexRC.y;
${i}
int b = index / ${a};
index -= b * ${a};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec${e.length}(${c});
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function bX(e,t,n){if(n)return`
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
2021-09-16 14:30:50 +02:00
${pm(["r","c","d","d2"],e)}
2021-09-11 17:11:38 +02:00
return ivec4(r, c, d, d2);
2021-05-18 14:11:17 +02:00
}
2021-09-29 15:32:30 +02:00
`;let r=mi(["r","c","d","d2"],e);return`
2021-09-11 17:11:38 +02:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${r}
return ivec4(r, c, d, d2);
2021-05-18 14:11:17 +02:00
}
2021-09-29 15:32:30 +02:00
`}function yX(e,t){let n=mi(["r","c","d","d2","d3"],e);return`
2021-09-11 17:11:38 +02:00
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
2021-05-18 14:11:17 +02:00
}
2021-09-29 15:32:30 +02:00
`}function vX(e,t){let n=mi(["r","c","d","d2","d3","d4"],e);return`
2021-09-11 17:11:38 +02:00
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
2021-05-18 14:11:17 +02:00
}
2021-09-16 14:30:50 +02:00
`}function xX(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return n?`
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));
}
`;let s=Math.ceil(e[1]/2);return n?`
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec2(r, c);
2021-05-18 14:11:17 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${r[0]}, ${r[1]}));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int index = resTexRC.x * ${r[1]} + resTexRC.y;
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return ivec2(r, c);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}function wX(e,t,n){return w.arraysEqual(e,t)?n?`
2021-09-11 17:11:38 +02:00
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:e[1]===1?n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:e[0]===1?n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:n?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
int r = index / outShape[1];
int c = index - r * outShape[1];
return ivec2(r, c);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}function gi(e){return`offset${e}`}function kX(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=In();return`
2021-09-11 17:11:38 +02:00
vec4 ${n}() {
return ${r.texture2D}(${t}, halfCR);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}function IX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;let[s,a]=e.shapeInfo.texShape;if(s===1&&a===1)return`
2021-09-11 17:11:38 +02:00
float ${r}() {
return sampleTexture(${n}, halfCR);
}
2021-09-29 15:32:30 +02:00
`;let o=gi(n);if(t)return`
2021-09-11 17:11:38 +02:00
float ${r}() {
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;let[i,c]=e.shapeInfo.texShape;return`
float ${r}() {
vec2 uv = uvFromFlat(${i}, ${c}, ${o});
return sampleTexture(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}function SX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=In();if(t)return`
2021-09-11 17:11:38 +02:00
vec4 ${r}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${a.texture2D}(${n}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;let o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return`
vec4 ${r}(int index) {
vec2 uv = packedUVfrom1D(
${o[0]}, ${o[1]}, index);
return ${a.texture2D}(${n}, uv);
}
2021-09-16 14:30:50 +02:00
`}function CX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
2021-09-11 17:11:38 +02:00
float ${r}(int index) {
2021-09-16 14:30:50 +02:00
${Eu(e)}
2021-09-11 17:11:38 +02:00
}
`;let s=e.shapeInfo.texShape,a=s[0],o=s[1];if(o===1&&a===1)return`
float ${r}(int index) {
return sampleTexture(${n}, halfCR);
}
2021-09-29 15:32:30 +02:00
`;let i=gi(n);return o===1?t?`
2021-09-11 17:11:38 +02:00
float ${r}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${a}.0);
return sampleTexture(${n}, uv);
}
`:a===1?t?`
float ${r}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);
return sampleTexture(${n}, uv);
}
`:t?`
float ${r}(int index) {
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int index) {
vec2 uv = uvFromFlat(${a}, ${o}, index + ${i});
return sampleTexture(${n}, uv);
}
2021-09-16 14:30:50 +02:00
`}function TX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=a[0],i=a[1],c=In();if(a!=null&&w.arraysEqual(n,a))return t?`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return ${c.texture2D}(${r}, uv);
}
`:`
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);
return ${c.texture2D}(${r}, uv);
}
`;if(t)return`
vec4 ${s}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
return ${c.texture2D}(${r}, uv);
}
`;let u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],l=Math.ceil(n[1]/2);return`
vec4 ${s}(int row, int col) {
vec2 uv = packedUVfrom2D(${l}, ${u[0]}, ${u[1]}, row, col);
return ${c.texture2D}(${r}, uv);
}
2021-09-16 14:30:50 +02:00
`}function NX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(a!=null&&w.arraysEqual(n,a)){if(t)return`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`;let p=a[0],h=a[1];return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
2021-09-16 14:30:50 +02:00
`}let{newShape:o,keptDims:i}=w.squeezeShape(n),c=o;if(c.length<n.length){let p=Au(e,c),h=["row","col"];return`
${_u(p,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col) {
2021-09-16 14:30:50 +02:00
return ${s}(${Du(h,i)});
2021-09-11 17:11:38 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
2021-09-16 14:30:50 +02:00
${Eu(e)}
2021-09-11 17:11:38 +02:00
}
2021-09-29 15:32:30 +02:00
`;let u=a[0],l=a[1],d=gi(r);return 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(0.5, (index + 0.5) / float(${r}TexShape[0]));
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
return sampleTexture(${r}, uv);
}
`:u===1?t?`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${r}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${l}.0, 0.5);
return sampleTexture(${r}, uv);
}
`:t?`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${r}Shape[1] + col + ${d};
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${n[1]} + col + ${d};
vec2 uv = uvFromFlat(${u}, ${l}, index);
return sampleTexture(${r}, uv);
}
2021-09-16 14:30:50 +02:00
`}function _X(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=Au(e,p),m=["b","row","col"];return`
${P2(f,t)}
2021-09-11 17:11:38 +02:00
vec4 ${s}(int b, int row, int col) {
2021-09-16 14:30:50 +02:00
return ${s}(${Du(m,h)});
2021-09-11 17:11:38 +02:00
}
2021-09-16 14:30:50 +02:00
`}let i=In();if(t)return`
2021-09-11 17:11:38 +02:00
vec4 ${s}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${i.texture2D}(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;let c=o[0],u=o[1],l=Math.ceil(n[2]/2),d=l*Math.ceil(n[1]/2);return`
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${c}, ${u}, ${d}, ${l}, b, row, col);
return ${i.texture2D}(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}function EX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],o=n[2],{newShape:i,keptDims:c}=w.squeezeShape(n),u=i;if(u.length<n.length){let m=Au(e,u),g=["row","col","depth"];return`
${_u(m,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth) {
2021-09-16 14:30:50 +02:00
return ${s}(${Du(g,c)});
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${a}, ${o}, 1)));
2021-09-16 14:30:50 +02:00
${Eu(e)}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;let l=e.shapeInfo.texShape,d=l[0],p=l[1],h=e.shapeInfo.flatOffset;if(p===a&&h==null)return t?`
float ${s}(int row, int col, int depth) {
int stride1 = ${r}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${p}.0, ${d}.0);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;if(p===o&&h==null)return t?`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`:`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${n[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${d}.0);
return sampleTexture(${r}, uv);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`;let f=gi(r);return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${r}Shape[1] * ${r}Shape[2];
int stride1 = ${r}Shape[2];
int index = row * ${a} + col * ${o} + depth + ${f};
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} + depth + ${f};
vec2 uv = uvFromFlat(${d}, ${p}, index);
return sampleTexture(${r}, uv);
}
2021-09-16 14:30:50 +02:00
`}function AX(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=In();if(t)return`
2021-09-11 17:11:38 +02:00
vec4 ${r}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${n}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${s.texture2D}(${n}, uv);
}
`;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,c=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],u=c[0],l=c[1],d=Math.ceil(a[o-1]/2),p=d*Math.ceil(a[o-2]/2),h="int b, int row, int col",f=`b * ${p} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<o-1;m++)h=`int b${m}, `+h,p*=a[o-m-1],f=`b${m} * ${p} + `+f;return`
vec4 ${r}(${h}) {
int index = ${f};
int texR = index / ${l};
int texC = index - texR * ${l};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${u});
return ${s.texture2D}(${n}, uv);
}
2021-09-16 14:30:50 +02:00
`}function DX(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:c,keptDims:u}=w.squeezeShape(n);if(c.length<n.length){let y=Au(e,c),v=["row","col","depth","depth2"];return`
${_u(y,t)}
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2021-09-16 14:30:50 +02:00
return ${s}(${Du(v,u)});
2021-09-11 17:11:38 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${i}, ${o}, ${a}, 1)));
2021-09-16 14:30:50 +02:00
${Eu(e)}
2021-09-11 17:11:38 +02:00
}
`;let l=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(h===i&&l==null)return t?`
float ${s}(int row, int col, int depth, int depth2) {
${f}
${m}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${o}, ${a}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
`;if(h===a&&l==null)return t?`
float ${s}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}TexShape[1], ${r}TexShape[0]);
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${n[1]*n[2]}, ${n[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${r}, uv);
}
2021-09-29 15:32:30 +02:00
`;let b=gi(r);return t?`
2021-09-11 17:11:38 +02:00
float ${s}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
${f}
${m}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${b});
return sampleTexture(${r}, uv);
}
`:`
float ${s}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} +
depth * ${a} + depth2;
vec2 uv = uvFromFlat(${p}, ${h}, index + ${b});
return sampleTexture(${r}, uv);
}
2021-09-16 14:30:50 +02:00
`}function $X(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,o=t[2]*a,i=t[1]*o,{newShape:c,keptDims:u}=w.squeezeShape(t);if(c.length<t.length){let m=Au(e,c),g=["row","col","depth","depth2","depth3"];return`
${_u(m)}
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
2021-09-16 14:30:50 +02:00
return ${r}(${Du(g,u)});
2021-09-11 17:11:38 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${i}, ${o}, ${a}, ${s})) +
depth3;
2021-09-16 14:30:50 +02:00
${Eu(e)}
2021-09-11 17:11:38 +02:00
}
`;let l=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&l==null)return`
float ${r}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${o}, ${a}, ${s}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
`;if(h===s&&l==null)return`
float ${r}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
2021-09-29 15:32:30 +02:00
`;let f=gi(n);return`
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} + depth * ${a} +
depth2 * ${s} + depth3 + ${f};
vec2 uv = uvFromFlat(${p}, ${h}, index);
return sampleTexture(${n}, uv);
}
2021-09-16 14:30:50 +02:00
`}function FX(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=w.squeezeShape(t);if(s.length<t.length){let g=Au(e,s),b=["row","col","depth","depth2","depth3","depth4"];return`
${_u(g)}
2021-09-11 17:11:38 +02:00
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
2021-09-16 14:30:50 +02:00
return ${r}(${Du(b,a)});
2021-09-11 17:11:38 +02:00
}
`}let o=t[5],i=t[4]*o,c=t[3]*i,u=t[2]*c,l=t[1]*u;if(e.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${l}, ${u}, ${c}, ${i})) +
dot(
vec2(depth3, depth4),
vec2(${o}, 1)));
2021-09-16 14:30:50 +02:00
${Eu(e)}
2021-09-11 17:11:38 +02:00
}
`;let d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===l&&d==null)return`
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${u}, ${c}, ${i}, ${o})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
`;if(f===o&&d==null)return`
float ${r}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
2021-09-29 15:32:30 +02:00
`;let m=gi(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.
int index = row * ${l} + col * ${u} + depth * ${c} +
depth2 * ${i} + depth3 * ${o} + depth4 + ${m};
vec2 uv = uvFromFlat(${h}, ${f}, index);
return sampleTexture(${n}, uv);
}
2021-09-16 14:30:50 +02:00
`}function Eu(e){let t=e.name,n=w.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
2021-09-16 14:30:50 +02:00
`}function RX(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=R2(e.shapeInfo.logicalShape,t.logicalShape),c=ht(o),u=o-a,l,d=["x","y","z","w","u","v"];a===0?l="":o<2&&i.length>=1?l="coords = 0;":l=i.map(y=>`coords.${d[y+u]} = 0;`).join(`
2021-09-11 17:11:38 +02:00
`);let p="";o<2&&a>0?p="coords":p=e.shapeInfo.logicalShape.map((y,v)=>`coords.${d[v+u]}`).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,b=w.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!b)h=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(m&&!b)o===1?h=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:h=`
return vec4(outputValue.x);
`;else if(i.length){let y=a-2,v=a-1;i.indexOf(y)>-1&&i.indexOf(v)>-1?h="return vec4(outputValue.x);":i.indexOf(y)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(v)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${s}() {
${c} coords = getOutputCoords();
${l}
vec4 outputValue = get${r}(${p});
${h}
}
2021-09-16 14:30:50 +02:00
`}function PX(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===c&&e.shapeInfo.flatOffset==null&&w.arraysEqual(o,a))return`
2021-09-11 17:11:38 +02:00
float ${s}() {
return sampleTexture(${n}, resultUV);
}
2021-09-16 14:30:50 +02:00
`;let u=ht(c),l=R2(e.shapeInfo.logicalShape,t.logicalShape),d=c-i,p,h=["x","y","z","w","u","v"];i===0?p="":c<2&&l.length>=1?p="coords = 0;":p=l.map(m=>`coords.${h[m+d]} = 0;`).join(`
2021-09-11 17:11:38 +02:00
`);let f="";return c<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+d]}`).join(", "),`
float ${s}() {
${u} coords = getOutputCoords();
${p}
return get${r}(${f});
}
2021-09-16 14:30:50 +02:00
`}function ht(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function Rw(e,t,n){let{newShape:r,keptDims:s}=w.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):r,c=!e&&a>1&&!w.arraysEqual(t,n)&&r.length<a||o;return{useSqueezeShape:c,uniformShape:c?i:t,keptDims:s}}function Au(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Du(e,t){return t.map(n=>e[n]).join(", ")}function OX(e,t,n,r){let s=n.map((v,x)=>{let k={logicalShape:v.shape,texShape:v.isUniform?null:v.texData.texShape,isUniform:v.isUniform,isPacked:v.isUniform?!1:v.texData.isPacked,flatOffset:null};return v.texData!=null&&v.texData.slice!=null&&v.texData.slice.flatOffset>0&&(k.flatOffset=v.texData.slice.flatOffset),{name:t.variableNames[x],shapeInfo:k}}),a=s.map(v=>v.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=eX(s,o,t),c=e.createProgram(i),u=null,l=e.getUniformLocation(c,"NAN",!1);Q().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(c,"INFINITY",!1));let d=!1,p={},h={},f={};for(let v=0;v<t.variableNames.length;v++){let x=t.variableNames[v];p[x]=e.getUniformLocation(c,x,d),p[`offset${x}`]=e.getUniformLocation(c,`offset${x}`,d),t.enableShapeUniforms&&(h[`${x}Shape`]=e.getUniformLocation(c,`${x}Shape`,d),f[`${x}TexShape`]=e.getUniformLocation(c,`${x}TexShape`,d))}let m,g,b;t.enableShapeUniforms&&(m=e.getUniformLocation(c,"outShape",d),b=e.getUniformLocation(c,"outShapeStrides",d),g=e.getUniformLocation(c,"outTexShape",d));let y=[];return t.customUniforms&&t.customUniforms.forEach((v,x)=>{y[x]=e.getUniformLocation(c,v.name,d)}),{program:t,source:i,webGLProgram:c,uniformLocations:p,customUniformLocations:y,inShapeInfos:a,outShapeInfo:o,infLoc:u,nanLoc:l,inShapesLocations:h,inTexShapesLocations:f,outShapeLocation:m,outShapeStridesLocation:b,outTexShapeLocation:g}}function M2(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,r)=>{let s=n.logicalShape,a=t[r],o=a.shape;if(!w.arraysEqual(s,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${o} must match`);if(n.isUniform&&a.isUniform)return;let i=n.texShape,c=a.isUniform?null:a.texData.texShape;if(!w.arraysEqual(i,c))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${c} must match`)})}function MX(e,t,n,r,s){t.program.enableShapeUniforms||(M2(t.inShapeInfos,n),M2([t.outShapeInfo],[r]));let a=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a,o[0],o[1]):e.setOutputMatrixTexture(a,o[0],o[1]),e.setProgram(t.webGLProgram),Q().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((c,u)=>{let l=t.program.variableNames[u],d=t.uniformLocations[l],p=t.uniformLocations[`offset${l}`],h=t.inShapesLocations[`${l}Shape`],f=t.inTexShapesLocations[`${l}TexShape`];if(h){let{uniformShape:m}=Rw(t.program.packedInputs,c.shape,c.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,c.texData.texShape[0],c.texData.texShape[1]),d!=null){if(c.isUniform){if(w.sizeFromShape(c.shape)<2)e.gl.uniform1f(d,c.uniformValues[0]);else{let m=c.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(d,m)}return}c.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,c.texData.slice.flatOffset),e.setInputMatrixTexture(c.texData.texture,d,u)}});let i=t.outShapeLocation;if(i)switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(r
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2021-09-29 15:32:30 +02:00
${this.enableShapeUniforms?pm(["r","c","d"],e):mi(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${t.output} = result;
}
2021-09-16 14:30:50 +02:00
`}},zX=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Fd.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=In();this.outputShape=e,this.enableShapeUniforms=gr(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2021-09-29 15:32:30 +02:00
${this.enableShapeUniforms?pm(["r","c","d"],e):mi(["r","c","d"],e)}
2021-09-11 17:11:38 +02:00
return ivec3(r, c, d);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
${t.output} = result;
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},WX=class{constructor(e){this.variableNames=["A"],this.outTexUsage=fr.DOWNLOAD;let t=In();this.outputShape=e,this.userCode=`
${F2}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
2021-09-16 14:30:50 +02:00
`}},VX=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=fr.DOWNLOAD;let t=In();this.outputShape=e,this.userCode=`
${F2}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
2021-09-16 14:30:50 +02:00
`}},UX=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=In();this.outputShape=e,this.enableShapeUniforms=gr(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode=`
${this.enableShapeUniforms?Fw():$w(e)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = idiv(flatIndex, 4, 1.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
vec4 values = ${n.texture2D}(A, uv);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${n.output} = vec4(${r}, 0., 0., 0.);
}
2021-09-16 14:30:50 +02:00
`}},GX=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=In();this.outputShape=e,this.enableShapeUniforms=gr(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let o=0;o<=1;o++){let i=a*2+o;r+=`
2021-09-11 17:11:38 +02:00
localCoords = coords;
if(localCoords[2] + ${o} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
localCoords[2] += ${o};
if (localCoords[1] + ${a} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
localCoords[1] += ${a};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
flatIndex = idiv(flatIndex, 4, 1.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
values = ${n.texture2D}(A, uv);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (offset == 0) {
result[${i}] = values[0];
} else if (offset == 1) {
result[${i}] = values[1];
} else if (offset == 2) {
result[${i}] = values[2];
} else {
result[${i}] = values[3];
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
`}this.userCode=`
2021-09-16 14:30:50 +02:00
${this.enableShapeUniforms?Fw():$w(e)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${r}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${n.output} = ${s};
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},L2={};Re(L2,{bindVertexProgramAttributeStreams:()=>q2,createBufferFromOutputTexture:()=>Y2,createFloat16MatrixTexture:()=>U2,createFloat16PackedMatrixTexture:()=>j2,createFloat32MatrixTexture:()=>V2,createIndexBuffer:()=>W2,createPackedMatrixTexture:()=>H2,createUnsignedBytesMatrixTexture:()=>G2,createVertexBuffer:()=>z2,createVertexShader:()=>B2,downloadByteEncodedFloatMatrixFromOutputTexture:()=>J2,downloadFloat32MatrixFromBuffer:()=>Z2,downloadMatrixFromPackedOutputTexture:()=>eN,downloadPackedMatrixFromBuffer:()=>Q2,getInternalFormatForFloat16MatrixTexture:()=>Ow,getInternalFormatForFloat16PackedMatrixTexture:()=>Bw,getInternalFormatForFloat32MatrixTexture:()=>Pw,getInternalFormatForPackedMatrixTexture:()=>Lw,getInternalFormatForUnsignedBytesMatrixTexture:()=>Mw,uploadDenseMatrixToTexture:()=>K2,uploadPixelDataToTexture:()=>X2});function B2(e){let t=In(),n=`${t.version}
2021-09-11 17:11:38 +02:00
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
2021-09-29 15:32:30 +02:00
}`;return d2(e,n)}function z2(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 m2(e,t)}function W2(e){let t=new Uint16Array([0,1,2,2,1,3]);return g2(e,t)}function Ld(e,t,n,r,s,a){y2(t,n);let o=b2(e),i=e.TEXTURE_2D;return xe(e,()=>e.bindTexture(i,o)),xe(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),xe(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),xe(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),xe(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),xe(e,()=>e.texImage2D(i,0,r,t,n,0,s,a,null)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function Pw(e){return e.internalFormatFloat}function V2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,Pw(r),r.textureFormatFloat,e.FLOAT)}function Ow(e){return e.internalFormatHalfFloat}function U2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,Ow(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function Mw(e){return e.downloadTextureFormat}function G2(e,t,n,r){let[s,a]=Rd(t,n);return Ld(e,s,a,Mw(r),e.RGBA,e.UNSIGNED_BYTE)}function Lw(e){return e.internalFormatPackedFloat}function H2(e,t,n,r){let[s,a]=Tu(t,n);return Ld(e,s,a,Lw(r),e.RGBA,e.FLOAT)}function Bw(e){return e.internalFormatPackedHalfFloat}function j2(e,t,n,r){let[s,a]=Tu(t,n);return Ld(e,s,a,Bw(r),e.RGBA,r.textureTypeHalfFloat)}function q2(e,t,n){let r=0,s=3*4,a=3*4+2*4;return xe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),_w(e,t,"clipSpacePos",n,3,a,r)&&_w(e,t,"uv",n,2,a,s)}function K2(e,t,n,r,s,a){xe(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,i,c;s instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,c=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,c=a.internalFormatPackedFloat),o.set(s),xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,c,n,r,0,e.RGBA,i,o)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function X2(e,t,n){xe(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):xe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),xe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Y2(e,t,n,r){let s=e.createBuffer();xe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));let i=4*4*t*n;return xe(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),xe(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),xe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function Z2(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 J2(e,t,n,r){let[s,a]=Rd(t,n),o=4,i=new Uint8Array(BK(t*n,o));return xe(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function Q2(e,t,n,r,s,a,o,i){let c=e,u=new Float32Array(zK(a,o));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,u),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),u}function eN(e,t,n){let r=new Float32Array(t*n*4);return xe(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}var tN=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=Q().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,c2(t,e)):this.gl=ps(t);let n="WEBGL_color_buffer_float",r="EXT_color_buffer_half_float";if(Q().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Pd(this.gl,s),mr(this.gl,a))this.textureHalfFloatExtension=Pd(this.gl,a);else if(Q().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),mr(this.gl,r))this.colorBufferHalfFloatExtension=Pd(this.gl,r);else if(Q().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",mr(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(mr(this.gl,r))this.
2021-09-11 17:11:38 +02:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2021-09-16 14:30:50 +02:00
`;else{let n=Sn("rc",t),r=ht(t),s=F7(t,e,n),a=R7(t,e[e.length-1],e[e.length-2],n),o=P7(e,n);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} rc = getOutputCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(${s}) {
setOutput(vec4(0));
} else {
${a}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(vec4(${o}));
2021-04-01 19:39:54 +02:00
}
}
2021-09-16 14:30:50 +02:00
`}}};function $7(e,t){let n=[];for(let r=0;r<=1;r++)for(let s=0;s<=1;s++){let a=`${r===0?"r":"rp1"}, ${s===0?"c":"cp1"}`;for(let o=2;o<e;o++)a=`${t[t.length-1-o]},`+a;n.push(a)}return n}function F7(e,t,n){if(e===1)return`rc > ${t[0]}`;let r="";for(let s=e-2;s<e;s++)r+=`${n[s]} >= ${t[s]}`,s<e-1&&(r+="||");return r}function R7(e,t,n,r){if(e===1)return"";let s=r.slice(-2);return`
2021-09-11 17:11:38 +02:00
int r = ${s[0]};
int c = ${s[1]};
int rp1 = r + 1;
int cp1 = c + 1;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
bool cEdge = cp1 >= ${t};
bool rEdge = rp1 >= ${n};
2021-09-16 14:30:50 +02:00
`}function P7(e,t){let n=e.length,r=$7(n,t);return n===1?`getA(rc),
2021-09-11 17:11:38 +02:00
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${r[0]}),
cEdge ? 0. : getA(${r[1]}),
rEdge ? 0. : getA(${r[2]}),
2021-09-16 14:30:50 +02:00
rEdge || cEdge ? 0. : getA(${r[3]})`}var oN=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=gr(this.outputShape.length);let n="";for(let r=0;r<4;r++){let s="thisRC = rc;";r%2==1&&(s+="thisRC.z += 1;"),r>1&&(s+="thisRC.y += 1;"),n+=`
2021-09-11 17:11:38 +02:00
${s}
${r>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result[${r}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${r>0?"}":""}
`}this.userCode=`
2021-09-16 14:30:50 +02:00
${O7(t,this.enableShapeUniforms)}
${this.enableShapeUniforms?Fw():$w(e)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 rc = getOutputCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0.);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 thisRC;
int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${n}
2021-04-01 19:39:54 +02:00
setOutput(result);
}
2021-09-16 14:30:50 +02:00
`}};function O7(e,t){return`
2021-09-11 17:11:38 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
2021-09-29 15:32:30 +02:00
${t?QK(["r","c","d"],"inputShape"):mi(["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-29 15:32:30 +02:00
`}var M7=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=cN(t,n),s=uN(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=iN(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let i=this.freeTextures[s].shift();return this.usedTextures[s].push(i),i}let o;return r===on.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===on.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===on.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===on.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===on.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(e,t,n,r){if(this.freeTextures==null)return;let s=cN(n,r),a=uN(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);let o=iN(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=Q().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let c=this.usedTextures[a],u=c.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");c.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function L7(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function iN(e,t,n,r,s){let a=B7(t,r),o;if(s){let[c,u]=Tu(e[0],e[1]);o=c*u}else{let[c,u]=Rd(e[0],e[1]);o=c*u}let i=L7(n,a);return o*i}function B7(e,t){switch(e){case on.PACKED_2X2_FLOAT32:return Lw(t);case on.PACKED_2X2_FLOAT16:return Bw(t);case on.UNPACKED_FLOAT32:return Pw(t);case on.UNPACKED_FLOAT16:return Ow(t);case on.PACKED_4X1_UNSIGNED_BYTE:return Mw(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function z7(e){return Q().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?on.PACKED_2X2_FLOAT32:on.UNPACKED_FLOAT32:e?on.PACKED_2X2_FLOAT16:on.UNPACKED_FLOAT16}function cN(e,t){if(e===fr.UPLOAD)return on.PACKED_2X2_FLOAT32;if(e===fr.RENDER||e==null)return z7(t);if(e===fr.DOWNLOAD||e===fr.PIXELS)return on.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function uN(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var Ia=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=gr(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
float unaryOperation(float x) {
${t}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
2021-09-11 17:11:38 +02:00
setOutput(y);
}
2021-09-16 14:30:50 +02:00
`}},Hr="if (isnan(x)) return x;",W7="return x;",lN="return abs(x);",V7="return (x >= 0.0) ? x : (exp(x) - 1.0);",U7=Hr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : x;
2021-09-16 14:30:50 +02:00
`,G7=Hr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2021-09-16 14:30:50 +02:00
`,hm="return x;",H7="return 1.0 / (1.0 + exp(-1.0 * x));",j7="return x;",q7=`
2021-09-11 17:11:38 +02:00
vec4 result;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2021-09-16 14:30:50 +02:00
`,K7=`
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2021-09-16 14:30:50 +02:00
`,X7=`
2021-09-11 17:11:38 +02:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
return result;
2021-09-16 14:30:50 +02:00
`,Y7="return 1.0 / (1.0 + exp(-1.0 * x));",$u=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=gr(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
vec4 unaryOperation(vec4 x) {
${t}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},Z7=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=Sn("rc",t),r=ht(t),s=A7(t,n),a=n.slice(-2),o=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} rc = getOutputCoords();
vec4 packedInput = getA(${s});
setOutput(getChannel(packedInput, ${o}));
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}},J7=as.whereImpl,Q7=1e-7,e9=1e-4,fm={};function t9(e){return e in fm||(fm[e]={}),fm[e]}var n9=Q().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),r9=600;function s9(){return Q().global.screen==null?1024:Q().global.screen.height*Q().global.screen.width*window.devicePixelRatio*r9/1024/1024}var mm=class extends bl{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Q().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=ps(Q().getNumber("WEBGL_VERSION"));this.binaryCache=t9(Q().getNumber("WEBGL_VERSION")),this.gpgpu=new tN(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new M7(this.gpgpu),this.numMBBeforeWarning=s9(),this.texData=new Dp(this,Cs())}nextDataId(){return mm.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((Q().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Q().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:fr.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,r,s){if(Q().getBool("DEBUG")&&this.checkNumericalProblems(t),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:fr.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 $u(o,hm):d=new Ia(o,hm);let p=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:r}],r),h=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return n;let c=this.activeTimers!=null,u;c&&(u=w.now());let l;if(r==="complex64"){let d=this.readSync(s.real.dataId),p=this.readSync(s.imag.dataId);l=_.mergeRealAndImagArrays(d,p)}else l=this.getValuesFromTexture(e);return c&&(this.downloadWaitMs+=w.now()-u),this.convertAndCacheOnCPU(e,l)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(s!=null){let h;i?h=new $u(r,hm):h=new Ia(r,hm);let f=this.runWebGLProgram(h,[{dataId:e,shape:r,dtype:a}],a),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(n!=null)return this.convertAndCacheOnCPU(e);if(!Q().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&Q().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let c=null,u;if(a!=="complex64"&&Q().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let h=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(h.texture,...am(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let l;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];l=_.mergeRealAndImagArrays(f,m)}else if(c==null)l=this.getValuesFromTexture(e);else{let h=w.sizeFromShape(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,h)}if(u!=null&&this.disposeIntermediateTensorInfo(u),c!=null){let h=this.gpgpu.gl;xe(h,()=>h.deleteBuffer(c))}let d=this.convertAndCacheOnCPU(e,l),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(h=>h(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Cs().remo
2021-09-11 17:11:38 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2021-09-16 14:30:50 +02:00
`,Fu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=gr(this.outputShape.length),this.userCode=`
2021-09-11 17:11:38 +02:00
float binaryOperation(float a, float b) {
${e}
2021-04-01 19:39:54 +02:00
}
void main() {
2021-09-11 17:11:38 +02:00
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
2021-09-16 14:30:50 +02:00
`}},gm=`
2021-09-11 17:11:38 +02:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2021-09-16 14:30:50 +02:00
`,Bd=class{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length;this.enableShapeUniforms=gr(s);let a="";if(r)if(s===0||w.sizeFromShape(this.outputShape)===1)a=`
2021-09-11 17:11:38 +02:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else if(a=`
2021-09-16 14:30:50 +02:00
${ht(s)} coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
`,s===1)this.enableShapeUniforms?a+=`
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`:a+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
2021-09-16 14:30:50 +02:00
`;else{let i=Sn("coords",s);this.enableShapeUniforms?a+=`
2021-09-11 17:11:38 +02:00
bool nextRowOutOfBounds =
(${i[s-2]} + 1) >= outShape[${s} - 2];
bool nextColOutOfBounds =
(${i[s-1]} + 1) >= outShape[${s} - 1];
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`:a+=`
bool nextRowOutOfBounds =
(${i[s-2]} + 1) >= ${this.outputShape[s-2]};
bool nextColOutOfBounds =
(${i[s-1]} + 1) >= ${this.outputShape[s-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = binaryOperation(a, b);
${a}
2021-04-01 19:39:54 +02:00
setOutput(result);
}
2021-09-29 15:32:30 +02:00
`}};function nr(e){let{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var c9={kernelName:ro,backendName:"webgl",kernelFunc:nr};function Sa(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=nr({inputs:{x:r},backend:n}),c=nr({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:c},a}var u9={kernelName:Bp,backendName:"webgl",kernelFunc:Sa},hN="return (a < 0.) ? b * a : a;",fN=`
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2021-09-29 15:32:30 +02:00
`;function l9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=n.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),i=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(fN,s.shape,o.shape):new Fu(hN,s.shape,o.shape),c=n.runWebGLProgram(i,[s,o],s.dtype);return n.disposeIntermediateTensorInfo(o),c}var d9={kernelName:so,backendName:"webgl",kernelFunc:l9},mN="return (a < 0.) ? b * a : a;",gN=`
2021-09-11 17:11:38 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2021-09-29 15:32:30 +02:00
`;function p9(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(gN,r.shape,s.shape):new Fu(mN,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)}var h9={kernelName:yo,backendName:"webgl",kernelFunc:p9},bN="if (isnan(x)) return x;",f9=`
2021-09-11 17:11:38 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2021-09-16 14:30:50 +02:00
`,m9=`
2021-09-11 17:11:38 +02:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2021-09-29 15:32:30 +02:00
`;function Xe({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{let{x:o}=s,i=a,c=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let d=i.texData.get(o.dataId),p=n(d.values,c);return i.makeTensorInfo(o.shape,c,p)}let u=Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,l;return u?l=new $u(o.shape,t):l=new Ia(o.shape,e),i.runWebGLProgram(l,[o],c)}}function cn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:o,backend:i})=>{let{a:c,b:u}=o,l=i;if(r&&c.dtype==="complex64"){let f=l.texData.get(c.dataId),m=l.texData.get(u.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(v=>{let[x,k]=v,C={dataId:x.dataId,dtype:x.dtype,shape:c.shape},N={dataId:k.dataId,dtype:k.dtype,shape:u.shape},$=new Fu(e,c.shape,u.shape);return l.runWebGLProgram($,[C,N],kr(x.dtype,k.dtype))}),y=Sa({inputs:{real:g,imag:b},backend:l});return l.disposeIntermediateTensorInfo(g),l.disposeIntermediateTensorInfo(b),y}let d=a||kr(c.dtype,u.dtype);if((c.dtype==="string"||u.dtype==="string"||l.shouldExecuteOnCPU([c,u]))&&s!=null){let f=l.texData.get(c.dataId).values,m=l.texData.get(u.dataId).values,g=c.dtype==="string"?_.fromUint8ToStringArray(f):f,b=c.dtype==="string"?_.fromUint8ToStringArray(m):m,[y,v]=s(c.shape,u.shape,g,b,d),x=l.makeTensorInfo(v,d),k=l.texData.get(x.dataId);return k.values=y,x}let p=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new Bd(t,c.shape,u.shape,n):h=new Fu(e,c.shape,u.shape),l.runWebGLProgram(h,[c,u],d)}}function bm(e,t=!1){if(e==="linear")return t?j7:W7;if(e==="relu")return t?K7:U7;if(e==="elu")return t?q7:V7;if(e==="relu6")return t?X7:G7;if(e==="prelu")return t?gN:mN;if(e==="leakyrelu")return t?fN:hN;if(e==="sigmoid")return t?Y7:H7;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var yN=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=gr(this.outputShape.length);let u=r?e[1]:e[2],l=Math.ceil(u/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=s?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m=`vec4 activation(vec4 a) {
2021-09-11 17:11:38 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
}`:c?m=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${o}
}`:m=`vec4 activation(vec4 x) {
${o}
}`,g="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),c&&this.variableNames.push("leakyreluAlpha");let y="rc.x",v="rc.x";e[0]<t[0]?y=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(v=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
${m}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${l}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${l}; i++) {
int batchA = ${y};
int batchB = ${v};
vec4 a = getMatrixA(batchA, ${d});
vec4 b = getMatrixB(batchB, ${p});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${h[0]} * ${f[0]});
result += (${h[1]} * ${f[1]});
}
return result;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${b}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${g}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(result);
}
2021-09-16 14:30:50 +02:00
`}},vN={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},xN=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.assertAndGetBroadcastShape(t,n),this.userCode=`
2021-09-11 17:11:38 +02:00
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
2021-09-29 15:32:30 +02:00
`}},wN="return a * b;";function Ww(e){let{inputs:t,backend:n}=e,{a:r,b:s}=t,a=_.upcastType(r.dtype,s.dtype);if(r.dtype==="complex64"){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),u=new xN(vN.REAL,r.shape,s.shape),l=new xN(vN.IMAG,r.shape,s.shape),d=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:r.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape}],p=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(l,d,"float32"),f=Sa({inputs:{real:p,imag:h},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}if(n.shouldExecuteOnCPU([r,s])){let i=n.texData.get(r.dataId),c=n.texData.get(s.dataId),[u,l]=d7(r.shape,s.shape,i.values,c.values,a),d=n.makeTensorInfo(l,a),p=n.texData.get(d.dataId);return p.values=u,d}let o;return Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?o=new Bd(wN,r.shape,s.shape):o=new Fu(wN,r.shape,s.shape),n.runWebGLProgram(o,[r,s],a)}var g9={kernelName:fo,backendName:"webgl",kernelFunc:Ww};function b9(e,t,n){let r=[hi(e.shape),...fi(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[hi(t),...fi(t)],o=new oN(a,r),i=!0,c=[r],u=n.runWebGLProgram(o,[s],e.dtype,c,i);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function be(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=n,i=w.sizeFromShape(s.shape),c=w.inferFromImplicitShape(a,i),u=w.sizeFromShape(c);w.assert(i===u,()=>`The new shape (${c}) has ${u} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let l=o.texData.get(s.dataId);return l.isPacked&&!Md(s.shape,c)&&!(l.texture!==null&&Md(l.shape,c))?b9(s,c,o):(o.incRef(s.dataId),{dataId:s.dataId,shape:c,dtype:s.dtype})}var y9={kernelName:Rc,backendName:"webgl",kernelFunc:be},kN=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o=Math.floor(n/4)*4,i=n%4,c="sumValue += dot(values, ones);";if(t!=null){let l=1/t;c=`sumValue += dot(values * ${w.isInt(l)?l.toPrecision(2):l}, ones);`}let u="";s%n>0&&(u=`
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) {
${u}
return getX(batch, inIdx);
2021-04-01 19:39:54 +02:00
}
void main() {
2021-09-11 17:11:38 +02:00
ivec2 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
int batch = coords[0];
2021-09-11 17:11:38 +02:00
int outIdx = coords[1];
int inOffset = outIdx * ${n};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float sumValue = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${o}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${c}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + ${o};
if (${i===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${c}
} else if (${i===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${c}
} else if (${i===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${c}
}
setOutput(sumValue);
}
2021-09-16 14:30:50 +02:00
`}},v9=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let c=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?c="sumValue":t==="prod"?c="prodValue":t==="all"?c="allValue":t==="any"&&(c="anyValue");let u=Math.floor(n/4)*4,l=n%4,d=`
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;
for (int i = 0; i < ${u}; i += 4) {
int inIdx = inOffset + i;
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + ${u};
if (${l===1}) {
${p} values = ${p}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
} else if (${l===2}) {
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
} else if (${l===3}) {
${p} values = ${p}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
}
setOutput(${c});
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function x9(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 bi(e,t,n,r){let s=x9(e.shape),a=e;for(let o=0;o<s.length;o++){let{inSize:i,windowSize:c,outSize:u}=s[o],l,d;n==="mean"?l=o===0?new kN({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u},i):new kN({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u}):l=new v9({windowSize:c,inSize:i,batchSize:e.shape[0],outSize:u},n),d=a,a=r.runWebGLProgram(l,[a],t),d.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(d)}return a}var w9=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];this.outputShape=n,this.rank=n.length;let r=ht(this.rank),s=k9(t);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} resRC = getOutputCoords();
setOutput(getA(${s}));
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}};function k9(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 I9=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let u=0;u<n.length;u++)n[u]=e[t[u]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let r=ht(this.rank),s=aN("rc",this.rank),a=new Array(this.rank);for(let u=0;u<t.length;u++)a[t[u]]=s[u];let o=`vec2(${a.slice(-2).join()})`,i=`++${s[this.rank-1]} < ${n[this.rank-1]}`,c=`getChannel(getA(${a.join()}), ${o})`;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${c};
if(${i}) {
result[1] = ${c};
}
2021-09-11 17:11:38 +02:00
--${s[this.rank-1]};
if(++${s[this.rank-2]} < ${n[this.rank-2]}) {
result[2] = ${c};
if(${i}) {
result[3] = ${c};
}
}
2021-09-11 17:11:38 +02:00
setOutput(result);
}
2021-09-29 15:32:30 +02:00
`}};function ym(e,t,n){let r=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new I9(e.shape,t):new w9(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function S9(e,t,n,r){let s=t,a=e.shape.length,o=w.parseAxisParam(s,e.shape),i=o,c=_.getAxesPermutation(i,a),u=c!=null,l=e;u&&(l=ym(e,c,r),i=_.getInnerMostAxes(i.length,a)),_.assertAxesAreInnerMostDims("sum",i,a);let[d,p]=_.computeOutAndReduceShapes(l.shape,i),h=d;n&&(h=_.expandShapeToKeepDim(d,o));let f=w.sizeFromShape(p),g=w.sizeFromShape(e.shape)/f,b=be({inputs:{x:l},attrs:{shape:[g,f]},backend:r}),y=Ch(e.dtype),v=bi(b,y,"sum",r),x=be({inputs:{x:v},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(v),u&&r.disposeIntermediateTensorInfo(l),x}function vm(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return S9(s,a,o,n)}var C9={kernelName:_o,backendName:"webgl",kernelFunc:vm};function Cn(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,o=n,i=s.shape.length,c=new Array(i);for(let l=0;l<c.length;l++)c[l]=s.shape[a[l]];let u;if(o.shouldExecuteOnCPU([s])){let d=o.texData.get(s.dataId).values,p=zw(d,s.shape,s.dtype,a,c);u=o.makeTensorInfo(c,s.dtype);let h=o.texData.get(u.dataId);h.values=p}else u=ym(s,a,o);return u}var T9={kernelName:Ro,backendName:"webgl",kernelFunc:Cn},IN=1e3;function xm({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:c=null}){let u=e.shape.length,l=t.shape.length,d=n?e.shape[u-2]:e.shape[u-1],p=r?t.shape[l-1]:t.shape[l-2],h=n?e.shape[u-1]:e.shape[u-2],f=r?t.shape[l-2]:t.shape[l-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),b=w.sizeFromShape(m),y=w.sizeFromShape(g),v=b===y||b===1||y===1;w.assert(u>=2&&l>=2&&v,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let k=(b>y?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);w.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`);let C=n?[b,d,h]:[b,h,d],N=r?[y,f,p]:[y,p,f],$=be({inputs:{x:e},backend:s,attrs:{shape:C}}),R=be({inputs:{x:t},backend:s,attrs:{shape:N}}),O=[$,R],D=Math.max(b,y),P=n?$.shape[1]:$.shape[2],T=a!=null,L=o!=null,G=c==="leakyrelu",j=c!=null?bm(c,!0):null,q=T||L||G||j!=null,K;if((h===1||f===1)&&P>IN&&q===!1){let ne=$,re=R;n&&(ne=Cn({inputs:{x:$},backend:s,attrs:{perm:[0,2,1]}}),O.push(ne)),r&&(re=Cn({inputs:{x:R},backend:s,attrs:{perm:[0,2,1]}}),O.push(re));let se=f!==1,J=f===1,ie=ne;se&&(ie=be({inputs:{x:ne},backend:s,attrs:{shape:[D,P,1]}}),O.push(ie));let ue=f===1?2:1,le=re;J&&(le=be({inputs:{x:re},backend:s,attrs:{shape:[D,1,P]}}),O.push(le));let me=Ww({inputs:{a:ie,b:le},backend:s});K=vm({inputs:{x:me},backend:s,attrs:{axis:ue,keepDims:!0}}),O.push(me)}else{let ne=kr(e.dtype,t.dtype),re=new yN(C,N,[D,h,f],n,r,T,j,L,G),se=[$,R];if(a!=null&&se.push(a),L&&se.push(o),G){let J=s.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));se.push(J),O.push(J)}K=s.runWebGLProgram(re,se,ne)}let te=be({inputs:{x:K},backend:s,attrs:{shape:k}});O.push(K);for(let ne of O)s.disposeIntermediateTensorInfo(ne);return te}function N9(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:c,transposeB:u,activation:l,leakyreluAlpha:d}=r;return xm({a:s,b:a,transposeA:c,transposeB:u,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:l})}var _9={kernelName:Po,backendName:"webgl",kernelFunc:N9},SN="return abs(x);";function E9(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=rN(a.values);return n.makeTensorInfo(r.shape,r.dtype,o)}let s;return Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new $u(r.shape,SN):s=new Ia(r.shape,SN),n.runWebGLProgram(s,[r],r.dtype)}var A9={kernelName:Xi,backendName:"webgl",kernelFunc:E9},D9=Hr+`
2021-09-11 17:11:38 +02:00
if (abs(x) > 1.) {
return NAN;
}
2021-09-11 17:11:38 +02:00
return acos(x);
2021-09-16 14:30:50 +02:00
`,$9=Xe({opSnippet:D9}),F9={kernelName:Yi,backendName:"webgl",kernelFunc:$9},R9=Hr+`
2021-09-11 17:11:38 +02:00
if (x < 1.0) return NAN;
2021-09-29 15:32:30 +02:00
return log(x + sqrt(x * x - 1.0));`,P9=Xe({opSnippet:R9}),O9={kernelName:Zi,backendName:"webgl",kernelFunc:P9},CN="return a + b;",M9=cn({opSnippet:CN,packedOpSnippet:CN,supportsComplex:!0,cpuKernelImpl:jX}),L9={kernelName:Js,backendName:"webgl",kernelFunc:M9},B9=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let n=[];this.variableNames.forEach(s=>{n.push(`float v${s} = get${s}AtOutCoords();`)});let r=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${n.join(`
`)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result = ${r};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},z9=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let n=[];this.variableNames.forEach(s=>{n.push(`vec4 v${s} = get${s}AtOutCoords();`)});let r=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${n.join(`
`)}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = ${r};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function wm(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return nr({inputs:{x:r[0]},backend:n});if(r.length>Q().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),u=wm({inputs:r.slice(0,c),backend:n}),l=wm({inputs:r.slice(c),backend:n});return wm({inputs:[u,l],backend:n})}let s=r.map(c=>c.dtype).reduce((c,u)=>kr(c,u)),a=r.map(c=>c.shape),i=Q().getBool("WEBGL_PACK")?new z9(r[0].shape,a):new B9(r[0].shape,a);return n.runWebGLProgram(i,r,s)}var W9={kernelName:La,backendName:"webgl",kernelFunc:wm};function V9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=_.getAxesPermutation(u,i),d=s;l!=null&&(d=Cn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=_.getInnerMostAxes(u.length,i)),_.assertAxesAreInnerMostDims("all",u,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,u),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=bi(m,m.dtype,"all",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(d),b}var U9={kernelName:Ji,backendName:"webgl",kernelFunc:V9};function G9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=_.getAxesPermutation(u,i),d=s;l!=null&&(d=Cn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=_.getInnerMostAxes(u.length,i)),_.assertAxesAreInnerMostDims("any",u,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,u),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=bi(m,m.dtype,"any",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(d),b}var H9={kernelName:Qi,backendName:"webgl",kernelFunc:G9},j9=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let o=t==="max"?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${r};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${r}; i++) {
int inIdx = ${i};
float candidate = getA(batch, inIdx);
if (candidate ${o} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(float(bestIndex));
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},q9=class{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,c=ht(i),u=Sn("coords",i),l,d;if(a===1){d=i+1;let N=ht(d);l=`
2021-09-11 17:11:38 +02:00
${N} sourceLocR = ${N}(${u.join()}, 0);
++${u[i-1]};
${N} sourceLocG = ${N}(${u.join()}, 0);
++${u[i-2]};
${N} sourceLocA = ${N}(${u.join()}, 0);
--${u[i-1]};
${N} sourceLocB = ${N}(${u.join()}, 0);
--${u[i-2]};`}else d=i,l=`
${c} sourceLocR = coords;
++${u[i-1]};
${c} sourceLocG = coords;
++${u[i-2]};
${c} sourceLocA = coords;
--${u[i-1]};
${c} sourceLocB = coords;
2021-09-16 14:30:50 +02:00
--${u[i-2]};`;let p=["x","y","z","w","u","v"].slice(0,d),h="."+p[d-1],f=p.map(N=>"int "+N),m=Sn("sourceLocR",d-1).concat("inIdx.r"),g=Sn("sourceLocG",d-1).concat("inIdx.g"),b=Sn("sourceLocB",d-1).concat("inIdx.b"),y=Sn("sourceLocA",d-1).concat("inIdx.a"),v=n==="max"?"greaterThan":"lessThan",x=r?"":`
2021-09-11 17:11:38 +02:00
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${b.join()}),
getBestIndicesAChannel(${y.join()})));`,k=`vec4(
getAChannel(${m.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${b.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${y.join()}) : 0.)`,C=r?"":`
float getBestIndicesAChannel(${f.join()}) {
return getChannel(getBestIndicesA(${p.join()}),
vec2(${p.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${f.join()}) {
return getChannel(getA(${p.join()}),
vec2(${p.slice(-2).join()}));
}
${C}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
${c} coords = getOutputCoords();
bool hasNextCol = ${u[i-1]} < ${o[i-1]-1};
bool hasNextRow = ${u[i-2]} < ${o[i-2]-1};
${l}
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
sourceLocB${h}, sourceLocA${h}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${k};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${x}
vec4 candidate = ${k};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${v}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(bestIndex);
}
2021-09-29 15:32:30 +02:00
`}};function TN(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 j9(i,n,r==null),u=[t];r!=null&&u.push(r);let l=e.runWebGLProgram(c,u,"int32");if(l.shape[1]===1)return l;let d=TN(e,t,n,l);return e.disposeIntermediateTensorInfo(l),d}function NN(e,t,n,r=null){let s=r!=null?r.shape:t.shape,a=s[s.length-1],o=_.computeOptimalWindowSize(a),i=new q9(s,o,n,r==null),c=r==null?[t]:[t,r],u=e.runWebGLProgram(i,c,"int32");if(u.shape.length===t.shape.length){let l=NN(e,t,n,u);return e.disposeIntermediateTensorInfo(u),l}return u}function _N(e,t,n,r){let s=[n];if(_.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!Q().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let a=[],o=e.texData.get(t.dataId),i=o!==null&&o.isPacked,c=t;i&&(c=e.unpackTensor(t),a.push(c));let[u,l]=_.computeOutAndReduceShapes(c.shape,s),d=w.sizeFromShape(l),p=be({inputs:{x:c},backend:e,attrs:{shape:[-1,d]}});a.push(p);let h=TN(e,p,r);a.push(h);let f=be({inputs:{x:h},backend:e,attrs:{shape:u}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return NN(e,t,r)}function K9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,u=[];i!=null&&(c=Cn({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMax",[o[0]],c.shape.length);let l=_N(n,c,o[0],"max");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),l}var X9={kernelName:Ba,backendName:"webgl",kernelFunc:K9};function Y9(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=_.getAxesPermutation(o,s.shape.length),c=s,u=[];i!=null&&(c=Cn({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(c),o=_.getInnerMostAxes(o.length,c.shape.length)),_.assertAxesAreInnerMostDims("argMin",[o[0]],c.shape.length);let l=_N(n,c,o[0],"min");return u.forEach(d=>n.disposeIntermediateTensorInfo(d)),l}var Z9={kernelName:xl,backendName:"webgl",kernelFunc:Y9},J9=Hr+`
2021-09-11 17:11:38 +02:00
if (abs(x) > 1.) {
2021-04-01 19:39:54 +02:00
return NAN;
}
2021-09-11 17:11:38 +02:00
return asin(x);
2021-09-16 14:30:50 +02:00
`,Q9=Xe({opSnippet:J9}),eY={kernelName:ec,backendName:"webgl",kernelFunc:Q9},tY=Hr+"return log(x + sqrt(x * x + 1.0));",nY=Xe({opSnippet:tY}),rY={kernelName:tc,backendName:"webgl",kernelFunc:nY},sY=Hr+`
2021-09-11 17:11:38 +02:00
return atan(x);
2021-09-16 14:30:50 +02:00
`,aY=Xe({opSnippet:sY}),oY={kernelName:nc,backendName:"webgl",kernelFunc:aY},iY=f9+`
2021-09-11 17:11:38 +02:00
return atan(a, b);
2021-09-16 14:30:50 +02:00
`,cY=`
2021-09-11 17:11:38 +02:00
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2021-09-16 14:30:50 +02:00
`+m9+`
2021-09-11 17:11:38 +02:00
return result;
2021-09-16 14:30:50 +02:00
`,uY=cn({opSnippet:iY,packedOpSnippet:cY}),lY={kernelName:sc,backendName:"webgl",kernelFunc:uY},dY=Hr+`
2021-09-11 17:11:38 +02:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2021-09-16 14:30:50 +02:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,pY=Xe({opSnippet:dY}),hY={kernelName:rc,backendName:"webgl",kernelFunc:pY},zd=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,c=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(f||(b="-1.0 / 1e-20"),n){let N=">=";this.userCode=`
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-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${l};
wR += ${c}) {
int xR = xRCorner + wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${d};
wC += ${u}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${N} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${r?s?m:g:`wR * ${d} + wC`};
}
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(float(minMaxPosition));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;return}let y="max",v=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(v="avgValue / count");let x=Math.floor(a/4)*4,k=a%4,C=`
if (${f}) {
avgValue += dot(values, ones);
2021-04-01 19:39:54 +02:00
} else {
2021-09-11 17:11:38 +02:00
minMaxValue = ${y}(values, minMaxValue);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;this.userCode=`
const ivec2 strides = ivec2(${o}, ${i});
const ivec2 pads = ivec2(${p}, ${h});
const float initializationValue = ${b};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int batch = coords[0];
2021-04-01 19:39:54 +02:00
int d = coords[3];
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${b});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${l};
wR += ${c}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${x}; wC += 4) {
int xC = xCCorner + wC * ${u};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
getValue(batch, xR, xC + 2 * ${u}, d),
getValue(batch, xR, xC + 3 * ${u}, d)
);
${C}
}
int xC = xCCorner + ${x};
if (${k===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${C}
} else if (${k===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
initializationValue,
initializationValue
);
${C}
} else if (${k===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
getValue(batch, xR, xC + 2 * ${u}, d),
initializationValue
);
${C}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput(${v});
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},Vw=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,c=e.strideWidth,u=e.dilationDepth,l=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let y=t==="avg",v="0.0";if(y||(v="-1.0 / 1e-20"),n){let R=">=";this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec3 strides =
ivec3(${o}, ${i}, ${c});
const ivec3 pads = ivec3(${m}, ${g}, ${b});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wD = 0; wD < ${p};
wD += ${u}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${h};
wR += ${l}) {
int xR = xRCorner + wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${f};
wC += ${d}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${R} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${r?s?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} +
wR * ${f} + wC`};
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput(float(minMaxPosition));
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`;return}let x="max",k=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(k="avgValue / count");let C=Math.floor(a/4)*4,N=a%4,$=`
2021-09-11 17:11:38 +02:00
if (${y}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${x}(values, minMaxValue);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`;this.userCode=`
const ivec3 strides =
ivec3(${o}, ${i}, ${c});
const ivec3 pads = ivec3(${m}, ${g}, ${b});
const float initializationValue = ${v};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${v});
float avgValue = 0.0;
count = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wD = 0; wD < ${p};
wD += ${u}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${h};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${C}; wC += 4) {
int xC = xCCorner + wC * ${d};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
getValue(batch, xD, xR, xC + 3 * ${d}, ch)
);
2021-09-16 14:30:50 +02:00
${$}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
int xC = xCCorner + ${C};
if (${N===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
2021-09-16 14:30:50 +02:00
${$}
2021-09-11 17:11:38 +02:00
} else if (${N===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
initializationValue,
initializationValue
);
2021-09-16 14:30:50 +02:00
${$}
2021-09-11 17:11:38 +02:00
} else if (${N===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-16 14:30:50 +02:00
${$}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput(${k});
2021-04-01 19:39:54 +02:00
}
}
2021-09-29 15:32:30 +02:00
`}};function fY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Nu(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,u=1;w.assert(_.eitherStridesOrDilationsAreOne(o,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let l=_.computePool2DInfo(s.shape,a,o,u,i,c);if(l.filterWidth===1&&l.filterHeight===1&&w.arraysEqual(l.inShape,l.outShape))return nr({inputs:{x:s},backend:n});let d=new zd(l,"avg",!1);return n.runWebGLProgram(d,[s],"float32")}var mY={kernelName:za,backendName:"webgl",kernelFunc:fY};function gY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:c,dataFormat:u}=r,l=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,l,i,c,u),p=new Vw(d,"avg",!1);return n.runWebGLProgram(p,[s],"float32")}var bY={kernelName:wl,backendName:"webgl",kernelFunc:gY},yY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=i-1-e.padInfo.top,l=c-1-e.padInfo.left,d=1/(t*n);this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${u}, ${l});
const float avgMultiplier = float(${d});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${i};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${r}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
int idyR = int(dyR);
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${c};
wC+= ${o}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier;
2021-04-01 19:39:54 +02:00
}
}
setOutput(dotProd);
}
2021-09-16 14:30:50 +02:00
`}},vY=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=l-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`
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-09-11 17:11:38 +02:00
for (int wD = 0; wD < ${l};
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
int idyD = int(dyD);
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${d};
wR += ${c}) {
float dyR = float(dyRCorner + wR) / ${a}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p};
wC += ${u}) {
float dyC = float(dyCCorner + wC) / ${o}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
2021-04-01 19:39:54 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2021-09-11 17:11:38 +02:00
dotProd += dyValue * avgMultiplier;
2021-04-01 19:39:54 +02:00
}
}
}
setOutput(dotProd);
}
2021-09-29 15:32:30 +02:00
`}};function xY(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:u,dimRoundingMode:l}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,u,l),h=new vY(p);return n.runWebGLProgram(h,[s],o.dtype)}var wY={kernelName:Mp,backendName:"webgl",kernelFunc:xY};function kY(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Nu([s,a],"avgPoolGrad");let{filterSize:i,strides:c,pad:u}=r,l=_.computePool2DInfo(o.shape,i,c,1,u),d=new yY(l);return n.runWebGLProgram(d,[s],o.dtype)}var IY={kernelName:Op,backendName:"webgl",kernelFunc:kY};function SY(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return xm({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var CY={kernelName:Wa,backendName:"webgl",kernelFunc:SY},TY=class{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let o="0.0";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";s!=null&&(_.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${o};
float scale = ${i};
float inv = scale * inversesqrt(variance + float(${a}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},NY=class{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";r!=null&&(_.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";s!=null&&(_.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
vec4 offset = ${o};
vec4 scale = ${i};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput((x - mean) * inv + offset);
}
2021-09-29 15:32:30 +02:00
`}},_Y=({inputs:e,backend:t,attrs:n})=>{let{x:r,mean:s,variance:a,offset:o,scale:i}=e;w.assert(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(o==null||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(i==null||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:c}=n;c==null&&(c=.001);let u=[r,s,a],l=null;o!=null&&(l=o.shape,u.push(o));let d=null;i!=null&&(d=i.shape,u.push(i));let p=Q().getBool("WEBGL_PACK_NORMALIZATION")?new NY(r.shape,s.shape,a.shape,l,d,c):new TY(r.shape,s.shape,a.shape,l,d,c);return t.runWebGLProgram(p,u,u[0].dtype)},EY={kernelName:to,backendName:"webgl",kernelFunc:_Y},AY=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=ht(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=DY(this.rank),r,s=e.map((a,o)=>`sourceLoc.${Uw[o]} = start[${o}] + coords.${Uw[o]};`);r=`
2021-09-11 17:11:38 +02:00
${t} sourceLoc;
${t} coords = getOutputCoords();
${s.join(`
`)}
`,this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
${r}
setOutput(getSource(${n}));
}
2021-09-16 14:30:50 +02:00
`}},Uw=["x","y","z","w","u","v"];function DY(e){if(e===1)return"sourceLoc";if(e<=6)return Uw.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var $Y=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=ht(this.rank),n=Sn("coords",this.rank),r=Sn("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,o=`
2021-09-11 17:11:38 +02:00
result.x = ${a};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${r[this.rank-1]};
result.y = ${a};
--${r[this.rank-1]};
}
`,i=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
++${r[this.rank-2]};
result.z = ${a};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${r[this.rank-1]};
result.w = ${a};
}
}
`,c=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((u,l)=>`start[${l}]`).join()});`:e.map((u,l)=>`${r[l]} = ${n[l]} + start[${l}];`).join(`
`);this.userCode=`
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${c}
vec4 result = vec4(0.);
${o}
${i}
setOutput(result);
}
2021-09-29 15:32:30 +02:00
`}};function FY(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=vn.computeFlatOffset(t,w.computeStrides(e.shape));s.slice&&(i+=s.slice.flatOffset),o.slice={flatOffset:i,origDataId:s.slice&&s.slice.origDataId||e.dataId};let c=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,c+1),a}function Ru(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,c]=vn.parseSliceParams(s,a,o);if(vn.assertParamsValid(s,i,c),w.sizeFromShape(c)===0)return n.makeTensorInfo(c,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||s.dtype==="string"){let d=n.texData.get(s.dataId),p=y7(d.values,i,c,s.shape,s.dtype);return n.makeTensorInfo(c,s.dtype,p)}let{isPacked:u}=n.texData.get(s.dataId),l=vn.isSliceContinous(s.shape,i,c);if(u||!l){let d=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new $Y(c):new AY(c),p=[i];return n.runWebGLProgram(d,[s],s.dtype,p)}return n.uploadToGPU(s.dataId),FY(s,i,c,n)}var RY={kernelName:Lc,backendName:"webgl",kernelFunc:Ru},PY=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;w.assert(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,v)=>y*v),c=_.getReshaped(s.shape,a,i),u=_.getPermuted(c.length,a.length),l=_.getReshapedPermuted(s.shape,a,i),d=_.getSliceBeginCoords(o,a.length),p=_.getSliceSize(l,o,a.length),h=[],f=be({inputs:{x:s},backend:n,attrs:{shape:c}}),m=Cn({inputs:{x:f},backend:n,attrs:{perm:u}}),g=be({inputs:{x:m},backend:n,attrs:{shape:l}}),b=Ru({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},OY={kernelName:ac,backendName:"webgl",kernelFunc:PY};function MY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.readSync(s.dataId),c=n.readSync(a.dataId),u=nN(i,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}var LY={kernelName:Lp,backendName:"webgl",kernelFunc:MY},BY="return float(a != b);",EN=cn({opSnippet:BY,cpuKernelImpl:h7,dtype:"bool"}),zY={kernelName:Tc,backendName:"webgl",kernelFunc:EN};function Wd(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return nr({inputs:{x:s.complexTensorInfos.real},backend:n})}var WY={kernelName:oh,backendName:"webgl",kernelFunc:Wd},VY="return float(int(x));";function UY(e,t){let n=new Ia(e.shape,VY),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function Gw(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return nr({inputs:{x:s},backend:n});let o=It(s.shape),i=Gw({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),c=Sa({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),c}if(s.dtype==="complex64"){let o=Wd({inputs:{input:s},backend:n}),i=Gw({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=nr({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return UY(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),c=EN({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 GY={kernelName:Va,backendName:"webgl",kernelFunc:Gw},AN="return ceil(x);",HY=Xe({opSnippet:AN,packedOpSnippet:AN,cpuKernelImpl:KX}),jY={kernelName:Ua,backendName:"webgl",kernelFunc:HY},qY=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(clamp(value, minVal, maxVal));
}
2021-09-16 14:30:50 +02:00
`}},KY=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
vec4 value = getAAtOutCoords();
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (any(isnan(value))) {
setOutput(value);
return;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
2021-09-29 15:32:30 +02:00
`}};function XY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i;Q().getBool("WEBGL_PACK_CLIP")?i=new KY(s.shape):i=new qY(s.shape);let c=[[a],[o]];return n.runWebGLProgram(i,[s],s.dtype,c)}var YY={kernelName:Qs,backendName:"webgl",kernelFunc:XY},ZY=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
2021-09-16 14:30:50 +02:00
`}};function DN(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function JY(e){let{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new ZY(r.shape),o=[DN(r,s.complexTensorInfos.real),DN(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var QY={kernelName:kl,backendName:"webgl",kernelFunc:JY},eZ=class{constructor(e){this.outputShape=[],this.outputShape=_.computeOutShape(e,1),this.variableNames=e.map((a,o)=>`T${o}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let o=t[a-1];n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${o}));`)}let r=t.length,s=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${s}));`),this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${n.join(`
`)}
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},tZ=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=ht(r),a=Sn("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((f,m)=>`T${m}`);let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let c=o[t],u=o.slice(-2),l=o.join(),d=`if (${c} < ${i[0]}) {
2021-09-11 17:11:38 +02:00
return getChannel(
getT0(${l}), vec2(${u.join()}));
}`;for(let f=1;f<i.length;f++){let m=i[f-1];d+=`
if (${c} < ${i[f]} && ${c} >= ${i[f-1]}) {
return getChannel(
2021-09-16 14:30:50 +02:00
getT${f}(${km(o,c,m)}),
vec2(${km(u,c,m)}));
2021-09-11 17:11:38 +02:00
}`}let p=i.length,h=i[i.length-1];d+=`
return getChannel(
2021-09-16 14:30:50 +02:00
getT${p}(${km(o,c,h)}),
vec2(${km(u,c,h)}));`,this.userCode=`
2021-09-11 17:11:38 +02:00
float getValue(${o.map(f=>"int "+f)}) {
${d}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
${s} coords = getOutputCoords();
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
${a[r-1]} = ${a[r-1]} + 1;
if (${a[r-1]} < ${n[r-1]}) {
result.g = getValue(${a});
}
${a[r-2]} = ${a[r-2]} + 1;
if (${a[r-2]} < ${n[r-2]}) {
result.a = getValue(${a});
}
${a[r-1]} = ${a[r-1]} - 1;
if (${a[r-2]} < ${n[r-2]} &&
${a[r-1]} < ${n[r-1]}) {
result.b = getValue(${a});
}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function km(e,t,n){let r=e.indexOf(t);return e.map((a,o)=>o===r?`${a} - ${n}`:a).join()}function Im(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return nr({inputs:{x:s.complexTensorInfos.imag},backend:n})}var nZ={kernelName:Qp,backendName:"webgl",kernelFunc:Im};function Pu(e,t,n){let r=e[0].dtype;if(r==="complex64"){let l=e.map(m=>Wd({inputs:{input:m},backend:n})),d=e.map(m=>Im({inputs:{input:m},backend:n})),p=Pu(l,t,n),h=Pu(d,t,n),f=Sa({inputs:{real:p,imag:h},backend:n});return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),d.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}let s=n.shouldExecuteOnCPU(e);if(r==="string"&&(s=!0),s){let l=e.map(b=>{let y=w.sizeFromShape(b.shape.slice(t));return be({inputs:{x:b},backend:n,attrs:{shape:[-1,y]}})}),d=l.map(b=>({vals:n.readSync(b.dataId),shape:b.shape})),p=_.computeOutShape(l.map(b=>b.shape),1),h=l[0].shape[0]===1,f=XX(d,p,r,h),m=_.computeOutShape(e.map(b=>b.shape),t),g=n.makeTensorInfo(m,r,f);return l.forEach(b=>n.disposeIntermediateTensorInfo(b)),g}if(e.length>Q().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(e.length/2),d=Pu(e.slice(0,l),t,n),p=Pu(e.slice(l),t,n),h=Pu([d,p],t,n);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),h}if(Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let l=new tZ(e.map(d=>d.shape),t);return n.runWebGLProgram(l,e,r)}let{tensors2D:a,outShape:o}=rZ(e,t,n),i=new eZ(a.map(l=>l.shape)),c=n.runWebGLProgram(i,a,r);a.forEach(l=>n.disposeIntermediateTensorInfo(l));let u=be({inputs:{x:c},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(c),u}function rZ(e,t,n){let r=_.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>be({inputs:{x:a},attrs:{shape:[-1,w.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:r}}function $N(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=_.computeOutShape(t.map(u=>u.shape),a);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(u=>w.sizeFromShape(u.shape)>0);if(i.length===1)return nr({inputs:{x:i[0]},backend:n});let c=i.map(u=>u.shape);return _.assertParamsConsistent(c,a),Pu(i,a,n)}var sZ={kernelName:oc,backendName:"webgl",kernelFunc:$N},FN=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,c=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,b=m?2:3,y=m?3:1,v="",x="";n&&(r?v=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?v=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}`:v=`
float activation(float x) {
${n}
}
`,x="result = activation(result);");let k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${v}
const ivec2 strides = ivec2(${i}, ${c});
const ivec2 pads = ivec2(${a}, ${o});
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int batch = coords[0];
int d2 = coords[${y}];
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
ivec2 xRCCorner =
ivec2(coords[${g}], coords[${b}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${d}; wR++) {
int xR = xRCorner + wR * ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p}; wC++) {
int xC = xCCorner + wC * ${l};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
if (${f===1}) {
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
dotProd +=
getX(batch, xR, xC, ${h}) *
getW(wR, wC, ${h}, d2);
} else {
dotProd +=
getX(batch, ${h}, xR, xC) *
getW(wR, wC, ${h}, d2);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
} else if (${f===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
} else if (${f===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2),
getW(wR, wC, ${h} + 2, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${m}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1),
getX(batch, xR, xC, ${h} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC),
getX(batch, ${h} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd;
${k}
${x}
setOutput(result);
}
2021-09-16 14:30:50 +02:00
`}},aZ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,c=e.dilationHeight,u=e.dilationWidth,l=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
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;
for (int wF = 0; wF < ${l}; wF++) {
int xF = xFCorner + wF * ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${d}; wR++) {
int xR = xRCorner + wR * ${c};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${p}; wC++) {
int xC = xCCorner + wC * ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d1 = 0; d1 < ${h}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${f===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${h}) *
getW(wF, wR, wC, ${h}, d2);
} else if (${f===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${h}),
getX(batch, xF, xR, xC, ${h} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${h}, d2),
getW(wF, wR, wC, ${h} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${f===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${h}),
getX(batch, xF, xR, xC, ${h} + 1),
getX(batch, xF, xR, xC, ${h} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${h}, d2),
getW(wF, wR, wC, ${h} + 1, d2),
getW(wF, wR, wC, ${h} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},oZ=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=gr(this.outputShape.length);let{dataFormat:n}=t,r=In(),s=n==="channelsLast",a=s?0:1,o=s?1:2,i=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`,c="";for(let u=0;u<=1;u++)for(let l=0;l<=1;l++)c+=`
2021-09-11 17:11:38 +02:00
blockIndex = rc.y + ${l};
pos = rc.x + ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${i}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(d0 < inputShape[${a}] && d0 >= 0) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
inChannels);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if(d1 < inputShape[${o}] && d1 >= 0) {
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
ch = imod(pos, inChannels);
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
if (${s}) {
innerDims = vec2(d1, ch);
result[${u*2+l}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${u*2+l}] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
2021-04-30 18:01:04 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec2 rc = getOutputCoords();
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
vec4 result = vec4(0);
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
${c}
2021-04-30 18:01:04 +02:00
2021-09-11 17:11:38 +02:00
${r.output} = result;
2021-04-30 18:01:04 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function RN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let c=e.shape,u=r.texData.get(e.dataId),l=n.inChannels,d=c[0]*c[1]*c[2],p=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,b=[];if(!((d===1||p===1)&&l>IN)&&u.isPacked&&h&&u.texture!=null&&c[2]%2!=0&&w.arraysEqual(u.shape.slice(-3),c.slice(-3))){let x=c[0]*c[1]*(c[2]+1),k={dataId:e.dataId,shape:[1,x,n.inChannels],dtype:e.dtype},C=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,w.assert(Md(u.shape,k.shape),()=>`packed reshape ${u.shape} to ${k.shape} isn't free`);let N=be({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});b.push(N);let $=xm({a:k,b:N,backend:r,transposeA:f,transposeB:m,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),R=r.texData.get($.dataId);w.assert(R.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=C,R.shape=n.outShape,g=nr({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],k=be({inputs:{x:e},backend:r,attrs:{shape:[1,x,n.inChannels]}}),C=be({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),N=xm({a:k,b:C,transposeA:f,transposeB:m,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=be({inputs:{x:N},backend:r,attrs:{shape:n.outShape}}),b.push(k),b.push(C),b.push(N)}for(let x of b)r.disposeIntermediateTensorInfo(x);return g}function PN({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:c,filterHeight:u,inChannels:l,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=c*u*l,g=p*d,b=[m,g],y=!0,v=!1,x=[],k=be({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),C=be({inputs:{x:t},backend:r,attrs:{shape:[1,m,w.sizeFromShape(t.shape)/m]}});x.push(k),x.push(C);let N=new oZ(b,n),$=[k.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],R=r.runWebGLProgram(N,[k],"float32",$),O=be({inputs:{x:R},backend:r,attrs:{shape:[1,b[0],b[1]]}});x.push(R),x.push(O);let D=s!=null,P=a!=null,T=i==="leakyrelu",L=i?bm(i,!0):null,G=new yN(O.shape,C.shape,[1,g,n.outChannels],y,v,D,L,P,T),j=[O,C];if(s&&j.push(s),P&&j.push(a),T){let ne=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));j.push(ne),x.push(ne)}let q=r.runWebGLProgram(G,j,"float32"),K=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],te=be({inputs:{x:q},backend:r,attrs:{shape:K}});x.push(q);for(let ne of x)r.disposeIntermediateTensorInfo(ne);return te}function iZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:c,dilations:u,dimRoundingMode:l}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,a.shape,o,u,i,l,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=RN({x:s,filter:a,convInfo:p,backend:n});else if(Q().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)h=PN({x:s,filter:a,convInfo:p,backend:n});else{let m=new FN(p);h=n.runWebGLProgram(m,[s,a],"float32")}let f=be({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var cZ={kernelName:Ga,backendName:"webgl",kernelFunc:iZ},uZ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
ivec4 coords = getOutputCoords();
2021-09-11 17:11:38 +02:00
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${r};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${s};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${a}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput(dotProd);
}
2021-09-16 14:30:50 +02:00
`}},lZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,c=a?1:2,u=a?2:3,l=a?3:1;this.userCode=`
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];
int d1 = coords[${l}];
ivec2 dyCorner = ivec2(coords[${c}], coords[${u}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
int idyR = int(dyR);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = ${t} - 1 - wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
2021-04-01 19:39:54 +02:00
continue;
}
2021-09-11 17:11:38 +02:00
int idyC = int(dyC);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = ${n} - 1 - wC;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (${a}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},dZ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${s};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${n} - ${a};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${r} - ${o};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
2021-04-01 19:39:54 +02:00
}
}
}
2021-09-11 17:11:38 +02:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},pZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,c=n-1-e.padInfo.top,u=r-1-e.padInfo.left;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3(${i}, ${c}, ${u});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${s}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${n} - 1 - wR;
for (int wC = 0; wC < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${r} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
2021-04-01 19:39:54 +02:00
}
}
2021-09-11 17:11:38 +02:00
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function hZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:c,dimRoundingMode:u,filterShape:l}=r,d=_.convertConv2DDataFormat(c),p=_.computeConv2DInfo(s.shape,l,o,1,i,u,!1,d),h=new uZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var fZ={kernelName:zp,backendName:"webgl",kernelFunc:hZ};function mZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:c,dataFormat:u,dimRoundingMode:l}=r,d=_.convertConv2DDataFormat(u),p=_.computeConv2DInfo(o,a.shape,i,1,c,l,!1,d),h=new lZ(p);return n.runWebGLProgram(h,[s,a],"float32")}var gZ={kernelName:Ha,backendName:"webgl",kernelFunc:mZ};function bZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,u=_.computeConv3DInfo(s.shape,a.shape,o,c,i),l=new aZ(u);return n.runWebGLProgram(l,[s,a],"float32")}var yZ={kernelName:Il,backendName:"webgl",kernelFunc:bZ};function vZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:c}=r,u=_.computeConv3DInfo(s.shape,c,o,1,i),l=new dZ(u);return n.runWebGLProgram(l,[s,a],"float32")}var xZ={kernelName:Wp,backendName:"webgl",kernelFunc:vZ};function wZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:c}=r,u=_.computeConv3DInfo(c,a.shape,i,1,o),l=new pZ(u);return n.runWebGLProgram(l,[s,a],"float32")}var kZ={kernelName:Vp,backendName:"webgl",kernelFunc:wZ},IZ=bN+`
2021-09-11 17:11:38 +02:00
return cos(x);
2021-09-29 15:32:30 +02:00
`,SZ=Xe({opSnippet:IZ}),CZ={kernelName:ja,backendName:"webgl",kernelFunc:SZ},TZ=`
2021-09-11 17:11:38 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2021-09-29 15:32:30 +02:00
`,NZ=Xe({opSnippet:TZ}),_Z={kernelName:qa,backendName:"webgl",kernelFunc:NZ},EZ=class{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,c]=e,[u]=t,[l,d]=n;this.outputShape=[u,l,d,c];let p=r==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,b]=l>1?[`${(o-1)/(l-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[y,v,x]=d>1?[`${(i-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`
2021-09-11 17:11:38 +02:00
const float height_ratio = float(${m});
const float width_ratio = float(${y});
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${a}) {
return;
2021-04-01 19:39:54 +02:00
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
float height_scale = ${g};
float width_scale = ${v};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float in_y = ${b};
if( in_y < 0.0 || in_y > ${h} ) {
setOutput(float(${s}));
return;
}
float in_x = ${x};
if( in_x < 0.0 || in_x > ${f} ) {
setOutput(float(${s}));
return;
}
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${p} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},AZ=e=>{let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:c,extrapolationValue:u}=r,l=new EZ(s.shape,a.shape,i,c,u);return n.runWebGLProgram(l,[s,a,o],"float32")},DZ={kernelName:ic,backendName:"webgl",kernelFunc:AZ},ON=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(${MN(r,"coords")})`,a=e[e.length-1],o="",i="";t?(o=n?`end != ${a-1}`:"end != 0",i=n?"end + 1":"end - 1"):(o=n?`end + pow2 < ${a}`:"end >= pow2",i=n?"end + pow2":"end - pow2"),this.userCode=`
2021-04-01 19:39:54 +02:00
void main() {
2021-09-16 14:30:50 +02:00
${ht(r)} coords = getOutputCoords();
int end = ${LN(r,"coords")};
2021-09-11 17:11:38 +02:00
float val = ${s};
int pow2 = int(pow(2.0, index));
if (${o}) {
int idx = ${i};
2021-09-16 14:30:50 +02:00
${LN(r,"coords")} = idx;
val += getX(${MN(r,"coords")});
2021-09-11 17:11:38 +02:00
}
setOutput(val);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function MN(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 LN(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 $Z(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,c=s.shape.length,u=_.getAxesPermutation([a],c),l=s;u!=null&&(l=Cn({inputs:{x:s},backend:n,attrs:{perm:u}}));let d=_.getInnerMostAxes(1,c)[0];if(d!==c-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${s.shape.length-1} but got axis=${a}`);let p=l.shape[d],h=nr({inputs:{x:l},backend:n});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new ON(l.shape,!1,i),g=[[f]],b=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(b)}if(o){let f=new ON(l.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(u!=null){let f=_.getUndoAxesPermutation(u),m=Cn({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(l),m}return h}var FZ={kernelName:Ka,backendName:"webgl",kernelFunc:$Z};function RZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let c=n.readSync(s.dataId),u=n.readSync(a.dataId),l=nN(c,u,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,l)}else if(s.shape.length===2){let c=n.bufferSync(s),u=n.bufferSync(a),l=qX(c,u,o,i);return n.makeTensorInfo(l.shape,a.dtype,l.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}var PZ={kernelName:Up,backendName:"webgl",kernelFunc:RZ},OZ=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function MZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r;w.assert(a>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${a}`);let i=s.shape[0],c=o==="NHWC"?s.shape[1]:s.shape[2],u=o==="NHWC"?s.shape[2]:s.shape[3],l=o==="NHWC"?s.shape[3]:s.shape[1],d=c*a,p=u*a,h=l/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=new OZ(f,a,o);return n.runWebGLProgram(m,[s],s.dtype)}var LZ={kernelName:cc,backendName:"webgl",kernelFunc:MZ},BN=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=gr(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,c="",u="";n&&(r?c=`float activation(float a) {
2021-09-11 17:11:38 +02:00
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?c=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}`:c=`
float activation(float x) {
${n}
}
`,u="result = activation(result);");let l=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${c}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${i};
int q = d2 - d1 * ${i};
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${a}; wR++) {
int xR = xRCorner + wR * dilations[0];
if (xR < 0 || xR >= inDims[0]) {
continue;
}
for (int wC = 0; wC < ${o}; wC++) {
int xC = xCCorner + wC * dilations[1];
if (xC < 0 || xC >= inDims[1]) {
continue;
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
float result = dotProd;
${l}
${u}
setOutput(result);
}
2021-09-16 14:30:50 +02:00
`}},zN=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=gr(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,c=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,d=l,p=`
2021-09-11 17:11:38 +02:00
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<l;g++)p+=`
vec4 xTexelC${g*2};
int xTexelC${g*2}Ready;
vec4 xTexelC${g*2+1};
int xTexelC${g*2+1}Ready;
vec4 xC${g};`;for(let g=0;g<u;g++){for(let b=0;b<l;b++)p+=`
xTexelC${b*2} = vec4(0.0);
xTexelC${b*2}Ready = 0;
xTexelC${b*2+1} = vec4(0.0);
xTexelC${b*2+1}Ready = 0;
xC${b} = vec4(0.0);`;p+=`
xR = xRCorner + ${g} * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;for(let b=0;b<(d+1)/2;b++){let y=b*2;if(p+=`
xC = xCCorner + ${y*c};
`,i===1){if(y<l&&(o%2==1?(p+=`
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
`,c===1&&y>0?p+=`
xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy);
`:p+=`
xCOffset = xC + 1 - 2;
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
2021-07-29 15:05:49 +02:00
2021-09-11 17:11:38 +02:00
xC${y} = vec4(previous.zw, xTexelC${y}.xy);
2021-04-01 19:39:54 +02:00
} else {
2021-09-11 17:11:38 +02:00
xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);
}
`):p+=`
if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
xC${y} = xTexelC${y};
`,y+1<l)){let v=o%2==0?w.nearestLargerEven(c):c;c%2==0&&o%2==1||c%2!=0&&o%2!=1?(p+=`
xCOffset = xC + imod(pads[1], 2) + ${v};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xTexelC${y+1}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
`,c>1&&(p+=`
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
xTexelC${y}Ready = 1;
}
`),p+=`
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);
`):v===1?p+=`
xC${y+1} = xTexelC${y};
`:p+=`
xCOffset = xC + ${v};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
}
xTexelC${y+1}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xC${y+1} = xTexelC${y+1};
`}}else y<l&&(o%2==1?(p+=`
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xTexelC${y}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xC + 1, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xTexelC${y+1}Ready = 1;
}
xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
`,y+1<l&&(p+=`
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy);
`)):(p+=`
if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xTexelC${y}Ready = 1;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.);
}
xTexelC${y+1}Ready = 1;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
xC${y} = vec4(
xTexelC${y}.xy, xTexelC${y+1}.xy);
`,y+1<l&&(p+=`
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
`)));y<l&&(p+=`
wTexel = getW(${g}, ${y}, d1, q);
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
`,y+1<l&&(p+=`
wTexel = getW(${g}, ${y+1}, d1, q);
dotProd += xC${y+1} * vec4(wTexel.xz, wTexel.xz);
`))}p+=`
}
`}let h="",f="";n&&(r?h=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:s?h=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${n}
}`:h=`vec4 activation(vec4 x) {
${n}
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${h}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${a};
int q = d2 - d1 * ${a};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${p}
vec4 result = dotProd - vec4(0.000000000000001);
${m}
${f}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function BZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c,dimRoundingMode:u}=r,l=c;l==null&&(l=[1,1]),w.assert(_.eitherStridesOrDilationsAreOne(o,l),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`);let d=_.computeConv2DInfo(s.shape,a.shape,o,l,i,u,!0),p;Q().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels==1?p=new zN(d):p=new BN(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 zZ={kernelName:Xa,backendName:"webgl",kernelFunc:BZ},WZ=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${a} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${r};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${s};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},VZ=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${a}, ${o});
2021-04-01 19:39:54 +02:00
void main() {
2021-09-11 17:11:38 +02:00
ivec4 coords = getOutputCoords();
2021-04-01 19:39:54 +02:00
int batch = coords[0];
2021-09-11 17:11:38 +02:00
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float dotProd = 0.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${r}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wRPerm = ${t} - 1 - wR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
int wCPerm = ${n} - 1 - wC;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${i}; dm++) {
int d2 = d1 * ${i} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
2021-09-16 14:30:50 +02:00
`}};function UZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:u,filterShape:l}=r,d=_.computeConv2DInfo(s.shape,l,o,i,c,u,!0),p=new WZ(d);return n.runWebGLProgram(p,[s,a],"float32")}var GZ={kernelName:Gp,backendName:"webgl",kernelFunc:UZ};function HZ(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:c,dimRoundingMode:u,inputShape:l}=r,d=_.computeConv2DInfo(l,a.shape,o,i,c,u,!0),p=new VZ(d);return n.runWebGLProgram(p,[s,a],"float32")}var jZ={kernelName:Hp,backendName:"webgl",kernelFunc:HZ},qZ=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
2021-09-16 14:30:50 +02:00
`}};function KZ(e){let{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=w.sizeFromShape(r.shape),o=be({inputs:{x:r},backend:n,attrs:{shape:[a]}}),i=new qZ(a),c=n.runWebGLProgram(i,[o],o.dtype),u=be({inputs:{x:c},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(c),u}var XZ={kernelName:jp,backendName:"webgl",kernelFunc:KZ},YZ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:c,dilationWidth:u}=e,{top:l,left:d}=r;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 strides = ivec2(${s}, ${a});
const ivec2 pads = ivec2(${l}, ${d});
const float neg_infinity = -3.4e38;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.w;
ivec2 outTopLeftCorner =
coords.yz * strides - pads;
int hBeg = outTopLeftCorner.x;
int wBeg = outTopLeftCorner.y;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
float curVal = neg_infinity;
for (int h = 0; h < ${o}; h++) {
int hIn = hBeg + h * ${c};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if (hIn >= 0 && hIn < ${t}) {
for (int w = 0; w < ${i}; w++) {
int wIn = wBeg + w * ${u};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (wIn >= 0 && wIn < ${n}) {
float xVal = getX(batch, hIn, wIn, d1);
float wVal = getW(h, w, d1);
float val = xVal + wVal;
if (val > curVal) {
curVal = val;
}
}
}
}
2021-07-29 15:05:49 +02:00
}
2021-09-11 17:11:38 +02:00
float result = curVal;
setOutput(result);
2021-07-29 15:05:49 +02:00
}
2021-09-16 14:30:50 +02:00
`}};function ZZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:c}=r,u=_.computeDilation2DInfo(s.shape,a.shape,o,i,"NHWC",c),l,d=new YZ(u);l=n.runWebGLProgram(d,[s,a],"float32");let p=be({inputs:{x:l},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(l),p}var JZ={kernelName:Sl,backendName:"webgl",kernelFunc:ZZ};function QZ(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:c}=_.decodeEinsumEquation(s,a.length);_.checkEinsumDimSizes(o.length,c,a);let{path:u,steps:l}=_.getEinsumComputePath(i,c),d=l.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of l[m]){let{permutationIndices:b,expandDims:y}=_.getEinsumPermutation(h,c[g]),v;_.isIdentityPermutation(b)?v=a[g]:(v=Cn({inputs:{x:a[g]},backend:n,attrs:{perm:b}}),f.push(v));let x=v.shape.slice();for(let k=0;k<y.length;++k)x.splice(y[k],0,1);w.arraysEqual(v.shape,x)||(v=be({inputs:{x:v},backend:n,attrs:{shape:x}}),f.push(v)),p===null?p=v:(p=Ww({inputs:{a:v,b:p},backend:n}),f.push(p))}m<d-1&&(u[m]>=0&&(p=vm({inputs:{x:p},backend:n,attrs:{axis:u[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var eJ={kernelName:Xp,backendName:"webgl",kernelFunc:QZ},tJ="return (x >= 0.0) ? x : (exp(x) - 1.0);",nJ=`
2021-09-11 17:11:38 +02:00
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
2021-09-29 15:32:30 +02:00
`,rJ=Xe({opSnippet:tJ,packedOpSnippet:nJ}),sJ={kernelName:Za,backendName:"webgl",kernelFunc:rJ},aJ="return (b >= 1.0) ? a : a * (b + 1.0);",oJ=`
2021-09-11 17:11:38 +02:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
2021-09-16 14:30:50 +02:00
`,iJ=e=>{let{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=Q().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bd(oJ,r.shape,s.shape):new Fu(aJ,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)},cJ={kernelName:Yp,backendName:"webgl",kernelFunc:iJ},uJ=`
2021-09-11 17:11:38 +02:00
return vec4(equal(a, b));
2021-09-16 14:30:50 +02:00
`,lJ="return float(a == b);",dJ=cn({opSnippet:lJ,packedOpSnippet:uJ,dtype:"bool",cpuKernelImpl:YX}),pJ={kernelName:lc,backendName:"webgl",kernelFunc:dJ},hJ=`
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.
float p = ${_.ERF_P};
float a1 = ${_.ERF_A1};
float a2 = ${_.ERF_A2};
float a3 = ${_.ERF_A3};
float a4 = ${_.ERF_A4};
float a5 = ${_.ERF_A5};
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
2021-09-29 15:32:30 +02:00
`,fJ=Xe({opSnippet:hJ}),mJ={kernelName:uc,backendName:"webgl",kernelFunc:fJ},WN="return exp(x);",VN=Xe({opSnippet:WN,packedOpSnippet:WN,cpuKernelImpl:ZX}),gJ={kernelName:Ja,backendName:"webgl",kernelFunc:VN};function Hw(e){let{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),c=s;return s<0&&(w.assert(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),c=o+s+1),i.splice(c,0,1),be({inputs:{x:a},backend:r,attrs:{shape:i}})}var bJ={kernelName:dc,backendName:"webgl",kernelFunc:Hw},UN="return exp(x) - 1.0;",yJ=Xe({opSnippet:UN,packedOpSnippet:UN,cpuKernelImpl:JX}),vJ={kernelName:pc,backendName:"webgl",kernelFunc:yJ},GN=class{constructor(e,t,n){this.variableNames=["real","imag"];let r=t[1];this.outputShape=t;let s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${r}.0`:"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
2021-09-11 17:11:38 +02:00
const float exponentMultiplier = ${s};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${o}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${r});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${r}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${a};
}
return result;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function HN(e,t,n){let r=n.texData.get(e.dataId),s=w.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=s/a,i=be({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),c=i.shape,u=new GN("real",c,t),l=new GN("imag",c,t),d=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:c},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:c}],p=n.runWebGLProgram(u,d,"float32"),h=n.runWebGLProgram(l,d,"float32"),f=Sa({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);let m=be({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function xJ(e){let{inputs:t,backend:n}=e,{input:r}=t;return HN(r,!1,n)}var wJ={kernelName:Zp,backendName:"webgl",kernelFunc:xJ},kJ=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
// Input can be obtained from uniform value.
setOutput(value);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}};function Vd(e){let{backend:t,attrs:n}=e,{shape:r,value:s}=n,{dtype:a}=n;if(a=a||w.inferDtype(s),a==="string"){let o=w.getArrayFromDType(a,w.sizeFromShape(r));return o.fill(s),t.makeTensorInfo(r,a,o)}else{let o=new kJ(r,s),i=[[s]];return t.runWebGLProgram(o,[],a,i)}}var IJ={kernelName:Cl,backendName:"webgl",kernelFunc:Vd},SJ=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x - 1;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
2021-09-29 15:32:30 +02:00
`}},CJ={kernelName:hc,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new SJ(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},jN="return floor(x);",TJ=Xe({opSnippet:jN,packedOpSnippet:jN,cpuKernelImpl:QX}),NJ={kernelName:Qa,backendName:"webgl",kernelFunc:TJ},_J=`
2021-09-11 17:11:38 +02:00
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
2021-04-30 18:01:04 +02:00
}
2021-09-16 14:30:50 +02:00
`,EJ=`
2021-09-11 17:11:38 +02:00
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
2021-04-30 18:01:04 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return vec4(result);
2021-09-29 15:32:30 +02:00
`,AJ=cn({opSnippet:_J,packedOpSnippet:EJ,dtype:"int32"}),DJ={kernelName:eo,backendName:"webgl",kernelFunc:AJ},$J=class{constructor(e){this.variableNames=["A"];let t=In(),[n,r]=e;this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
2021-03-31 13:01:22 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(floor(value * 255.0 + 0.5));
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},FJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=In(),[n,r]=e;this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${r}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
2021-03-31 13:01:22 +02:00
}
2021-09-11 17:11:38 +02:00
${t.output} = result;
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}},RJ={kernelName:yh,backendName:"webgl",kernelFunc:PJ},Ou;function PJ(e){let{inputs:t,backend:n,attrs:r}=e,{pixels:s}=t,{numChannels:a}=r,o=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,[c,u]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],l=[u,c],d=[u,c,a];(i||o)&&(Ou==null&&(Ou=document.createElement("canvas").getContext("2d")),Ou.canvas.width=c,Ou.canvas.height=u,Ou.drawImage(s,0,0,c,u),s=Ou.canvas);let p=n.makeTensorInfo(l,"int32");n.texData.get(p.dataId).usage=fr.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),s);let h=Q().getBool("WEBGL_PACK")?new FJ(d):new $J(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function OJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:u,dataFormat:l,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=_.convertConv2DDataFormat(l),g=_.computeConv2DInfo(s.shape,a.shape,c,d,u,p,!1,m),b,y=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))b=RN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(Q().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)b=PN({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let x=o!=null,k=i!=null,C=h==="leakyrelu",N=h?bm(h,!1):null,$=new FN(g,x,N,k,C),R=[s,a];if(o&&R.push(o),i&&R.push(i),C){let O=n.makeTensorInfo([],"float32",w.createScalarValue(f,"float32"));R.push(O),y.push(O)}b=n.runWebGLProgram($,R,"float32")}let v=be({inputs:{x:b},backend:n,attrs:{shape:g.outShape}});return y.push(b),y.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var MJ={kernelName:Oo,backendName:"webgl",kernelFunc:OJ};function LJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:c,pad:u,dilations:l,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=r,f=[],m=l;m==null&&(m=[1,1]),w.assert(_.eitherStridesOrDilationsAreOne(c,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${c} and dilations '${m}'`);let g=_.computeConv2DInfo(s.shape,a.shape,c,m,u,d,!0),b=Q().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,y=p?bm(p,b):null,v=[s,a],x=o!=null,k=i!=null,C=p==="leakyrelu";if(x&&v.push(o),k&&v.push(i),C){let O=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));v.push(O),f.push(O)}let N;b?N=new zN(g,x,y,k,C):N=new BN(g,x,y,k,C);let $=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],R=n.runWebGLProgram(N,v,"float32",$);return f.forEach(O=>n.disposeIntermediateTensorInfo(O)),R}var BJ={kernelName:Mo,backendName:"webgl",kernelFunc:LJ},zJ=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let r=ht(t.length),s=ht(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2021-09-11 17:11:38 +02:00
${r} strides = ${r}(${this.strides});
void main() {
${s} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${a};
}
setOutput(getX(flattenIndex, coords[1]));
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}};function WJ(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,o=a[a.length-1],i=w.sizeFromShape(r.shape),[c,u,l,d]=_.prepareAndValidate(r,s),p=be({inputs:{x:s},backend:n,attrs:{shape:[u,o]}}),h=be({inputs:{x:r},backend:n,attrs:{shape:[w.sizeFromShape(r.shape)/l,l]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let b=n.readSync(s.dataId),y=n.bufferSync(r),v=e7(b,y,r.dtype,u,o,l,d,r.shape,i);return n.makeTensorInfo(c,r.dtype,v.values)}let f=new zJ(o,d,[u,l]),m=n.runWebGLProgram(f,[h,p],h.dtype),g=be({inputs:{x:m},backend:n,attrs:{shape:c}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var VJ={kernelName:mc,backendName:"webgl",kernelFunc:WJ},UJ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=ht(this.rank),r=GJ(e,2);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${r}));
}
2021-09-16 14:30:50 +02:00
`}};function GJ(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let s=0;s<e.length;s++)s===2?r.push("int(getIndices(resRC.x, resRC.z))"):r.push(`${n[s]}`);return r.join()}function qN(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,c=w.parseAxisParam(o,s.shape)[0],u=_.segment_util.collectGatherOpShapeInfo(s,a,c,i),l=w.sizeFromShape(a.shape),d=[],p=be({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=be({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,l/u.batchSize]}});d.push(p),d.push(h);let f=[u.batchSize,u.outerSize,l/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([s,a])||s.dtype==="string"){let y=n.bufferSync(h),v=n.bufferSync(p),x=t7(v,y,f);return d.forEach(k=>n.disposeIntermediateTensorInfo(k)),n.makeTensorInfo(u.outputShape,x.dtype,x.values)}let m=new UJ(p.shape,f),g=n.runWebGLProgram(m,[p,h],p.dtype);d.push(g);let b=be({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return d.forEach(y=>n.disposeIntermediateTensorInfo(y)),b}var HJ={kernelName:fc,backendName:"webgl",kernelFunc:qN},jJ="return float(a > b);",qJ=`
2021-09-11 17:11:38 +02:00
return vec4(greaterThan(a, b));
2021-09-16 14:30:50 +02:00
`,KJ=cn({opSnippet:jJ,packedOpSnippet:qJ,cpuKernelImpl:n7,dtype:"bool"}),XJ={kernelName:gc,backendName:"webgl",kernelFunc:KJ},YJ="return float(a >= b);",ZJ=`
2021-09-11 17:11:38 +02:00
return vec4(greaterThanEqual(a, b));
2021-09-29 15:32:30 +02:00
`,JJ=cn({opSnippet:YJ,packedOpSnippet:ZJ,dtype:"bool",cpuKernelImpl:r7}),QJ={kernelName:no,backendName:"webgl",kernelFunc:JJ};function eQ(e){let{inputs:t,backend:n}=e,{input:r}=t;return HN(r,!0,n)}var tQ={kernelName:Jp,backendName:"webgl",kernelFunc:eQ},nQ="return float(!isnan(x) && !isinf(x));",rQ=Xe({opSnippet:nQ,dtype:"bool"}),sQ={kernelName:bc,backendName:"webgl",kernelFunc:rQ},aQ="return float(isinf(x));",oQ=Xe({opSnippet:aQ,dtype:"bool"}),iQ={kernelName:yc,backendName:"webgl",kernelFunc:oQ},cQ="return float(isnan(x));",uQ=Xe({opSnippet:cQ,dtype:"bool"}),lQ={kernelName:vc,backendName:"webgl",kernelFunc:uQ},dQ="return float(a < b);",pQ=`
2021-09-11 17:11:38 +02:00
return vec4(lessThan(a, b));
2021-09-16 14:30:50 +02:00
`,hQ=cn({opSnippet:dQ,packedOpSnippet:pQ,cpuKernelImpl:s7,dtype:"bool"}),fQ={kernelName:xc,backendName:"webgl",kernelFunc:hQ},mQ="return float(a <= b);",gQ=`
2021-09-11 17:11:38 +02:00
return vec4(lessThanEqual(a, b));
2021-09-16 14:30:50 +02:00
`,bQ=cn({opSnippet:mQ,packedOpSnippet:gQ,cpuKernelImpl:a7,dtype:"bool"}),yQ={kernelName:wc,backendName:"webgl",kernelFunc:bQ};function vQ(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=o7(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var xQ={kernelName:eh,backendName:"webgl",kernelFunc:vQ},wQ=`if (x < 0.0) return NAN;
return log(x);`,kQ=`
2021-09-11 17:11:38 +02:00
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
2021-09-29 15:32:30 +02:00
`,IQ=Xe({opSnippet:wQ,packedOpSnippet:kQ,cpuKernelImpl:i7}),SQ={kernelName:ao,backendName:"webgl",kernelFunc:IQ},CQ="return log(1.0 + x);",TQ=Xe({opSnippet:CQ}),NQ={kernelName:kc,backendName:"webgl",kernelFunc:TQ},_Q="return float(a >= 1.0 && b >= 1.0);",EQ=`
2021-09-11 17:11:38 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2021-09-16 14:30:50 +02:00
`,AQ=cn({opSnippet:_Q,packedOpSnippet:EQ,dtype:"bool"}),DQ={kernelName:Ic,backendName:"webgl",kernelFunc:AQ},$Q="return float(!(x >= 1.0));",FQ=Xe({opSnippet:$Q}),RQ={kernelName:Tl,backendName:"webgl",kernelFunc:FQ},PQ="return float(a >= 1.0 || b >= 1.0);",OQ=`
2021-09-11 17:11:38 +02:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
2021-09-16 14:30:50 +02:00
`,MQ=cn({opSnippet:PQ,packedOpSnippet:OQ,dtype:"bool"}),LQ={kernelName:Nl,backendName:"webgl",kernelFunc:MQ},BQ=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,c=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${c})`:s===1?i=`1.0/(${c})`:i=`exp(log(${c}) * float(-${s}));`,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${a}; j <= ${a}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${o}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
float val = x * ${i};
setOutput(val);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},zQ=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,o=e[3]-1;this.outputShape=e;let i,c=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${c})`:s===1?i=`1.0/(${c})`:i=`exp(log(${c}) * float(-${s}));`,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${a};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${a}; j <= ${a}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
vec4 result = xAtOutputCoords * ${i};
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},WQ=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:c}=r,u=Q().getBool("WEBGL_PACK_NORMALIZATION")?new zQ(s.shape,a,o,i,c):new BQ(s.shape,a,o,i,c);return n.runWebGLProgram(u,[s],s.dtype)},VQ={kernelName:_l,backendName:"webgl",kernelFunc:WQ},UQ=class{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${r}) * norm + float(${n});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${r})
* float(${s})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${s});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
setOutput(result);
2021-03-26 15:26:02 +01:00
}
2021-09-29 15:32:30 +02:00
`}},GQ=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:c,alpha:u,beta:l}=r,d=new UQ(s.shape,i,c,u,l);return n.runWebGLProgram(d,[s,a,o],s.dtype)},HQ={kernelName:th,backendName:"webgl",kernelFunc:GQ};function jQ(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=be({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=bi(i,e.dtype,"max",r),u=be({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),u}function KN(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=_.getAxesPermutation(u,i),d=l!=null,p=n.shouldExecuteOnCPU([s]),h=s;if(d){if(p){let v=n.texData.get(h.dataId).values,x=new Array(i);for(let N=0;N<x.length;N++)x[N]=s.shape[l[N]];let k=zw(v,s.shape,s.dtype,l,x);h=n.makeTensorInfo(x,s.dtype);let C=n.texData.get(h.dataId);C.values=k}else h=ym(s,l,n);u=_.getInnerMostAxes(u.length,i)}_.assertAxesAreInnerMostDims("max",u,i);let[f,m]=_.computeOutAndReduceShapes(h.shape,u),g=f;o&&(g=_.expandShapeToKeepDim(f,c));let b;if(p){let v=n.texData.get(h.dataId).values,x=c7(v,w.sizeFromShape(m),g,s.dtype);b=n.makeTensorInfo(g,s.dtype);let k=n.texData.get(b.dataId);k.values=x}else b=jQ(h,m,g,n);return d&&n.disposeIntermediateTensorInfo(h),b}var qQ={kernelName:oo,backendName:"webgl",kernelFunc:KN},KQ=pN+`
2021-09-11 17:11:38 +02:00
return max(a, b);
2021-09-16 14:30:50 +02:00
`,XQ=`
2021-09-11 17:11:38 +02:00
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2021-09-16 14:30:50 +02:00
`+gm+`
2021-09-11 17:11:38 +02:00
return result;
2021-09-29 15:32:30 +02:00
`,YQ=cn({opSnippet:KQ,packedOpSnippet:XQ,cpuKernelImpl:u7}),ZQ={kernelName:io,backendName:"webgl",kernelFunc:YQ};function JQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Nu(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:c}=r,u=1;w.assert(_.eitherStridesOrDilationsAreOne(o,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let l=_.computePool2DInfo(s.shape,a,o,u,i,c);if(l.filterWidth===1&&l.filterHeight===1&&w.arraysEqual(l.inShape,l.outShape))return nr({inputs:{x:s},backend:n});let d=new zd(l,"max",!1);return n.runWebGLProgram(d,[s],s.dtype)}var QQ={kernelName:co,backendName:"webgl",kernelFunc:JQ};function eee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dataFormat:c,dimRoundingMode:u}=r,l=[1,1,1],d=_.computePool3DInfo(s.shape,a,o,l,i,u,c),p=new Vw(d,"max",!1);return n.runWebGLProgram(p,[s],s.dtype)}var tee={kernelName:El,backendName:"webgl",kernelFunc:eee},nee=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=s-1-e.padInfo.top,i=a-1-e.padInfo.left,c=s*a-1;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec2 pads = ivec2(${o}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${s};
wR += ${r}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${a}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${c} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${a} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},ree=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,c=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=i-1-e.padInfo.front,d=c-1-e.padInfo.top,p=u-1-e.padInfo.left,h=i*c*u-1;this.userCode=`
2021-09-11 17:11:38 +02:00
const ivec3 pads = ivec3(${l}, ${d}, ${p});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${i};
wD += ${s}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${c};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${u};
wC += ${o}) {
float dyC = float(dyCCorner + wC) / ${r}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${h} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${c} * ${u} +
wR * ${u} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function see(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:c,pad:u,dimRoundingMode:l}=r,d=[1,1,1],p=_.computePool3DInfo(o.shape,i,c,d,u,l),h=new Vw(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new ree(p),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var aee={kernelName:rh,backendName:"webgl",kernelFunc:see};function oee(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Nu([a,o],"maxPoolGrad");let{filterSize:c,strides:u,pad:l,dimRoundingMode:d}=r,p=_.computePool2DInfo(i.shape,c,u,1,l,d),h=!0,f=new zd(p,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new nee(p),b=n.runWebGLProgram(g,[s,m],i.dtype);return n.disposeIntermediateTensorInfo(m),b}var iee={kernelName:nh,backendName:"webgl",kernelFunc:oee};function cee(e,t,n,r){let s=new zd(n,"max",!1),a=r.runWebGLProgram(s,[e],"float32");s=new zd(n,"max",!0,!0,t);let o=r.runWebGLProgram(s,[e],"float32");return[a,o]}var uee={kernelName:sh,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,c=n;w.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let u=[1,1];w.assert(_.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let l=_.computePool2DInfo(r.shape,s,a,u,o),[d,p]=cee(r,i,l,c);return[d,p]}};function lee(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=be({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),c=bi(i,"float32","mean",r),u=be({inputs:{x:c},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(c),u}var dee={kernelName:uo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{keepDims:s,axis:a}=t,o=n,i=r.shape.length,c=w.parseAxisParam(a,r.shape),u=c,l=_.getAxesPermutation(u,i),d=l!=null,p=o.shouldExecuteOnCPU([r]),h=[],f=r;if(d){if(p){let x=o.texData.get(f.dataId).values,k=new Array(i);for(let $=0;$<k.length;$++)k[$]=r.shape[l[$]];let C=zw(x,r.shape,r.dtype,l,k);f=o.makeTensorInfo(k,r.dtype);let N=o.texData.get(f.dataId);N.values=C}else f=ym(r,l,o);h.push(f),u=_.getInnerMostAxes(u.length,i)}_.assertAxesAreInnerMostDims("sum",u,i);let[m,g]=_.computeOutAndReduceShapes(f.shape,u),b=m;s&&(b=_.expandShapeToKeepDim(m,c));let y=lee(f,g,b,o);for(let v of h)o.disposeIntermediateTensorInfo(v);return y}};function pee(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=w.parseAxisParam(a,s.shape),u=c,l=_.getAxesPermutation(u,i),d=s;l!=null&&(d=Cn({inputs:{x:s},backend:n,attrs:{perm:l}}),u=_.getInnerMostAxes(u.length,s.shape.length)),_.assertAxesAreInnerMostDims("min",u,i);let[p,h]=_.computeOutAndReduceShapes(d.shape,u),f=w.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=bi(m,m.dtype,"min",n),b;if(o){let y=_.expandShapeToKeepDim(p,c);b=be({inputs:{x:g},backend:n,attrs:{shape:y}})}else b=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),l!=null&&n.disposeIntermediateTensorInfo(d),b}var hee={kernelName:lo,backendName:"webgl",kernelFunc:pee},fee=pN+`
2021-09-11 17:11:38 +02:00
return min(a, b);
2021-09-16 14:30:50 +02:00
`,mee=`
2021-09-11 17:11:38 +02:00
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2021-09-16 14:30:50 +02:00
`+gm+`
2021-09-11 17:11:38 +02:00
return result;
2021-09-29 15:32:30 +02:00
`,gee=cn({opSnippet:fee,packedOpSnippet:mee,cpuKernelImpl:l7}),bee={kernelName:po,backendName:"webgl",kernelFunc:gee},yee=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,l)=>u[0]+e[l]+u[1]);let r=e.length,s=ht(r),a=t.map(u=>u[0]).join(","),o=t.map((u,l)=>u[0]+e[l]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),c=n==="reflect"?0:1;if(r===1){this.userCode=`
2021-09-11 17:11:38 +02:00
int start = ${a};
int end = ${o};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${c};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${c};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${s} start = ${s}(${a});
${s} end = ${s}(${o});
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outC = getOutputCoords();
for (int i = 0; i < ${r}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${c};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${c};
}
}
${s} coords = outC - start;
setOutput(getX(${i}));
}
2021-09-16 14:30:50 +02:00
`}},vee=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let r=e.length,s=ht(r),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=Sn("rc",r),c=Sn("source",r),u=`${i[r-1]} < ${this.outputShape[r-1]}`,l=r===1?"source":`vec2(${c.slice(-2).join()})`,d=n==="reflect"?0:1,p="";if(r===1){let h=`
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}
result[0] = getChannel(getX(${c.join()}), ${l});
${i[r-1]} += 1;
if(${u}) {
${h}
result[1] = getChannel(getX(${c.join()}), ${l});
}
`}else{let h=`
${s} source = rc;
${s} lt = ${s}(lessThan(source, start));
${s} gte = ${s}(greaterThanEqual(source, end));
${s} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${d}) +
gte * ((end - 1) * 2 - source + ${d});
source -= start;
`;p=`
${s} rc = outputLoc;
${h}
result[0] = getChannel(getX(${c.join()}), ${l});
${i[r-1]} += 1;
if(${u}) {
${h}
result[1] = getChannel(getX(${c.join()}), ${l});
}
rc = outputLoc;
${i[r-2]} += 1;
if(${i[r-2]} < ${this.outputShape[r-2]}) {
${h}
result[2] = getChannel(getX(${c.join()}), ${l});
${i[r-1]} += 1;
if(${u}) {
${h}
result[3] = getChannel(getX(${c.join()}), ${l});
}
}
`}this.userCode=`
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${o});
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${p}
setOutput(result);
2020-12-15 14:15:43 +01:00
}
2021-09-29 15:32:30 +02:00
`}},xee=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{paddings:s,mode:a}=n,o=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new vee(r.shape,s,a):new yee(r.shape,s,a);return t.runWebGLProgram(o,[r],r.dtype)},wee={kernelName:ho,backendName:"webgl",kernelFunc:xee},kee=`if (b == 0.0) return NAN;
2021-09-16 14:30:50 +02:00
return mod(a, b);`,Iee=`
2021-09-11 17:11:38 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2021-09-16 14:30:50 +02:00
`+gm+`
2021-09-11 17:11:38 +02:00
return result;
2021-09-16 14:30:50 +02:00
`,See=cn({opSnippet:kee,packedOpSnippet:Iee}),Cee={kernelName:Sc,backendName:"webgl",kernelFunc:See},Tee=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t-1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// If no other event happened, last event happened.
setOutput(float(${t-1}));
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},Nee=`
2021-09-11 17:11:38 +02:00
if (a == b) {
return 1.0;
};
2021-09-16 14:30:50 +02:00
return a / b;`,_ee=`
2021-09-11 17:11:38 +02:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.y == b.y) {
result.y = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.z == b.z) {
result.z = 1.;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if(a.w == b.w) {
result.w = 1.;
2021-04-01 19:39:54 +02:00
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
return result;
2021-09-29 15:32:30 +02:00
`,XN=cn({opSnippet:Nee,packedOpSnippet:_ee,checkOutOfBounds:!0}),Eee={kernelName:Ya,backendName:"webgl",kernelFunc:XN},YN="return a - b;",ZN=cn({opSnippet:YN,packedOpSnippet:YN,supportsComplex:!0,cpuKernelImpl:T7}),Aee={kernelName:Do,backendName:"webgl",kernelFunc:ZN};function JN(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=w.parseAxisParam([a],s.shape),i=KN({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),c=_.expandShapeToKeepDim(i.shape,o),u=be({inputs:{x:i},backend:n,attrs:{shape:c}}),l=ZN({inputs:{a:s,b:u},backend:n}),d=VN({inputs:{x:l},backend:n}),p=vm({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=be({inputs:{x:p},backend:n,attrs:{shape:c}}),f=XN({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}var Dee={kernelName:Eo,backendName:"webgl",kernelFunc:JN};function $ee(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r,c=i?s:JN({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),u=c.shape[0],l=c.shape[1],d=new Tee(u,l,a),p=[[o]],h=n.runWebGLProgram(d,[c],"int32",p);return i||n.disposeIntermediateTensorInfo(c),h}var Fee={kernelName:ah,backendName:"webgl",kernelFunc:$ee},QN="return -x;";function Ree(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.texData.get(r.dataId),[o,i]=p7(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s;return Q().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new $u(r.shape,QN):s=new Ia(r.shape,QN),n.runWebGLProgram(s,[r],r.dtype)}var Pee={kernelName:Cc,backendName:"webgl",kernelFunc:Ree},Oee=as.nonMaxSuppressionV3Impl;function Mee(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c}=r,u=n.readSync(s.dataId),l=n.readSync(a.dataId),{selectedIndices:d}=Oee(u,l,o,i,c);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var Lee={kernelName:Nc,backendName:"webgl",kernelFunc:Mee},Bee=as.nonMaxSuppressionV4Impl;function zee(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,padToMaxOutputSize:u}=r,l=n.readSync(s.dataId),d=n.readSync(a.dataId),{selectedIndices:p,validOutputs:h}=Bee(l,d,o,i,c,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Wee={kernelName:_c,backendName:"webgl",kernelFunc:zee},Vee=as.nonMaxSuppressionV5Impl;function Uee(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:c,softNmsSigma:u}=r,l=n.readSync(s.dataId),d=n.readSync(a.dataId),p=o,h=i,f=c,m=u,{selectedIndices:g,selectedScores:b}=Vee(l,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var Gee={kernelName:Ec,backendName:"webgl",kernelFunc:Uee},Hee=class{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${r}), float(${n}),
float(index == coords.y)));
2021-03-26 15:26:02 +01:00
}
2021-09-29 15:32:30 +02:00
`}},jee=e=>{let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,c=w.sizeFromShape(s.shape),u=new Hee(c,a,o,i),l=be({inputs:{x:s},backend:n,attrs:{shape:[c]}}),d=n.runWebGLProgram(u,[l],s.dtype);n.disposeIntermediateTensorInfo(l);let p=[...s.shape,a],h=be({inputs:{x:d},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(d),h},qee={kernelName:mo,backendName:"webgl",kernelFunc:jee};function Sm(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=Wd({inputs:{input:r},backend:n}),a=Sm({inputs:{x:s},backend:n}),o=Im({inputs:{input:r},backend:n}),i=Sm({inputs:{x:o},backend:n}),c=Sa({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Vd({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var Kee={kernelName:Kc,backendName:"webgl",kernelFunc:Sm};function e_(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(r.dtype==="complex64"){let s=Wd({inputs:{input:r},backend:n}),a=e_({inputs:{x:s},backend:n}),o=Im({inputs:{input:r},backend:n}),i=Sm({inputs:{x:o},backend:n}),c=Sa({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),c}else return Vd({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var Xee={kernelName:Ac,backendName:"webgl",kernelFunc:e_};function Yee(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return Hw({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(l=>{w.assertShapesMatch(a,l.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===l.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],c=t.map(l=>{let d=Hw({inputs:{input:l},backend:n,attrs:{dim:s}});return i.push(d),d}),u=$N({inputs:c,backend:n,attrs:{axis:s}});return i.forEach(l=>n.disposeIntermediateTensorInfo(l)),u}var Zee={kernelName:Dc,backendName:"webgl",kernelFunc:Yee},Jee=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((c,u)=>c[0]+e[u]+c[1]);let r=e.length,s=ht(r),a=t.map(c=>c[0]).join(","),o=t.map((c,u)=>c[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=`
2021-09-11 17:11:38 +02:00
int start = ${a};
int end = ${o};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${s} start = ${s}(${a});
${s} end = ${s}(${o});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${s} coords = outC - start;
setOutput(getX(${i}));
}
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},Qee=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let r=e.length,s=ht(r),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=Sn("rc",r),c=Sn("source",r),u=`${i[r-1]} < ${this.outputShape[r-1]}`,l=r===1?"source":`vec2(${c.slice(-2).join()})`,d=[`${s} rc = outputLoc;`,`${i[r-1]} += 1;
2021-09-11 17:11:38 +02:00
if(${u}) {
`,r===1?"":`}
rc = outputLoc;
${i[r-2]} += 1;
if(${i[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":` ${i[r-1]} += 1;
if(${u}) {`],p=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=r===1?2:4;f<m;f++)h+=`
${d[f]}
if (${p}) {
result[${f}] = float(value);
} else {
${s} source = rc - start;
result[${f}] = getChannel(getX(${c.join()}), ${l});
}
`;h+=r===1?"} ":"}}",this.userCode=`
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${o});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${h}
setOutput(result);
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}},t_=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(w.sizeFromShape(s.shape)===0){let u=a.map((l,d)=>l[0]+s.shape[d]+l[1]);return Vd({backend:n,attrs:{shape:u,value:o,dtype:s.dtype}})}let i=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Qee(s.shape,a,o):new Jee(s.shape,a,o),c=[[o]];return n.runWebGLProgram(i,[s],s.dtype,c)},ete={kernelName:go,backendName:"webgl",kernelFunc:t_},tte=`
2021-09-11 17:11:38 +02:00
if(a < 0.0 && floor(b) < b){
return NAN;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
if (b == 0.0) {
return 1.0;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
2021-09-16 14:30:50 +02:00
`,nte=`
2021-09-11 17:11:38 +02:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
2021-09-16 14:30:50 +02:00
`+gm+`
2021-09-11 17:11:38 +02:00
return result;
2021-09-29 15:32:30 +02:00
`,rte=cn({opSnippet:tte,packedOpSnippet:nte}),ste={kernelName:bo,backendName:"webgl",kernelFunc:rte};function ate(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,c=[],u=w.parseAxisParam(a,s.shape),l=u,d=_.getAxesPermutation(l,i),p=s;d!=null&&(p=Cn({inputs:{x:s},backend:n,attrs:{perm:d}}),l=_.getInnerMostAxes(l.length,i),c.push(p)),_.assertAxesAreInnerMostDims("prod",l,i);let h;if(n.shouldExecuteOnCPU([p])){let f=n.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:b}=f7(p.shape,p.dtype,f,l);h=n.makeTensorInfo(g,b,m)}else{let[f,m]=_.computeOutAndReduceShapes(p.shape,l),g=w.sizeFromShape(m),b=be({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),y=Ch(s.dtype),v=bi(b,y,"prod",n);h=be({inputs:{x:v},backend:n,attrs:{shape:f}}),c.push(b),c.push(v)}if(o){c.push(h);let f=_.expandShapeToKeepDim(h.shape,u);h=be({inputs:{x:h},backend:n,attrs:{shape:f}})}return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var ote={kernelName:$c,backendName:"webgl",kernelFunc:ate},n_=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=m7(r,s,a,o);return t.makeTensorInfo([i.length],o,i)},ite={kernelName:Al,backendName:"webgl",kernelFunc:n_},cte="return 1.0 / x;",ute=Xe({opSnippet:cte}),lte={kernelName:Fc,backendName:"webgl",kernelFunc:ute},dte=Hr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : x;
2021-09-16 14:30:50 +02:00
`,pte=`
2021-09-11 17:11:38 +02:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2021-09-29 15:32:30 +02:00
`,hte=Xe({opSnippet:dte,packedOpSnippet:pte}),fte={kernelName:vo,backendName:"webgl",kernelFunc:hte},mte=Hr+`
2021-09-11 17:11:38 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2021-09-16 14:30:50 +02:00
`,gte=`
2021-09-11 17:11:38 +02:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2021-09-29 15:32:30 +02:00
`,bte=Xe({opSnippet:mte,packedOpSnippet:gte}),yte={kernelName:wo,backendName:"webgl",kernelFunc:bte},vte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0]/l[0]},
${u[1]/l[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec2 sourceFracIndexRC = ${d};
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},xte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],d;s?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
${u[0]/l[0]},
${u[1]/l[1]},
${u[1]/l[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec3 sourceFracIndexRC = ${d};
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${c-1};
bool hasNextRow = coords.z < ${n-1};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
setOutput(newValue);
}
2021-09-29 15:32:30 +02:00
`}};function wte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,u]=i,l=Q().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new xte(s.shape,c,u,a,o):new vte(s.shape,c,u,a,o);return n.runWebGLProgram(l,[s],"float32")}var kte={kernelName:xo,backendName:"webgl",kernelFunc:wte},Ite=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],u=i[0]/c[0],l=i[1]/c[1],d=1/u,p=1/l,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
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-09-11 17:11:38 +02:00
const float heightScale = float(${u});
const float widthScale = float(${l});
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
const float invHeightScale = float(${d});
const float invWidthScale = float(${p});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
const int winHeight = int(${h});
const int winWidth = int(${f});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
2021-09-11 17:11:38 +02:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
2021-09-11 17:11:38 +02:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${s-1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput(accumulator);
2021-03-31 13:01:22 +02:00
}
2021-09-16 14:30:50 +02:00
`}};function Ste(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Ite(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Cte={kernelName:ch,backendName:"webgl",kernelFunc:Ste},Tte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0]/l[0]},
${u[1]/l[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec2 sourceFracIndexRC = ${p};
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
2021-04-01 19:39:54 +02:00
}
2021-09-16 14:30:50 +02:00
`}},Nte=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,c]=e;this.outputShape=[a,t,n,c];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],l=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0",p;s?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
2021-09-11 17:11:38 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
${u[0]/l[0]},
${u[1]/l[1]},
${u[1]/l[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
${i}.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Fractional source index.
vec3 sourceFracIndexRC = ${p};
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${c-1};
bool hasNextRow = coords.z < ${n-1};
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
vec4 newValue = vec4(
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput(newValue);
}
2021-09-16 14:30:50 +02:00
`}};function _te(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[c,u]=i,l=Q().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Nte(s.shape,c,u,a,o):new Tte(s.shape,c,u,a,o);return n.runWebGLProgram(l,[s],s.dtype)}var Ete={kernelName:Dl,backendName:"webgl",kernelFunc:_te},Ate=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],c=[n&&a>1?a-1:a,n&&o>1?o-1:o],u=i[0]/c[0],l=i[1]/c[1],d=1/u,p=1/l,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
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-09-11 17:11:38 +02:00
const float heightScale = float(${u});
const float widthScale = float(${l});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const float invHeightScale = float(${d});
const float invWidthScale = float(${p});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
const int winHeight = int(${h});
const int winWidth = int(${f});
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${o}) {
continue;
}
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracRow =
float(${i[0]}) *
(float(dyR) / float(${c[0]}));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
float sourceFracCol =
float(${i[1]}) *
(float(dyC) / float(${c[1]}));
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int sourceNearestRow = int(min(
float(int(${r}) - 1),
${n} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
int sourceNearestCol = int(min(
float(int(${s}) - 1),
${n} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
setOutput(accumulator);
}
2021-09-16 14:30:50 +02:00
`}};function Dte(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new Ate(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var $te={kernelName:ih,backendName:"webgl",kernelFunc:Dte},Fte=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
2021-09-16 14:30:50 +02:00
`;return}let r=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,s=e.map((o,i)=>r(i)).join(","),a=ht(n);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${s}));
}
2021-09-16 14:30:50 +02:00
`}},Rte=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;let r=Sn("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=ht(n);n===1?this.userCode=`
2021-09-11 17:11:38 +02:00
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${s}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${i(r.slice())};
if(${s}){
result.g = ${c(r.slice())};
}
if(${a}) {
result.b = ${u(r.slice())};
if(${s}) {
result.a = ${l(r.slice())};
}
}
setOutput(result);
}
2021-09-29 15:32:30 +02:00
`;function i(h){return d(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function u(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let f=e.map((b,y)=>p(y,h)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function p(h,f){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${f[h]} - 1`:`${f[h]}`}}};function Pte(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=s.shape.length,i=w.parseAxisParam(a,s.shape);if(o===0)return nr({inputs:{x:s},backend:n});let c=Q().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Rte(s.shape,i):new Fte(s.shape,i);return n.runWebGLProgram(c,[s],s.dtype)}var Ote={kernelName:ko,backendName:"webgl",kernelFunc:Pte},Mte=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],r=e[2];this.outputShape=e;let s="";typeof t=="number"?s=`float outputValue = ${t.toFixed(2)};`:s=`
2021-09-11 17:11:38 +02:00
vec3 fill = vec3(${t.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - params[0]) * params[3] -
(float(y) - params[1]) * params[2];
float coordYFloat = (float(x) - params[0]) * params[2] +
(float(y) - params[1]) * params[3];
int coordX = int(round(coordXFloat + params[0]));
int coordY = int(round(coordYFloat + params[1]));
${s}
if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
2021-09-16 14:30:50 +02:00
`}},Lte={kernelName:Xc,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,c=new Mte(r.shape,a),[u,l]=_.getImageCenter(o,r.shape[1],r.shape[2]),d=[[u,l,Math.sin(s),Math.cos(s)]];return i.runWebGLProgram(c,[r],r.dtype,d)}},Bte=`
2021-09-11 17:11:38 +02:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
2021-04-01 19:39:54 +02:00
}
}
2021-09-29 15:32:30 +02:00
`,zte=Xe({opSnippet:Bte}),Wte={kernelName:Io,backendName:"webgl",kernelFunc:zte},Vte="return inversesqrt(x);",Ute=Xe({opSnippet:Vte,cpuKernelImpl:g7}),Gte={kernelName:So,backendName:"webgl",kernelFunc:Ute},r_=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=ht(s.length),c=ht(a.length),u="";n===1?u="i":n===2&&(u="i, j");let l=`getIndices(${u})`,d="";r===1?d="i":r===2&&(d="i, coords[1]");let p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=`
2021-09-11 17:11:38 +02:00
${i} strides = ${i}(${s});
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
void main() {
${c} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${l});
flattenedIndex += index * ${h};
}
if (flattenedIndex == coords[0]) {
sum += ${p};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
2021-09-16 14:30:50 +02:00
`}};function Hte(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:c,sliceSize:u,strides:l,outputSize:d}=_.calculateShapes(a,s,o),p=[d/u,u];if(d===0)return n.makeTensorInfo(o,s.dtype);let h=be({inputs:{x:s},backend:n,attrs:{shape:[c,i]}}),f=be({inputs:{x:a},backend:n,attrs:{shape:[c,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new r_(c,i,h.shape.length,f.shape.length,l,p),b=n.runWebGLProgram(g,[f,h,m],f.dtype),y=be({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(m),y}var jte={kernelName:Pc,backendName:"webgl",kernelFunc:Hte},qte=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let r,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",r="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],c=[];for(let u=0;u<t.length;u++)c.push(`${o[u]}`),u<e&&i.push(`${o[u]}`);r=i.join(),s=c.join()}let a=ht(n);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${a} resRC = getOutputCoords();
float cVal = getC(${r});
if (cVal >= 1.0) {
setOutput(getA(${s}));
} else {
setOutput(getB(${s}));
}
2021-03-26 15:26:02 +01:00
}
2021-09-16 14:30:50 +02:00
`}};function Kte(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new qte(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(o,[r,s,a],kr(s.dtype,a.dtype))}var Xte={kernelName:Oc,backendName:"webgl",kernelFunc:Kte},Yte=`
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
float scaleAlpha = ${_.SELU_SCALEALPHA};
float scale = ${_.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2021-09-29 15:32:30 +02:00
`,Zte=Xe({opSnippet:Yte}),Jte={kernelName:Mc,backendName:"webgl",kernelFunc:Zte},s_="return 1.0 / (1.0 + exp(-1.0 * x));",Qte=Xe({opSnippet:s_,packedOpSnippet:s_,cpuKernelImpl:b7}),ene={kernelName:To,backendName:"webgl",kernelFunc:Qte},tne=`
2021-09-11 17:11:38 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2021-09-16 14:30:50 +02:00
`,nne=Xe({opSnippet:tne}),rne={kernelName:zc,backendName:"webgl",kernelFunc:nne},sne=bN+`
2021-09-11 17:11:38 +02:00
return sin(x);
2021-09-29 15:32:30 +02:00
`,ane=Xe({opSnippet:sne}),one={kernelName:Co,backendName:"webgl",kernelFunc:ane},ine=`
2021-09-11 17:11:38 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2021-09-16 14:30:50 +02:00
`,cne=Xe({opSnippet:ine}),une={kernelName:Bc,backendName:"webgl",kernelFunc:cne},lne=`
2021-09-11 17:11:38 +02:00
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
if (too_large){
result = x;
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
2021-04-01 19:39:54 +02:00
}
2021-09-11 17:11:38 +02:00
return result;
2021-09-16 14:30:50 +02:00
`,dne=Xe({opSnippet:lne}),pne={kernelName:Wc,backendName:"webgl",kernelFunc:dne},hne=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;w.assert(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((b,y)=>b*y),c=[[0,0]];c.push(...o);for(let b=1+a.length;b<s.shape.length;++b)c.push([0,0]);let u=[],l=t_({inputs:{x:s},backend:n,attrs:{paddings:c,constantValue:0}}),d=_.getReshaped(l.shape,a,i,!1),p=_.getPermuted(d.length,a.length,!1),h=_.getReshapedPermuted(l.shape,a,i,!1),f=be({inputs:{x:l},backend:n,attrs:{shape:d}}),m=Cn({inputs:{x:f},backend:n,attrs:{perm:p}}),g=be({inputs:{x:m},backend:n,attrs:{shape:h}});return u.push(l),u.push(f),u.push(m),u.forEach(b=>n.disposeIntermediateTensorInfo(b)),g},fne={kernelName:Vc,backendName:"webgl",kernelFunc:hne};function mne(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
2021-09-11 17:11:38 +02:00
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
2021-09-16 14:30:50 +02:00
${o.shape}`);let i=n.readSync(r.dataId),c=n.readSync(s.dataId),u=n.readSync(a.dataId),l=n.readSync(o.dataId)[0],[d,p,h,f,m]=v7(i,r.shape,r.dtype,c,s.dtype,u,l);return[n.makeTensorInfo(p,r.dtype,d),n.makeTensorInfo([p[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var gne={kernelName:uh,backendName:"webgl",kernelFunc:mne};function bne(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.readSync(s.dataId)),i=n.readSync(r.dataId),c=Array.from(n.readSync(a.dataId)),[u,l,d]=x7(i,r.shape,r.dtype,o,c);return[n.makeTensorInfo(l,r.dtype,u),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var yne={kernelName:lh,backendName:"webgl",kernelFunc:bne};function vne(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2021-09-16 14:30:50 +02:00
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[u,l]=sN(o,r.shape,r.dtype,i,c,!0);return n.makeTensorInfo(l,r.dtype,u)}var xne={kernelName:dh,backendName:"webgl",kernelFunc:vne};function wne(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
2021-09-11 17:11:38 +02:00
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
2021-09-29 15:32:30 +02:00
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),c=n.readSync(a.dataId),[u,l]=sN(o,r.shape,r.dtype,i,c);return n.makeTensorInfo(l,r.dtype,u)}var kne={kernelName:ph,backendName:"webgl",kernelFunc:wne};function Ine(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:c,numUpdates:u,strides:l,outputSize:d}=_.calculateShapes(a,s,i),p=!1,h=new r_(u,c,s.shape.length,a.shape.length,l,[d,1],p),f=n.runWebGLProgram(h,[a,s,o],a.dtype),m=be({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var Sne={kernelName:hh,backendName:"webgl",kernelFunc:Ine};function Cne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],c=_.prepareSplitSize(s,a,i),u=s.shape.length,l=new Array(u).fill(0),d=s.shape.slice();return c.map(p=>{let h=[...d];h[i]=p;let f=Ru({inputs:{x:s},backend:n,attrs:{begin:l,size:h}});return l[i]+=p,f})}var Tne={kernelName:Uc,backendName:"webgl",kernelFunc:Cne},a_="return sqrt(x);",Nne=Xe({opSnippet:a_,packedOpSnippet:a_,cpuKernelImpl:w7}),_ne={kernelName:No,backendName:"webgl",kernelFunc:Nne},Ene="return x * x;",Ane=Xe({opSnippet:Ene}),Dne={kernelName:$l,backendName:"webgl",kernelFunc:Ane},o_="return (a - b) * (a - b);",$ne=cn({opSnippet:o_,packedOpSnippet:o_}),Fne={kernelName:Ao,backendName:"webgl",kernelFunc:$ne};function Rne({inputs:e,attrs:t,backend:n}){let{x:r}=e,s=Hr+`
2021-09-11 17:11:38 +02:00
return x > 0.0 ? 1.0 : float(${t.alpha});
2021-09-29 15:32:30 +02:00
`,a=new Ia(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}var Pne={kernelName:ta,backendName:"webgl",kernelFunc:Rne},One=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let r=n.length,s=ht(n.length),a=ht(n.length),o="";if(r===1)o="coords * strides + begin";else{let i=0;o=n.map((c,u)=>(i++,n.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${i-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
2021-09-11 17:11:38 +02:00
${s} begin = ${s}(${e});
${s} strides = ${s}(${t});
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${o}));
2021-04-01 19:39:54 +02:00
}
2021-09-29 15:32:30 +02:00
`}};function Mne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:c,endMask:u,ellipsisMask:l,newAxisMask:d,shrinkAxisMask:p}=r,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:b,outShape:y}=vn.sliceInfo(s.shape,a,o,i,c,u,l,d,p),v=be({inputs:{x:s},backend:n,attrs:{shape:b}}),x;if(h){let C=Ru({inputs:{x:v},backend:n,attrs:{begin:f,size:g}});x=be({inputs:{x:C},backend:n,attrs:{shape:y}}),n.disposeIntermediateTensorInfo(C)}else if(y.some(C=>C===0))x=n.makeTensorInfo(y,s.dtype,[]);else if(n.shouldExecuteOnCPU([v])){let $=n.texData.get(v.dataId).values,R=ze(v.shape,v.dtype,$),O=k7(y,R,m,f);x=n.makeTensorInfo(y,v.dtype,O.values)}else{let N=new One(f,m,y);x=n.runWebGLProgram(N,[v],v.dtype)}let k=be({inputs:{x},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(x),k}var Lne={kernelName:Gc,backendName:"webgl",kernelFunc:Mne};function Bne(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:c,preserveShortSequences:u}=r,{data:l,dataSplits:d}=t,p=n.readSync(l.dataId),h=n.readSync(d.dataId),[f,m]=I7(p,h,s,a,o,i,c,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var zne={kernelName:fh,backendName:"webgl",kernelFunc:Bne};function Wne(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),c=n.readSync(o.dataId)[0],[u,l,d]=S7(i,c,s),p=l.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",l),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var Vne={kernelName:mh,backendName:"webgl",kernelFunc:Wne};function Une(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=C7(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var Gne={kernelName:gh,backendName:"webgl",kernelFunc:Une},Hne="return tan(x);",jne=Xe({opSnippet:Hne}),qne={kernelName:$o,backendName:"webgl",kernelFunc:jne},Kne=`
2021-09-11 17:11:38 +02:00
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
2021-09-29 15:32:30 +02:00
`,Xne=Xe({opSnippet:Kne}),Yne={kernelName:Fo,backendName:"webgl",kernelFunc:Xne},Zne=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[a]*t[a];this.outputShape=n,this.rank=n.length;let r=ht(this.rank),s=Jne(e);this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
${r} resRC = getOutputCoords();
setOutput(getA(${s}));
}
2021-09-29 15:32:30 +02:00
`}};function Jne(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),u=s.dtype==="string"?c.map(p=>w.decodeString(p)):c,l=ze(s.shape,s.dtype,u),d=N7(l,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new Zne(s.shape,a);return n.runWebGLProgram(o,[s],s.dtype)}var Qne={kernelName:ea,backendName:"webgl",kernelFunc:i_},ere=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
int i = isFirstInPair ? elemIdx : elemIdx - inc;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod(elemIdx, 2 * dir) >= dir;
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) { // Elements in opposite order of direction
int iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutput(float(i0));
} else {
setOutput(float(i1));
}
}
2021-09-16 14:30:50 +02:00
`}},tre=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=`
2021-09-11 17:11:38 +02:00
void main() {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float x0 = getX(batch, i0);
float x1 = i1 < n ? getX(batch, i1) : x0;
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
setOutput(x0 >= x1 ? float(i0) : float(i1));
}
2021-09-29 15:32:30 +02:00
`}};function yi(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function c_(e){let t=1;for(;t<e;)t*=2;return t}function nre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r,i=Q().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),c=Q().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=s.shape,l=u[u.length-1];if(n.shouldExecuteOnCPU([s])||l<i||a>c){let O=n.readSync(s.dataId),[D,P]=_7(O,u,s.dtype,a,o);return[n.makeTensorInfo(D.shape,D.dtype,D.values),n.makeTensorInfo(P.shape,P.dtype,P.values)]}if(a===0)return u[u.length-1]=0,[n.makeTensorInfo(u,s.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(l===1)return[s,Vd({attrs:{shape:u,dtype:"int32",value:0},backend:n})];let d=n.texData.get(s.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(s):s,m=w.sizeFromShape(u)/l,g=be({inputs:{x:h},attrs:{shape:[m,l]},backend:n});p&&yi(n,h);let b=c_(a),y=c_(l),v=null,x=()=>v===null?[g,g]:[g,v],k=(O,D,P)=>{let T=x(),L=new ere(P),j=[[l],[v===null?1:0],[Number.NEGATIVE_INFINITY],[O],[D]],q=v;v=n.runWebGLProgram(L,T,"int32",j),yi(n,q)};for(let O=1;O<b;O*=2){let D=O*2;for(let P=O;P>=1;P/=2)k(D,P,[m,y])}for(let O=y;O>b;O/=2){let D=x(),P=new tre([m,O/2]),L=[[l],[v===null?1:0],[b]],G=v;v=n.runWebGLProgram(P,D,"int32",L),yi(n,G);let j=b/2,q=j*2;for(let K=j;K>=1;K/=2)k(q,K,v.shape)}let C=v;v=Ru({inputs:{x:v},backend:n,attrs:{begin:0,size:[m,a]}}),yi(n,C);let N=qN({inputs:{x:g,indices:v},backend:n,attrs:{axis:1,batchDims:1}});yi(n,g);let $=u.slice(0,-1);$.push(a),C=v,v=be({inputs:{x:v},attrs:{shape:$},backend:n}),yi(n,C);let R=N;return N=be({inputs:{x:N},attrs:{shape:$},backend:n}),yi(n,R),[N,v]}var rre={kernelName:Hc,backendName:"webgl",kernelFunc:nre},sre=class{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(r){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode=`
2021-09-11 17:11:38 +02:00
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${i} == 2) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
if (inCoord < sz2) {
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
inCoord;
}
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
inCoord -= sz2 * float(int(float(inCoord / sz2)));
if (inCoord >= len) {
inCoord = sz2 - inCoord - 1.0;
}
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${i} == 3) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord -= len * float(int(float(inCoord / sz)));
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${i} == 4) {
return clamp(outCoord, 0.0, len - 1.0);
} else {
return outCoord;
}
}
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
float readWithFillValue(int batch, int coordY, int coordX,
int channel) {
float outputValue;
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = float(${s});
}
return outputValue;
}
2020-10-11 18:41:17 +02:00
2021-09-11 17:11:38 +02:00
void main() {
ivec4 coords = getOutputCoords();
float outputValue;
int batch = coords[0];
int x = coords[2];
int y = coords[1];
int channel = coords[3];
float xf = float(x);
float yf = float(y);
float a1 = getTransforms(batch, 0);
float a2 = getTransforms(batch, 1);
float a3 = getTransforms(batch, 2);
float b1 = getTransforms(batch, 3);
float b2 = getTransforms(batch, 4);
float b3 = getTransforms(batch, 5);
float c1 = getTransforms(batch, 6);
float c2 = getTransforms(batch, 7);
float projection = c1 * xf + c2 * yf + 1.0;
if (projection == 0.0) {
outputValue = float(${s});
} else {
float inX = (a1 * xf + a2 * yf + a3) / projection;
float inY = (b1 * xf + b2 * yf + b3) / projection;
float mapX = mapCoord(inX, float(${t}));
float mapY = mapCoord(inY, float(${e}));
2021-03-31 13:01:22 +02:00
2021-09-11 17:11:38 +02:00
if (${o} == 1) {
int coordY = int(round(mapY));
int coordX = int(round(mapX));
outputValue = readWithFillValue(batch, coordY, coordX,
channel);
} else {
float yFloor = floor(mapY);
float xFloor = floor(mapX);
float yCeil = yFloor + 1.0;
float xCeil = xFloor + 1.0;
float valueYFloor = (xCeil - mapX) *
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
float valueYCeil = (xCeil - mapX) *
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
outputValue = (yCeil - mapY) * valueYFloor +
(mapY - yFloor) * valueYCeil;
}
}
setOutput(outputValue);
}
2021-09-16 14:30:50 +02:00
`}};function are(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:c,outputShape:u}=r,[l,d,p,h]=s.shape,[f,m]=u!=null?u:[d,p],g=[l,f,m,h],b=new sre(d,p,o,i,c,g);return n.runWebGLProgram(b,[s,a],"float32")}var ore={kernelName:jc,backendName:"webgl",kernelFunc:are};function ire(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Nu(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=r.readSync(a.dataId),{outputValues:i,outputShape:c,indices:u}=E7(o,s,a.shape,a.dtype);return[r.makeTensorInfo(c,a.dtype,i),r.makeTensorInfo([u.length],"int32",u)]}var cre={kernelName:bh,backendName:"webgl",kernelFunc:ire};function ure(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s,i=o.shape.length,c=s.shape[a],u=new Array(i-1),l=0;for(let m=0;m<i;m++)m!==a&&(u[l++]=o.shape[m]);let d=[],p=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(c);for(let m=0;m<f.length;m++){p[a]=m;let g=Ru({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),b=be({inputs:{x:g},backend:n,attrs:{shape:u}});f[m]=b,d.push(g)}return d.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var lre={kernelName:qc,backendName:"webgl",kernelFunc:ure},dre=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,o=a*Math.ceil(s/n);this.outputShape=[r,o];let i="0.0",c="sumValue",u=Math.floor(n/4)*4,l=n%4,d=`
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-09-11 17:11:38 +02:00
for (int i = 0; i < ${u}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
2020-12-15 14:15:43 +01:00
}
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
int inIdx = inOffset + ${u};
if (${l===1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2020-12-15 14:15:43 +01:00
2021-09-11 17:11:38 +02:00
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
2021-03-26 15:26:02 +01:00
2021-09-11 17:11:38 +02:00
${d}
} else if (${l===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
${d}
} else if (${l===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2021-04-01 19:39:54 +02:00
2021-09-11 17:11:38 +02:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
2020-10-29 05:16:50 +01:00
2021-09-11 17:11:38 +02:00
${d}
}
setOutput(${c});
}
`}};function pre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r,i=s.shape.length,c=[],u=0,l=_.getAxesPermutation([u],i),d=s;l!=null&&(d=Cn({inputs:{x:s},backend:n,attrs:{perm:l}}),c.push(d),u=_.getInnerMostAxes(1,i)[0]);let p=_.segment_util.computeOutShape(d.shape,u,o),h=w.sizeFromShape([d.shape[u]]),f=be({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});c.push(f);let m=Ch(s.dtype),g=(x,k,C,N,$)=>{let R=x.shape[0],O=x.shape[1],D=_.segment_util.segOpComputeOptimalWindowSize(O,$),P={windowSize:D,inSize:O,batchSize:R,numSegments:$},T=new dre(P,k),L=n.compileAndRun(T,[x,C],N);if(c.push(L),L.shape[1]===$)return L;let G=n_({backend:n,attrs:{start:0,stop:$,step:1,dtype:"float32"}}),j=i_({inputs:{x:G},backend:n,attrs:{reps:[O/D]}});return c.push(G),c.push(j),g(L,k,j,N,$)},b=g(f,"unsortedSegmentSum",a,m,o),y=be({inputs:{x:b},backend:n,attrs:{shape:p}}),v=y;if(l!=null){c.push(y);let x=_.getUndoAxesPermutation(l);v=Cn({inputs:{x:v},backend:n,attrs:{perm:x}})}return c.forEach(x=>n.disposeIntermediateTensorInfo(x)),v}var hre={kernelName:Fl,backendName:"webgl",kernelFunc:pre},fre=[VQ,HQ,_9,A9,F9,O9,L9,W9,U9,H9,X9,Z9,eY,rY,lY,oY,hY,bY,mY,wY,IY,CY,EY,OY,LY,GY,jY,YY,QY,u9,sZ,fZ,gZ,cZ,xZ,kZ,yZ,CZ,_Z,DZ,FZ,PZ,LZ,GZ,jZ,zZ,XZ,JZ,eJ,sJ,cJ,pJ,mJ,gJ,bJ,vJ,wJ,IJ,CJ,NJ,DJ,RJ,MJ,BJ,VJ,HJ,XJ,QJ,c9,tQ,nZ,sQ,iQ,lQ,d9,fQ,yQ,xQ,NQ,SQ,DQ,RQ,LQ,qQ,tee,QQ,aee,iee,uee,ZQ,dee,hee,bee,wee,Cee,Fee,g9,Pee,Lee,Wee,Gee,zY,qee,Xee,Zee,ete,ste,h9,ote,ite,WY,Eee,lte,yte,fte,y9,kte,Cte,Ete,$te,Ote,Lte,Wte,Gte,jte,Xte,Jte,ene,rne,one,une,RY,Dee,pne,fne,gne,yne,xne,kne,Sne,Tne,_ne,Dne,Fne,Pne,Lne,zne,Vne,Gne,Aee,C9,qne,Yne,Qne,rre,ore,T9,cre,lre,hre,Kee];for(let e of fre)Pl(e);var Bn;(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"})(Bn||(Bn={}));var Ud;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(Ud||(Ud={}));var u_;function mre(e){u_=e.wasm.cwrap(Po,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function gre(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:c,transposeB:u,activation:l,leakyreluAlpha:d}=r,p=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let $=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=Ud[l];if(g==null)throw new Error(`${l} activation not yet supported for FusedConv2D in the wasm backend.`);let b=c?s.shape[2]:s.shape[1],y=u?a.shape[1]:a.shape[2],v=s.shape[0],x=n.makeOutput([v,b,y],s.dtype),k=n.dataIdMap.get(x.dataId).id,C=new Uint8Array(new Int32Array(s.shape).buffer),N=new Uint8Array(new Int32Array(a.shape).buffer);return u_(p,C,s.shape.length,h,N,a.shape.length,c,u,g,f,m,d||0,k),x}var bre={kernelName:Po,backendName:"wasm",setupFunc:mre,kernelFunc:gre};function un(e){let t;function n(s){t=s.wasm.cwrap(e,null,["number","number"])}function r(s){let{backend:a,inputs:{x:o}}=s,i=a.dataIdMap.get(o.dataId).id,c=a.makeOutput(o.shape,o.dtype),u=a.dataIdMap.get(c.dataId).id;return w.sizeFromShape(c.shape)===0||t(i,u),c}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:r}}var yre=un(Xi);function Tn(e,t,n){let r;function s(o){r=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:c}=o,{a:u,b:l}=c,d=i.dataIdMap.get(u.dataId).id,p=i.dataIdMap.get(l.dataId).id,h=n!=null?n:u.dtype,f=_.assertAndGetBroadcastShape(u.shape,l.shape),m=i.makeOutput(f,h);if(w.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(u.shape).buffer),b=new Uint8Array(new Int32Array(l.shape).buffer),y=i.dataIdMap.get(m.dataId).id,v=()=>r(d,g,u.shape.l
2021-04-26 20:45:49 +02:00
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
2021-04-30 18:01:04 +02:00
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
2021-08-31 18:21:57 +02:00
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
2021-04-26 20:45:49 +02:00
/** @license See the LICENSE file. */