face-api/dist/face-api.node.js

4163 lines
1.2 MiB
JavaScript
Raw Normal View History

2020-11-25 14:30:53 +01:00
var mZ=Object.create,Jm=Object.defineProperty,gZ=Object.getPrototypeOf,vZ=Object.prototype.hasOwnProperty,yZ=Object.getOwnPropertyNames,bZ=Object.getOwnPropertyDescriptor,WD=o=>Jm(o,"__esModule",{value:!0}),Zm=(o,a)=>()=>(a||(a={exports:{}},o(a.exports,a)),a.exports),kf=(o,a)=>{WD(o);for(var i in a)Jm(o,i,{get:a[i],enumerable:!0})},wZ=(o,a,i)=>{if(WD(o),a&&typeof a=="object"||typeof a=="function")for(let c of yZ(a))!vZ.call(o,c)&&c!=="default"&&Jm(o,c,{get:()=>a[c],enumerable:!(i=bZ(a,c))||i.enumerable});return o},se=o=>o&&o.__esModule?o:wZ(Jm(o!=null?mZ(gZ(o)):{},"default",{value:o,enumerable:!0}),o),Nx=Zm(xZ=>{kf(xZ,{FetchError:()=>sr,Headers:()=>jr,Request:()=>Bo,Response:()=>us,default:()=>FZ});var is=se(require("stream")),vx=se(require("http")),Qm=se(require("url")),VD=se(require("https")),$a=se(require("zlib")),TZ=is.default.Readable,Oo=Symbol("buffer"),yx=Symbol("type"),Fi=class{constructor(){this[yx]="";let a=arguments[0],i=arguments[1],c=[],f=0;if(a){let g=a,v=Number(g.length);for(let w=0;w<v;w++){let T=g[w],N;T instanceof Buffer?N=T:ArrayBuffer.isView(T)?N=Buffer.from(T.buffer,T.byteOffset,T.byteLength):T instanceof ArrayBuffer?N=Buffer.from(T):T instanceof Fi?N=T[Oo]:N=Buffer.from(typeof T=="string"?T:String(T)),f+=N.length,c.push(N)}}this[Oo]=Buffer.concat(c);let d=i&&i.type!==void 0&&String(i.type).toLowerCase();d&&!/[^\u0020-\u007E]/.test(d)&&(this[yx]=d)}get size(){return this[Oo].length}get type(){return this[yx]}text(){return Promise.resolve(this[Oo].toString())}arrayBuffer(){let a=this[Oo],i=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);return Promise.resolve(i)}stream(){let a=new TZ;return a._read=function(){},a.push(this[Oo]),a.push(null),a}toString(){return"[object Blob]"}slice(){let a=this.size,i=arguments[0],c=arguments[1],f,d;i===void 0?f=0:i<0?f=Math.max(a+i,0):f=Math.min(i,a),c===void 0?d=a:c<0?d=Math.max(a+c,0):d=Math.min(c,a);let g=Math.max(d-f,0),v=this[Oo],w=v.slice(f,f+g),T=new Fi([],{type:arguments[2]});return T[Oo]=w,T}};Object.defineProperties(Fi.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(Fi.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});function sr(o,a,i){Error.call(this,o),this.message=o,this.type=a,i&&(this.code=this.errno=i.code),Error.captureStackTrace(this,this.constructor)}sr.prototype=Object.create(Error.prototype);sr.prototype.constructor=sr;sr.prototype.name="FetchError";var bx;try{bx=require("encoding").convert}catch(o){}var Mo=Symbol("Body internals"),UD=is.default.PassThrough;function Hn(o){var a=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=i.size;let f=c===void 0?0:c;var d=i.timeout;let g=d===void 0?0:d;o==null?o=null:GD(o)?o=Buffer.from(o.toString()):Sf(o)||(Buffer.isBuffer(o)||(Object.prototype.toString.call(o)==="[object ArrayBuffer]"?o=Buffer.from(o):ArrayBuffer.isView(o)?o=Buffer.from(o.buffer,o.byteOffset,o.byteLength):o instanceof is.default||(o=Buffer.from(String(o))))),this[Mo]={body:o,disturbed:!1,error:null},this.size=f,this.timeout=g,o instanceof is.default&&o.on("error",function(v){let w=v.name==="AbortError"?v:new sr(`Invalid response body while trying to fetch ${a.url}: ${v.message}`,"system",v);a[Mo].error=w})}Hn.prototype={get body(){return this[Mo].body},get bodyUsed(){return this[Mo].disturbed},arrayBuffer(){return bc.call(this).then(function(o){return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)})},blob(){let o=this.headers&&this.headers.get("content-type")||"";return bc.call(this).then(function(a){return Object.assign(new Fi([],{type:o.toLowerCase()}),{[Oo]:a})})},json(){var o=this;return bc.call(this).then(function(a){try{return JSON.parse(a.toString())}catch(i){return Hn.Promise.reject(new sr(`invalid json response body at ${o.url} reason: ${i.message}`,"invalid-json"))}})},text(){return bc.call(this).then(function(o){return o.toString()})},buffer(){return bc.call(this)},textConverted(){var o=this;return bc.call(this).then(function(a){return kZ(a,o.headers)})}};Object.defineProperties(Hn.prototype,{body:{enumerable:
`)),p.join(`
`)}function eP(n,t,e,r){let s=O(t),u=r[r.length-1],l=new Array(u).fill(0),h=t.length,p=e==="complex64"?ah(n):n;if(h>1)for(let m=0;m<s/u;m++){let y=m*u;for(let b=0;b<u;b++)l[b]=Math.max(l[b],oh(p[y+b],0,e).length)}return l}function oh(n,t,e){let r;return Array.isArray(n)?r=`${parseFloat(n[0].toFixed(by))} + ${parseFloat(n[1].toFixed(by))}j`:dn(n)?r=`'${n}'`:e==="bool"?r=J2(n):r=parseFloat(n.toFixed(by)).toString(),St(r,t)}function J2(n){return n===0?"false":"true"}function jp(n,t,e,r,s,u=!0){let l=e==="complex64"?2:1,h=t[0],p=t.length;if(p===0){if(e==="complex64"){let I=ah(n);return[oh(I[0],0,e)]}return e==="bool"?[J2(n[0])]:[n[0].toString()]}if(p===1){if(h>Y2){let D=sh*l,R=Array.from(n.slice(0,D)),A=Array.from(n.slice((h-sh)*l,h*l));return e==="complex64"&&(R=ah(R),A=ah(A)),["["+R.map((L,_)=>oh(L,s[_],e)).join(", ")+", ..., "+A.map((L,_)=>oh(L,s[h-sh+_],e)).join(", ")+"]"]}let I=e==="complex64"?ah(n):Array.from(n);return["["+I.map((D,R)=>oh(D,s[R],e)).join(", ")+"]"]}let m=t.slice(1),y=r.slice(1),b=r[0]*l,x=[];if(h>Y2){for(let I=0;I<sh;I++){let D=I*b,R=D+b;x.push(...jp(n.slice(D,R),m,e,y,s,!1))}x.push("...");for(let I=h-sh;I<h;I++){let D=I*b,R=D+b;x.push(...jp(n.slice(D,R),m,e,y,s,I===h-1))}}else for(let I=0;I<h;I++){let D=I*b,R=D+b;x.push(...jp(n.slice(D,R),m,e,y,s,I===h-1))}let S=p===2?",":"";x[0]="["+x[0]+S;for(let I=1;I<x.length-1;I++)x[I]=" "+x[I]+S;let C=`,
`;for(let I=2;I<p;I++)C+=`
`;return x[x.length-1]=" "+x[x.length-1]+"]"+(u?"":C),x}function ah(n){let t=[];for(let e=0;e<n.length;e+=2)t.push([n[e],n[e+1]]);return t}class bn{constructor(t,e,r){if(this.dtype=e,this.shape=t.slice(),this.size=O(t),r!=null){let s=r.length;k(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(e==="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=r||Kt(e,this.size),this.strides=Jt(t)}set(t,...e){e.length===0&&(e=[0]),k(e.length===this.rank,()=>`The number of provided coordinates (${e.length}) must match the rank (${this.rank})`);let r=this.locToIndex(e);this.values[r]=t}get(...t){t.length===0&&(t=[0]);let e=0;for(let s of t){if(s<0||s>=this.shape[e]){let u=`Requested out of range element at ${t}. Buffer shape=${this.shape}`;throw new Error(u)}e++}let r=t[t.length-1];for(let s=0;s<t.length-1;++s)r+=this.strides[s]*t[s];return this.values[r]}locToIndex(t){if(this.rank===0)return 0;if(this.rank===1)return t[0];let e=t[t.length-1];for(let r=0;r<t.length-1;++r)e+=this.strides[r]*t[r];return e}indexToLoc(t){if(this.rank===0)return[];if(this.rank===1)return[t];let e=new Array(this.shape.length);for(let r=0;r<e.length-1;++r)e[r]=Math.floor(t/this.strides[r]),t-=e[r]*this.strides[r];return e[e.length-1]=t,e}get rank(){return this.shape.length}toTensor(){return Gs().makeTensor(this.values,this.shape,this.dtype)}}let Gs=null,Tu=null,Z2=null;function nP(n){Gs=n}function rP(n){Tu=n}function sP(n){Z2=n}class at{constructor(t,e,r,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=O(t),this.strides=Jt(t),this.dataId=r,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let t=await this.data();return Tu.buffer(this.shape,this.dtype,t)}bufferSync(){return Tu.buffer(this.shape,this.dtype,this.dataSync())}async array(){let t=await this.data();return Mr(this.shape,t)}arraySync(){return Mr(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let t=Gs().read(this.dataId);if(this.dtype==="string"){let e=await t;try{return e.map(r=>rh(r))}catch(r){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return t}dataSync(){this.throwIfDisposed();let t=Gs().readSync(this.dataId);if(this.dtype==="string")try{return t.map(e=>rh(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t}async bytes(){this.throwIfDisposed();let t=await Gs().read(this.dataId);return this.dtype==="string"?t:new Uint8Array(t.buffer)}dispose(){if(this.isDisposed)return;Gs().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(t=!1){return Tu.print(this,t)}clone(){return this.throwIfDisposed(),Tu.clone(this)}toString(t=!1){let e=this.dataSync();return tP(e,this.shape,this.dtype,t)}cast(t){return this.throwIfDisposed(),Tu.cast(this,t)}variable(t=!0,e,r){return this.throwIfDisposed(),Gs().makeVariable(this,t,e,r)}}Object.defineProperty(at,Symbol.hasInstance,{value:n=>!!n&&n.data!=null&&n.dataSync!=null&&n.throwIfDisposed!=null});class ih extends at{constructor(t,e,r,s){super(t.shape,t.dtype,t.dataId,s);this.trainable=e,this.name=r}assign(t){if(t.dtype!==this.dtype)throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);if(!K(t.shape,this.shape))throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);Gs().disposeTensor(this),this.dataId=t.dataId,Gs().incRef(this,null)}dispose(){Gs().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(ih,Symbol.hasInstance,{value:n=>n instanceof at&&n.assign!=null&&n.assign instanceof Function});(function(n){n.R0="R0",n.R1="R1",n.R2="R2",n.R3="R3",n.R4="R
Manifest JSON has weights with names: ${h.join(", ")}.`)}let p=s.reduce((S,C,I)=>(C&&S.push(I),S),[]),m=[];p.forEach(S=>{t[S].paths.forEach(C=>{let I=e+(e.endsWith("/")?"":"/")+C;m.push(I)})});let y=await n(m),b={},x=0;return p.forEach(S=>{let C=t[S].paths.length,I=0;for(let _=0;_<C;_++)I+=y[x+_].byteLength;let D=new ArrayBuffer(I),R=new Uint8Array(D),A=0;for(let _=0;_<C;_++){let B=new Uint8Array(y[x+_]);R.set(B,A),A+=B.byteLength}let L=u[S];L.forEach(_=>{let B=D.slice(_.groupOffset,_.groupOffset+_.sizeBytes),V=Jp(B,[_.manifestEntry]);for(let q in V)b[q]=V[q]}),x+=C}),b}}let XP="application/octet-stream",YP="application/json";class Fy{constructor(t,e){if(this.DEFAULT_METHOD="POST",e==null&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,this.weightUrlConverter=e.weightUrlConverter,e.fetchFunc!=null?(k(typeof e.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=e.fetchFunc):this.fetch=ft().platform.fetch,k(t!=null&&t.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(t)&&k(t.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${t.length}).`),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);e.body=new FormData;let r=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],s={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:r};e.body.append("model.json",new Blob([JSON.stringify(s)],{type:YP}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:XP}),"model.weights.bin");let u=await this.fetch(this.path,e);if(u.ok)return{modelArtifactsInfo:ch(t),responses:[u]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${u.status}.`)}async load(){let t=await this.fetch(this.path,this.requestInit);if(!t.ok)throw new Error(`Request to ${this.path} failed with status code ${t.status}. Please verify this URL points to the model JSON of the model to load.`);let e;try{e=await t.json()}catch(S){let C=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?C+=" 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.":C+=" Please make sure the server is serving valid JSON for this request.",new Error(C)}let r=e.modelTopology,s=e.weightsManifest,u=e.generatedBy,l=e.convertedBy,h=e.format,p=e.userDefinedMetadata;if(r==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let m,y;if(s!=null){let S=await this.loadWeights(s);[m,y]=S}let b={modelTopology:r,weightSpecs:m,weightData:y,userDefinedMetadata:p,generatedBy:u,convertedBy:l,format:h},x=e.modelInitializer;return x&&(b.modelInitializer=x),b}async loadWeights(t){let e=Array.isArray(this.path)?this.path[1]:this.path,[r,s]=JP(e),u=this.weightPathPrefix||r,l=[];for(let y of t)l.push(...y.weights);let h=[],p=[];for(let y of t)for(let b of y.paths)this.weightUrlConverter!=null?p.push(this.weightUrlConverter(b)):h.push(u+b+s);this.weightUrlConverter&&h.push(...await Promise.all(p));let m=await yS(h,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[l,Zp(m)]}}Fy.URL_SCHEME_REGEX=/^https?:\/\//;function JP(n){let t=n.lastIndexOf("/"),e=n.lastIndexOf("?"),r=n.su
Actual: ${s}.
Expected: ${u}.`);for(let l=0;l<u.length;++l){let h=s[l],p=u[l];if(!e(h,p))throw new Error(`Arrays differ: actual[${l}] = ${h}, expected[${l}] = ${p}.
Actual: ${s}.
Expected: ${u}.`)}}function vO(n,t){n().then(()=>t.fail(),()=>t())}function yO(n,t){let e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return dn(n)||dn(n[0])||dn(t)||dn(t[0])?Vy(n,e,(r,s)=>r==s):Vy(n,t,(r,s)=>Gy(r,s,0))}function Uy(n,t,e){if(e==null&&(e=ad()),!Gy(n,t,e))throw new Error(`Numbers differ: actual === ${n}, expected === ${t}`)}function Gy(n,t,e){return!isFinite(n)&&!isFinite(t)?!0:!(isNaN(n)||isNaN(t)||Math.abs(n-t)>e)}function bO(n,t,e){for(let r=0;r<n.length;r++)if(n[r]<t||n[r]>e)throw new Error(`Value out of range:${n[r]} low: ${t}, high: ${e}`)}function wO(n,t){expect(new Float32Array(n)).toEqual(new Float32Array(t))}var xO=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:RS,expectArraysClose:gO,testEpsilon:ad,expectPromiseToFail:vO,expectArraysEqual:yO,expectNumbersClose:Uy,expectValuesInRange:bO,expectArrayBuffersEqual:wO});let PS="2.7.0";function TO(){ft().set("PROD",!0)}function kO(){ft().set("DEBUG",!0)}function SO(){ft().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Tn(n){ft().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}sP(Tn);function CO(){J.disposeVariables()}function yo(){return J}function id(){return J.memory()}function NO(n){return J.profile(n)}function ot(n,t){return J.tidy(n,t)}function oe(n){let t=mo(n);t.forEach(e=>e.dispose())}function An(n){return J.keep(n)}function IO(n){return J.time(n)}function OS(n){return J.setBackend(n)}function EO(){return J.ready()}function DO(){return J.backendName}function $O(n){J.removeBackend(n)}function AO(n){return J.findBackend(n)}function _O(n){return J.findBackendFactory(n)}function Hy(n,t,e=1){return J.registerBackend(n,t,e)}function MS(){return J.backend}function FO(n,t){ft().setPlatform(n,t)}function RO(n,t){let e=z(n,"a","add"),r=z(t,"b","add");[e,r]=nn(e,r);let s=(l,h)=>{let p=l.add(e,r);return h([e,r]),p},u={a:e,b:r};return J.runKernelFunc(s,u,null,ri)}let Nt=X({add_:RO});function PO(n,t){let e=z(n,"a","floorDiv"),r=z(t,"b","floorDiv");[e,r]=nn(e,r);let s=(l,h)=>{let p=l.floorDiv(e,r);return h([e,r]),p},u={a:e,b:r};return J.runKernelFunc(s,u,null,Uv)}let ud=X({floorDiv_:PO});function OO(n,t){let e=z(n,"a","div"),r=z(t,"b","div");if([e,r]=nn(e,r),e.dtype==="int32"&&r.dtype==="int32")return ud(e,r);let s=(h,p)=>{let m=h.realDivide(e,r);return p([e,r]),m},u={a:e,b:r},l={};return J.runKernelFunc(s,u,null,mu,l)}let Ht=X({div_:OO});function MO(n,t){let e=z(n,"a","mul"),r=z(t,"b","mul");[e,r]=nn(e,r);let s=(l,h)=>{let p=l.multiply(e,r);return h([e,r]),p},u={a:e,b:r};return J.runKernelFunc(s,u,null,gu)}let st=X({mul_:MO});function LO(n){let t=z(n,"x","abs"),e={x:t};return J.runKernelFunc((r,s)=>(s([t]),t.dtype==="complex64"?r.complexAbs(t):r.abs(t)),e,null,hp)}let kn=X({abs_:LO});function BO(n){let t=z(n,"x","acos"),e={x:t};return J.runKernelFunc((r,s)=>{let u=r.acos(t);return s([t]),u},e,null,dl)}let qy=X({acos_:BO});function zO(n){let t=z(n,"x","acosh"),e={x:t};return J.runKernelFunc((r,s)=>{let u=r.acosh(t);return s([t]),u},e,null,ml)}let jy=X({acosh_:zO});function WO(n){k(Array.isArray(n),()=>"The argument passed to tf.addN() must be a list of tensors"),k(n.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${n.length}`);let t=n.map((u,l)=>z(u,`tensors${l}`,"addN")),e=t[0];t.forEach(u=>{if(u.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(u=>{if(!K(u.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=(u,l)=>{let h=u.addN(t);return l(t),h},s=t;return J.runKernelFunc(r,s,null,$v)}let LS=X({addN_:WO});function Ky(n,t){for(let e=0;e<n.length;++e)if(n[n.length-e-1]!==t-1-e)return!1;return!0}function BS(n,t,e){let r=n.length+t.length,s=[],u=0,l=0;for(let h=0;h<r;h++)e.indexOf(h)===-1?s.push(n[u++]):s.push(t[l++]);return s}function Bn(n,t){let e=[],r=n.length;for(let u=0;u<r;u++)t.indexOf(u)===-1&&e.push(n[u]);let s=t.map(u=>n[u]);return[e,s]}function zn(n,t
with dtype ${l.dtype}. `)});let r=(l,h)=>{let p=Et(t,e[0].shape)[0],m=bo(e.map(x=>x.shape),p);if(O(m)===0)return vn([],m);if(e=e.filter(x=>x.size>0),e.length===1)return e[0];let y=e.map(x=>x.shape);fd(y,p);let b=l.concat(e,p);return h(e),b},s=e,u={axis:t};return J.runKernelFunc(r,s,null,kl,u)}let sn=X({concat_:rM});function sM(n){let t=z(n,"x","sigmoid"),e={x:t};return J.runKernelFunc((r,s)=>{let u=r.sigmoid(t);return s([u]),u},e,null,Yl)}let js=X({sigmoid_:sM});function oM(n,t,e){let r=z(n,"x","slice");if(r.rank===0)throw new Error("Slicing scalar is not possible");let s=(h,p)=>{let[m,y]=od(r,t,e);return By(r,m,y),p([r]),h.slice(r,m,y)},u={x:r},l={begin:t,size:e};return J.runKernelFunc(s,u,null,Pp,l)}let ge=X({slice_:oM});function aM(n){let t=z(n,"x","tanh"),e={x:t};return J.runKernelFunc((r,s)=>{let u=r.tanh(t);return s([u]),u},e,null,Ql)}let Du=X({tanh_:aM});function iM(n,t,e,r,s,u){let l=z(n,"forgetBias","basicLSTMCell"),h=z(t,"lstmKernel","basicLSTMCell"),p=z(e,"lstmBias","basicLSTMCell"),m=z(r,"data","basicLSTMCell"),y=z(s,"c","basicLSTMCell"),b=z(u,"h","basicLSTMCell"),x=sn([m,b],1),S=xe(x,h),C=Nt(S,p),I=C.shape[0],D=C.shape[1]/4,R=[I,D],A=ge(C,[0,0],R),L=ge(C,[0,D],R),_=ge(C,[0,D*2],R),B=ge(C,[0,D*3],R),V=Nt(st(js(A),Du(L)),st(y,js(Nt(l,_)))),q=st(Du(V),js(B));return[V,q]}let uM=X({basicLSTMCell_:iM});function cM(n,t,e){let r=z(n,"x","batchToSpaceND"),s=t.reduce((p,m)=>p*m);k(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),k(e.length===t.length,()=>`crops.length is ${e.length} but should be equal to blockShape.length ${t.length}`),k(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 u=p=>p.batchToSpaceND(r,t,e),l={x:r},h={blockShape:t,crops:e};return J.runKernelFunc(u,l,null,Rv,h)}let mh=X({batchToSpaceND_:cM});function lM(n){let t;return n.rank===0||n.rank===1?t=rt(n,[1,1,1,n.size]):n.rank===2?t=rt(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?t=rt(n,[1,n.shape[0],n.shape[1],n.shape[2]]):t=n,t}function hM(n,t,e,r,s,u){u==null&&(u=.001);let l=z(n,"x","batchNorm"),h=z(t,"mean","batchNorm"),p=z(e,"variance","batchNorm"),m;s!=null&&(m=z(s,"scale","batchNorm"));let y;r!=null&&(y=z(r,"offset","batchNorm")),k(h.rank===p.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(y==null||h.rank===y.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(m==null||h.rank===m.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let b=lM(l),x=(D,R)=>(R([b,h,p,m]),D.batchNorm(b,pd(h),pd(p),pd(y),pd(m),u)),S={x:b,scale:m,offset:y,mean:h,variance:p},C={varianceEpsilon:u},I=J.runKernelFunc(x,S,null,$l,C);return rt(I,l.shape)}function pd(n){return n==null?null:n.rank===0?rt(n,[n.size]):n.rank===1?n:n.rank===2?rt(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?rt(n,[1,n.shape[0],n.shape[1],n.shape[2]]):n}let fi=X({batchNorm_:hM});function fM(n,t,e,r,s,u){let l=z(n,"x","batchNorm"),h=z(t,"mean","batchNorm"),p=z(e,"variance","batchNorm"),m;s!=null&&(m=z(s,"scale","batchNorm"));let y;return r!=null&&(y=z(r,"offset","batchNorm")),k(l.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${l.rank}.`),k(h.rank===2||h.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${h.rank}.`),k(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${p.rank}.`),m!=null&&k(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${m.rank}.`),y!=null&&k(y.rank===2||y.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${y.rank}.`),fi(l,h,p,y,m,u)}let zS=X({batchNorm2d_:fM});function pM(n,t,e,r,s,u){let l=z(n,"x","batchNorm"),h=z(t,"mean","batchNorm"),p=z(e,"variance","batchNorm"),m;s!=null&&(m=z(s,"scale","batchNorm"));let y;return r!=null&&(y=z(r,"offset","batchNorm")),k(l.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${l.rank}.`),
${s} and ${t} for depthToSpace with input shape
${r.shape}`),k(u*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${u} and ${t} for depthToSpace with input shape
${r.shape}`),k(l%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${l} for depthToSpace with input shape ${r.shape}`);let h=y=>y.depthToSpace(r,t,e),p={x:r},m={blockSize:t,dataFormat:e};return J.runKernelFunc(h,p,null,N2,m)}let ib=X({depthToSpace_:FM});function RM(n,t,e,r,s="NHWC",u=[1,1],l){let h=z(n,"x","depthwiseConv2d"),p=z(t,"filter","depthwiseConv2d"),m=h,y=!1;h.rank===3&&(y=!0,m=rt(h,[1,h.shape[0],h.shape[1],h.shape[2]])),k(m.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${m.rank}.`),k(p.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),k(m.shape[3]===p.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${m.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),l!=null&&k(nt(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${l} but got pad ${r}.`);let b=(I,D)=>{u==null&&(u=[1,1]),k(wn(e,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${e} and dilations '${u}'`);let R=Kn(m.shape,p.shape,e,u,r,l,!0),A=I.depthwiseConv2D(m,p,R);return D([m,p]),A},x={x:m,filter:p},S={strides:e,pad:r,dataFormat:s,dilations:u,dimRoundingMode:l},C=J.runKernelFunc(b,x,null,bp,S);return y?rt(C,[C.shape[1],C.shape[2],C.shape[3]]):C}let pi=X({depthwiseConv2d_:RM});function PM(n){let t=z(n,"x","diag"),e=s=>{let u=rt(t,[t.size]),l=s.diag(u),h=[...n.shape,...n.shape];return rt(l,h)},r={x:t};return J.runKernelFunc(e,r,null,I2)}let OM=X({diag_:PM});function MM(n,t,e,r,s=[1,1],u="NHWC"){let l=z(n,"x","dilation2d"),h=z(t,"filter","dilation2d");k(l.rank===3||l.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${l.rank}.`),k(h.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${h.rank}.`),k(u==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${u}`);let p=l,m=!1;l.rank===3&&(p=rt(l,[1,l.shape[0],l.shape[1],l.shape[2]]),m=!0);let y={x:p,filter:h},b={strides:e,pad:r,dilations:s},x=J.runKernel(wp,y,b);return m?rt(x,[x.shape[1],x.shape[2],x.shape[3]]):x}let ub=X({dilation2d_:MM});function di(n,t){let e=n.length,r=[];for(let s=0;s<e;s++){let u=e-1-s,l=n[u]||1,h=t[t.length-1-s]||1;h>1&&l===1&&r.unshift(u)}return r}function Sn(n,t){let e=[];for(let r=0;r<t.length;r++){let s=n[n.length-r-1],u=t.length-r-1,l=t[u];(s==null||s===1&&l>1)&&e.unshift(u)}return e}function ve(n,t){let e=[],r=Math.max(n.length,t.length);for(let s=0;s<r;s++){let u=n[n.length-s-1];u==null&&(u=1);let l=t[t.length-s-1];if(l==null&&(l=1),u===1)e.unshift(l);else if(l===1)e.unshift(u);else if(u!==l){let h=`Operands could not be broadcast together with shapes ${n} and ${t}.`;throw Error(h)}else e.unshift(u)}return e}function LM(n,t){let e=z(n,"a","equal"),r=z(t,"b","equal");[e,r]=nn(e,r),ve(e.shape,r.shape);let s=l=>l.equal(e,r),u={a:e,b:r};return J.runKernelFunc(s,u,null,D2)}let gs=X({equal_:LM});function BM(n,t,e){let r=z(t,"a","where"),s=z(e,"b","where"),u=z(n,"condition","where","bool"),l=ve(r.shape,s.shape),h=gh(r,l),p=gh(s,l);u.rank===1&&k(u.shape[0]===r.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),u.rank!==1&&$(u.shape,p.shape,"Error in where: ");let m=(b,x)=>{let S=b.select(u,h,p);return x([u]),S},y={condition:u,t:h,e:p};return J.runKernelFunc(m,y,null,uy)}let er=X({where_:BM});function zM(n){let t=z(n,"x","zerosLike"),e={x:t};return J.runKernelFunc(r=>r.zerosLike(t),e,null,my)}let fe=X({zerosLike_:zM});function WM(n,t){let e=z(n,"a","div"),r=z(t,"b","div");[e,r]=nn(e,r);let s=Ht(e,r),u=fe(s),l=gs(r,u);return er(l,u,s)}let cb=X({divNoNan_:WM});function VM(n,t){let e=z(n,"t1","dot"),r=z(t,"t2","dot");k((e.rank===1||e.rank===2)&&(r.rank===1||r.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${e.rank} and ${r.rank}.`);let s=e.rank===1?e.size:e.shape[1],u=r.rank===1?r.size:r.shape[0];if(k(s===u,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${u}.`),e.rank===1&&r.rank===1){let l=rt(e,[1,-1]),h=rt(r,[-1,1]),p=xe(l,h
rank ${u.rank}.`),k(nt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let l=u,h=!1;u.rank===3&&(h=!0,l=rt(u,[1,u.shape[0],u.shape[1],u.shape[2]]));let p=(x,S)=>{let C=x.localResponseNormalization4D(l,t,e,r,s);return S([l,C]),C},m={x:l},y={depthRadius:t,bias:e,alpha:r,beta:s},b=J.runKernelFunc(p,m,null,jv,y);return h?rt(b,[b.shape[1],b.shape[2],b.shape[3]]):b}let pb=X({localResponseNormalization_:hL});function fL(n){let t=z(n,"x","log"),e={x:t};return J.runKernelFunc((r,s)=>{let u=r.log(t);return s([t]),u},e,null,Pl)}let Nr=X({log_:fL});function pL(n){let t=z(n,"x","log1p"),e={x:t};return J.runKernelFunc((r,s)=>{let u=r.log1p(t);return s([t]),u},e,null,Ol)}let wd=X({log1p_:pL});function dL(n){return k(Ln(n),()=>"The f passed in grad(f) must be a function"),(t,e)=>{let r=z(t,"x","tf.grad",null),s=e!=null?z(e,"dy","tf.grad"):null;return J.tidy(()=>{let{value:u,grads:l}=J.gradients(()=>n(r),[r],s);return s!=null&&$(u.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),xd(l),l[0]})}}function mL(n){return k(Ln(n),()=>"The f passed in grads(f) must be a function"),(t,e)=>{k(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let r=uh(t,"args","tf.grads",null),s=e!=null?z(e,"dy","tf.grads"):null;return J.tidy(()=>{let{value:u,grads:l}=J.gradients(()=>n(...r),r,s);return s!=null&&$(u.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),xd(l),l})}}function gL(n){return k(Ln(n),()=>"The f passed in valueAndGrad(f) must be a function"),(t,e)=>{k(t instanceof at,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),k(e==null||e instanceof at,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:r,value:s}=J.gradients(()=>n(t),[t],e);return xd(r),{grad:r[0],value:s}}}function vL(n){return k(Ln(n),()=>"The f passed in valueAndGrads(f) must be a function"),(t,e)=>{k(Array.isArray(t)&&t.every(s=>s instanceof at),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),k(e==null||e instanceof at,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let r=J.gradients(()=>n(...t),t,e);return e!=null&&$(r.value.shape,e.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),xd(r.grads),r}}function db(n,t){k(Ln(n),()=>"The f passed in variableGrads(f) must be a function"),k(t==null||Array.isArray(t)&&t.every(m=>m instanceof ih),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let e=t!=null;if(!e){t=[];for(let m in J.registeredVariables)t.push(J.registeredVariables[m])}let r=e?t.filter(m=>!m.trainable):null,s=t.length;t=t.filter(m=>m.trainable),k(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);let u=!0,{value:l,grads:h}=J.gradients(n,t,null,u);k(h.some(m=>m!=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()."),k(l.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${l.rank} tensor`);let p={};return t.forEach((m,y)=>{h[y]!=null&&(p[m.name]=h[y])}),r!=null&&r.forEach(m=>p[m.name]=null),{value:l,grads:p}}function Ks(n){return J.customGrad(n)}function xd(n){let t=n.filter(e=>e==null).length;if(t>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 yL(n){let t=z(n,"x","neg"),e={x:t};return J.runKernelFunc(r=>r.neg(t),e,null,ty)}let on=X({neg_:yL});function bL(n){let t=z(n,"x","softplus"),e={x:t};return J.runKernelFunc((r,s)=>{let u=r.softplus(t);return s([t]),u},e,null,Jl)}let Ru=X({softplus_:bL});function wL(n){let t=z(n,"x","logSigmoid"),e=Ks(r=>{let s=on(Ru(on(r))),u=l=>{let h=st(l,js(on(r)));return h};return{value:s,gradFunc:u}});return e(t)}let tC=X({logSigmoid_:wL});function xL(n,t=null,e=!1){let r=z(n,"x","max"),s=(h,p)=>{let m=Et(t,r.shape),y=m,b=hr(y,r.rank),x=r;b!=null&&(x=re(r,b),y=Cr(y.length,x.rank));let S=h.max(x,y);b!=null&&x.dispose();let C=S;if(e){let I=zn(C.shape,Et(t,r.shape));C=rt(C,I),S.dispose()}return p([r,C]),C},u={x:r},l={reductionIndices:t,keepDims:e};return J.runKernelFunc(s,u,null,Ml,l)}let dr=X({max_:xL});function TL(n,t){let e=z(n,"a","sub"),r=z(t,"b","sub");[e,r]=nn(e,r);let s=(l,h)=>{let p=l.subtract(e,r);return h([e,r]),p},u={a:e,b:r};return J.runKernelFunc(s,u,null,bu)}let Mt=X({sub_:TL});function kL(n,t=null,e=!1){let r=z(n,"x","sum");r.dtype==="bool"&&(r=Rt(r,"int32"));let s=(h,p)=>{p([r]);let m=Et(t,r.shape),y=hr(m,r.rank),b=m,x=r;y!=null&&(x=re(r,y),b=Cr(b.length,r.rank));let S=h.sum(x,b);if(e){let C=zn(S.shape,m);S=rt(S,C)}return S},u={x:r},l={axis:t,keepDims:e};return J.runKernelFunc(s,u,null,cy,l)}let Xt=X({sum_:kL});function SL(n,t=-1){let e=z(n,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and axis was ${t}`);let r=(l,h)=>{let p=!0,m=dr(n,t,!0),y=Mt(n,m),b=Mt(Rt(y,"float32"),Nr(Xt(Br(y),t,p)));return h([b]),b},s={logits:e},u={axis:t};return J.runKernelFunc(r,s,null,qv,u)}let Td=X({logSoftmax_:SL});function CL(n,t=null,e=!1){let r=z(n,"x","logSumExp"),s=Et(t,r.shape),u=dr(r,s,!0),l=Mt(r,u),h=Br(l),p=Xt(h,s),m=Nr(p),y=Nt(rt(u,m.shape),m);if(e){let b=zn(y.shape,s);return rt(y,b)}return y}let mb=X({logSumExp_:CL});function NL(n,t){let e=z(n,"a","logicalAnd","bool"),r=z(t,"b","logicalAnd","bool");ve(e.shape,r.shape);let s={a:e,b:r};return J.runKernelFunc(u=>u.logicalAnd(e,r),s,null,P2)}let es=X({logicalAnd_:NL});function IL(n){let t=z(n,"x","logicalNot","bool"),e={x:t};return J.runKernelFunc(r=>r.logicalNot(t),e,null,Ip)}let xh=X({logicalNot_:IL});function EL(n,t){let e=z(n,"a","logicalOr","bool"),r=z(t,"b","logicalOr","bool");ve(e.shape,r.shape);let s={a:e,b:r};return J.runKernelFunc(u=>u.logicalOr(e,r),s,null,O2)}let kd=X({logicalOr_:EL});function DL(n,t){let e=z(n,"a","logicalXor","bool"),r=z(t,"b","logicalXor","bool");return ve(e.shape,r.shape),es(kd(n,t),xh(es(n,t)))}let eC=X({logicalXor_:DL});function $L(n,t,e,r,s){let u=z(n,"x","maxPool"),l=1,h=u,p=!1;u.rank===3&&(p=!0,h=rt(u,[1,u.shape[0],u.shape[1],u.shape[2]])),k(h.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${h.rank}.`),k(wn(e,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${l}'`),s!=null&&k(nt(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let m=(S,C)=>{let I=tr(h.shape,t,e,1,r,s),D;return I.filterWidth===1&&I.filterHeight===1&&K(I.inShape,I.outShape)?D=h.clone():D=S.maxPool(h,I),C([h,D]),D},y={x:h},b={filterSize:t,strides:e,pad:r,dimRoundingMode:s},x=J.runKernelFunc(m,y,null,Ll,b);return p?rt(x,[x.shape[1],x.shape[2],x.shape[3]]):x}let Th=X({maxPool_:$L});function AL(n,t=[1,1,1],e,r,s,u="NDHWC",l){l==null?l=[1,1,1]:Tn("dilations is deprecated, this field will be gone in v3.0.0.");let h=z(n,"x","maxPool3d"),p=h,m=!1;h.rank===4&&(m=!0,p=rt(h,[1,h.shape[0],h.shape[1],h.shape[2],h.shape[3]])),k(p.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${p.rank}.`),k(u==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${u}`),k(wn(e,l),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${e} and dilations '${l}'`),s!=null&&k(nt(r),()=>`Error in maxPool3d: pad must be an integer when
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 l}else{let u=n;if(u.className==null||u.config==null)throw new Q(`${r}: Improper config format: ${JSON.stringify(u)}.
'className' and 'config' must set.`);let l=u.className,h,p;if(l in e?[h,p]=e[l]:l in rs?[h,p]=rs.className:l in t&&([h,p]=t[l]),h==null)throw new Q(`Unknown ${r}: ${l}. This may be due to one of the following reasons:
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(p!=null){let m={};for(let S of Object.keys(rs))m[S]=rs[S];for(let S of Object.keys(e))m[S]=e[S];let y=u.config;y.customObjects=m;let b=Object.assign({},rs);for(let S of Object.keys(e))rs[S]=e[S];tw(u.config);let x=p(h,u.config,e,s);return rs=Object.assign({},b),x}else{let m=Object.assign({},rs);for(let b of Object.keys(e))rs[b]=e[b];let y=new h(u.config);return rs=Object.assign({},m),y}}}function iV(n,t){return n<t?-1:n>t?1:0}function Xd(n,t){return-1*iV(n,t)}function mht(n){switch(n){case"float32":return"float32";default:throw new Q(`Invalid dtype: ${n}`)}}function ght(n,t){if(n==null||t==null)return n===t;if(n.length!==t.length)return!1;for(let e=0;e<n.length;++e)if(n[e]!==t[e])return!1;return!0}function ma(n){if(n==null)return n;let t=[];for(let e of n)t.indexOf(e)===-1&&t.push(e);return t}function uV(n){if(n==null)throw new Q(`Invalid value in obj: ${JSON.stringify(n)}`);for(let t in n)if(n.hasOwnProperty(t))return!1;return!0}function Hu(n,t,e){if(e==null)return;if(n.indexOf(e)<0)throw new Q(`${e} is not a valid ${t}. Valid values are ${n} or null/undefined.`)}function ew(n,t,e=0,r=Infinity){return Vr(e>=0),Vr(r>=e),Array.isArray(n)&&n.length>=e&&n.length<=r&&n.every(s=>typeof s===t)}function _n(n,t){Array.isArray(n)?(k(n.length>0,()=>`${t} is unexpectedly an empty array.`),n.forEach((e,r)=>_n(e,`element ${r+1} of ${t}`))):k(Number.isInteger(n)&&n>0,()=>`Expected ${t} to be a positive integer, but got ${tN(n)}.`)}function tN(n){return n===null?"null":Array.isArray(n)?"["+n.map(t=>tN(t)).join(",")+"]":typeof n=="string"?`"${n}"`:`${n}`}function cV(n,t){let e=cr(),r,s=(...u)=>{let l=cr();return l-e<t||(e=l,r=n(...u)),r};return s}function eN(n){return n==="relu"?"relu":n==="linear"?"linear":n==="elu"?"elu":null}function vht(...n){Vr(n.length>0,"arrayOfValues is empty");for(let t of n)Vr(Array.isArray(t),"one of the values is not an array"),Vr(t.length>0,"one of the values is empty");return n.reduce((t,e)=>t.length===0?e.map(r=>[r]):e.map(r=>t.map(s=>[...s,r])).reduce((r,s)=>r.concat(s),[]),[])}function nw(n,t){return ot(()=>Wn(Xt(st(n,n),t,!0)))}class Wh extends li{getConfig(){return{}}}class rw extends Wh{constructor(t){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return ot(()=>{let e=nw(t,this.axis),r=fr(e,0,this.maxValue);return st(t,Ht(r,Nt(Cn(),e)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}rw.className="MaxNorm",kt(rw);class sw extends Wh{constructor(t){super();this.defaultAxis=0,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return ot(()=>Ht(t,Nt(Cn(),nw(t,this.axis))))}getConfig(){return{axis:this.axis}}}sw.className="UnitNorm",kt(sw);class ow extends Wh{apply(t){return Ys(t)}}ow.className="NonNeg",kt(ow);class aw extends Wh{constructor(t){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=t.minValue!=null?t.minValue:this.defaultMinValue,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.rate=t.rate!=null?t.rate:this.defaultRate,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return ot(()=>{let e=nw(t,this.axis),r=Nt(st(this.rate,fr(e,this.minValue,this.maxValue)),st(1-this.rate,e));return st(t,Ht(r,Nt(Cn(),e)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}aw.className="MinMaxNorm",kt(aw);let nN={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Nn(n){return Qb(n)}function rN(n,t={}){return zh(n,Lr.getMap().classNameMap,t,"constraint")}function In(n){if(n==null)return null;if(typeof n=="string"){let t=n in nN?nN[n]:n,e={className:t,config:{}};return rN(e)}else return n instanceof Wh?n:rN(n)}function lV(n){return new rw(n)}function hV(n){return new sw(n)}function fV(){return new ow}function pV(n){return new aw(n)}var dV=Object.freeze({__proto__:null,maxNorm:lV,unitNorm:hV,non
because the value dtype is ${e.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=e.shape),os(this.elementShape,e.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${t}.`),r.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${t}, because it has already been read.`);if(r.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${t}, because it has already been written.`);r.tensor=e,An(e),r.written=!0,this.tensors[t]=r}writeMany(t,e){if(t.length!==e.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${t.length} is not the same as tensors size: ${e.length}.`);t.forEach((r,s)=>this.write(r,e[s]))}gather(t,e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${e}`);if(t)t=t.slice(0,this.size());else{t=[];for(let s=0;s<this.size();s++)t.push(s)}if(t.length===0)return vn([],[0].concat(this.elementShape));let r=this.readMany(t);return os(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),mr(r,0)}concat(t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${t}`);if(this.size()===0)return vn([],[0].concat(this.elementShape));let e=[];for(let s=0;s<this.size();s++)e.push(s);let r=this.readMany(e);return os(this.elementShape,r[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${r[0].shape})`),sn(r,0)}scatter(t,e){if(e.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${e.dtype}`);if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let r=Math.max(...t);if(!this.dynamicSize&&r>=this.maxSize)throw new Error(`Max index must be < array size (${r} vs. ${this.maxSize})`);this.writeMany(t,bs(e,0))}split(t,e){if(e.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${e.dtype}`);let r=0,s=t.map(p=>(r+=p,r));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
2020-10-15 12:48:39 +02:00
tensor.shape[0], but sum of lengths is
2020-11-25 14:30:53 +01:00
${r}, and tensor's shape is: ${e.shape}`);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${t.length}), and the TensorArray is not marked as dynamically resizeable`);let u=r===0?0:e.size/r,l=[];ot(()=>{e=rt(e,[1,r,u]);for(let p=0;p<t.length;++p){let m=p===0?0:s[p-1],y=[0,m,0],b=[1,t[p],u];l[p]=rt(ge(e,y,b),this.elementShape)}return l});let h=[];for(let p=0;p<t.length;p++)h[p]=p;this.writeMany(h,l)}}class ec{constructor(t,e,r,s=-1){this.tensors=t,this.elementShape=e,this.elementDtype=r,t!=null&&t.forEach(u=>{if(r!==u.dtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${u.dtype}`);os(e,u.shape,"TensorList shape mismatch: "),An(u)}),this.idTensor=Ot(0),this.maxNumElements=s,An(this.idTensor)}get id(){return this.idTensor.id}copy(){return new ec([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(t){this.tensors.forEach(e=>{(t==null||!t.has(e.id))&&e.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(t,e,r=-1){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);if(r!==-1&&this.tensors.length!==r)throw new Error(`Operation expected a list with ${r} elements but got a list with ${this.tensors.length} elements.`);return os(t,this.elementShape,"TensorList shape mismatch: "),ot(()=>{let s=this.tensors.map(u=>rt(u,t));return mr(s,0)})}popBack(t,e){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let r=this.tensors.pop();return os(r.shape,t,"TensorList shape mismatch: "),rt(r,t)}pushBack(t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(os(t.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");An(t),this.tensors.push(t)}resize(t){if(t<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${t}`);if(this.maxNumElements!==-1&&t>this.maxNumElements)throw new Error(`TensorListResize input size ${t} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=t}getItem(t,e,r){if(r!==this.elementDtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${this.elementDtype}`);if(t<0||t>this.tensors.length)throw new Error(`Trying to access element ${t} in a list with ${this.tensors.length} elements.`);if(this.tensors[t]==null)throw new Error(`element at index ${t} is null.`);return os(this.tensors[t].shape,e,"TensorList shape mismatch: "),this.tensors[t]}setItem(t,e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error(`Trying to set element ${t} in a list with max ${this.maxNumElements} elements.`);os(this.elementShape,e.shape,"TensorList shape mismatch: "),An(e),this.tensors[t]=e}gather(t,e,r){if(e!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e}, but list elements ${this.elementDtype}`);return os(this.elementShape,r,"TensorList shape mismatch: "),t=t.slice(0,this.size()),t.length===0?vn([],[0].concat(this.elementShape)):ot(()=>{let s=t.map(u=>rt(this.tensors[u],r));return mr(s,0)})}concat(t,e){if(!!t&&t!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${t}`);return os(this.elementShape,e,"TensorList shape mismatch: "),this.size()===0?vn([],[0].concat(this.elementShape)):ot(()=>{let r=this.tensors.map(s=>rt(s,e));return sn(r,0)})}}function Fq(n,t,e){let r=n.dtype;if(n.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${n.shape}`);if(n.dtype!==e)throw new Error(`Invalid data types; op elements ${n.dtype}, but list elements ${e}`);let s=n.shape.slice(1
2020-10-15 12:48:39 +02:00
tensor.shape[0], but sum of lengths is
2020-11-25 14:30:53 +01:00
${r}, and tensor's shape is: ${n.shape}`);let u=r===0?0:n.size/r,l=ot(()=>{let p=[];n=rt(n,[1,r,u]);for(let m=0;m<t.length;++m){let y=m===0?0:s[m-1],b=[0,y,0],x=[1,t[m],u];p[m]=rt(ge(n,b,x),e)}return n.dispose(),p}),h=new ec([],e,n.dtype,t.length);for(let p=0;p<l.length;p++)h.setItem(p,l[p]);return h}let Mq=async(n,t,e)=>{switch(n.op){case"If":case"StatelessIf":{let r=P("thenBranch",n,t,e),s=P("elseBranch",n,t,e),u=P("cond",n,t,e),l=P("args",n,t,e),h=await u.data();return h[0]?e.functionMap[r].executeFunctionAsync(l,e.tensorArrayMap,e.tensorListMap):e.functionMap[s].executeFunctionAsync(l,e.tensorArrayMap,e.tensorListMap)}case"While":case"StatelessWhile":{let r=P("body",n,t,e),s=P("cond",n,t,e),u=P("args",n,t,e),l=await e.functionMap[s].executeFunctionAsync(u,e.tensorArrayMap,e.tensorListMap),h=u.map(y=>y.id),p=await l[0].data();l.forEach(y=>{!y.kept&&h.indexOf(y.id)===-1&&y.dispose()});let m=u;for(;p[0];){let y=m;m=await e.functionMap[r].executeFunctionAsync(m,e.tensorArrayMap,e.tensorListMap);let b=m.map(S=>S.id);y.forEach(S=>{!S.kept&&h.indexOf(S.id)===-1&&b.indexOf(S.id)===-1&&S.dispose()});let x=await e.functionMap[s].executeFunctionAsync(m,e.tensorArrayMap,e.tensorListMap);p=await x[0].data(),x.forEach(S=>{!S.kept&&h.indexOf(S.id)===-1&&b.indexOf(S.id)===-1&&S.dispose()})}return m}case"LoopCond":{let r=P("pred",n,t,e);return[Do(r)]}case"Switch":{let r=P("pred",n,t,e),s=P("data",n,t,e);return s.kept||(s=Do(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{let r=n.inputNames.find(s=>yr(s,t,e)!==void 0);if(r){let s=yr(r,t,e);return[Do(s)]}return}case"Enter":{let r=P("frameName",n,t,e),s=P("tensor",n,t,e);return e.enterFrame(r),[Do(s)]}case"Exit":{let r=P("tensor",n,t,e);return e.exitFrame(),[Do(r)]}case"NextIteration":{let r=P("tensor",n,t,e);return e.nextIteration(),[Do(r)]}case"TensorArrayV3":{let r=P("size",n,t,e),s=P("dtype",n,t,e),u=P("elementShape",n,t,e),l=P("dynamicSize",n,t,e),h=P("clearAfterRead",n,t,e),p=P("identicalElementShapes",n,t,e),m=P("name",n,t,e),y=new _q(m,s,r,u,p,l,h);return e.addTensorArray(y),[y.idTensor,Ot(1)]}case"TensorArrayWriteV3":{let r=P("tensorArrayId",n,t,e),s=P("index",n,t,e),u=P("tensor",n,t,e),l=e.getTensorArray(r.id);return l.write(s,u),[l.idTensor]}case"TensorArrayReadV3":{let r=P("tensorArrayId",n,t,e),s=P("index",n,t,e),u=e.getTensorArray(r.id);return[u.read(s)]}case"TensorArrayGatherV3":{let r=P("tensorArrayId",n,t,e),s=P("indices",n,t,e),u=P("dtype",n,t,e),l=e.getTensorArray(r.id);return[l.gather(s,u)]}case"TensorArrayScatterV3":{let r=P("tensorArrayId",n,t,e),s=P("indices",n,t,e),u=P("tensor",n,t,e),l=e.getTensorArray(r.id);return l.scatter(s,u),[l.idTensor]}case"TensorArrayConcatV3":{let r=P("tensorArrayId",n,t,e),s=e.getTensorArray(r.id),u=P("dtype",n,t,e);return[s.concat(u)]}case"TensorArraySplitV3":{let r=P("tensorArrayId",n,t,e),s=P("tensor",n,t,e),u=P("lengths",n,t,e),l=e.getTensorArray(r.id);return l.split(u,s),[l.idTensor]}case"TensorArraySizeV3":{let r=P("tensorArrayId",n,t,e),s=e.getTensorArray(r.id);return[Ot(s.size(),"int32")]}case"TensorArrayCloseV3":{let r=P("tensorArrayId",n,t,e),s=e.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{let r=P("tensorListId",n,t,e),s=P("index",n,t,e),u=P("tensor",n,t,e),l=e.getTensorList(r.id);return l.setItem(s,u),[l.idTensor]}case"TensorListGetItem":{let r=P("tensorListId",n,t,e),s=P("index",n,t,e),u=P("elementShape",n,t,e),l=P("elementDType",n,t,e),h=e.getTensorList(r.id);return[h.getItem(s,u,l)]}case"TensorListScatterV2":case"TensorListScatter":{let r=P("indices",n,t,e),s=P("tensor",n,t,e),u=P("elementShape",n,t,e),l=P("numElements",n,t,e),h=Pq(s,r,u,l);return e.addTensorList(h),[h.idTensor]}case"TensorListReserve":{let r=P("elementShape",n,t,e),s=P("elementDType",n,t,e),u=P("numElements",n,t,e),l=Rq(r,s,u);return e.addTensorList(l),[l.idTensor]}case"TensorListGather":{let r=P("tensorListId",n,t,e),s=P("indices",n,t,e),u=P("elementShape",n,t,e),l=P("elementDType",n,t,e),h=e.getTensorList(r.id);return[h.gather(s,l,u)]}case"TensorListStack":{let r=P("tensorListId",n,t,e),s=P("e
${t}`);let s;return this.size===Infinity||this.size==null?s=this.size:e?s=Math.ceil(this.size/t):s=Math.floor(this.size/t),Ar(async()=>(await r.iterator()).columnMajorBatch(t,e,$j),s)}concatenate(t){let e=this,r;return this.size===Infinity||t.size===Infinity?r=Infinity:this.size!=null&&t.size!=null?r=this.size+t.size:r=null,Ar(async()=>(await e.iterator()).concatenate(await t.iterator()),r)}filter(t){let e=this,r;return this.size===Infinity?r=Infinity:r=null,Ar(async()=>(await e.iterator()).filter(s=>ot(()=>t(s))),r)}async forEachAsync(t){return(await this.iterator()).forEachAsync(t)}map(t){let e=this;return Ar(async()=>(await e.iterator()).map(r=>ot(()=>t(r))),this.size)}mapAsync(t){let e=this;return Ar(async()=>(await e.iterator()).mapAsync(t),this.size)}prefetch(t){if(t==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let e=this;return Ar(async()=>(await e.iterator()).prefetch(t),this.size)}repeat(t){let e=this,r;return this.size!=null&&t>0?r=this.size*t:t===0?r=0:this.size!=null&&(t===void 0||t<0)?r=Infinity:r=null,Ar(async()=>{let s=lf(async()=>({value:await e.iterator(),done:!1}));return KI(s.take(t))},r)}skip(t){let e=this,r;return this.size!=null&&t>=0&&this.size>=t?r=this.size-t:this.size!=null&&(this.size<t||t===void 0||t<0)?r=0:r=null,Ar(async()=>(await e.iterator()).skip(t),r)}shuffle(t,e,r=!0){if(t==null||t<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 s=this,u=Lu(e||cr().toString());return Ar(async()=>{let l=u.int32();return r&&(l+=u.int32()),(await s.iterator()).shuffle(t,l.toString())},this.size)}take(t){let e=this,r;return this.size!=null&&this.size>t?r=t:this.size!=null&&this.size<=t?r=this.size:r=null,Ar(async()=>(await e.iterator()).take(t),r)}async toArray(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}rc.MAX_BUFFER_SIZE=1e4;function Ar(n,t=null){return new class extends rc{constructor(){super(...arguments);this.size=t}async iterator(){return n()}}}function Ej(n){return Ar(async()=>jI(n),n.length)}function Dj(n){if(!nc(n))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(n))for(let e=0;e<n.length;e++)t=t==null?n[e].size:Math.min(t,n[e].size);else if(n instanceof Object)for(let e in n)t=t==null?n[e].size:Math.min(t,n[e].size);return Ar(async()=>{let e=await HI(n,r=>{if(r instanceof rc)return{value:r.iterator(),recurse:!1};if(nc(r))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return mj(e,Sa.SHORTEST)},t)}function $j(n){if(n===null)return null;let t=n[0];if(hj(t)){let e=Aj(n);return{value:e,recurse:!1}}return{value:null,recurse:!0}}function Aj(n){if(n.length===0)throw new Error("Can't make a batch of zero elements.");return n[0]instanceof at?mr(n):vn(n)}class ZI extends rc{constructor(t){super();this.input=t}async iterator(){let t=await this.input.iterator(),e=t.decodeUTF8(),r=e.split(`
`).map(s=>(s.endsWith("\r")&&(s=s.slice(0,-1)),s));return r}}let Rm='"',hf=Symbol("out"),QI=Symbol("field"),Pm=Symbol("quote"),H0=Symbol("quoteafterquote"),tE=Symbol("quoteinquote");class eE extends rc{constructor(t,e){super();this.input=t,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new ZI(t),e||(e={}),this.hasHeader=!(e.hasHeader===!1),this.fullColumnNames=e.columnNames,this.columnConfigs=e.columnConfigs,this.configuredColumnsOnly=e.configuredColumnsOnly,e.delimWhitespace?(k(e.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=e.delimiter?e.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let t=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!t)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&t&&k(t.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 ("+t.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=t);let e=this.fullColumnNames.reduce((s,u)=>(s[u]=s[u]+1||1,s),{}),r=Object.keys(e).filter(s=>e[s]>1);if(k(r.length===0,()=>"Duplicate column names found: "+r.toString()),this.columnConfigs)for(let s of Object.keys(this.columnConfigs)){let u=this.fullColumnNames.indexOf(s);if(u===-1)throw new Error('The key "'+s+'" 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 this.base.iterator(),e=await t.next();if(e.done)throw new Error("No data was found for CSV parsing.");let r=e.value,s=this.parseRow(r,!1);return s}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let t=await this.base.iterator();return this.hasHeader&&(t=t.skip(1)),t.map(e=>this.makeDataElement(e))}makeDataElement(t){let e=this.parseRow(t),r={},s={};for(let u=0;u<this.fullColumnNames.length;u++){let l=this.fullColumnNames[u],h=this.columnConfigs?this.columnConfigs[l]:null;if(this.configuredColumnsOnly&&!h)continue;{let p=e[u],m=null;if(p==="")if(h&&h.default!==void 0)m=h.default;else{if(h&&(h.required||h.isLabel))throw new Error(`Required column ${l} is empty in this line: ${t}`);m=void 0}else{let y=Number(p);if(isNaN(y))h&&h.dtype==="bool"?m=this.getBoolean(p):m=p;else if(!h||!h.dtype)m=y;else switch(h.dtype){case"float32":m=y;break;case"int32":m=Math.floor(y);break;case"bool":m=this.getBoolean(p);break;default:m=y}}h&&h.isLabel?s[l]=m:r[l]=m}}return Object.keys(s).length===0?r:{xs:r,ys:s}}getBoolean(t){return t==="1"||t.toLowerCase()==="true"?1:0}parseRow(t,e=!0){let r=[],s=0,u=t.length,l=hf;for(let h=0;h<u;h++)switch(l){case hf:switch(t.charAt(h)){case Rm:s=h+1,l=Pm;break;case this.delimiter:if(s=h+1,this.delimiter===" "&&this.delimWhitespace)break;r.push(""),l=hf;break;default:l=QI,s=h;break}break;case QI:switch(t.charAt(h)){case this.delimiter:r.push(t.substring(s,h)),l=hf,s=h+1;break;default:}break;case Pm:switch(t.charAt(h)){case Rm:l=H0;break;default:}break;case H0:switch(t.charAt(h)){case this.delimiter:r.push(t.substring(s,h-1)),l=hf,s=h+1;break;case Rm:l=Pm;break;default:l=tE;break}break;case tE:switch(t.charAt(h)){case Rm:l=Pm;break;default:}break;default:}if(l===H0?r.push(t.substring(s,u-1)):r.push(t.substring(s)),e&&r.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${r}`);return r}}class q0 extends Rn{constructor(t){super();this.microphoneConfig=t,this.isClosed=!1,this.fftSize=t.fftSize||1024;let e=Math.log2(this.fftSize);if(this.fftSize<0||e<4||e>14||!Number.isInteger(e))throw new Error(
2020-10-15 12:48:39 +02:00
============================
2020-11-25 14:30:53 +01: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.
============================`));let s={};return this.data.set(s,{values:t,dtype:r,refCount:1}),s}makeTensorInfo(t,e,r){let s;if(e==="string"&&r!=null&&r.length>0&&dn(r[0])){let u=r.map(l=>qp(l));s=this.write(u,t,e)}else s=this.write(r,t,e);return{dataId:s,shape:t,dtype:e}}incRef(t){let e=this.data.get(t);e.refCount++}decRef(t){if(this.data.has(t)){let e=this.data.get(t);e.refCount--}}move(t,e,r,s){this.data.set(t,{values:e,dtype:s,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(t){return this.readSync(t)}readSync(t){let{dtype:e,complexTensorInfos:r}=this.data.get(t);if(e==="complex64"){let s=this.readSync(r.real.dataId),u=this.readSync(r.imag.dataId);return So(s,u)}return this.data.get(t).values}bufferSync(t){let e=this.readSync(t.dataId),r=e;if(t.dtype==="string")try{r=e.map(s=>rh(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ae(t.shape,t.dtype,r)}makeOutput(t,e,r){let s=this.write(t,e,r);return yo().makeTensorFromDataId(s,e,r,this)}disposeData(t){if(this.data.has(t)){let{complexTensorInfos:e}=this.data.get(t);e!=null&&(this.disposeData(e.real.dataId),this.disposeData(e.imag.dataId)),this.data.delete(t)}}disposeIntermediateTensorInfo(t){let e=t.dataId;if(this.data.has(e)){let r=this.data.get(e);r.refCount--,r.refCount<1&&this.disposeData(e)}}async time(t){let e=cr();t();let r=cr()-e;return{kernelMs:r}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}stridedSlice(t,e,r,s){At(t,"stridedSlice");let u=sd(e,r,s);if(u.some(p=>p===0))return vn([],u);let l=Ae(u,t.dtype),h=this.bufferSync(t);for(let p=0;p<l.size;p++){let m=l.indexToLoc(p),y=new Array(m.length);for(let b=0;b<y.length;b++)y[b]=m[b]*s[b]+e[b];l.set(h.get(...y),...m)}return l.toTensor()}diag(t){let e=this.readSync(t.dataId),r=Ae([t.size,t.size],t.dtype),s=r.values;for(let u=0;u<e.length;u++)s[u*t.size+u]=e[u];return r.toTensor()}unstack(t,e){let r=t.shape[e],s=new Array(t.rank-1),u=0;for(let m=0;m<t.rank;m++)m!==e&&(s[u++]=t.shape[m]);let l=new Array(t.rank).fill(0),h=t.shape.slice();h[e]=1;let p=new Array(r);for(let m=0;m<p.length;m++)l[e]=m,p[m]=ge(t,l,h).reshape(s);return p}reverse(t,e){At(t,"reverse");let r=Ae(t.shape,t.dtype),s=this.bufferSync(t);for(let u=0;u<r.size;u++){let l=r.indexToLoc(u),h=l.slice();e.forEach(p=>h[p]=t.shape[p]-1-h[p]),r.set(s.get(...h),...l)}return r.toTensor()}neg(t){return At(t,"neg"),st(Ot(-1),t)}addN(t){At(t,"addN");let e=t.map(u=>this.readSync(u.dataId)),r=Ae(t[0].shape,t[0].dtype),s=r.values;for(let u=0;u<t.length;u++){let l=e[u];for(let h=0;h<s.length;h++)s[h]+=l[h]}return r.toTensor()}softmax(t,e){let r=Et([e],t.shape),s=dr(t,r),u=zn(s.shape,r),l=Mt(t,s.reshape(u)),h=Br(l),p=this.sum(h,r).reshape(u);return Ht(h,p)}pow(t,e){return At([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,(r,s)=>Math.pow(r,s))}floorDiv(t,e){At([t,e],"floorDiv");let r=(u,l)=>Math.floor(u/l),s="int32";return this.broadcastedBinaryOp(t,e,s,r)}sum(t,e){At(t,"sum"),lr("sum",e,t.rank);let[r,s]=Bn(t.shape,e),u=Qn(t.dtype,"int32"),l=Se(r,u),h=O(s),p=this.readSync(l.dataId),m=this.readSync(t.dataId);for(let y=0;y<p.length;++y){let b=y*h,x=0;for(let S=0;S<h;++S)x+=m[b+S];p[y]=x}return l}prod(t,e){At(t,"sum");let[r,s]=Bn(t.shape,e),u=Qn(t.dtype,"int32"),l=Se(r,u),h=O(s),p=this.readSync(l.dataId),m=this.readSync(t.dataId);for(let y=0;y<p.length;++y){let b=y*h,x=1;for(let S=0;S<h;++S)x*=m[b+S];p[y]=x}return l}unsortedSegmentSum(t,e,r){At(t,"unsortedSegmentSum");let s=[],u=t.rank-e.rank;for(let l=0;l<u;++l)e=e.expandDims(l+1);for(let l=0;l<r;++l){let h=Ot(l,"int32"),p=gs(h,e).asType("float32"),m=p.mul(t).sum(0);s.push(m)}return mr(s)}argMin(t,e){At(t,"argMin");let r=[e];lr("argMin",r,t.rank);let[s,u]=Bn(t.shape,r),l=Se(s,"int32"),h=O(u),p=this.readSync(l.dataId),m=this.readSync(t.dataId);for(let y=0;y<p.length;++y){let b=y*h,x=m[b],S=0;for(let C=0;C<h;++C){let I=m[b+C];I<x&&(x=I,S=C)}p[y]=S}return l}argMax(t,e){At(t,"argMax");let r=[e];lr("argMax",r,t.rank);let[s,u]=Bn(t.shape,r),l=Se(s,"int32"),h=O
`),u=s.length.toString().length+2,l=s.map((b,x)=>St((x+1).toString(),u)+b),h=0;for(let b=0;b<l.length;b++)h=Math.max(l[b].length,h);let p=l.slice(0,r-1),m=l.slice(r-1,r),y=l.slice(r);console.log(p.join(`
2020-10-15 12:48:39 +02:00
`)),console.log(t.split(`
2020-11-25 14:30:53 +01:00
`)[0]),console.log(`%c ${St(m[0],h)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(y.join(`
`))}function y8(n){return $o(n,()=>n.createProgram(),"Unable to create WebGLProgram.")}function b8(n,t){if(zt(n,()=>n.linkProgram(t)),n.getProgramParameter(t,n.LINK_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function rx(n,t){if(zt(n,()=>n.validateProgram(t)),n.getProgramParameter(t,n.VALIDATE_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function w8(n,t){let e=$o(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return zt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),zt(n,()=>n.bufferData(n.ARRAY_BUFFER,t,n.STATIC_DRAW)),e}function x8(n,t){let e=$o(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return zt(n,()=>n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e)),zt(n,()=>n.bufferData(n.ELEMENT_ARRAY_BUFFER,t,n.STATIC_DRAW)),e}function Mft(){return ft().getNumber("WEBGL_VERSION")===2?1:4}function T8(n){return $o(n,()=>n.createTexture(),"Unable to create WebGLTexture.")}function k8(n,t){let e=ft().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||t<=0){let r=`[${n}x${t}]`;throw new Error("Requested texture size "+r+" is invalid.")}if(n>e||t>e){let r=`[${n}x${t}]`,s=`[${e}x${e}]`;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+s+".")}}function S8(n){return $o(n,()=>n.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function LE(n,t,e,r,s,u,l){let h=n.getAttribLocation(t,e);return h===-1?!1:(zt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,r)),zt(n,()=>n.vertexAttribPointer(h,s,n.FLOAT,!1,u,l)),zt(n,()=>n.enableVertexAttribArray(h)),!0)}function C8(n,t,e){zE(n,e),zt(n,()=>n.activeTexture(n.TEXTURE0+e)),zt(n,()=>n.bindTexture(n.TEXTURE_2D,t))}function Lft(n,t){zE(n,t),zt(n,()=>n.activeTexture(n.TEXTURE0+t)),zt(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function N8(n,t,e){return $o(n,()=>n.getUniformLocation(t,e),'uniform "'+e+'" not present in program.')}function I8(n,t,e){return n.getUniformLocation(t,e)}function E8(n,t,e,r){zt(n,()=>C8(n,t,r)),zt(n,()=>n.uniform1i(e,r))}function Bft(n){zt(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,null)),zt(n,()=>n.viewport(0,0,n.canvas.width,n.canvas.height)),zt(n,()=>n.scissor(0,0,n.canvas.width,n.canvas.height))}function sx(n,t,e){zt(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,e)),zt(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0))}function BE(n,t){zt(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,t)),zt(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0))}function Lm(n){let t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+D8(n,t))}function D8(n,t){switch(t){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function $o(n,t,e){let r=zt(n,()=>t());if(r==null)throw new Error(e);return r}function zE(n,t){let e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+n.TEXTURE0;if(r<n.TEXTURE0||r>e){let s=`[gl.TEXTURE0, gl.TEXTURE${e}]`;throw new Error(`textureUnit must be in ${s}.`)}}function uc(n,t=2){return O(n.slice(0,n.length-t))}function cc(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function ox(n){let t=[1,1,1],e=n.length===0||n.length===1&&n[0]===1;return e||(t=[uc(n),...cc(n)]),t}function $8(n,t=!1){let e=ft().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(e=e*2,n=n.map((s,u)=>u>=n.length-2?w(n[u]):n[u]),n.length===1&&(n=[2,n[0]])),n.length!==2){let s=Wt(n);n=s.newShape}let r=O(n);if(n.length<=1&&r<=e)return[1,r];if(n.length===2&&n[0]<=e&&n[1]<=e)return n;if(n.length===3&&n[0]*n[1]<=e&&n[2]<=e)return[n[0]*n[1],n[2]];if(n.length===3&&n[0]<=e&&n[1]*n[2]<=e)return[n[0],n[1]*n[2]];if(n.length===4&&n[0]*n[1]*n[2]<=e&&n[3]<=e)return[n[0]*n[1]*n[2]
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${r.join(`
2020-10-15 12:48:39 +02:00
`)}
float result = ${s};
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class Z8{constructor(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((u,l)=>`T${l}`);let r=[];this.variableNames.forEach(u=>{r.push(`vec4 v${u} = get${u}AtOutCoords();`)});let s=this.variableNames.map(u=>`v${u}`).join(" + ");this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${r.join(`
2020-10-15 12:48:39 +02:00
`)}
vec4 result = ${s};
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class Q8{constructor(t,e,r){this.variableNames=["A"];let{windowSize:s,batchSize:u,outSize:l}=t;r||this.variableNames.push("bestIndicesA"),this.outputShape=[u,l];let h=e==="max"?">":"<",p=r?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${s}; i++) {
2020-11-25 14:30:53 +01:00
int inIdx = ${p};
2020-10-15 12:48:39 +02:00
float candidate = getA(batch, inIdx);
2020-11-25 14:30:53 +01:00
if (candidate ${h} bestValue) {
2020-10-15 12:48:39 +02:00
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
2020-11-25 14:30:53 +01:00
`}}function VE(n,t){return["x","y","z","w","u","v"].slice(0,t).map(e=>`${n}.${e}`)}function nr(n,t){return t===1?[n]:VE(n,t)}function tX(n,t){if(n===1)return"rc";let e="";for(let r=0;r<n;r++)e+=t[r],r<n-1&&(e+=",");return e}function rr(){let n,t,e,r,s,u,l,h,p,m;return ft().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",t="in",e="out",r="in",s="texture",u="outputColor",l="out vec4 outputColor;",h=`
2020-10-15 12:48:39 +02:00
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
2020-11-25 14:30:53 +01:00
`,p="",m=`
2020-10-15 12:48:39 +02:00
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-11-25 14:30:53 +01:00
`):(n="",t="attribute",e="varying",r="varying",s="texture2D",u="gl_FragColor",l="",h=`
2020-10-15 12:48:39 +02:00
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
2020-11-25 14:30:53 +01:00
`,p=`
2020-10-15 12:48:39 +02:00
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
2020-11-25 14:30:53 +01:00
`,m=`
2020-10-15 12:48:39 +02:00
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-11-25 14:30:53 +01:00
`),{version:n,attribute:t,varyingVs:e,varyingFs:r,texture2D:s,output:u,defineOutput:l,defineSpecialNaN:h,defineSpecialInf:p,defineRound:m}}function $i(n,t,e="index"){let r=Jt(t);return r.map((s,u)=>{let l=`int ${n[u]} = ${e} / ${s}`,h=u===r.length-1?`int ${n[u+1]} = ${e} - ${n[u]} * ${s}`:`index -= ${n[u]} * ${s}`;return`${l}; ${h};`}).join("")}function Um(n){return n.length===1?`${n[0]}`:`vec${n.length}(${n.join(",")})`}function Vft(n,t){if(n.length!==t.length)throw new Error(`Vectors to be dotted must be of the same length -got ${n.length} and ${t.length}`);let e=[],r=Math.floor(n.length/4),s=n.length%4;for(let u=0;u<r;u++){let l=n.slice(u*4,u*4+4),h=t.slice(u*4,u*4+4);e.push(`${Um(l)}, ${Um(h)}`)}if(s!==0){let u=n.slice(r*4),l=t.slice(r*4);u.length===1&&(u=u.map(h=>`float(${h})`),l=l.map(h=>`float(${h})`)),e.push(`${Um(u)}, ${Um(l)}`)}return e.map((u,l)=>`dot(${u})`).join("+")}function ux(n){let t=Jt(n).map(e=>e.toString());return`
2020-10-15 12:48:39 +02:00
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
2020-11-25 14:30:53 +01:00
`}let UE=`
2020-10-15 12:48:39 +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);
}
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;
}
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;
}
2020-11-25 14:30:53 +01:00
`;let{getBroadcastDims:GE}=Kb;function eX(n,t,e,r){let s=[];n.forEach(C=>{let I=O(C.shapeInfo.logicalShape);C.shapeInfo.isUniform?s.push(`uniform float ${C.name}${I>1?`[${I}]`:""};`):(s.push(`uniform sampler2D ${C.name};`),s.push(`uniform int offset${C.name};`))});let u=s.join(`
`),l=n.map(C=>nX(C,t,r)).join(`
`),h=t.texShape,p=rr(),m=oX(p),y,b,x=uX(p);t.isPacked?(y=rX(t.logicalShape,h),b=iX(p)):(y=sX(t.logicalShape,h),b=aX(p)),r&&(x+=fX);let S=[x,m,b,u,y,l,e].join(`
`);return S}function lc(n){let t=n.shapeInfo.logicalShape;switch(t.length){case 0:return SX(n);case 1:return NX(n);case 2:return EX(n);case 3:return $X(n);case 4:return _X(n);case 5:return FX(n);case 6:return RX(n);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function HE(n){let t=n.shapeInfo.logicalShape;switch(t.length){case 0:return kX(n);case 1:return CX(n);case 2:return IX(n);case 3:return DX(n);default:return AX(n)}}function nX(n,t,e=!1){let r="";e?r+=HE(n):r+=lc(n);let s=n.shapeInfo.logicalShape,u=t.logicalShape;return s.length<=u.length&&(e?r+=PX(n,t):r+=OX(n,t)),r}function rX(n,t){switch(n.length){case 0:return qE();case 1:return pX(n,t);case 2:return xX(n,t);case 3:return mX(n,t);default:return vX(n,t)}}function sX(n,t){switch(n.length){case 0:return qE();case 1:return dX(n,t);case 2:return TX(n,t);case 3:return gX(n,t);case 4:return yX(n,t);case 5:return bX(n,t);case 6:return wX(n,t);default:throw new Error(`${n.length}-D output sampling is not yet supported`)}}function oX(n){return`
2020-10-15 12:48:39 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
2020-11-25 14:30:53 +01:00
return ${n.texture2D}(textureSampler, uv).r;
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function aX(n){return`
2020-10-15 12:48:39 +02:00
void setOutput(float val) {
2020-11-25 14:30:53 +01:00
${n.output} = vec4(val, 0, 0, 0);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function iX(n){return`
2020-10-15 12:48:39 +02:00
void setOutput(vec4 val) {
2020-11-25 14:30:53 +01:00
${n.output} = val;
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function uX(n){let t=`${n.version}
2020-10-15 12:48:39 +02:00
precision highp float;
precision highp int;
precision highp sampler2D;
2020-11-25 14:30:53 +01:00
${n.varyingFs} vec2 resultUV;
${n.defineOutput}
2020-10-15 12:48:39 +02:00
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;
2020-11-25 14:30:53 +01:00
${n.defineSpecialNaN}
${n.defineSpecialInf}
${n.defineRound}
2020-10-15 12:48:39 +02:00
int imod(int x, int y) {
return x - y * (x / y);
}
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;
}
//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);
}
2020-11-25 14:30:53 +01:00
${cX}
${lX}
${hX}
`;return t}let cX=`
2020-10-15 12:48:39 +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);
}
2020-11-25 14:30:53 +01:00
`,lX=`
2020-10-15 12:48:39 +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);
}
2020-11-25 14:30:53 +01:00
`,hX=`
2020-10-15 12:48:39 +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);
}
2020-11-25 14:30:53 +01:00
`,fX=`
2020-10-15 12:48:39 +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;
}
2020-11-25 14:30:53 +01:00
`;function qE(){return`
2020-10-15 12:48:39 +02:00
int getOutputCoords() {
return 0;
}
2020-11-25 14:30:53 +01:00
`}function pX(n,t){let e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return e[0]===1?`
2020-10-15 12:48:39 +02:00
int getOutputCoords() {
2020-11-25 14:30:53 +01:00
return 2 * int(resultUV.x * ${e[1]}.0);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`:e[1]===1?`
2020-10-15 12:48:39 +02:00
int getOutputCoords() {
2020-11-25 14:30:53 +01:00
return 2 * int(resultUV.y * ${e[0]}.0);
2020-10-15 12:48:39 +02:00
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-11-25 14:30:53 +01:00
vec2(${e[0]}, ${e[1]}));
return 2 * (resTexRC.x * ${e[1]} + resTexRC.y);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function dX(n,t){return t[0]===1?`
2020-10-15 12:48:39 +02:00
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
2020-11-25 14:30:53 +01:00
`}function mX(n,t){let e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[2]/2),s=r*Math.ceil(n[1]/2);return`
2020-10-15 12:48:39 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-11-25 14:30:53 +01:00
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
int b = index / ${s};
index -= b * ${s};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
2020-10-15 12:48:39 +02:00
return ivec3(b, r, c);
}
2020-11-25 14:30:53 +01:00
`}function gX(n,t){let e=$i(["r","c","d"],n);return`
2020-10-15 12:48:39 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-11-25 14:30:53 +01:00
${e}
2020-10-15 12:48:39 +02:00
return ivec3(r, c, d);
}
2020-11-25 14:30:53 +01:00
`}function vX(n,t){let e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(n[n.length-1]/2),s=r*Math.ceil(n[n.length-2]/2),u=s,l="",h="b, r, c";for(let p=2;p<n.length-1;p++)u*=n[n.length-p-1],l=`
int b${p} = index / ${u};
index -= b${p} * ${u};
`+l,h=`b${p}, `+h;return`
ivec${n.length} getOutputCoords() {
2020-10-15 12:48:39 +02:00
ivec2 resTexRC = ivec2(resultUV.yx *
2020-11-25 14:30:53 +01:00
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
${l}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
int b = index / ${s};
index -= b * ${s};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
return ivec${n.length}(${h});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function yX(n,t){let e=$i(["r","c","d","d2"],n);return`
2020-10-15 12:48:39 +02:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-11-25 14:30:53 +01:00
${e}
2020-10-15 12:48:39 +02:00
return ivec4(r, c, d, d2);
}
2020-11-25 14:30:53 +01:00
`}function bX(n,t){let e=$i(["r","c","d","d2","d3"],n);return`
2020-10-15 12:48:39 +02:00
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-11-25 14:30:53 +01:00
${e}
2020-10-15 12:48:39 +02:00
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
2020-11-25 14:30:53 +01:00
`}function wX(n,t){let e=$i(["r","c","d","d2","d3","d4"],n);return`
2020-10-15 12:48:39 +02:00
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-11-25 14:30:53 +01:00
${e}
2020-10-15 12:48:39 +02:00
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
2020-11-25 14:30:53 +01:00
`}function xX(n,t){let e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(K(n,t))return`
2020-10-15 12:48:39 +02:00
ivec2 getOutputCoords() {
2020-11-25 14:30:53 +01:00
return 2 * ivec2(resultUV.yx * vec2(${e[0]}, ${e[1]}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let r=Math.ceil(n[1]/2);return`
2020-10-15 12:48:39 +02:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-11-25 14:30:53 +01:00
vec2(${e[0]}, ${e[1]}));
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
int index = resTexRC.x * ${e[1]} + resTexRC.y;
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
2020-10-15 12:48:39 +02:00
return ivec2(r, c);
}
2020-11-25 14:30:53 +01:00
`}function TX(n,t){return K(n,t)?`
2020-10-15 12:48:39 +02:00
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
2020-11-25 14:30:53 +01:00
`:n[1]===1?`
2020-10-15 12:48:39 +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);
}
2020-11-25 14:30:53 +01:00
`:n[0]===1?`
2020-10-15 12:48:39 +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);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-11-25 14:30:53 +01:00
int r = index / ${n[1]};
int c = index - r * ${n[1]};
2020-10-15 12:48:39 +02:00
return ivec2(r, c);
}
2020-11-25 14:30:53 +01:00
`}function Ai(n){return`offset${n}`}function kX(n){let t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),r=rr();return`
vec4 ${e}() {
return ${r.texture2D}(${t}, halfCR);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function SX(n){let t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(n.shapeInfo.isUniform)return`float ${e}() {return ${t};}`;let[r,s]=n.shapeInfo.texShape;if(r===1&&s===1)return`
float ${e}() {
2020-10-15 12:48:39 +02:00
return sampleTexture(${t}, halfCR);
}
2020-11-25 14:30:53 +01:00
`;let[u,l]=n.shapeInfo.texShape,h=Ai(t);return`
float ${e}() {
vec2 uv = uvFromFlat(${u}, ${l}, ${h});
2020-10-15 12:48:39 +02:00
return sampleTexture(${t}, uv);
}
2020-11-25 14:30:53 +01:00
`}function CX(n){let t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),r=n.shapeInfo.texShape,s=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],u=rr();return`
vec4 ${e}(int index) {
2020-10-15 12:48:39 +02:00
vec2 uv = packedUVfrom1D(
2020-11-25 14:30:53 +01:00
${s[0]}, ${s[1]}, index);
return ${u.texture2D}(${t}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function NX(n){let t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(n.shapeInfo.isUniform)return`
float ${e}(int index) {
${hc(n)}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let r=n.shapeInfo.texShape,s=r[0],u=r[1];if(u===1&&s===1)return`
float ${e}(int index) {
2020-10-15 12:48:39 +02:00
return sampleTexture(${t}, halfCR);
}
2020-11-25 14:30:53 +01:00
`;let l=Ai(t);return u===1?`
float ${e}(int index) {
vec2 uv = vec2(0.5, (float(index + ${l}) + 0.5) / ${s}.0);
2020-10-15 12:48:39 +02:00
return sampleTexture(${t}, uv);
}
2020-11-25 14:30:53 +01:00
`:s===1?`
float ${e}(int index) {
vec2 uv = vec2((float(index + ${l}) + 0.5) / ${u}.0, 0.5);
2020-10-15 12:48:39 +02:00
return sampleTexture(${t}, uv);
}
`:`
2020-11-25 14:30:53 +01:00
float ${e}(int index) {
vec2 uv = uvFromFlat(${s}, ${u}, index + ${l});
2020-10-15 12:48:39 +02:00
return sampleTexture(${t}, uv);
}
2020-11-25 14:30:53 +01:00
`}function IX(n){let t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),s=n.shapeInfo.texShape,u=s[0],l=s[1],h=rr();if(s!=null&&K(t,s))return`
vec4 ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${u}.0);
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
return ${h.texture2D}(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let p=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],m=Math.ceil(t[1]/2);return`
vec4 ${r}(int row, int col) {
vec2 uv = packedUVfrom2D(${m}, ${p[0]}, ${p[1]}, row, col);
return ${h.texture2D}(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function EX(n){let t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),s=n.shapeInfo.texShape;if(s!=null&&K(t,s)){let b=s[0],x=s[1];return`
float ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${x}.0, ${b}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}let{newShape:u,keptDims:l}=Wt(t),h=u;if(h.length<t.length){let b=fc(n,h),x=["row","col"];return`
${lc(b)}
float ${r}(int row, int col) {
return ${r}(${pc(x,l)});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}if(n.shapeInfo.isUniform)return`
float ${r}(int row, int col) {
2020-10-15 12:48:39 +02:00
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
2020-11-25 14:30:53 +01:00
${hc(n)}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let p=s[0],m=s[1],y=Ai(e);return m===1?`
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${y}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${p}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`:p===1?`
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${y}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${m}.0, 0.5);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
`:`
2020-11-25 14:30:53 +01:00
float ${r}(int row, int col) {
2020-10-15 12:48:39 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-11-25 14:30:53 +01:00
int index = row * ${t[1]} + col + ${y};
vec2 uv = uvFromFlat(${p}, ${m}, index);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function DX(n){let t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),s=n.shapeInfo.texShape,u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(t[0]===1){let b=t.slice(1),x=[1,2],S=fc(n,b),C=["b","row","col"];return`
${HE(S)}
vec4 ${r}(int b, int row, int col) {
return ${r}(${pc(C,x)});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}let l=u[0],h=u[1],p=Math.ceil(t[2]/2),m=p*Math.ceil(t[1]/2),y=rr();return`
vec4 ${r}(int b, int row, int col) {
2020-10-15 12:48:39 +02:00
vec2 uv = packedUVfrom3D(
2020-11-25 14:30:53 +01:00
${l}, ${h}, ${m}, ${p}, b, row, col);
return ${y.texture2D}(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function $X(n){let t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),s=t[1]*t[2],u=t[2],{newShape:l,keptDims:h}=Wt(t),p=l;if(p.length<t.length){let C=fc(n,p),I=["row","col","depth"];return`
${lc(C)}
float ${r}(int row, int col, int depth) {
return ${r}(${pc(I,h)});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}if(n.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth) {
2020-10-15 12:48:39 +02:00
int index = round(dot(vec3(row, col, depth),
2020-11-25 14:30:53 +01:00
vec3(${s}, ${u}, 1)));
${hc(n)}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let m=n.shapeInfo.texShape,y=m[0],b=m[1],x=n.shapeInfo.flatOffset;if(b===s&&x==null)return`
float ${r}(int row, int col, int depth) {
2020-10-15 12:48:39 +02:00
float texR = float(row);
2020-11-25 14:30:53 +01:00
float texC = dot(vec2(col, depth), vec2(${u}, 1));
2020-10-15 12:48:39 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-11-25 14:30:53 +01:00
vec2(${b}.0, ${y}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;if(b===u&&x==null)return`
float ${r}(int row, int col, int depth) {
2020-10-15 12:48:39 +02:00
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
2020-11-25 14:30:53 +01:00
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${b}.0, ${y}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let S=Ai(e);return`
float ${r}(int row, int col, int depth) {
2020-10-15 12:48:39 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-11-25 14:30:53 +01:00
int index = row * ${s} + col * ${u} + depth + ${S};
vec2 uv = uvFromFlat(${y}, ${b}, index);
return sampleTexture(${e}, uv);
}
`}function AX(n){let t=n.shapeInfo.logicalShape,e=t.length,r=n.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),u=n.shapeInfo.texShape,l=[Math.ceil(u[0]/2),Math.ceil(u[1]/2)],h=l[0],p=l[1],m=Math.ceil(t[e-1]/2),y=m*Math.ceil(t[e-2]/2),b="int b, int row, int col",x=`b * ${y} + (row / 2) * ${m} + (col / 2)`;for(let C=2;C<e-1;C++)b=`int b${C}, `+b,y*=t[e-C-1],x=`b${C} * ${y} + `+x;let S=rr();return`
vec4 ${s}(${b}) {
int index = ${x};
int texR = index / ${p};
int texC = index - texR * ${p};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${h});
return ${S.texture2D}(${r}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function _X(n){let t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),s=t[3],u=t[2]*s,l=t[1]*u,{newShape:h,keptDims:p}=Wt(t);if(h.length<t.length){let C=fc(n,h),I=["row","col","depth","depth2"];return`
${lc(C)}
float ${r}(int row, int col, int depth, int depth2) {
return ${r}(${pc(I,p)});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}if(n.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth, int depth2) {
2020-10-15 12:48:39 +02:00
int index = round(dot(vec4(row, col, depth, depth2),
2020-11-25 14:30:53 +01:00
vec4(${l}, ${u}, ${s}, 1)));
${hc(n)}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let m=n.shapeInfo.flatOffset,y=n.shapeInfo.texShape,b=y[0],x=y[1];if(x===l&&m==null)return`
float ${r}(int row, int col, int depth, int depth2) {
2020-10-15 12:48:39 +02:00
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
2020-11-25 14:30:53 +01:00
vec3(${u}, ${s}, 1));
2020-10-15 12:48:39 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-11-25 14:30:53 +01:00
vec2(${x}.0, ${b}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;if(x===s&&m==null)return`
float ${r}(int row, int col, int depth, int depth2) {
2020-10-15 12:48:39 +02:00
float texR = dot(vec3(row, col, depth),
vec3(${t[1]*t[2]}, ${t[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-11-25 14:30:53 +01:00
vec2(${x}.0, ${b}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let S=Ai(e);return`
float ${r}(int row, int col, int depth, int depth2) {
2020-10-15 12:48:39 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-11-25 14:30:53 +01:00
int index = row * ${l} + col * ${u} +
depth * ${s} + depth2;
vec2 uv = uvFromFlat(${b}, ${x}, index + ${S});
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function FX(n){let t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),s=t[4],u=t[3]*s,l=t[2]*u,h=t[1]*l,{newShape:p,keptDims:m}=Wt(t);if(p.length<t.length){let I=fc(n,p),D=["row","col","depth","depth2","depth3"];return`
${lc(I)}
float ${r}(int row, int col, int depth, int depth2, int depth3) {
return ${r}(${pc(D,m)});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}if(n.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth, int depth2, int depth3) {
2020-10-15 12:48:39 +02:00
float index = dot(
vec4(row, col, depth, depth2),
2020-11-25 14:30:53 +01:00
vec4(${h}, ${l}, ${u}, ${s})) +
2020-10-15 12:48:39 +02:00
depth3;
2020-11-25 14:30:53 +01:00
${hc(n)}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let y=n.shapeInfo.flatOffset,b=n.shapeInfo.texShape,x=b[0],S=b[1];if(S===h&&y==null)return`
float ${r}(int row, int col, int depth, int depth2, int depth3) {
2020-10-15 12:48:39 +02:00
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
2020-11-25 14:30:53 +01:00
vec4(${l}, ${u}, ${s}, 1));
2020-10-15 12:48:39 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-11-25 14:30:53 +01:00
vec2(${S}.0, ${x}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;if(S===s&&y==null)return`
float ${r}(int row, int col, int depth, int depth2, int depth3) {
2020-10-15 12:48:39 +02:00
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) /
2020-11-25 14:30:53 +01:00
vec2(${S}.0, ${x}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let C=Ai(e);return`
float ${r}(int row, int col, int depth, int depth2, int depth3) {
2020-10-15 12:48:39 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-11-25 14:30:53 +01:00
int index = row * ${h} + col * ${l} + depth * ${u} +
depth2 * ${s} + depth3 + ${C};
vec2 uv = uvFromFlat(${x}, ${S}, index);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function RX(n){let t=n.shapeInfo.logicalShape,e=n.name,r="get"+e.charAt(0).toUpperCase()+e.slice(1),{newShape:s,keptDims:u}=Wt(t);if(s.length<t.length){let D=fc(n,s),R=["row","col","depth","depth2","depth3","depth4"];return`
${lc(D)}
float ${r}(int row, int col, int depth,
2020-10-15 12:48:39 +02:00
int depth2, int depth3, int depth4) {
2020-11-25 14:30:53 +01:00
return ${r}(${pc(R,u)});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}let l=t[5],h=t[4]*l,p=t[3]*h,m=t[2]*p,y=t[1]*m;if(n.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth,
2020-10-15 12:48:39 +02:00
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
2020-11-25 14:30:53 +01:00
vec4(${y}, ${m}, ${p}, ${h})) +
2020-10-15 12:48:39 +02:00
dot(
vec2(depth3, depth4),
2020-11-25 14:30:53 +01:00
vec2(${l}, 1)));
${hc(n)}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let b=n.shapeInfo.flatOffset,x=n.shapeInfo.texShape,S=x[0],C=x[1];if(C===y&&b==null)return`
float ${r}(int row, int col, int depth,
2020-10-15 12:48:39 +02:00
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
2020-11-25 14:30:53 +01:00
vec4(${m}, ${p}, ${h}, ${l})) +
2020-10-15 12:48:39 +02:00
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-11-25 14:30:53 +01:00
vec2(${C}.0, ${S}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;if(C===l&&b==null)return`
float ${r}(int row, int col, int depth,
2020-10-15 12:48:39 +02:00
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) /
2020-11-25 14:30:53 +01:00
vec2(${C}.0, ${S}.0);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;let I=Ai(e);return`
float ${r}(int row, int col, int depth,
2020-10-15 12:48:39 +02:00
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
2020-11-25 14:30:53 +01:00
int index = row * ${y} + col * ${m} + depth * ${p} +
depth2 * ${h} + depth3 * ${l} + depth4 + ${I};
vec2 uv = uvFromFlat(${S}, ${C}, index);
return sampleTexture(${e}, uv);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function hc(n){let t=n.name,e=O(n.shapeInfo.logicalShape);return e<2?`return ${t};`:`
for (int i = 0; i < ${e}; i++) {
2020-10-15 12:48:39 +02:00
if (i == index) {
return ${t}[i];
}
}
2020-11-25 14:30:53 +01:00
`}function PX(n,t){let e=n.name,r=e.charAt(0).toUpperCase()+e.slice(1),s="get"+r+"AtOutCoords",u=n.shapeInfo.logicalShape.length,l=t.logicalShape.length,h=GE(n.shapeInfo.logicalShape,t.logicalShape),p=We(l),m=l-u,y,b=["x","y","z","w","u","v"];u===0?y="":l<2&&h.length>=1?y="coords = 0;":y=h.map(A=>`coords.${b[A+m]} = 0;`).join(`
`);let x="";l<2&&u>0?x="coords":x=n.shapeInfo.logicalShape.map((A,L)=>`coords.${b[L+m]}`).join(", ");let S="return outputValue;",C=O(n.shapeInfo.logicalShape),I=C===1,D=O(t.logicalShape),R=D===1;if(u===1&&!I&&!R)S=`
2020-10-15 12:48:39 +02:00
return vec4(outputValue.xy, outputValue.xy);
2020-11-25 14:30:53 +01:00
`;else if(I&&!R)l===1?S=`
2020-10-15 12:48:39 +02:00
return vec4(outputValue.x, outputValue.x, 0., 0.);
2020-11-25 14:30:53 +01:00
`:S=`
2020-10-15 12:48:39 +02:00
return vec4(outputValue.x);
2020-11-25 14:30:53 +01:00
`;else if(h.length){let A=u-2,L=u-1;h.indexOf(A)>-1&&h.indexOf(L)>-1?S="return vec4(outputValue.x);":h.indexOf(A)>-1?S="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":h.indexOf(L)>-1&&(S="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${s}() {
2020-10-15 12:48:39 +02:00
${p} coords = getOutputCoords();
2020-11-25 14:30:53 +01:00
${y}
vec4 outputValue = get${r}(${x});
${S}
}
`}function OX(n,t){let e=n.name,r=e.charAt(0).toUpperCase()+e.slice(1),s="get"+r+"AtOutCoords",u=t.texShape,l=n.shapeInfo.texShape,h=n.shapeInfo.logicalShape.length,p=t.logicalShape.length;if(!n.shapeInfo.isUniform&&h===p&&n.shapeInfo.flatOffset==null&&K(l,u))return`
float ${s}() {
return sampleTexture(${e}, resultUV);
}
`;let m=We(p),y=GE(n.shapeInfo.logicalShape,t.logicalShape),b=p-h,x,S=["x","y","z","w","u","v"];h===0?x="":p<2&&y.length>=1?x="coords = 0;":x=y.map(I=>`coords.${S[I+b]} = 0;`).join(`
`);let C="";return p<2&&h>0?C="coords":C=n.shapeInfo.logicalShape.map((I,D)=>`coords.${S[D+b]}`).join(", "),`
float ${s}() {
${m} coords = getOutputCoords();
${x}
return get${r}(${C});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}function We(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error(`GPU for rank ${n} is not yet supported`)}function fc(n,t){let e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function pc(n,t){return t.map(e=>n[e]).join(", ")}class MX{constructor(t,e,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k(t.length>2,()=>`Packed arg${r.charAt(0).toUpperCase()+r.slice(1)} supports only inputs with rank above 2.`);let u=t[t.length-1],l=Math.ceil(u/e);this.outputShape=t.slice(0,-1),l>1&&this.outputShape.push(l),s||this.variableNames.push("bestIndicesA");let h=this.outputShape,p=h.length,m=We(p),y=nr("coords",p),b,x;if(l===1){x=p+1;let j=We(x);b=`
${j} sourceLocR = ${j}(${y.join()}, 0);
++${y[p-1]};
${j} sourceLocG = ${j}(${y.join()}, 0);
++${y[p-2]};
${j} sourceLocA = ${j}(${y.join()}, 0);
--${y[p-1]};
${j} sourceLocB = ${j}(${y.join()}, 0);
--${y[p-2]};`}else x=p,b=`
${m} sourceLocR = coords;
++${y[p-1]};
${m} sourceLocG = coords;
++${y[p-2]};
${m} sourceLocA = coords;
--${y[p-1]};
${m} sourceLocB = coords;
--${y[p-2]};`;let S=["x","y","z","w","u","v"].slice(0,x),C="."+S[x-1],I=S.map(j=>"int "+j),D=nr("sourceLocR",x-1).concat("inIdx.r"),R=nr("sourceLocG",x-1).concat("inIdx.g"),A=nr("sourceLocB",x-1).concat("inIdx.b"),L=nr("sourceLocA",x-1).concat("inIdx.a"),_=r==="max"?"greaterThan":"lessThan",B=s?"":`
inIdx = round(vec4(getBestIndicesAChannel(${D.join()}),
getBestIndicesAChannel(${R.join()}),
getBestIndicesAChannel(${A.join()}),
getBestIndicesAChannel(${L.join()})));`,V=`vec4(
getAChannel(${D.join()}),
hasNextCol ? getAChannel(${R.join()}) : 0.,
hasNextRow ? getAChannel(${A.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${L.join()}) : 0.)`,q=s?"":`
float getBestIndicesAChannel(${I.join()}) {
return getChannel(getBestIndicesA(${S.join()}),
vec2(${S.slice(-2).join()}));
2020-10-15 12:48:39 +02:00
}`;this.userCode=`
2020-11-25 14:30:53 +01:00
float getAChannel(${I.join()}) {
return getChannel(getA(${S.join()}),
vec2(${S.slice(-2).join()}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
${q}
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${m} coords = getOutputCoords();
bool hasNextCol = ${y[p-1]} < ${h[p-1]-1};
bool hasNextRow = ${y[p-2]} < ${h[p-2]-1};
${b}
ivec4 srcIdx = ivec4(sourceLocR${C}, sourceLocG${C},
sourceLocB${C}, sourceLocA${C}) * ${e};
2020-10-15 12:48:39 +02:00
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
2020-11-25 14:30:53 +01:00
vec4 bestValue = ${V};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
for (int i = 0; i < ${e}; i++) {
2020-10-15 12:48:39 +02:00
inIdx = srcIdx;
2020-11-25 14:30:53 +01:00
${B}
vec4 candidate = ${V};
2020-10-15 12:48:39 +02:00
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
2020-11-25 14:30:53 +01:00
vec4(${_}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2020-10-15 12:48:39 +02:00
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
2020-11-25 14:30:53 +01:00
`}}class LX{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;let e=t.filterHeight,r=t.filterWidth,s=t.strideHeight,u=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,p=t.effectiveFilterHeight,m=t.effectiveFilterWidth,y=p-1-t.padInfo.top,b=m-1-t.padInfo.left,x=1/(e*r);this.userCode=`
const ivec2 pads = ivec2(${y}, ${b});
const float avgMultiplier = float(${x});
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${p};
wR += ${l}) {
2020-10-15 12:48:39 +02:00
float dyR = float(dyRCorner + wR) / ${s}.0;
2020-11-25 14:30:53 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
2020-10-15 12:48:39 +02:00
continue;
}
int idyR = int(dyR);
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${m};
wC+= ${h}) {
float dyC = float(dyCCorner + wC) / ${u}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class BX{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;let e=t.filterDepth,r=t.filterHeight,s=t.filterWidth,u=t.strideDepth,l=t.strideHeight,h=t.strideWidth,p=t.dilationDepth,m=t.dilationHeight,y=t.dilationWidth,b=t.effectiveFilterDepth,x=t.effectiveFilterHeight,S=t.effectiveFilterWidth,C=b-1-t.padInfo.front,I=x-1-t.padInfo.top,D=S-1-t.padInfo.left,R=1/(e*r*s);this.userCode=`
const ivec3 pads = ivec3(${C}, ${I}, ${D});
const float avgMultiplier = float(${R});
2020-10-15 12:48:39 +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(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-11-25 14:30:53 +01:00
for (int wD = 0; wD < ${b};
wD += ${p}) {
float dyD = float(dyDCorner + wD) / ${u}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
2020-10-15 12:48:39 +02:00
continue;
}
int idyD = int(dyD);
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${x};
wR += ${m}) {
float dyR = float(dyRCorner + wR) / ${l}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${S};
wC += ${y}) {
float dyC = float(dyCCorner + wC) / ${h}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}let jE=`
2020-10-15 12:48:39 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-11-25 14:30:53 +01:00
`,zX=`
2020-10-15 12:48:39 +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;
}
2020-11-25 14:30:53 +01:00
`,WX=`
2020-10-15 12:48:39 +02:00
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
2020-11-25 14:30:53 +01:00
`,Uft="return (a - b) * (a - b);",VX="return float(a == b);",UX="return float(a < b);",GX="return float(a <= b);",HX="return float(a > b);",qX="return float(a >= b);",jX="return float(a >= 1.0 && b >= 1.0);",KX="return float(a >= 1.0 || b >= 1.0);",XX=jE+`
2020-10-15 12:48:39 +02:00
return max(a, b);
2020-11-25 14:30:53 +01:00
`,YX=jE+`
2020-10-15 12:48:39 +02:00
return min(a, b);
2020-11-25 14:30:53 +01:00
`,JX=`if (b == 0.0) return NAN;
return mod(a, b);`,ZX="return (b >= 1.0) ? a : a * (b + 1.0);",KE="return (a < 0.) ? b * a : a;";class Yn{constructor(t,e,r){this.variableNames=["A","B"],this.outputShape=ve(e,r),this.userCode=`
2020-10-15 12:48:39 +02:00
float binaryOperation(float a, float b) {
2020-11-25 14:30:53 +01:00
${t}
2020-10-15 12:48:39 +02:00
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
2020-11-25 14:30:53 +01:00
`}}let Gm=`
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
`,QX=`
2020-10-15 12:48:39 +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]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
2020-11-25 14:30:53 +01:00
`,tY=`
2020-10-15 12:48:39 +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);
// 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;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
2020-11-25 14:30:53 +01:00
`+Gm+`
2020-10-15 12:48:39 +02:00
return result;
2020-11-25 14:30:53 +01:00
`,XE=`
2020-10-15 12:48:39 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2020-11-25 14:30:53 +01:00
`,eY=`
2020-10-15 12:48:39 +02:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
2020-11-25 14:30:53 +01:00
`,nY=`
2020-10-15 12:48:39 +02:00
return vec4(equal(a, b));
2020-11-25 14:30:53 +01:00
`,Gft=`
2020-10-15 12:48:39 +02:00
return vec4(notEqual(a, b));
2020-11-25 14:30:53 +01:00
`,rY=`
2020-10-15 12:48:39 +02:00
return vec4(lessThan(a, b));
2020-11-25 14:30:53 +01:00
`,sY=`
2020-10-15 12:48:39 +02:00
return vec4(lessThanEqual(a, b));
2020-11-25 14:30:53 +01:00
`,oY=`
2020-10-15 12:48:39 +02:00
return vec4(greaterThan(a, b));
2020-11-25 14:30:53 +01:00
`,aY=`
2020-10-15 12:48:39 +02:00
return vec4(greaterThanEqual(a, b));
2020-11-25 14:30:53 +01:00
`,iY=`
2020-10-15 12:48:39 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2020-11-25 14:30:53 +01:00
`,uY=`
2020-10-15 12:48:39 +02:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
2020-11-25 14:30:53 +01:00
`,cY=`
2020-10-15 12:48:39 +02:00
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-11-25 14:30:53 +01:00
`+Gm+`
2020-10-15 12:48:39 +02:00
return result;
2020-11-25 14:30:53 +01:00
`,lY=`
2020-10-15 12:48:39 +02:00
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-11-25 14:30:53 +01:00
`+Gm+`
2020-10-15 12:48:39 +02:00
return result;
2020-11-25 14:30:53 +01:00
`,hY=`
2020-10-15 12:48:39 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2020-11-25 14:30:53 +01:00
`+Gm+`
2020-10-15 12:48:39 +02:00
return result;
2020-11-25 14:30:53 +01:00
`;class Ao{constructor(t,e,r,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=ve(e,r);let u=this.outputShape.length,l="";if(s)if(u===0||O(this.outputShape)===1)l=`
2020-10-15 12:48:39 +02:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
2020-11-25 14:30:53 +01:00
`;else{let h=We(u);if(l=`
${h} coords = getOutputCoords();
`,u===1)l+=`
2020-10-15 12:48:39 +02:00
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
2020-11-25 14:30:53 +01:00
`;else{let p=nr("coords",u);l+=`
2020-10-15 12:48:39 +02:00
bool nextRowOutOfBounds =
2020-11-25 14:30:53 +01:00
(${p[u-2]} + 1) >= ${this.outputShape[u-2]};
2020-10-15 12:48:39 +02:00
bool nextColOutOfBounds =
2020-11-25 14:30:53 +01:00
(${p[u-1]} + 1) >= ${this.outputShape[u-1]};
2020-10-15 12:48:39 +02:00
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) {
2020-11-25 14:30:53 +01:00
${t}
2020-10-15 12:48:39 +02:00
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
2020-11-25 14:30:53 +01:00
${l}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class fY{constructor(t){this.variableNames=["A"],this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
2020-11-25 14:30:53 +01:00
`}getCustomSetupFunc(t,e){return(r,s)=>{this.minLoc==null&&(this.minLoc=r.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=r.getUniformLocationNoThrow(s,"maxVal")),r.gl.uniform1f(this.minLoc,t),r.gl.uniform1f(this.maxLoc,e)}}}class pY{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float minVal;
uniform float maxVal;
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
2020-11-25 14:30:53 +01:00
`}getCustomSetupFunc(t,e){return(r,s)=>{this.minLoc==null&&(this.minLoc=r.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=r.getUniformLocationNoThrow(s,"maxVal")),r.gl.uniform1f(this.minLoc,t),r.gl.uniform1f(this.maxLoc,e)}}}class dY{constructor(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// 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))
);
}
2020-11-25 14:30:53 +01:00
`}}class mY{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideHeight,r=t.strideWidth,s=t.padInfo.top,u=t.padInfo.left,l=t.dataFormat==="channelsLast";this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// 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;
2020-11-25 14:30:53 +01:00
for (int b = 0; b < ${t.batchSize}; b++) {
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${e} - ${s};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${r} - ${u};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
if (${l}) {
2020-10-15 12:48:39 +02:00
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);
}
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class gY{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterHeight,r=t.filterWidth,s=t.strideHeight,u=t.strideWidth,l=t.dataFormat==="channelsLast",h=e-1-t.padInfo.top,p=r-1-t.padInfo.left,m=l?1:2,y=l?2:3,b=l?3:1;this.userCode=`
const ivec2 pads = ivec2(${h}, ${p});
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
2020-11-25 14:30:53 +01:00
int d1 = coords[${b}];
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
ivec2 dyCorner = ivec2(coords[${m}], coords[${y}]) - pads;
2020-10-15 12:48:39 +02:00
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${e}; wR++) {
2020-10-15 12:48:39 +02:00
float dyR = float(dyRCorner + wR) / ${s}.0;
2020-11-25 14:30:53 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
2020-10-15 12:48:39 +02:00
continue;
}
int idyR = int(dyR);
2020-11-25 14:30:53 +01:00
int wRPerm = ${e} - 1 - wR;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${u}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-11-25 14:30:53 +01:00
int wCPerm = ${r} - 1 - wC;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (${l}) {
2020-10-15 12:48:39 +02:00
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;
}
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class vY{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideDepth,r=t.strideHeight,s=t.strideWidth,u=t.padInfo.front,l=t.padInfo.top,h=t.padInfo.left;this.userCode=`
2020-10-15 12:48:39 +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;
float dotProd = 0.0;
2020-11-25 14:30:53 +01:00
for (int b = 0; b < ${t.batchSize}; b++) {
for (int yF = 0; yF < ${t.outDepth}; yF++) {
int xF = wF + yF * ${e} - ${u};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xF < 0 || xF >= ${t.inDepth}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${r} - ${l};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${h};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class yY{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterDepth,r=t.filterHeight,s=t.filterWidth,u=t.strideDepth,l=t.strideHeight,h=t.strideWidth,p=e-1-t.padInfo.front,m=r-1-t.padInfo.top,y=s-1-t.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${p}, ${m}, ${y});
2020-10-15 12:48:39 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
2020-11-25 14:30:53 +01:00
for (int wF = 0; wF < ${e}; wF++) {
float dyF = float(dyFCorner + wF) / ${u}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyF < 0.0 || dyF >= ${t.outDepth}.0 || fract(dyF) > 0.0) {
2020-10-15 12:48:39 +02:00
continue;
}
int idyF = int(dyF);
2020-11-25 14:30:53 +01:00
int wFPerm = ${e} - 1 - wF;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${r}; wR++) {
float dyR = float(dyRCorner + wR) / ${l}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-11-25 14:30:53 +01:00
int wRPerm = ${r} - 1 - wR;
2020-10-15 12:48:39 +02:00
for (int wC = 0; wC < ${s}; wC++) {
2020-11-25 14:30:53 +01:00
float dyC = float(dyCCorner + wC) / ${h}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
2020-11-25 14:30:53 +01:00
for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
2020-10-15 12:48:39 +02:00
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class bY{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;let e=t.strideHeight,r=t.strideWidth,s=t.padInfo.top,u=t.padInfo.left,l=t.outChannels/t.inChannels;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
2020-11-25 14:30:53 +01:00
int d2 = d1 * ${l} + dm;
2020-10-15 12:48:39 +02:00
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
2020-11-25 14:30:53 +01:00
for (int b = 0; b < ${t.batchSize}; b++) {
for (int yR = 0; yR < ${t.outHeight}; yR++) {
int xR = wR + yR * ${e} - ${s};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int yC = 0; yC < ${t.outWidth}; yC++) {
int xC = wC + yC * ${r} - ${u};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class wY{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;let e=t.filterHeight,r=t.filterWidth,s=t.strideHeight,u=t.strideWidth,l=e-1-t.padInfo.top,h=r-1-t.padInfo.left,p=t.outChannels/t.inChannels;this.userCode=`
const ivec2 pads = ivec2(${l}, ${h});
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${e}; wR++) {
2020-10-15 12:48:39 +02:00
float dyR = float(dyRCorner + wR) / ${s}.0;
2020-11-25 14:30:53 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
2020-10-15 12:48:39 +02:00
continue;
}
int idyR = int(dyR);
2020-11-25 14:30:53 +01:00
int wRPerm = ${e} - 1 - wR;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${u}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-11-25 14:30:53 +01:00
int wCPerm = ${r} - 1 - wC;
2020-10-15 12:48:39 +02:00
// TO DO: Vec4 over the channelMul
2020-11-25 14:30:53 +01:00
for (int dm = 0; dm < ${p}; dm++) {
int d2 = d1 * ${p} + dm;
2020-10-15 12:48:39 +02:00
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class YE{constructor(t,e=!1,r=null,s=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;let u=t.padInfo.top,l=t.padInfo.left,h=t.strideHeight,p=t.strideWidth,m=t.dilationHeight,y=t.dilationWidth,b=t.filterHeight,x=t.filterWidth,S=Math.floor(t.inChannels/4)*4,C=t.inChannels%4,I=t.dataFormat==="channelsLast",D=I?1:2,R=I?2:3,A=I?3:1,L="",_="";r&&(s?L=`float activation(float a) {
2020-10-15 12:48:39 +02:00
float b = getPreluActivationWeightsAtOutCoords();
2020-11-25 14:30:53 +01:00
${r}
}`:L=`
2020-10-15 12:48:39 +02:00
float activation(float x) {
2020-11-25 14:30:53 +01:00
${r}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`,_="result = activation(result);");let B=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${L}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
const ivec2 strides = ivec2(${h}, ${p});
const ivec2 pads = ivec2(${u}, ${l});
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
2020-11-25 14:30:53 +01:00
int d2 = coords[${A}];
2020-10-15 12:48:39 +02:00
ivec2 xRCCorner =
2020-11-25 14:30:53 +01:00
ivec2(coords[${D}], coords[${R}]) * strides - pads;
2020-10-15 12:48:39 +02:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// 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;
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${b}; wR++) {
int xR = xRCorner + wR * ${m};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${x}; wC++) {
int xC = xCCorner + wC * ${y};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int d1 = 0; d1 < ${S}; d1 += 4) {
2020-10-15 12:48:39 +02:00
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)
);
2020-11-25 14:30:53 +01:00
if (${I}) {
2020-10-15 12:48:39 +02:00
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);
}
}
2020-11-25 14:30:53 +01:00
if (${C===1}) {
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (${I}) {
2020-10-15 12:48:39 +02:00
dotProd +=
2020-11-25 14:30:53 +01:00
getX(batch, xR, xC, ${S}) *
getW(wR, wC, ${S}, d2);
2020-10-15 12:48:39 +02:00
} else {
dotProd +=
2020-11-25 14:30:53 +01:00
getX(batch, ${S}, xR, xC) *
getW(wR, wC, ${S}, d2);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
} else if (${C===2}) {
2020-10-15 12:48:39 +02:00
vec2 wValues = vec2(
2020-11-25 14:30:53 +01:00
getW(wR, wC, ${S}, d2),
getW(wR, wC, ${S} + 1, d2)
2020-10-15 12:48:39 +02:00
);
2020-11-25 14:30:53 +01:00
if (${I}) {
2020-10-15 12:48:39 +02:00
vec2 xValues = vec2(
2020-11-25 14:30:53 +01:00
getX(batch, xR, xC, ${S}),
getX(batch, xR, xC, ${S} + 1)
2020-10-15 12:48:39 +02:00
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
2020-11-25 14:30:53 +01:00
getX(batch, ${S}, xR, xC),
getX(batch, ${S} + 1, xR, xC)
2020-10-15 12:48:39 +02:00
);
dotProd += dot(xValues, wValues);
}
2020-11-25 14:30:53 +01:00
} else if (${C===3}) {
2020-10-15 12:48:39 +02:00
vec3 wValues = vec3(
2020-11-25 14:30:53 +01:00
getW(wR, wC, ${S}, d2),
getW(wR, wC, ${S} + 1, d2),
getW(wR, wC, ${S} + 2, d2)
2020-10-15 12:48:39 +02:00
);
2020-11-25 14:30:53 +01:00
if (${I}) {
2020-10-15 12:48:39 +02:00
vec3 xValues = vec3(
2020-11-25 14:30:53 +01:00
getX(batch, xR, xC, ${S}),
getX(batch, xR, xC, ${S} + 1),
getX(batch, xR, xC, ${S} + 2)
2020-10-15 12:48:39 +02:00
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
2020-11-25 14:30:53 +01:00
getX(batch, ${S}, xR, xC),
getX(batch, ${S} + 1, xR, xC),
getX(batch, ${S} + 2, xR, xC)
2020-10-15 12:48:39 +02:00
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
2020-11-25 14:30:53 +01:00
${B}
${_}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class xY{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;let e=t.padInfo.front,r=t.padInfo.top,s=t.padInfo.left,u=t.strideDepth,l=t.strideHeight,h=t.strideWidth,p=t.dilationDepth,m=t.dilationHeight,y=t.dilationWidth,b=t.filterDepth,x=t.filterHeight,S=t.filterWidth,C=Math.floor(t.inChannels/4)*4,I=t.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${u}, ${l}, ${h});
const ivec3 pads = ivec3(${e}, ${r}, ${s});
2020-10-15 12:48:39 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// 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;
2020-11-25 14:30:53 +01:00
for (int wF = 0; wF < ${b}; wF++) {
int xF = xFCorner + wF * ${p};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xF < 0 || xF >= ${t.inDepth}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${x}; wR++) {
int xR = xRCorner + wR * ${m};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${S}; wC++) {
int xC = xCCorner + wC * ${y};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int d1 = 0; d1 < ${C}; d1 += 4) {
2020-10-15 12:48:39 +02:00
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)
);
dotProd += dot(xValues, wValues);
}
2020-11-25 14:30:53 +01:00
if (${I===1}) {
2020-10-15 12:48:39 +02:00
dotProd +=
2020-11-25 14:30:53 +01:00
getX(batch, xF, xR, xC, ${C}) *
getW(wF, wR, wC, ${C}, d2);
} else if (${I===2}) {
2020-10-15 12:48:39 +02:00
vec2 xValues = vec2(
2020-11-25 14:30:53 +01:00
getX(batch, xF, xR, xC, ${C}),
getX(batch, xF, xR, xC, ${C} + 1)
2020-10-15 12:48:39 +02:00
);
vec2 wValues = vec2(
2020-11-25 14:30:53 +01:00
getW(wF, wR, wC, ${C}, d2),
getW(wF, wR, wC, ${C} + 1, d2)
2020-10-15 12:48:39 +02:00
);
dotProd += dot(xValues, wValues);
2020-11-25 14:30:53 +01:00
} else if (${I===3}) {
2020-10-15 12:48:39 +02:00
vec3 xValues = vec3(
2020-11-25 14:30:53 +01:00
getX(batch, xF, xR, xC, ${C}),
getX(batch, xF, xR, xC, ${C} + 1),
getX(batch, xF, xR, xC, ${C} + 2)
2020-10-15 12:48:39 +02:00
);
vec3 wValues = vec3(
2020-11-25 14:30:53 +01:00
getW(wF, wR, wC, ${C}, d2),
getW(wF, wR, wC, ${C} + 1, d2),
getW(wF, wR, wC, ${C} + 2, d2)
2020-10-15 12:48:39 +02:00
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class JE{constructor(t,e=!1,r=null,s=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;let u=t.inHeight,l=t.inWidth,h=t.padInfo.top,p=t.padInfo.left,m=t.strideHeight,y=t.strideWidth,b=t.dilationHeight,x=t.dilationWidth,S=t.filterHeight,C=t.filterWidth,I=t.outChannels/t.inChannels,D="",R="";r&&(s?D=`float activation(float a) {
2020-10-15 12:48:39 +02:00
float b = getPreluActivationWeightsAtOutCoords();
2020-11-25 14:30:53 +01:00
${r}
}`:D=`
2020-10-15 12:48:39 +02:00
float activation(float x) {
2020-11-25 14:30:53 +01:00
${r}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`,R="result = activation(result);");let A=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${D}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
const ivec2 strides = ivec2(${m}, ${y});
const ivec2 pads = ivec2(${h}, ${p});
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
2020-11-25 14:30:53 +01:00
int d1 = d2 / ${I};
int q = d2 - d1 * ${I};
2020-10-15 12:48:39 +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.
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${S}; wR++) {
int xR = xRCorner + wR * ${b};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${u}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${C}; wC++) {
int xC = xCCorner + wC * ${x};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${l}) {
2020-10-15 12:48:39 +02:00
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
2020-11-25 14:30:53 +01:00
${A}
${R}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class ZE{constructor(t,e=!1,r=null,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;let u=t.inHeight,l=t.inWidth,h=t.padInfo.top,p=t.padInfo.left,m=t.strideHeight,y=t.strideWidth,b=t.dilationHeight,x=t.dilationWidth,S=t.filterHeight,C=t.filterWidth,I=C,D="int xR; int xC; int xCOffset;";for(let _=0;_<S;_++)for(let B=0;B<C;B++)D+=`
vec4 xTexelR${_}C${B*2} = vec4(0.);
vec4 wR${_}C${B} = vec4(0.);
vec4 xR${_}C${B} = vec4(0.);`;for(let _=0;_<S;_++)for(let B=0;B<I;B++){let V=B*2;if(D+=`
xR = xRCorner + ${_*b};
xC = xCCorner + ${V*x};
`,y===1){if(V<C&&(p%2===1?D+=`
2020-10-15 12:48:39 +02:00
xCOffset = xC + 1;
2020-11-25 14:30:53 +01:00
if(xR >= 0 && xR < ${u} && xCOffset >= 0 && xCOffset < ${l}) {
xTexelR${_}C${V} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2020-11-25 14:30:53 +01:00
if(xCOffset + 1 >= ${l}) {
xTexelR${_}C${V}.zw = vec2(0.);
2020-10-15 12:48:39 +02:00
}
} else {
2020-11-25 14:30:53 +01:00
xTexelR${_}C${V} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
xCOffset = xC + 1 - 2;
2020-11-25 14:30:53 +01:00
if(xR >= 0 && xR < ${u} && xCOffset >= 0 && xCOffset < ${l}) {
2020-10-15 12:48:39 +02:00
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2020-11-25 14:30:53 +01:00
if(xCOffset + 1 >= ${l}) {
2020-10-15 12:48:39 +02:00
previous.zw = vec2(0.);
}
2020-11-25 14:30:53 +01:00
xR${_}C${V} = vec4(previous.zw, xTexelR${_}C${V}.xy);
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
xR${_}C${V} = vec4(0, 0, xTexelR${_}C${V}.xy);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`:D+=`
if(xR >= 0 && xR < ${u} && xC >= 0 && xC < ${l}) {
xTexelR${_}C${V} = getX(batch, xR, xC, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
xTexelR${_}C${V} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
xR${_}C${V} = xTexelR${_}C${V};
`,V+1<C)){let q=p%2===0?w(x):x;x%2===0&&p%2===1||x%2!==0&&p%2!==1?(D+=`
xCOffset = xC + ${p%2} + ${q};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if(xR >= 0 && xR < ${u} &&
xCOffset >= 0 && xCOffset < ${l}) {
xTexelR${_}C${V+2} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`,x>1&&(D+=`
2020-10-15 12:48:39 +02:00
xCOffset -= 2;
2020-11-25 14:30:53 +01:00
if(xR >= 0 && xR < ${u} &&
xCOffset >= 0 && xCOffset < ${l}) {
xTexelR${_}C${V} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
xTexelR${_}C${V} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`),D+=`
xR${_}C${V+1} = vec4(
xTexelR${_}C${V}.zw, xTexelR${_}C${V+2}.xy);
`):D+=`
xCOffset = xC + ${q};
if(xR >= 0 && xR < ${u} &&
xCOffset >= 0 && xCOffset < ${l}) {
xTexelR${_}C${V+2} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
xR${_}C${V+1} = xTexelR${_}C${V+2};
`}}else V<C&&(D+=`
if(xR >= 0 && xR < ${u}) {
`,p%2===1?(D+=`
xCOffset = xC + 1 - ${y};
if(xCOffset >= 0 && xCOffset < ${l}) {
xTexelR${_}C${V} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
xTexelR${_}C${V} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
if(xC + 1 >= 0 && xC + 1 < ${l}) {
xTexelR${_}C${V+2} = getX(batch, xR, xC + 1, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
xTexelR${_}C${V+2} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
xR${_}C${V} = vec4(
xTexelR${_}C${V}.zw, xTexelR${_}C${V+2}.zw);
`,V+1<C&&(D+=`
2020-10-15 12:48:39 +02:00
vec4 final = vec4(0.);
2020-11-25 14:30:53 +01:00
xCOffset = xC + 1 + ${y};
if(xCOffset >= 0 && xCOffset < ${l}) {
2020-10-15 12:48:39 +02:00
final = getX(batch, xR, xCOffset, d1);
}
2020-11-25 14:30:53 +01:00
xR${_}C${V+1} = vec4(xTexelR${_}C${V+2}.xy, final.xy);
`)):(D+=`
if(xC >= 0 && xC < ${l}) {
xTexelR${_}C${V} = getX(batch, xR, xC, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
xTexelR${_}C${V} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
xCOffset = xC + ${y};
if(xCOffset >= 0 && xCOffset < ${l}) {
xTexelR${_}C${V+2} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
xTexelR${_}C${V+2} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
xR${_}C${V} = vec4(
xTexelR${_}C${V}.xy, xTexelR${_}C${V+2}.xy);
`,V+1<C&&(D+=`
xR${_}C${V+1} = vec4(
xTexelR${_}C${V}.zw, xTexelR${_}C${V+2}.zw);
`)),D+="}");V<C&&(D+=`
vec4 wTexelR${_}C${V} = getW(${_}, ${V}, d1, q);
wR${_}C${V} = vec4(wTexelR${_}C${V}.xz, wTexelR${_}C${V}.xz);
`,V+1<C&&(D+=`
vec4 wTexelR${_}C${V+1} = getW(${_}, ${V+1}, d1, q);
wR${_}C${V+1} =
vec4(wTexelR${_}C${V+1}.xz, wTexelR${_}C${V+1}.xz);`))}for(let _=0;_<S;_++)for(let B=0;B<C;B++)D+=`dotProd += xR${_}C${B} * wR${_}C${B};`;let R="",A="";r&&(s?R=`vec4 activation(vec4 a) {
2020-10-15 12:48:39 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-11-25 14:30:53 +01:00
${r}
}`:R=`vec4 activation(vec4 x) {
${r}
}`,A="result = activation(result);");let L=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${R}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
const ivec2 strides = ivec2(${m}, ${y});
const ivec2 pads = ivec2(${h}, ${p});
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
2020-11-25 14:30:53 +01:00
${D}
2020-10-15 12:48:39 +02:00
vec4 result = dotProd;
2020-11-25 14:30:53 +01:00
${L}
${A}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class TY{constructor(t,e,r,s,u){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[l,h,p,m]=t,[y]=e,[b,x]=r;this.outputShape=[y,b,x,m];let S=s==="bilinear"?1:0,[C,I]=[`${h-1}.0`,`${p-1}.0`],[D,R,A]=b>1?[`${(h-1)/(b-1)}`,"(y2-y1) * height_ratio",`y1*${C} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${C}`],[L,_,B]=x>1?[`${(p-1)/(x-1)}`,"(x2-x1) * width_ratio",`x1*${I} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${I}`];this.userCode=`
const float height_ratio = float(${D});
const float width_ratio = float(${L});
2020-10-15 12:48:39 +02:00
void main() {
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));
2020-11-25 14:30:53 +01:00
if(bInd < 0 || bInd >= ${l}) {
2020-10-15 12:48:39 +02:00
return;
}
2020-11-25 14:30:53 +01:00
float height_scale = ${R};
float width_scale = ${_};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
float in_y = ${A};
if( in_y < 0.0 || in_y > ${C} ) {
setOutput(float(${u}));
2020-10-15 12:48:39 +02:00
return;
}
2020-11-25 14:30:53 +01:00
float in_x = ${B};
if( in_x < 0.0 || in_x > ${I} ) {
setOutput(float(${u}));
2020-10-15 12:48:39 +02:00
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
2020-11-25 14:30:53 +01:00
if(${S} == 1) {
2020-10-15 12:48:39 +02:00
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
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);
}
}
2020-11-25 14:30:53 +01:00
`}}class QE{constructor(t,e,r){this.variableNames=["x"],this.outputShape=t;let s=t.length,u=e?"0.0":`getX(${tD(s,"coords")})`,l=t[t.length-1],h="",p="";e?(h=r?`end != ${l-1}`:"end != 0",p=r?"end + 1":"end - 1"):(h=r?`end + pow2 < ${l}`:"end >= pow2",p=r?"end + pow2":"end - pow2"),this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float index;
void main() {
2020-11-25 14:30:53 +01:00
${We(s)} coords = getOutputCoords();
int end = ${eD(s,"coords")};
float val = ${u};
2020-10-15 12:48:39 +02:00
int pow2 = int(pow(2.0, index));
2020-11-25 14:30:53 +01:00
if (${h}) {
int idx = ${p};
${eD(s,"coords")} = idx;
val += getX(${tD(s,"coords")});
2020-10-15 12:48:39 +02:00
}
setOutput(val);
}
2020-11-25 14:30:53 +01:00
`}getCustomSetupFunc(t){return(e,r)=>{this.index==null&&(this.index=e.getUniformLocation(r,"index")),e.gl.uniform1f(this.index,t)}}}function tD(n,t){if(n===1)return`${t}`;if(n===2)return`${t}.x, ${t}.y`;if(n===3)return`${t}.x, ${t}.y, ${t}.z`;if(n===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${n} is not yet supported`)}function eD(n,t){if(n===1)return`${t}`;if(n===2)return`${t}.y`;if(n===3)return`${t}.z`;if(n===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${n} is not yet supported`)}class kY{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=gf.DENSE;let e=yf(t),r=rr();this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-11-25 14:30:53 +01:00
${$i(["r","c","d"],t)}
2020-10-15 12:48:39 +02:00
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-11-25 14:30:53 +01:00
vec2(${e[0]}, ${e[1]}));
int index = 4 * (resTexRC.x * ${e[1]} + resTexRC.y);
2020-10-15 12:48:39 +02:00
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
2020-11-25 14:30:53 +01:00
${r.output} = result;
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class SY{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=gf.DENSE;let e=yf(t),r=rr();this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-11-25 14:30:53 +01:00
${$i(["r","c","d"],t)}
2020-10-15 12:48:39 +02:00
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-11-25 14:30:53 +01:00
vec2(${e[0]}, ${e[1]}));
int index = 4 * (resTexRC.x * ${e[1]} + resTexRC.y);
2020-10-15 12:48:39 +02:00
vec4 result = vec4(0.);
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));
}
2020-11-25 14:30:53 +01:00
${r.output} = result;
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class CY{constructor(t,e,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=r,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
2020-11-25 14:30:53 +01:00
int in_h = h / ${e};
int offset_h = imod(h, ${e});
int in_w = w / ${e};
int offset_w = imod(w, ${e});
int offset_d = (offset_h * ${e} + offset_w) *
2020-10-15 12:48:39 +02:00
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}class NY{constructor(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
2020-11-25 14:30:53 +01:00
`}}class IY{constructor(t){this.variableNames=["A"],this.outTexUsage=Hr.DOWNLOAD;let e=rr();this.outputShape=t,this.userCode=`
${UE}
2020-10-15 12:48:39 +02:00
void main() {
float x = getAAtOutCoords();
2020-11-25 14:30:53 +01:00
${e.output} = encode_float(x);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class EY{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Hr.DOWNLOAD;let e=rr();this.outputShape=t,this.userCode=`
${UE}
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
2020-11-25 14:30:53 +01:00
${e.output} = encode_float(x);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class DY{constructor(t,e,r=!1){this.variableNames=["A"];let s=rr(),[u,l]=e;this.outputShape=t;let h="result";r&&(h="floor(result * 255. + 0.5)"),this.userCode=`
${ux(t)}
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
2020-11-25 14:30:53 +01:00
int r = flatIndex / ${l};
int c = imod(flatIndex, ${l});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${l}.0, ${u}.0);
2020-10-15 12:48:39 +02:00
vec4 values = ${s.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
2020-11-25 14:30:53 +01:00
${s.output} = vec4(${h}, 0., 0., 0.);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class $Y{constructor(t,e,r=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let s=rr(),[u,l]=e;this.outputShape=t;let h="",p="result";r&&(p="floor(result * 255. + 0.5)");for(let m=0;m<=1;m++)for(let y=0;y<=1;y++){let b=m*2+y;h+=`
2020-10-15 12:48:39 +02:00
localCoords = coords;
2020-11-25 14:30:53 +01:00
if(localCoords[2] + ${y} < ${t[2]}) {
localCoords[2] += ${y};
if(localCoords[1] + ${m} < ${t[1]}) {
localCoords[1] += ${m};
2020-10-15 12:48:39 +02:00
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
2020-11-25 14:30:53 +01:00
r = flatIndex / ${l};
c = imod(flatIndex, ${l});
uv = (vec2(c, r) + halfCR) / vec2(${l}.0, ${u}.0);
2020-10-15 12:48:39 +02:00
values = ${s.texture2D}(A, uv);
if(offset == 0) {
2020-11-25 14:30:53 +01:00
result[${b}] = values[0];
2020-10-15 12:48:39 +02:00
} else if(offset == 1) {
2020-11-25 14:30:53 +01:00
result[${b}] = values[1];
2020-10-15 12:48:39 +02:00
} else if(offset == 2) {
2020-11-25 14:30:53 +01:00
result[${b}] = values[2];
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
result[${b}] = values[3];
2020-10-15 12:48:39 +02:00
}
}
}
`}this.userCode=`
2020-11-25 14:30:53 +01:00
${ux(t)}
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
2020-11-25 14:30:53 +01:00
${h}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
${s.output} = ${p};
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class AY{constructor(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
2020-11-25 14:30:53 +01:00
`}getCustomSetupFunc(t){return(e,r)=>{this.valueLoc==null&&(this.valueLoc=e.getUniformLocationNoThrow(r,"value")),e.gl.uniform1f(this.valueLoc,t)}}}class _Y{constructor(t,e,r){this.variableNames=["A","indices"];let s=t.slice();s[r]=e,this.outputShape=s,this.rank=s.length;let u=We(this.rank),l=FY(t,r);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${u} resRC = getOutputCoords();
setOutput(getA(${l}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}function FY(n,t){let e=n.length;if(e>4)throw Error(`Gather for rank ${e} is not yet supported`);if(e===1)return"int(getIndices(resRC))";let r=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let u=0;u<n.length;u++)u===t?s.push(`int(getIndices(${r[u]}))`):s.push(`${r[u]}`);return s.join()}class RY{constructor(t,e,r){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=r;let s=We(e.length),u=We(r.length),l=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2020-10-15 12:48:39 +02:00
${s} strides = ${s}(${this.strides});
void main() {
2020-11-25 14:30:53 +01:00
${u} coords = getOutputCoords();
2020-10-15 12:48:39 +02:00
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
2020-11-25 14:30:53 +01:00
flattenIndex += index * ${l};
2020-10-15 12:48:39 +02:00
}
setOutput(getX(flattenIndex, coords[1]));
}
2020-11-25 14:30:53 +01:00
`}}function PY(n){let t=rr(),e=`${t.version}
2020-10-15 12:48:39 +02:00
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
2020-11-25 14:30:53 +01:00
}`;return d8(n,e)}function OY(n){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 w8(n,t)}function MY(n){let t=new Uint16Array([0,1,2,2,1,3]);return x8(n,t)}function wf(n,t,e,r,s,u){k8(t,e);let l=T8(n),h=n.TEXTURE_2D;return zt(n,()=>n.bindTexture(h,l)),zt(n,()=>n.texParameteri(h,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)),zt(n,()=>n.texParameteri(h,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),zt(n,()=>n.texParameteri(h,n.TEXTURE_MIN_FILTER,n.NEAREST)),zt(n,()=>n.texParameteri(h,n.TEXTURE_MAG_FILTER,n.NEAREST)),zt(n,()=>n.texImage2D(h,0,r,t,e,0,s,u,null)),zt(n,()=>n.bindTexture(n.TEXTURE_2D,null)),l}function nD(n){return n.internalFormatFloat}function LY(n,t,e,r){let[s,u]=vf(t,e);return wf(n,s,u,nD(r),r.textureFormatFloat,n.FLOAT)}function rD(n){return n.internalFormatHalfFloat}function BY(n,t,e,r){let[s,u]=vf(t,e);return wf(n,s,u,rD(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function sD(n){return n.downloadTextureFormat}function zY(n,t,e,r){let[s,u]=vf(t,e);return wf(n,s,u,sD(r),n.RGBA,n.UNSIGNED_BYTE)}function oD(n){return n.internalFormatPackedFloat}function WY(n,t,e,r){let[s,u]=ic(t,e);return wf(n,s,u,oD(r),n.RGBA,n.FLOAT)}function aD(n){return n.internalFormatPackedHalfFloat}function VY(n,t,e,r){let[s,u]=ic(t,e);return wf(n,s,u,aD(r),n.RGBA,r.textureTypeHalfFloat)}function UY(n,t,e){let r=0,s=3*4,u=3*4+2*4;zt(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e));let l=LE(n,t,"clipSpacePos",e,3,u,r);return l&&LE(n,t,"uv",e,2,u,s)}function GY(n,t,e,r,s,u){zt(n,()=>n.bindTexture(n.TEXTURE_2D,t));let l,h,p;s instanceof Uint8Array?(l=new Uint8Array(e*r*4),h=n.UNSIGNED_BYTE,p=n.RGBA):(l=new Float32Array(e*r*4),h=n.FLOAT,p=u.internalFormatPackedFloat),l.set(s),zt(n,()=>n.texImage2D(n.TEXTURE_2D,0,p,e,r,0,n.RGBA,h,l)),zt(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function HY(n,t,e){zt(n,()=>n.bindTexture(n.TEXTURE_2D,t)),e.data instanceof Uint8Array?zt(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)):zt(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)),zt(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function qY(n,t,e,r){let s=n.createBuffer();zt(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,s));let u=4,l=4,h=u*l*t*e;return zt(n,()=>n.bufferData(n.PIXEL_PACK_BUFFER,h,n.STREAM_READ)),zt(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)),zt(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,null)),s}function jY(n,t,e){let r=n,s=new Float32Array(e);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 KY(n,t,e,r){let[s,u]=vf(t,e),l=4,h=new Uint8Array(i8(t*e,l));return zt(n,()=>n.readPixels(0,0,s,u,r.downloadTextureFormat,n.UNSIGNED_BYTE,h)),new Float32Array(h.buffer)}function XY(n,t,e,r,s,u,l,h){let p=n,m=new Float32Array(u8(u,l));return p.bindBuffer(p.PIXEL_PACK_BUFFER,t),p.getBufferSubData(p.PIXEL_PACK_BUFFER,0,m),p.bindBuffer(p.PIXEL_PACK_BUFFER,null),m}function YY(n,t,e){let r=new Float32Array(t*e*4);return zt(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,r)),r}class JY{constructor(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let e=ft().getNumber("WEBGL_VERSION");t!=null?(this.gl=t,s8(e,t)):this.gl=eo(e);let r="WEBGL_color_buffer_float",s="EXT_color_buffer_half_float";if(ft().getNumber("WEBGL_VERSION")===1){let u="OES_texture_float",l="OES_texture_half_float";if(this.textureFloatExtension=Mm(this.gl,u),as(this.gl,l))this.textureHalfFloatExtension=Mm(this.gl,l);else if(ft().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(r),as(this.gl,s))this.colorBufferHalfFloatExtension=Mm(this.gl,s);else if(ft().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(r="EXT_color_buffer_float",as(this.gl,r))this.colorBufferFloatExtension=this.gl.getExtension(r);else if(as(
blockIndex = rc.y + ${V};
pos = rc.x + ${B};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if(blockIndex < ${t[1]} && pos < ${t[0]}) {
offsetY = int(blockIndex / (${m})) * ${h} - ${C};
d0 = offsetY + ${b} * (pos / ${I});
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if(d0 < ${e[A]} && d0 >= 0) {
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
offsetX = int(mod(float(blockIndex), ${m}.) * ${l}. - ${S}.);
d1 = offsetX + ${y} * (int(mod(float(pos), ${I}.) / ${u}.));
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if(d1 < ${e[L]} && d1 >= 0) {
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
ch = int(mod(float(pos), ${u}.));
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (${R}) {
2020-10-15 12:48:39 +02:00
innerDims = vec2(d1, ch);
2020-11-25 14:30:53 +01:00
result[${B*2+V}] = getChannel(
2020-10-15 12:48:39 +02:00
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
2020-11-25 14:30:53 +01:00
result[${B*2+V}] = getChannel(
2020-10-15 12:48:39 +02:00
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
2020-11-25 14:30:53 +01:00
${_}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
${D.output} = result;
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class r7{constructor(t,e,r,s,u){this.variableNames=["x"],this.outputShape=[];let l=e,h=t[3]-1;this.outputShape=t;let p,m=`float(${r}) + float(${s}) * sum`;u===.5?p=`inversesqrt(${m})`:u===1?p=`1.0/(${m})`:p=`exp(log(${m}) * float(-${u}));`,this.userCode=`
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
for (int j = -${l}; j <= ${l}; j++) {
2020-10-15 12:48:39 +02:00
int idx = d + j;
2020-11-25 14:30:53 +01:00
if (idx >= 0 && idx <= ${h}) {
2020-10-15 12:48:39 +02:00
float z = getX(b, r, c, idx);
sum += z * z;
}
}
2020-11-25 14:30:53 +01:00
float val = x * ${p};
2020-10-15 12:48:39 +02:00
setOutput(val);
}
2020-11-25 14:30:53 +01:00
`}}class s7{constructor(t,e,r,s,u){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=r,this.alpha=s,this.beta=u,this.userCode=`
2020-10-15 12:48:39 +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) {
2020-11-25 14:30:53 +01:00
int depthBegin = int(max(0.0, float(d - ${e})));
2020-10-15 12:48:39 +02:00
int depthEnd = int(min(float(${this.depth}),
2020-11-25 14:30:53 +01:00
float(d + ${e} + 1)));
2020-10-15 12:48:39 +02:00
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;
}
}
2020-11-25 14:30:53 +01:00
norm = float(${s}) * norm + float(${r});
2020-10-15 12:48:39 +02:00
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(${s})
2020-11-25 14:30:53 +01:00
* float(${u})
2020-10-15 12:48:39 +02:00
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
2020-11-25 14:30:53 +01:00
dyi += pow(norm, -1.0 * ${u});
2020-10-15 12:48:39 +02:00
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class o7{constructor(t,e,r,s,u){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let l=e,h=t[3]-1;this.outputShape=t;let p,m=`float(${r}) + float(${s}) * sum`;u===.5?p=`inversesqrt(${m})`:u===1?p=`1.0/(${m})`:p=`exp(log(${m}) * float(-${u}));`,this.userCode=`
2020-10-15 12:48:39 +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
);
2020-11-25 14:30:53 +01:00
int firstChannel = d - ${l};
2020-10-15 12:48:39 +02:00
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));
}
}
ivec2 depth = ivec2(d, d + 1);
2020-11-25 14:30:53 +01:00
for (int j = - ${l}; j <= ${l}; j++) {
2020-10-15 12:48:39 +02:00
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
2020-11-25 14:30:53 +01:00
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${h}));
2020-10-15 12:48:39 +02:00
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;
}
}
2020-11-25 14:30:53 +01:00
vec4 result = xAtOutputCoords * ${p};
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class a7{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;let e=t.strideHeight,r=t.strideWidth,s=t.dilationHeight,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,h=u-1-t.padInfo.top,p=l-1-t.padInfo.left,m=u*l-1;this.userCode=`
const ivec2 pads = ivec2(${h}, ${p});
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${u};
2020-10-15 12:48:39 +02:00
wR += ${s}) {
2020-11-25 14:30:53 +01:00
float dyR = float(dyRCorner + wR) / ${e}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
2020-10-15 12:48:39 +02:00
continue;
}
int idyR = int(dyR);
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${l}; wC++) {
float dyC = float(dyCCorner + wC) / ${r}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
2020-11-25 14:30:53 +01:00
int maxPosValue = ${m} - int(getMaxPos(b, idyR, idyC, d));
2020-10-15 12:48:39 +02:00
// Get the current value, check it against the value from the
// position matrix.
2020-11-25 14:30:53 +01:00
int curPosValue = wR * ${l} + wC;
2020-10-15 12:48:39 +02:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class i7{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;let e=t.strideDepth,r=t.strideHeight,s=t.strideWidth,u=t.dilationDepth,l=t.dilationHeight,h=t.dilationWidth,p=t.effectiveFilterDepth,m=t.effectiveFilterHeight,y=t.effectiveFilterWidth,b=p-1-t.padInfo.front,x=m-1-t.padInfo.top,S=y-1-t.padInfo.left,C=p*m*y-1;this.userCode=`
const ivec3 pads = ivec3(${b}, ${x}, ${S});
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
for (int wD = 0; wD < ${p};
wD += ${u}) {
float dyD = float(dyDCorner + wD) / ${e}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
2020-10-15 12:48:39 +02:00
continue;
}
int idyD = int(dyD);
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${m};
wR += ${l}) {
float dyR = float(dyRCorner + wR) / ${r}.0;
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${y};
wC += ${h}) {
2020-10-15 12:48:39 +02:00
float dyC = float(dyCCorner + wC) / ${s}.0;
2020-11-25 14:30:53 +01:00
if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
2020-10-15 12:48:39 +02:00
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2020-11-25 14:30:53 +01:00
int maxPosValue = ${C} -
2020-10-15 12:48:39 +02:00
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
2020-11-25 14:30:53 +01:00
wD * ${m} * ${y} +
wR * ${y} + wC;
2020-10-15 12:48:39 +02:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
2020-11-25 14:30:53 +01:00
`}}class cx{constructor(t,e,r,s=!1,u=!1,l=!1,h=null,p=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r;let m=s?t[1]:t[2],y=Math.ceil(m/2),b=s?"i * 2, rc.y":"rc.y, i * 2",x=u?"rc.z, i * 2":"i * 2, rc.z",S=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],C=u?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],I="",D="";h&&(p?I=`vec4 activation(vec4 a) {
2020-10-15 12:48:39 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-11-25 14:30:53 +01:00
${h}
}`:I=`vec4 activation(vec4 x) {
${h}
}`,D="result = activation(result);");let R=l?"result += getBiasAtOutCoords();":"";l&&this.variableNames.push("bias"),p&&this.variableNames.push("preluActivationWeights");let A="rc.x",L="rc.x";t[0]<e[0]?A=`int(min(float(rc.x), ${t[0]-1}.))`:e[0]<t[0]&&(L=`int(min(float(rc.x), ${e[0]-1}.))`),this.userCode=`
${I}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
const float sharedDimension = ${y}.0;
2020-10-15 12:48:39 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
2020-11-25 14:30:53 +01:00
for (int i = 0; i < ${y}; i++) {
int batchA = ${A};
int batchB = ${L};
vec4 a = getMatrixA(batchA, ${b});
vec4 b = getMatrixB(batchB, ${x});
2020-10-15 12:48:39 +02:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
2020-11-25 14:30:53 +01:00
result += (${S[0]} * ${C[0]});
result += (${S[1]} * ${C[1]});
2020-10-15 12:48:39 +02:00
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2020-11-25 14:30:53 +01:00
${R}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
${D}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class u7{constructor(t,e,r){this.variableNames=["probs"],this.outputShape=[t,r],this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float seed;
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
2020-11-25 14:30:53 +01:00
for (int i = 0; i < ${e-1}; i++) {
2020-10-15 12:48:39 +02:00
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
2020-11-25 14:30:53 +01:00
setOutput(float(${e-1}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}getCustomSetupFunc(t){return(e,r)=>{this.seedLoc==null&&(this.seedLoc=e.getUniformLocation(r,"seed")),e.gl.uniform1f(this.seedLoc,t)}}}class c7{constructor(t,e,r,s){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
2020-11-25 14:30:53 +01:00
setOutput(mix(float(${s}), float(${r}),
2020-10-15 12:48:39 +02:00
float(index == coords.y)));
}
2020-11-25 14:30:53 +01:00
`}}class l7{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;let e=t.length;if(e===0)this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2020-11-25 14:30:53 +01:00
`;else{let r=nr("rc",e),s=We(e),u=f7(e,t,r),l=p7(e,t[t.length-1],t[t.length-2],r),h=d7(t,r);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} rc = getOutputCoords();
2020-11-25 14:30:53 +01:00
if(${u}) {
2020-10-15 12:48:39 +02:00
setOutput(vec4(0));
} else {
2020-11-25 14:30:53 +01:00
${l}
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
setOutput(vec4(${h}));
2020-10-15 12:48:39 +02:00
}
}
2020-11-25 14:30:53 +01:00
`}}}function h7(n,t){let e=[];for(let r=0;r<=1;r++)for(let s=0;s<=1;s++){let u=`${r===0?"r":"rp1"}, ${s===0?"c":"cp1"}`;for(let l=2;l<n;l++)u=`${t[t.length-1-l]},`+u;e.push(u)}return e}function f7(n,t,e){if(n===1)return`rc > ${t[0]}`;let r="";for(let s=n-2;s<n;s++)r+=`${e[s]} >= ${t[s]}`,s<n-1&&(r+="||");return r}function p7(n,t,e,r){if(n===1)return"";let s=r.slice(-2);return`
int r = ${s[0]};
int c = ${s[1]};
2020-10-15 12:48:39 +02:00
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
2020-11-25 14:30:53 +01:00
bool rEdge = rp1 >= ${e};
`}function d7(n,t){let e=n.length,r=h7(e,t);return e===1?`getA(rc),
rc + 1 >= ${n[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${r[0]}),
cEdge ? 0. : getA(${r[1]}),
rEdge ? 0. : getA(${r[2]}),
rEdge || cEdge ? 0. : getA(${r[3]})`}class m7{constructor(t,e,r){this.variableNames=["x"],this.outputShape=e.map((m,y)=>m[0]+t[y]+m[1]);let s=t.length,u=We(s),l=e.map(m=>m[0]).join(","),h=e.map((m,y)=>m[0]+t[y]).join(","),p=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=`
int start = ${l};
int end = ${h};
2020-10-15 12:48:39 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
2020-11-25 14:30:53 +01:00
setOutput(float(${r}));
2020-10-15 12:48:39 +02:00
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
2020-11-25 14:30:53 +01:00
${u} start = ${u}(${l});
${u} end = ${u}(${h});
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${u} outC = getOutputCoords();
2020-10-15 12:48:39 +02:00
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
2020-11-25 14:30:53 +01:00
setOutput(float(${r}));
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
${u} coords = outC - start;
setOutput(getX(${p}));
2020-10-15 12:48:39 +02:00
}
}
2020-11-25 14:30:53 +01:00
`}}class g7{constructor(t,e,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((I,D)=>I[0]+t[D]+I[1]);let s=t.length,u=We(s),l=e.map(I=>I[0]).join(","),h=e.map((I,D)=>I[0]+t[D]).join(","),p=nr("rc",s),m=nr("source",s),y=`${p[s-1]} < ${this.outputShape[s-1]}`,b=s===1?"source":`vec2(${m.slice(-2).join()})`,x=[`${u} rc = outputLoc;`,`${p[s-1]} += 1;
if(${y}) {
2020-10-15 12:48:39 +02:00
`,s===1?"":`}
rc = outputLoc;
2020-11-25 14:30:53 +01:00
${p[s-2]} += 1;
if(${p[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${p[s-1]} += 1;
if(${y}) {`],S=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",C="";for(let I=0,D=s===1?2:4;I<D;I++)C+=`
${x[I]}
if (${S}) {
result[${I}] = float(${r});
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
${u} source = rc - start;
result[${I}] = getChannel(getX(${m.join()}), ${b});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;C+=s===1?"} ":"}}",this.userCode=`
const ${u} start = ${u}(${l});
const ${u} end = ${u}(${h});
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${u} outputLoc = getOutputCoords();
2020-10-15 12:48:39 +02:00
vec4 result = vec4(0.);
2020-11-25 14:30:53 +01:00
${C}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}class xf{constructor(t,e,r,s=!1,u=!1){if(this.variableNames=["x"],e==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let l=t.filterWidth,h=t.strideHeight,p=t.strideWidth,m=t.dilationHeight,y=t.dilationWidth,b=t.effectiveFilterHeight,x=t.effectiveFilterWidth,S=t.padInfo.top,C=t.padInfo.left;this.outputShape=t.outShape;let I=e==="avg",D=`((batch * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + d`,R=`(xR * ${t.inWidth} + xC) * ${t.inChannels} + d`,A="0.0";if(I||(A="-1.0 / 1e-20"),r){let j=">=";this.userCode=`
const ivec2 strides = ivec2(${h}, ${p});
const ivec2 pads = ivec2(${S}, ${C});
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
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
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${b};
wR += ${m}) {
2020-10-15 12:48:39 +02:00
int xR = xRCorner + wR;
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${x};
wC += ${y}) {
2020-10-15 12:48:39 +02:00
int xC = xCCorner + wC;
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
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);
2020-11-25 14:30:53 +01:00
if (value ${j} currMinMaxValue) {
2020-10-15 12:48:39 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
2020-11-25 14:30:53 +01:00
minMaxPosition = ${s?u?D:R:`wR * ${x} + wC`};
2020-10-15 12:48:39 +02:00
}
}
}
setOutput(float(minMaxPosition));
}
2020-11-25 14:30:53 +01:00
`;return}let L="max",_=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(_="avgValue / count");let B=Math.floor(l/4)*4,V=l%4,q=`
if (${I}) {
2020-10-15 12:48:39 +02:00
avgValue += dot(values, ones);
} else {
2020-11-25 14:30:53 +01:00
minMaxValue = ${L}(values, minMaxValue);
2020-10-15 12:48:39 +02:00
}
`;this.userCode=`
2020-11-25 14:30:53 +01:00
const ivec2 strides = ivec2(${h}, ${p});
const ivec2 pads = ivec2(${S}, ${C});
const float initializationValue = ${A};
2020-10-15 12:48:39 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
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
2020-11-25 14:30:53 +01:00
vec4 minMaxValue = vec4(${A});
2020-10-15 12:48:39 +02:00
float avgValue = 0.0;
count = 0.0;
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${b};
wR += ${m}) {
2020-10-15 12:48:39 +02:00
int xR = xRCorner + wR;
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${B}; wC += 4) {
int xC = xCCorner + wC * ${y};
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2020-11-25 14:30:53 +01:00
getValue(batch, xR, xC + ${y}, d),
getValue(batch, xR, xC + 2 * ${y}, d),
getValue(batch, xR, xC + 3 * ${y}, d)
2020-10-15 12:48:39 +02:00
);
2020-11-25 14:30:53 +01:00
${q}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
int xC = xCCorner + ${B};
if (${V===1}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
2020-11-25 14:30:53 +01:00
${q}
} else if (${V===2}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2020-11-25 14:30:53 +01:00
getValue(batch, xR, xC + ${y}, d),
2020-10-15 12:48:39 +02:00
initializationValue,
initializationValue
);
2020-11-25 14:30:53 +01:00
${q}
} else if (${V===3}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2020-11-25 14:30:53 +01:00
getValue(batch, xR, xC + ${y}, d),
getValue(batch, xR, xC + 2 * ${y}, d),
2020-10-15 12:48:39 +02:00
initializationValue
);
2020-11-25 14:30:53 +01:00
${q}
2020-10-15 12:48:39 +02:00
}
}
2020-11-25 14:30:53 +01:00
setOutput(${_});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class lx{constructor(t,e,r,s=!1,u=!1){if(this.variableNames=["x"],e==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let l=t.filterWidth,h=t.strideDepth,p=t.strideHeight,m=t.strideWidth,y=t.dilationDepth,b=t.dilationHeight,x=t.dilationWidth,S=t.effectiveFilterDepth,C=t.effectiveFilterHeight,I=t.effectiveFilterWidth,D=t.padInfo.front,R=t.padInfo.top,A=t.padInfo.left;this.outputShape=t.outShape;let L=e==="avg",_="0.0";if(L||(_="-1.0 / 1e-20"),r){let tt=">=";this.userCode=`
2020-10-15 12:48:39 +02:00
const ivec3 strides =
2020-11-25 14:30:53 +01:00
ivec3(${h}, ${p}, ${m});
const ivec3 pads = ivec3(${D}, ${R}, ${A});
2020-10-15 12:48:39 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// 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;
2020-11-25 14:30:53 +01:00
for (int wD = 0; wD < ${S};
wD += ${y}) {
2020-10-15 12:48:39 +02:00
int xD = xDCorner + wD;
2020-11-25 14:30:53 +01:00
if (xD < 0 || xD >= ${t.inDepth}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${C};
wR += ${b}) {
2020-10-15 12:48:39 +02:00
int xR = xRCorner + wR;
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${I};
wC += ${x}) {
2020-10-15 12:48:39 +02:00
int xC = xCCorner + wC;
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
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);
2020-11-25 14:30:53 +01:00
if (value ${tt} currMinMaxValue) {
2020-10-15 12:48:39 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
2020-11-25 14:30:53 +01:00
minMaxPosition = ${s?u?`(((batch * ${t.inDepth} + xD) * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`((xD * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`wD * ${C} * ${I} +
wR * ${I} + wC`};
2020-10-15 12:48:39 +02:00
}
}
}
}
setOutput(float(minMaxPosition));
}
2020-11-25 14:30:53 +01:00
`;return}let B="max",V=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(V="avgValue / count");let q=Math.floor(l/4)*4,j=l%4,et=`
if (${L}) {
2020-10-15 12:48:39 +02:00
avgValue += dot(values, ones);
} else {
2020-11-25 14:30:53 +01:00
minMaxValue = ${B}(values, minMaxValue);
2020-10-15 12:48:39 +02:00
}
`;this.userCode=`
const ivec3 strides =
2020-11-25 14:30:53 +01:00
ivec3(${h}, ${p}, ${m});
const ivec3 pads = ivec3(${D}, ${R}, ${A});
const float initializationValue = ${_};
2020-10-15 12:48:39 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
2020-11-25 14:30:53 +01:00
if (xC < 0 || xC >= ${t.inWidth}) {
2020-10-15 12:48:39 +02:00
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2020-11-25 14:30:53 +01:00
vec4 minMaxValue = vec4(${_});
2020-10-15 12:48:39 +02:00
float avgValue = 0.0;
count = 0.0;
2020-11-25 14:30:53 +01:00
for (int wD = 0; wD < ${S};
wD += ${y}) {
2020-10-15 12:48:39 +02:00
int xD = xDCorner + wD;
2020-11-25 14:30:53 +01:00
if (xD < 0 || xD >= ${t.inDepth}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wR = 0; wR < ${C};
wR += ${b}) {
2020-10-15 12:48:39 +02:00
int xR = xRCorner + wR;
2020-11-25 14:30:53 +01:00
if (xR < 0 || xR >= ${t.inHeight}) {
2020-10-15 12:48:39 +02:00
continue;
}
2020-11-25 14:30:53 +01:00
for (int wC = 0; wC < ${q}; wC += 4) {
int xC = xCCorner + wC * ${x};
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-11-25 14:30:53 +01:00
getValue(batch, xD, xR, xC + ${x}, ch),
getValue(batch, xD, xR, xC + 2 * ${x}, ch),
getValue(batch, xD, xR, xC + 3 * ${x}, ch)
2020-10-15 12:48:39 +02:00
);
2020-11-25 14:30:53 +01:00
${et}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
int xC = xCCorner + ${q};
if (${j===1}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
2020-11-25 14:30:53 +01:00
${et}
} else if (${j===2}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-11-25 14:30:53 +01:00
getValue(batch, xD, xR, xC + ${x}, ch),
2020-10-15 12:48:39 +02:00
initializationValue,
initializationValue
);
2020-11-25 14:30:53 +01:00
${et}
} else if (${j===3}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-11-25 14:30:53 +01:00
getValue(batch, xD, xR, xC + ${x}, ch),
getValue(batch, xD, xR, xC + 2 * ${x}, ch),
2020-10-15 12:48:39 +02:00
initializationValue
);
2020-11-25 14:30:53 +01:00
${et}
2020-10-15 12:48:39 +02:00
}
}
2020-11-25 14:30:53 +01:00
setOutput(${V});
2020-10-15 12:48:39 +02:00
}
}
2020-11-25 14:30:53 +01:00
`}}class uD{constructor(t,e){this.variableNames=["x"];let{windowSize:r,batchSize:s,inSize:u,outSize:l}=t;this.outputShape=[s,l];let h="0.0",p="";e==="prod"?h="1.0":e==="min"?(h="1.0 / 1e-20",p="min"):e==="max"&&(h="-1.0 / 1e-20",p="max");let m=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="sum"?m="sumValue":e==="prod"?m="prodValue":e==="all"?m="allValue":e==="any"&&(m="anyValue");let y=Math.floor(r/4)*4,b=r%4,x=`
if (${e==="sum"}) {
2020-10-15 12:48:39 +02:00
sumValue += dot(values, ones);
2020-11-25 14:30:53 +01:00
} else if (${e==="prod"}) {
2020-10-15 12:48:39 +02:00
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
2020-11-25 14:30:53 +01:00
minMaxValue = ${p}(values, minMaxValue);
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`,S="vec4";e==="all"?(h="1.0",x=`
2020-10-15 12:48:39 +02:00
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
2020-11-25 14:30:53 +01:00
`,S="bvec4"):e==="any"&&(h="0.0",x=`
2020-10-15 12:48:39 +02:00
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
2020-11-25 14:30:53 +01:00
`,S="bvec4");let C="";u%r>0&&(C=`
if (inIdx < 0 || inIdx >= ${u}) {
2020-10-15 12:48:39 +02:00
return initializationValue;
}
`),this.userCode=`
2020-11-25 14:30:53 +01:00
const float initializationValue = ${h};
2020-10-15 12:48:39 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
2020-11-25 14:30:53 +01:00
${C}
2020-10-15 12:48:39 +02:00
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
2020-11-25 14:30:53 +01:00
int inOffset = outIdx * ${r};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
vec4 minMaxValue = vec4(${h});
2020-10-15 12:48:39 +02:00
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
2020-11-25 14:30:53 +01:00
for (int i = 0; i < ${y}; i += 4) {
2020-10-15 12:48:39 +02:00
int inIdx = inOffset + i;
2020-11-25 14:30:53 +01:00
${S} values = ${S}(
2020-10-15 12:48:39 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2020-11-25 14:30:53 +01:00
${x}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
int inIdx = inOffset + ${y};
if (${b===1}) {
${S} values = ${S}(
2020-10-15 12:48:39 +02:00
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2020-11-25 14:30:53 +01:00
${x}
} else if (${b===2}) {
${S} values = ${S}(
2020-10-15 12:48:39 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2020-11-25 14:30:53 +01:00
${x}
} else if (${b===3}) {
${S} values = ${S}(
2020-10-15 12:48:39 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2020-11-25 14:30:53 +01:00
${x}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
setOutput(${m});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class cD{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;let r="";for(let s=0;s<4;s++){let u="thisRC = rc;";s%2===1&&(u+="thisRC.z += 1;"),s>1&&(u+="thisRC.y += 1;"),r+=`
${u}
2020-10-15 12:48:39 +02:00
${s>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${s}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${s>0?"}":""}
`}this.userCode=`
2020-11-25 14:30:53 +01:00
${v7(e)}
${ux(t)}
2020-10-15 12:48:39 +02:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
2020-11-25 14:30:53 +01:00
int rows = ${t[1]};
int cols = ${t[2]};
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
${r}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}function v7(n){let t=$i(["r","c","d"],n);return`
2020-10-15 12:48:39 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
2020-11-25 14:30:53 +01:00
`}class y7{constructor(t,e,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;let[,s,u]=e.shape,[,l,h]=t.shape,p=[r&&l>1?s-1:s,r&&h>1?u-1:u],m=[r&&l>1?l-1:l,r&&h>1?h-1:h],y=p[0]/m[0],b=p[1]/m[1],x=1/y,S=1/b,C=Math.ceil(x)*2+2,I=Math.ceil(S)*2+2;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
2020-11-25 14:30:53 +01:00
const float heightScale = float(${y});
const float widthScale = float(${b});
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
const float invHeightScale = float(${x});
const float invWidthScale = float(${S});
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
const int winHeight = int(${C});
const int winWidth = int(${I});
2020-10-15 12:48:39 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
2020-11-25 14:30:53 +01:00
if (dyR < 0 || dyR >= ${l}) {
2020-10-15 12:48:39 +02:00
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
2020-11-25 14:30:53 +01:00
if (dyC < 0 || dyC >= ${h}) {
2020-10-15 12:48:39 +02:00
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
2020-11-25 14:30:53 +01:00
int rightDxCIndex = int(min(ceil(dxC), ${u-1}.0));
2020-10-15 12:48:39 +02:00
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
2020-11-25 14:30:53 +01:00
`}}class b7{constructor(t,e,r,s){this.variableNames=["A"],this.outputShape=[];let[u,l,h,p]=t;this.outputShape=[u,e,r,p];let m=[s&&e>1?l-1:l,s&&r>1?h-1:h],y=[s&&e>1?e-1:e,s&&r>1?r-1:r];this.userCode=`
2020-10-15 12:48:39 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2020-11-25 14:30:53 +01:00
${m[0]/y[0]},
${m[1]/y[1]});
const vec2 inputShapeRC = vec2(${l}.0, ${h}.0);
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
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);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
2020-11-25 14:30:53 +01:00
`}}class w7{constructor(t,e,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[u,l,h,p]=t;this.outputShape=[u,e,r,p];let m=[s&&e>1?l-1:l,s&&r>1?h-1:h],y=[s&&e>1?e-1:e,s&&r>1?r-1:r];this.userCode=`
2020-10-15 12:48:39 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
2020-11-25 14:30:53 +01:00
${m[0]/y[0]},
${m[1]/y[1]},
${m[1]/y[1]});
const vec3 inputShapeRC = vec3(${l}.0, ${h}.0,
${h}.0);
2020-10-15 12:48:39 +02:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
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);
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
2020-11-25 14:30:53 +01:00
bool hasNextCol = d < ${p-1};
bool hasNextRow = coords.z < ${r-1};
2020-10-15 12:48:39 +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);
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);
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);
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);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
2020-11-25 14:30:53 +01:00
`}}class x7{constructor(t,e,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;let[,s,u]=e.shape,[,l,h]=t.shape,p=[r&&l>1?s-1:s,r&&h>1?u-1:u],m=[r&&l>1?l-1:l,r&&h>1?h-1:h],y=p[0]/m[0],b=p[1]/m[1],x=1/y,S=1/b,C=Math.ceil(x)*2+2,I=Math.ceil(S)*2+2;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
2020-11-25 14:30:53 +01:00
const float heightScale = float(${y});
const float widthScale = float(${b});
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
const float invHeightScale = float(${x});
const float invWidthScale = float(${S});
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
const int winHeight = int(${C});
const int winWidth = int(${I});
2020-10-15 12:48:39 +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)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
2020-11-25 14:30:53 +01:00
if (dyR < 0 || dyR >= ${l}) {
2020-10-15 12:48:39 +02:00
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
2020-11-25 14:30:53 +01:00
if (dyC < 0 || dyC >= ${h}) {
2020-10-15 12:48:39 +02:00
continue;
}
float sourceFracRow =
2020-11-25 14:30:53 +01:00
float(${p[0]}) *
(float(dyR) / float(${m[0]}));
2020-10-15 12:48:39 +02:00
float sourceFracCol =
2020-11-25 14:30:53 +01:00
float(${p[1]}) *
(float(dyC) / float(${m[1]}));
2020-10-15 12:48:39 +02:00
int sourceNearestRow = int(min(
float(int(${s}) - 1),
2020-11-25 14:30:53 +01:00
${r} ? float(round(sourceFracRow)) :
2020-10-15 12:48:39 +02:00
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
2020-11-25 14:30:53 +01:00
float(int(${u}) - 1),
${r} ? float(round(sourceFracCol)) :
2020-10-15 12:48:39 +02:00
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
2020-11-25 14:30:53 +01:00
`}}class T7{constructor(t,e,r,s){this.variableNames=["A"],this.outputShape=[];let[u,l,h,p]=t;this.outputShape=[u,e,r,p];let m=[s&&e>1?l-1:l,s&&r>1?h-1:h],y=[s&&e>1?e-1:e,s&&r>1?r-1:r],b=s?"0.5":"0.0";this.userCode=`
2020-10-15 12:48:39 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2020-11-25 14:30:53 +01:00
${m[0]/y[0]},
${m[1]/y[1]});
const vec2 inputShapeRC = vec2(${l}.0, ${h}.0);
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
2020-11-25 14:30:53 +01:00
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${b})));
2020-10-15 12:48:39 +02:00
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
2020-11-25 14:30:53 +01:00
`}}class k7{constructor(t,e){this.variableNames=["x"];let r=t.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);if(this.outputShape=t,r===1){this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
int coord = getOutputCoords();
2020-11-25 14:30:53 +01:00
setOutput(getX(${t[0]} - coord - 1));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`;return}let s=h=>e.indexOf(h)!==-1&&t[h]!==1?`${t[h]} - coords[${h}] - 1`:`coords[${h}]`,u=t.map((h,p)=>s(p)).join(","),l=We(r);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${l} coords = getOutputCoords();
setOutput(getX(${u}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class S7{constructor(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let r=t.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);this.outputShape=t;let s=nr("rc",r),u=`${s[r-1]} + 1 < ${this.outputShape[r-1]}`,l=`${s[r-2]} + 1 < ${this.outputShape[r-2]}`,h=We(r);r===1?this.userCode=`
2020-10-15 12:48:39 +02:00
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
2020-11-25 14:30:53 +01:00
result.r = getChannel(getX(${t[0]} - rc - 1),
${t[0]} - rc - 1);
if(${u}){
result.g = getChannel(getX(${t[0]} - (rc + 1) - 1),
${t[0]} - (rc + 1) - 1);
2020-10-15 12:48:39 +02:00
}
setOutput(result);
}
`:this.userCode=`
void main() {
2020-11-25 14:30:53 +01:00
${h} rc = getOutputCoords();
2020-10-15 12:48:39 +02:00
vec4 result = vec4(0.);
2020-11-25 14:30:53 +01:00
result.r = ${p(s.slice())};
if(${u}){
result.g = ${m(s.slice())};
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
if(${l}) {
result.b = ${y(s.slice())};
if(${u}) {
result.a = ${b(s.slice())};
2020-10-15 12:48:39 +02:00
}
}
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`;function p(C){return x(C)}function m(C){return C[r-1]="("+C[r-1]+" + 1)",x(C)}function y(C){return C[r-2]="("+C[r-2]+" + 1)",x(C)}function b(C){return C[r-1]="("+C[r-1]+" + 1)",C[r-2]="("+C[r-2]+" + 1)",x(C)}function x(C){let I=t.map((A,L)=>S(L,C)),D=I.join(","),R=I.slice(-2).join(",");return`getChannel(getX(${D}), vec2(${R}))`}function S(C,I){return e.indexOf(C)!==-1&&t[C]!==1?`${t[C]} - ${I[C]} - 1`:`${I[C]}`}}}class lD{constructor(t,e,r,s,u,l,h=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=l;let p=We(u.length),m=We(l.length),y="";r===1?y="i":r===2&&(y="i, j");let b=`getIndices(${y})`,x="";s===1?x="i":s===2&&(x="i, coords[1]");let S=`getUpdates(${x})`,C=e>1?"strides[j]":"strides";this.userCode=`
${p} strides = ${p}(${u});
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${m} coords = getOutputCoords();
2020-10-15 12:48:39 +02:00
float sum = 0.0;
bool found = false;
2020-11-25 14:30:53 +01:00
for (int i = 0; i < ${t}; i++) {
2020-10-15 12:48:39 +02:00
int flattenedIndex = 0;
2020-11-25 14:30:53 +01:00
for (int j = 0; j < ${e}; j++) {
int index = round(${b});
flattenedIndex += index * ${C};
2020-10-15 12:48:39 +02:00
}
if (flattenedIndex == coords[0]) {
2020-11-25 14:30:53 +01:00
sum += ${S};
2020-10-15 12:48:39 +02:00
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
2020-11-25 14:30:53 +01:00
`}}class C7{constructor(t,e){this.variableNames=["x","segmentIds"];let r=t.windowSize,s=t.batchSize,u=t.inSize,l=t.numSegments,h=l*Math.ceil(u/r);this.outputShape=[s,h];let p="0.0",m="sumValue",y=Math.floor(r/4)*4,b=r%4,x=`
2020-10-15 12:48:39 +02:00
sumValue += dot(values, segFilter);
2020-11-25 14:30:53 +01:00
`,S="";u%r>0&&(S=`
if (inIdx < 0 || inIdx >= ${u}) {
2020-10-15 12:48:39 +02:00
return initializationValue;
}
2020-11-25 14:30:53 +01:00
`);let C="";u%r>0&&(C=`
if (inIdx < 0 || inIdx >= ${u}) {
2020-10-15 12:48:39 +02:00
return -1.0;
}
`),this.userCode=`
2020-11-25 14:30:53 +01:00
const float initializationValue = ${p};
2020-10-15 12:48:39 +02:00
float getValue(int batch, int inIdx) {
2020-11-25 14:30:53 +01:00
${S}
2020-10-15 12:48:39 +02:00
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
2020-11-25 14:30:53 +01:00
${C}
2020-10-15 12:48:39 +02:00
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
2020-11-25 14:30:53 +01:00
${l})) * float(${r}));
int currentSeg = int(mod(float(outIdx), float(${l})));
2020-10-15 12:48:39 +02:00
float sumValue = 0.0;
2020-11-25 14:30:53 +01:00
for (int i = 0; i < ${y}; i += 4) {
2020-10-15 12:48:39 +02:00
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
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
);
2020-11-25 14:30:53 +01:00
${x}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
int inIdx = inOffset + ${y};
if (${b===1}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
2020-11-25 14:30:53 +01:00
${x}
} else if (${b===2}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
2020-11-25 14:30:53 +01:00
${x}
} else if (${b===3}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
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-11-25 14:30:53 +01:00
${x}
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
setOutput(${m});
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class N7{constructor(t,e,r){this.variableNames=["c","a","b"],this.outputShape=e;let s,u;if(r>4)throw Error(`Where for rank ${r} is not yet supported`);if(r===1)u="resRC",s="resRC";else{let h=["resRC.x","resRC.y","resRC.z","resRC.w"],p=[],m=[];for(let y=0;y<e.length;y++)m.push(`${h[y]}`),y<t&&p.push(`${h[y]}`);s=p.join(),u=m.join()}let l=We(r);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${l} resRC = getOutputCoords();
2020-10-15 12:48:39 +02:00
float cVal = getC(${s});
if (cVal >= 1.0) {
2020-11-25 14:30:53 +01:00
setOutput(getA(${u}));
2020-10-15 12:48:39 +02:00
} else {
2020-11-25 14:30:53 +01:00
setOutput(getB(${u}));
2020-10-15 12:48:39 +02:00
}
}
2020-11-25 14:30:53 +01:00
`}}class I7{constructor(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;let e=We(this.rank),r=`uniform int start[${this.rank}];`,s=E7(this.rank),u,l=t.map((h,p)=>`sourceLoc.${hx[p]} = start[${p}] + coords.${hx[p]};`);u=`
${e} sourceLoc;
${e} coords = getOutputCoords();
${l.join(`
2020-10-15 12:48:39 +02:00
`)}
`,this.userCode=`
2020-11-25 14:30:53 +01:00
${r}
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${u}
2020-10-15 12:48:39 +02:00
setOutput(getSource(${s}));
}
2020-11-25 14:30:53 +01:00
`}getCustomSetupFunc(t){if(t.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${t.length})`);return(e,r)=>{if(this.startLoc==null&&(this.startLoc=e.getUniformLocationNoThrow(r,"start"),this.startLoc==null))return;e.gl.uniform1iv(this.startLoc,t)}}}let hx=["x","y","z","w","u","v"];function E7(n){if(n===1)return"sourceLoc";if(n<=6)return hx.slice(0,n).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}class D7{constructor(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;let e=We(this.rank),r=nr("coords",this.rank),s=nr("sourceLoc",this.rank),u=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,l=`getChannel(getSource(${s.join()}), ${u})`,h=`
result.x = ${l};
if (++${r[this.rank-1]} < ${t[this.rank-1]}) {
2020-10-15 12:48:39 +02:00
++${s[this.rank-1]};
2020-11-25 14:30:53 +01:00
result.y = ${l};
2020-10-15 12:48:39 +02:00
--${s[this.rank-1]};
}
2020-11-25 14:30:53 +01:00
`,p=this.rank===1?"":`
--${r[this.rank-1]};
if (++${r[this.rank-2]} < ${t[this.rank-2]}) {
2020-10-15 12:48:39 +02:00
++${s[this.rank-2]};
2020-11-25 14:30:53 +01:00
result.z = ${l};
if (++${r[this.rank-1]} < ${t[this.rank-1]}) {
2020-10-15 12:48:39 +02:00
++${s[this.rank-1]};
2020-11-25 14:30:53 +01:00
result.w = ${l};
2020-10-15 12:48:39 +02:00
}
}
2020-11-25 14:30:53 +01:00
`,m=this.rank<=4?`sourceLoc = coords +
${e}(${t.map((y,b)=>`start[${b}]`).join()});`:t.map((y,b)=>`${s[b]} = ${r[b]} + start[${b}];`).join(`
2020-10-15 12:48:39 +02:00
`);this.userCode=`
uniform int start[${this.rank}];
void main() {
2020-11-25 14:30:53 +01:00
${e} coords = getOutputCoords();
${e} sourceLoc;
${m}
2020-10-15 12:48:39 +02:00
vec4 result = vec4(0.);
2020-11-25 14:30:53 +01:00
${h}
${p}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}getCustomSetupFunc(t){if(t.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${t.length})`);return(e,r)=>{if(this.startLoc==null&&(this.startLoc=e.getUniformLocationNoThrow(r,"start"),this.startLoc==null))return;e.gl.uniform1iv(this.startLoc,t)}}}class $7{constructor(t,e,r){this.variableNames=["x"],this.outputShape=r;let s=r.length,u=We(r.length),l=We(r.length),h="";if(s===1)h="coords * strides + begin";else{let p=0;h=r.map((m,y)=>(p++,r.length===1?`coords * strides[${y}] + begin[${y}]`:`coords[${p-1}] * strides[${y}] + begin[${y}]`)).join(",")}this.userCode=`
${u} begin = ${u}(${t});
${u} strides = ${u}(${e});
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
${l} coords = getOutputCoords();
setOutput(getX(${h}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}class A7{constructor(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(t,e,r){let s=fD(e,r),u=pD(t,s,r);u in this.freeTextures||(this.freeTextures[u]=[]),u in this.usedTextures||(this.usedTextures[u]=[]);let l=hD(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r);if(this.freeTextures[u].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=l,this.log();let p=this.freeTextures[u].shift();return this.usedTextures[u].push(p),p}let h;return s===Vn.PACKED_2X2_FLOAT32?h=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):s===Vn.PACKED_2X2_FLOAT16?h=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):s===Vn.UNPACKED_FLOAT32?h=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):s===Vn.UNPACKED_FLOAT16?h=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):s===Vn.PACKED_4X1_UNSIGNED_BYTE&&(h=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[u].push(h),this.numUsedTextures++,this._numBytesAllocated+=l,this.log(),h}releaseTexture(t,e,r,s){if(this.freeTextures==null)return;let u=fD(r,s),l=pD(e,u,s);l in this.freeTextures||(this.freeTextures[l]=[]);let h=hD(e,u,this.gpgpu.gl,this.gpgpu.textureConfig,s),p=ft().get("WEBGL_DELETE_TEXTURE_THRESHOLD");p!==-1&&this._numBytesAllocated>p?(this.gpgpu.deleteMatrixTexture(t),this._numBytesAllocated-=h):(this.freeTextures[l].push(t),this.numFreeTextures++,this._numBytesFree+=h),this.numUsedTextures--;let m=this.usedTextures[l],y=m.indexOf(t);if(y<0)throw new Error("Cannot release a texture that was never provided by this texture manager");m.splice(y,1),this.log()}log(){if(!this.logEnabled)return;let t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${t})`);let e=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*e)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures==null)return;for(let t in this.freeTextures)this.freeTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e)});for(let t in this.usedTextures)this.usedTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}function _7(n,t){let e=n;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===n.RGBA)return 16;if(t===e.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function hD(n,t,e,r,s){let u=F7(t,r),l;if(s){let[p,m]=ic(n[0],n[1]);l=p*m}else{let[p,m]=vf(n[0],n[1]);l=p*m}let h=_7(e,u);return l*h}function F7(n,t){switch(n){case Vn.PACKED_2X2_FLOAT32:return oD(t);case Vn.PACKED_2X2_FLOAT16:return aD(t);case Vn.UNPACKED_FLOAT32:return nD(t);case Vn.UNPACKED_FLOAT16:return rD(t);case Vn.PACKED_4X1_UNSIGNED_BYTE:return sD(t);default:throw new Error(`Unknown physical texture type ${n}`)}}function R7(n){return ft().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?Vn.PACKED_2X2_FLOAT32:Vn.UNPACKED_FLOAT32:n?Vn.PACKED_2X2_FLOAT16:Vn.UNPACKED_FLOAT16}function fD(n,t){if(n===Hr.UPLOAD)return Vn.PACKED_2X2_FLOAT32;if(n===Hr.RENDER||n==null)return R7(t);if(n===Hr.DOWNLOAD||n===Hr.PIXELS)return Vn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${n}`)}function pD(n,t,e){return`${n[0]}_${n[1]}_${t}_${e}`}class P7{constructor(t,e){this.variableNames=["A"];let r=new Array(t.length);for(let l=0;l<r.length;l++)r[l]=t[l]*e[l];this.outputShape=r,this.rank=r.length;let s=We(this.rank),u=O7(t);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} resRC = getOutputCoords();
2020-11-25 14:30:53 +01:00
setOutput(getA(${u}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}function O7(n){let t=n.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${n[0]})`;let e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let s=0;s<n.length;s++)r.push(`imod(${e[s]}, ${n[s]})`);return r.join()}class ye{constructor(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
float unaryOperation(float x) {
2020-11-25 14:30:53 +01:00
${e}
2020-10-15 12:48:39 +02:00
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
2020-11-25 14:30:53 +01:00
`}}let _o="if (isnan(x)) return x;",M7="return x;",dD="return abs(x);",mD=_o+`
2020-10-15 12:48:39 +02:00
return (x < 0.0) ? 0.0 : x;
2020-11-25 14:30:53 +01:00
`,gD=_o+`
2020-10-15 12:48:39 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2020-11-25 14:30:53 +01:00
`,vD="return (x >= 0.0) ? x : (exp(x) - 1.0);",L7=`
2020-10-15 12:48:39 +02:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2020-11-25 14:30:53 +01:00
float scaleAlpha = ${qd};
float scale = ${jd};
2020-10-15 12:48:39 +02:00
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2020-11-25 14:30:53 +01:00
`;function B7(n=0){return _o+`
return x > 0.0 ? 1.0 : float(${n});
`}let yD="return -x;",bD="return ceil(x);",wD="return floor(x);",z7=`
2020-10-15 12:48:39 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2020-11-25 14:30:53 +01:00
`,W7="return float(isnan(x));",V7="return float(isinf(x));",U7="return float(!isnan(x) && !isinf(x));",G7=`
2020-10-15 12:48:39 +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;
}
}
2020-11-25 14:30:53 +01:00
`,xD="return exp(x);",TD="return exp(x) - 1.0;",H7=`if (x < 0.0) return NAN;
return log(x);`,q7="return log(1.0 + x);",j7="return sqrt(x);",K7="return inversesqrt(x);",X7="return 1.0 / (1.0 + exp(-1.0 * x));",Y7=`
2020-10-15 12:48:39 +02:00
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
2020-11-25 14:30:53 +01:00
`,J7=_o+`
2020-10-15 12:48:39 +02:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
2020-11-25 14:30:53 +01:00
`,Z7=_o+`
2020-10-15 12:48:39 +02:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
2020-11-25 14:30:53 +01:00
`,Q7=_o+`
2020-10-15 12:48:39 +02:00
return atan(x);
2020-11-25 14:30:53 +01:00
`,tJ=`
2020-10-15 12:48:39 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2020-11-25 14:30:53 +01:00
`,eJ=`
2020-10-15 12:48:39 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2020-11-25 14:30:53 +01:00
`,nJ=`
2020-10-15 12:48:39 +02:00
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
2020-11-25 14:30:53 +01:00
`,rJ=_o+"return log(x + sqrt(x * x + 1.0));",sJ=_o+`
2020-10-15 12:48:39 +02:00
if (x < 1.0) return NAN;
2020-11-25 14:30:53 +01:00
return log(x + sqrt(x * x - 1.0));`,oJ=_o+`
2020-10-15 12:48:39 +02:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2020-11-25 14:30:53 +01:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,aJ=`
2020-10-15 12:48:39 +02:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2020-11-25 14:30:53 +01:00
float p = ${zb};
float a1 = ${Wb};
float a2 = ${Vb};
float a3 = ${Ub};
float a4 = ${Gb};
float a5 = ${Hb};
2020-10-15 12:48:39 +02:00
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
2020-11-25 14:30:53 +01:00
`,iJ="return 1.0 / x;",uJ="return float(!(x >= 1.0));",Hm="return x;";let cJ="return x;",lJ=`
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
`,kD=`
2020-10-15 12:48:39 +02:00
vec4 result = x * 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;
2020-11-25 14:30:53 +01:00
`,SD=`
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
`,CD=`
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
`;class Tf{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
vec4 unaryOperation(vec4 x) {
2020-11-25 14:30:53 +01:00
${e}
2020-10-15 12:48:39 +02:00
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
2020-11-25 14:30:53 +01:00
`}}class hJ{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;let e=t.length,r=nr("rc",e),s=We(e),u=tX(e,r),l=r.slice(-2),h=e<=1?"rc":`vec2(${l.join(",")})`;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} rc = getOutputCoords();
2020-11-25 14:30:53 +01:00
vec4 packedInput = getA(${u});
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
setOutput(getChannel(packedInput, ${h}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}let{segment_util:ND}=Kb,fJ=Xb,pJ=Yb,dJ=Jb,mJ=Pd,gJ=1e-7,vJ=1e-4,qm={};function yJ(n){return n in qm||(qm[n]={}),qm[n]}function jm(n,t=!1){if(n==="linear")return t?cJ:M7;if(n==="relu")return t?kD:mD;if(n==="elu")return t?CD:vD;if(n==="relu6")return t?SD:gD;if(n==="prelu")return t?XE:KE;throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`)}let bJ=128,wJ=600;function xJ(){return ft().global.screen==null?1024:ft().global.screen.height*ft().global.screen.width*window.devicePixelRatio*wJ/1024/1024}let ID=1e3;class TJ extends f{constructor(t){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!ft().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(t==null){let e=eo(ft().getNumber("WEBGL_VERSION"));this.binaryCache=yJ(ft().getNumber("WEBGL_VERSION")),this.gpgpu=new JY(e),this.canvas=e.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=t,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=t.gl.canvas;this.textureManager=new A7(this.gpgpu),this.numMBBeforeWarning=xJ(),this.texData=new c(this,yo())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(t,e,r){if((ft().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||ft().getBool("DEBUG"))&&this.checkNumericalProblems(t),r==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s={};return this.texData.set(s,{shape:e,dtype:r,values:t,usage:Hr.UPLOAD,refCount:1,complexParentRefCount:0}),s}incRef(t){let e=this.texData.get(t);e.refCount++}decRef(t){if(this.texData.has(t)){let e=this.texData.get(t);e.refCount--}}move(t,e,r,s){if(ft().getBool("DEBUG")&&this.checkNumericalProblems(e),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:r,dtype:s,values:e,usage:Hr.UPLOAD,refCount:1,complexParentRefCount:0})}disposeIntermediateTensorInfo(t){let e=t.dataId;if(this.texData.has(e)){let r=this.texData.get(e);r.refCount--,r.refCount<1&&this.disposeData(e)}}readSync(t){let e=this.texData.get(t),{values:r,dtype:s,complexTensorInfos:u,slice:l,shape:h,isPacked:p}=e;if(l!=null){let x;p?x=new Tf(h,Hm):x=new ye(h,Hm);let S=this.runWebGLProgram(x,[{dataId:t,shape:h,dtype:s}],s),C=this.readSync(S.dataId);return this.disposeIntermediateTensorInfo(S),C}if(r!=null)return this.convertAndCacheOnCPU(t);if(s==="string")return r;let m=this.activeTimers!=null,y;m&&(y=cr());let b;if(s==="complex64"){let x=this.readSync(u.real.dataId),S=this.readSync(u.imag.dataId);b=So(x,S)}else b=this.getValuesFromTexture(t);return m&&(this.downloadWaitMs+=cr()-y),this.convertAndCacheOnCPU(t,b)}async read(t){if(this.pendingRead.has(t)){let C=this.pendingRead.get(t);return new Promise(I=>C.push(I))}let e=this.texData.get(t),{values:r,shape:s,slice:u,dtype:l,complexTensorInfos:h,isPacked:p}=e;if(u!=null){let C;p?C=new Tf(s,Hm):C=new ye(s,Hm);let I=this.runWebGLProgram(C,[{dataId:t,shape:s,dtype:l}],l),D=this.read(I.dataId);return this.disposeIntermediateTensorInfo(I),D}if(r!=null)return this.convertAndCacheOnCPU(t);if(!ft().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&ft().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let m=null,y;if(l!=="complex64"&&ft().get("WEBGL_BUFFER_SUPPORTED")){y=this.decode(t);let C=this.texData.get(y.dataId);m=this.gpgpu.createBufferFromTexture(C.texture,...yf(s))}this.pendingRead.set(t,[]),l!=="complex64"&&await this.gpgpu.createAndWaitForFence();let b;if(l==="complex64"){let C=await Promise.all([this.read(h.real.dataId),this.read(h.imag.dataId)]),I=C[0],D=C[1];b=So(I,D)}else if(m==null)b=this.getValuesFromTexture(t);else{let C=O(s);b=this.gpgpu.downloadFloat32MatrixFromBuffer(m,C)}y!=null&&this.disposeIntermediateTensorInfo(y);let x=this
2020-10-15 12:48:39 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-11-25 14:30:53 +01:00
`,DJ=`
2020-10-15 12:48:39 +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;
2020-11-25 14:30:53 +01:00
`;function Km(n){return({inputs:t,backend:e})=>{let{x:r}=t,s=e,u=new ye(r.shape,n);return s.runWebGLProgram(u,[r],r.dtype)}}function mc({opSnippet:n,packedOpSnippet:t,checkOutOfBounds:e=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:u}){return({inputs:l,backend:h})=>{let{a:p,b:m}=l,y=h;if(r&&p.dtype==="complex64"){let C=y.texData.get(p.dataId),I=y.texData.get(m.dataId),[D,R]=[[C.complexTensorInfos.real,I.complexTensorInfos.real],[C.complexTensorInfos.imag,I.complexTensorInfos.imag]].map(L=>{let[_,B]=L,V={dataId:_.dataId,dtype:_.dtype,shape:p.shape},q={dataId:B.dataId,dtype:B.dtype,shape:m.shape},j=new Yn(n,p.shape,m.shape);return y.runWebGLProgram(j,[V,q],Qn(_.dtype,B.dtype))}),A=dc({inputs:{real:D,imag:R},backend:y});return y.disposeIntermediateTensorInfo(D),y.disposeIntermediateTensorInfo(R),A}let b=u||Qn(p.dtype,m.dtype);if(y.shouldExecuteOnCPU([p,m])&&s!=null){let C=y.texData.get(p.dataId),I=y.texData.get(m.dataId),[D,R]=s(p.shape,m.shape,C.values,I.values,b),A=y.makeTensorInfo(R,b),L=y.texData.get(A.dataId);return L.values=D,A}let x=ft().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,S;return x?S=new Ao(t,p.shape,m.shape,e):S=new Yn(n,p.shape,m.shape),y.runWebGLProgram(S,[p,m],b)}}let DD="return a + b;",$J=mc({opSnippet:DD,packedOpSnippet:DD,supportsComplex:!0,cpuKernelImpl:B8}),AJ={kernelName:ri,backendName:"webgl",kernelFunc:$J};let _J=EJ+`
2020-10-15 12:48:39 +02:00
return atan(a, b);
2020-11-25 14:30:53 +01:00
`,FJ=`
2020-10-15 12:48:39 +02:00
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-11-25 14:30:53 +01:00
`+DJ+`
2020-10-15 12:48:39 +02:00
return result;
2020-11-25 14:30:53 +01:00
`,RJ=mc({opSnippet:_J,packedOpSnippet:FJ}),PJ={kernelName:fp,backendName:"webgl",kernelFunc:RJ};function OJ(n){let{inputs:t,backend:e,attrs:r}=n,{x:s}=t;bf(s,"avgPool");let{filterSize:u,strides:l,pad:h,dimRoundingMode:p}=r,m=1;k(wn(l,m),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let y=tr(s.shape,u,l,m,h,p);if(y.filterWidth===1&&y.filterHeight===1&&K(y.inShape,y.outShape))return Fo({inputs:{x:s},backend:e});let b=new xf(y,"avg",!1);return e.runWebGLProgram(b,[s],"float32")}let MJ={kernelName:wl,backendName:"webgl",kernelFunc:OJ};function LJ(n){let{inputs:t,backend:e,attrs:r}=n,{dy:s,input:u}=t,l=u;bf([s,u],"avgPoolBackprop");let{filterSize:h,strides:p,pad:m}=r,y=tr(l.shape,h,p,1,m),b=new LX(y);return e.runWebGLProgram(b,[s],l.dtype)}let BJ={kernelName:pp,backendName:"webgl",kernelFunc:LJ};class zJ{constructor(t,e,r,s,u,l){this.outputShape=[],this.variableNames=["x","mean","variance"],ve(t,e),ve(t,r);let h="0.0";s!=null&&(ve(t,s),this.variableNames.push("offset"),h="getOffsetAtOutCoords()");let p="1.0";u!=null&&(ve(t,u),this.variableNames.push("scale"),p="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
2020-11-25 14:30:53 +01:00
float offset = ${h};
float scale = ${p};
float inv = scale * inversesqrt(variance + float(${l}));
2020-10-15 12:48:39 +02:00
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
2020-11-25 14:30:53 +01:00
`}}class WJ{constructor(t,e,r,s,u,l){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],ve(t,e),ve(t,r);let h="vec4(0.0)";s!=null&&(ve(t,s),this.variableNames.push("offset"),h="getOffsetAtOutCoords()");let p="vec4(1.0)";u!=null&&(ve(t,u),this.variableNames.push("scale"),p="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
2020-11-25 14:30:53 +01:00
vec4 offset = ${h};
vec4 scale = ${p};
2020-10-15 12:48:39 +02:00
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
2020-11-25 14:30:53 +01:00
vec4 inv = scale * inversesqrt(variance + vec4(${l}));
2020-10-15 12:48:39 +02:00
setOutput((x - mean) * inv + offset);
}
2020-11-25 14:30:53 +01:00
`}}let VJ=({inputs:n,backend:t,attrs:e})=>{let{x:r,mean:s,variance:u,offset:l,scale:h}=n;k(s.shape.length===u.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(l==null||s.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(h==null||s.shape.length===h.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:p}=e;p==null&&(p=.001);let m=[r,s,u],y=null;l!=null&&(y=l.shape,m.push(l));let b=null;h!=null&&(b=h.shape,m.push(h));let x=ft().getBool("WEBGL_PACK_NORMALIZATION")?new WJ(r.shape,s.shape,u.shape,y,b,p):new zJ(r.shape,s.shape,u.shape,y,b,p),S=t.runWebGLProgram(x,m,m[0].dtype);return S},UJ={kernelName:$l,backendName:"webgl",kernelFunc:VJ};let GJ="return float(a != b);",$D=mc({opSnippet:GJ,dtype:"bool"}),HJ={kernelName:zl,backendName:"webgl",kernelFunc:$D};function fx(n){let{inputs:t,backend:e}=n,{input:r}=t,s=e.texData.get(r.dataId);return Fo({inputs:{x:s.complexTensorInfos.real},backend:e})}let qJ={kernelName:Rp,backendName:"webgl",kernelFunc:fx};let jJ="return float(int(x));";function KJ(n,t){let e=new ye(n.shape,jJ),r=t.runWebGLProgram(e,[n],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function px(n){let{inputs:t,backend:e,attrs:r}=n,{x:s}=t,{dtype:u}=r;if(u==="complex64"){if(s.dtype==="complex64")return Fo({inputs:{x:s},backend:e});let l=Se(s.shape),h=px({inputs:{x:s},backend:e,attrs:{dtype:"float32"}}),p=dc({inputs:{real:h,imag:l},backend:e});return l.dispose(),e.disposeIntermediateTensorInfo(h),p}if(s.dtype==="complex64"){let l=fx({inputs:{input:s},backend:e}),h=px({inputs:{x:l},backend:e,attrs:{dtype:u}});return e.disposeIntermediateTensorInfo(l),h}if(!me(s.dtype,u)){let l=Fo({inputs:{x:s},backend:e});return{dataId:l.dataId,shape:l.shape,dtype:u}}if(u==="int32")return KJ(s,e);if(u==="bool"){let l=e.makeTensorInfo([],"bool",_t("bool",1)),h={a:s,b:l},p=$D({inputs:h,backend:e});return e.disposeIntermediateTensorInfo(l),p}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${u}`)}let XJ={kernelName:pu,backendName:"webgl",kernelFunc:px};class YJ{constructor(t){this.outputShape=[],this.outputShape=bo(t,1),this.variableNames=t.map((l,h)=>`T${h}`);let e=new Array(t.length-1);e[0]=t[0][1];for(let l=1;l<e.length;l++)e[l]=e[l-1]+t[l][1];let r=[`if (yC < ${e[0]}) setOutput(getT0(yR, yC));`];for(let l=1;l<e.length;l++){let h=e[l-1];r.push(`else if (yC < ${e[l]}) setOutput(getT${l}(yR, yC-${h}));`)}let s=e.length,u=e[e.length-1];r.push(`else setOutput(getT${s}(yR, yC-${u}));`),this.userCode=`
2020-10-29 05:16:50 +01:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
2020-11-25 14:30:53 +01:00
${r.join(`
2020-10-29 05:16:50 +01:00
`)}
}
2020-11-25 14:30:53 +01:00
`}}class JJ{constructor(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=bo(t,e);let r=this.outputShape,s=r.length,u=We(s),l=nr("coords",s),h=["x","y","z","w","u","v"].slice(0,s);this.variableNames=t.map((I,D)=>`T${D}`);let p=new Array(t.length-1);p[0]=t[0][e];for(let I=1;I<p.length;I++)p[I]=p[I-1]+t[I][e];let m=h[e],y=h.slice(-2),b=h.join(),x=`if (${m} < ${p[0]}) {
2020-10-29 05:16:50 +01:00
return getChannel(
2020-11-25 14:30:53 +01:00
getT0(${b}), vec2(${y.join()}));
}`;for(let I=1;I<p.length;I++){let D=p[I-1];x+=`
if (${m} < ${p[I]} && ${m} >= ${p[I-1]}) {
2020-10-29 05:16:50 +01:00
return getChannel(
2020-11-25 14:30:53 +01:00
getT${I}(${Xm(h,m,D)}),
vec2(${Xm(y,m,D)}));
}`}let S=p.length,C=p[p.length-1];x+=`
2020-10-29 05:16:50 +01:00
return getChannel(
2020-11-25 14:30:53 +01:00
getT${S}(${Xm(h,m,C)}),
vec2(${Xm(y,m,C)}));`,this.userCode=`
float getValue(${h.map(I=>"int "+I)}) {
${x}
2020-10-29 05:16:50 +01:00
}
void main() {
2020-11-25 14:30:53 +01:00
${u} coords = getOutputCoords();
vec4 result = vec4(getValue(${l}), 0., 0., 0.);
2020-10-29 05:16:50 +01:00
2020-11-25 14:30:53 +01:00
${l[s-1]} = ${l[s-1]} + 1;
if (${l[s-1]} < ${r[s-1]}) {
result.g = getValue(${l});
2020-10-29 05:16:50 +01:00
}
2020-11-25 14:30:53 +01:00
${l[s-2]} = ${l[s-2]} + 1;
if (${l[s-2]} < ${r[s-2]}) {
result.a = getValue(${l});
2020-10-29 05:16:50 +01:00
}
2020-11-25 14:30:53 +01:00
${l[s-1]} = ${l[s-1]} - 1;
if (${l[s-2]} < ${r[s-2]} &&
${l[s-1]} < ${r[s-1]}) {
result.b = getValue(${l});
2020-10-29 05:16:50 +01:00
}
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}function Xm(n,t,e){let r=n.indexOf(t),s=n.map((u,l)=>l===r?`${u} - ${e}`:u);return s.join()}function AD(n){let{inputs:t,backend:e}=n,{input:r}=t,s=e.texData.get(r.dataId);return Fo({inputs:{x:s.complexTensorInfos.imag},backend:e})}let ZJ={kernelName:Np,backendName:"webgl",kernelFunc:AD};function QJ(n,t,e){let r=[uc(n.shape),...cc(n.shape)],s={dtype:n.dtype,shape:r,dataId:n.dataId},u=[uc(t),...cc(t)],l=new cD(u,r),h=!0,p=e.runWebGLProgram(l,[s],n.dtype,null,h);return{dataId:p.dataId,shape:t,dtype:p.dtype}}function Ro(n){let{inputs:t,backend:e,attrs:r}=n,{x:s}=t,{shape:u}=r,l=e,h=O(s.shape),p=Gt(u,h),m=O(p);k(h===m,()=>`The new shape (${p}) has ${m} elements and the old shape (${s.shape}) has ${h} elements. The new shape and old shape must have the same number of elements.`);let y=l.texData.get(s.dataId);return y.isPacked&&!zm(s.shape,p)&&!(y.texture!==null&&zm(y.shape,p))?QJ(s,p,l):(l.incRef(s.dataId),{dataId:s.dataId,shape:p,dtype:s.dtype})}let t9={kernelName:Ul,backendName:"webgl",kernelFunc:Ro};function gc(n,t,e){let r=n[0].dtype;if(r==="complex64"){let m=n.map(C=>fx({inputs:{input:C},backend:e})),y=n.map(C=>AD({inputs:{input:C},backend:e})),b=gc(m,t,e),x=gc(y,t,e),S=dc({inputs:{real:b,imag:x},backend:e});return m.forEach(C=>e.disposeIntermediateTensorInfo(C)),y.forEach(C=>e.disposeIntermediateTensorInfo(C)),e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(x),S}if(n.length>ft().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let m=Math.floor(n.length/2),y=gc(n.slice(0,m),t,e),b=gc(n.slice(m),t,e),x=gc([y,b],t,e);return e.disposeIntermediateTensorInfo(y),e.disposeIntermediateTensorInfo(b),x}if(ft().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&n[0].shape.length>1){let m=new JJ(n.map(y=>y.shape),t);return e.runWebGLProgram(m,n,r)}let s=bo(n.map(m=>m.shape),t),u=n.map(m=>Ro({inputs:{x:m},attrs:{shape:[-1,O(m.shape.slice(t))]},backend:e})),l=new YJ(u.map(m=>m.shape)),h=e.runWebGLProgram(l,u,r);u.forEach(m=>e.disposeIntermediateTensorInfo(m));let p=Ro({inputs:{x:h},attrs:{shape:s},backend:e});return e.disposeIntermediateTensorInfo(h),p}function e9(n){let{inputs:t,backend:e,attrs:r}=n,{axis:s}=r,u=Et(s,t[0].shape)[0],l=bo(t.map(m=>m.shape),u);if(O(l)===0)return e.makeTensorInfo(l,t[0].dtype,[]);let h=t.filter(m=>O(m.shape)>0);if(h.length===1)return h[0];let p=h.map(m=>m.shape);return fd(p,u),gc(h,u,e)}let n9={kernelName:kl,backendName:"webgl",kernelFunc:e9};let r9=ED+`
2020-10-15 12:48:39 +02:00
return cos(x);
2020-11-25 14:30:53 +01:00
`,s9=Km(r9),o9={kernelName:du,backendName:"webgl",kernelFunc:s9};let a9=`
2020-10-15 12:48:39 +02:00
if (a == b) {
return 1.0;
};
2020-11-25 14:30:53 +01:00
return a / b;`,i9=`
2020-10-15 12:48:39 +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.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
2020-11-25 14:30:53 +01:00
`,u9=mc({opSnippet:a9,packedOpSnippet:i9,checkOutOfBounds:!0}),c9={kernelName:mu,backendName:"webgl",kernelFunc:u9};class _D{constructor(t,e,r){this.variableNames=["real","imag"];let s=e[1];this.outputShape=e;let u=r?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,l=r?`${s}.0`:"1.0",h;if(t==="real")h="return real * expR - imag * expI;";else if(t==="imag")h="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${t}.`);this.userCode=`
const float exponentMultiplier = ${u};
2020-10-29 05:16:50 +01:00
float unaryOpComplex(float real, float expR, float imag, float expI) {
2020-11-25 14:30:53 +01:00
${h}
2020-10-29 05:16:50 +01:00
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${s});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${s}; 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 +=
2020-11-25 14:30:53 +01:00
unaryOpComplex(real, expR, imag, expI) / ${l};
2020-10-29 05:16:50 +01:00
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
2020-11-25 14:30:53 +01:00
`}}function FD(n,t,e){let r=e.texData.get(n.dataId),s=O(n.shape),u=n.shape[n.shape.length-1],l=s/u,h=Ro({inputs:{x:n},backend:e,attrs:{shape:[l,u]}}),p=h.shape,m=new _D("real",p,t),y=new _D("imag",p,t),b=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:p},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:p}],x=e.runWebGLProgram(m,b,"float32"),S=e.runWebGLProgram(y,b,"float32"),C=dc({inputs:{real:x,imag:S},backend:e});e.disposeIntermediateTensorInfo(x),e.disposeIntermediateTensorInfo(S);let I=Ro({inputs:{x:C},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(I),I}function l9(n){let{inputs:t,backend:e}=n,{input:r}=t;return FD(r,!1,e)}let h9={kernelName:kp,backendName:"webgl",kernelFunc:l9};class f9{constructor(t){this.variableNames=["Image"],this.outputShape=[];let e=t[2];this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
2020-11-25 14:30:53 +01:00
int coordX = ${e} - x;
2020-10-15 12:48:39 +02:00
float outputValue;
2020-11-25 14:30:53 +01:00
if(coordX >= 0 && coordX < ${e}) {
2020-10-15 12:48:39 +02:00
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
2020-11-25 14:30:53 +01:00
`}}let p9={kernelName:Sp,backendName:"webgl",kernelFunc:({inputs:n,backend:t})=>{let{image:e}=n,r=t,s=new f9(e.shape),u=r.runWebGLProgram(s,[e],e.dtype);return u}};class d9{constructor(t){this.variableNames=["A"];let e=rr(),[r,s]=t;this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
2020-11-25 14:30:53 +01:00
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${r}.0);
2020-10-15 12:48:39 +02:00
2020-11-25 14:30:53 +01:00
vec4 values = ${e.texture2D}(A, uv);
2020-10-15 12:48:39 +02:00
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;
}
setOutput(floor(value * 255.0 + 0.5));
}
2020-11-25 14:30:53 +01:00
`}}class m9{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let e=rr(),[r,s]=t;this.outputShape=t,this.userCode=`
2020-10-15 12:48:39 +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) /
2020-11-25 14:30:53 +01:00
vec2(${s}.0, ${r}.0);
vec4 values = ${e.texture2D}(A, uv);
2020-10-15 12:48:39 +02:00
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);
}
}
2020-11-25 14:30:53 +01:00
${e.output} = result;
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}let g9={kernelName:Bp,backendName:"webgl",kernelFunc:v9},vc;function v9(n){let{inputs:t,backend:e,attrs:r}=n,{pixels:s}=t,{numChannels:u}=r,l=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,h=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,[p,m]=l?[s.videoWidth,s.videoHeight]:[s.width,s.height],y=[m,p],b=[m,p,u];(h||l)&&(vc==null&&(vc=document.createElement("canvas").getContext("2d")),vc.canvas.width=p,vc.canvas.height=m,vc.drawImage(s,0,0,p,m),s=vc.canvas);let x=e.makeTensorInfo(y,"int32");e.texData.get(x.dataId).usage=Hr.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(x.dataId),s);let S=ft().getBool("WEBGL_PACK")?new m9(b):new d9(b),C=e.runWebGLProgram(S,[x],"int32");return e.disposeData(x.dataId),C}function y9(n){let{inputs:t,backend:e}=n,{input:r}=t;return FD(r,!0,e)}let b9={kernelName:Cp,backendName:"webgl",kernelFunc:y9};class RD{constructor(t,e){this.variableNames=["x"];let{windowSize:r,batchSize:s,inSize:u,outSize:l}=t;this.outputShape=[s,l];let h=Math.floor(r/4)*4,p=r%4,m="sumValue += dot(values, ones);";if(e!=null){let b=1/e;m=`sumValue += dot(values * ${nt(b)?b.toPrecision(2):b}, ones);`}let y="";u%r>0&&(y=`
if (inIdx < 0 || inIdx >= ${u}) {
2020-10-29 05:16:50 +01:00
return 0.0;
}
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
2020-11-25 14:30:53 +01:00
${y}
2020-10-29 05:16:50 +01:00
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
2020-11-25 14:30:53 +01:00
int inOffset = outIdx * ${r};
2020-10-29 05:16:50 +01:00
float sumValue = 0.0;
2020-11-25 14:30:53 +01:00
for (int i = 0; i < ${h}; i += 4) {
2020-10-29 05:16:50 +01:00
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2020-11-25 14:30:53 +01:00
${m}
2020-10-29 05:16:50 +01:00
}
2020-11-25 14:30:53 +01:00
int inIdx = inOffset + ${h};
if (${p===1}) {
2020-10-29 05:16:50 +01:00
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
2020-11-25 14:30:53 +01:00
${m}
} else if (${p===2}) {
2020-10-29 05:16:50 +01:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
2020-11-25 14:30:53 +01:00
${m}
} else if (${p===3}) {
2020-10-29 05:16:50 +01:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
2020-11-25 14:30:53 +01:00
${m}
2020-10-29 05:16:50 +01:00
}
setOutput(sumValue);
}
2020-11-25 14:30:53 +01:00
`}}function w9(n){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let e=t.length?t[t.length-1].outSize:n[1],r=yh(e);t.push({inSize:e,windowSize:r,outSize:Math.ceil(e/r)})}return t}function PD(n,t,e,r){let s=w9(n.shape),u=n;for(let l=0;l<s.length;l++){let{inSize:h,windowSize:p,outSize:m}=s[l],y,b;e==="mean"?y=l===0?new RD({windowSize:p,inSize:h,batchSize:n.shape[0],outSize:m},h):new RD({windowSize:p,inSize:h,batchSize:n.shape[0],outSize:m}):y=new uD({windowSize:p,inSize:h,batchSize:n.shape[0],outSize:m},e),b=u,u=r.runWebGLProgram(y,[u],t),b.dataId!==n.dataId&&r.disposeIntermediateTensorInfo(b)}return u}function x9(n,t,e,r){let s=O(t),u=O(n.shape),l=u/s,h=Ro({inputs:{x:n},attrs:{shape:[l,s]},backend:r}),p=PD(h,n.dtype,"max",r),m=Ro({inputs:{x:p},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),m}class T9{constructor(t,e){this.variableNames=["A"];let r=new Array(t.length);for(let l=0;l<r.length;l++)r[l]=t[e[l]];this.outputShape=r,this.rank=r.length;let s=We(this.rank),u=k9(e);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} resRC = getOutputCoords();
2020-11-25 14:30:53 +01:00
setOutput(getA(${u}));
2020-10-15 12:48:39 +02:00
}
2020-11-25 14:30:53 +01:00
`}}function k9(n){let t=n.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let s=0;s<n.length;s++)r[n[s]]=e[s];return r.join()}class S9{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let r=new Array(t.length);for(let y=0;y<r.length;y++)r[y]=t[e[y]];if(this.outputShape=r,this.rank=r.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let s=We(this.rank),u=VE("rc",this.rank),l=new Array(this.rank);for(let y=0;y<e.length;y++)l[e[y]]=u[y];let h=`vec2(${l.slice(-2).join()})`,p=`++${u[this.rank-1]} < ${r[this.rank-1]}`,m=`getChannel(getA(${l.join()}), ${h})`;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} rc = getOutputCoords();
vec4 result = vec4(0.);
2020-11-25 14:30:53 +01:00
result[0] = ${m};
if(${p}) {
result[1] = ${m};
}
--${u[this.rank-1]};
if(++${u[this.rank-2]} < ${r[this.rank-2]}) {
result[2] = ${m};
if(${p}) {
result[3] = ${m};
2020-10-15 12:48:39 +02:00
}
}
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}function dx(n,t,e){let r=ft().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new S9(n.shape,t):new T9(n.shape,t);return e.runWebGLProgram(r,[n],n.dtype)}let C9={kernelName:Ml,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{x:r}=n,{reductionIndices:s,keepDims:u}=t,l=e,h=r.shape.length,p=Et(s,r.shape),m=p,y=hr(m,h),b=y!=null,x=l.shouldExecuteOnCPU([r]),S=r;if(b){if(x){let A=l.texData.get(S.dataId),L=A.values,_=new Array(h);for(let q=0;q<_.length;q++)_[q]=r.shape[y[q]];let B=ix(L,r.shape,r.dtype,y,_);S=l.makeTensorInfo(_,r.dtype);let V=l.texData.get(S.dataId);V.values=B}else S=dx(r,y,l);m=Cr(m.length,h)}lr("max",m,h);let[C,I]=Bn(S.shape,m),D=C;u&&(D=zn(C,p));let R;if(x){let A=l.texData.get(S.dataId),L=A.values,_=H8(L,O(I),D,r.dtype);R=l.makeTensorInfo(D,r.dtype);let B=l.texData.get(R.dataId);B.values=_}else R=x9(S,I,D,l);return b&&l.disposeIntermediateTensorInfo(S),R}};function N9(n){let{inputs:t,backend:e,attrs:r}=n,{x:s}=t;bf(s,"maxPool");let{filterSize:u,strides:l,pad:h,dimRoundingMode:p}=r,m=1;k(wn(l,m),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let y=tr(s.shape,u,l,m,h,p);if(y.filterWidth===1&&y.filterHeight===1&&K(y.inShape,y.outShape))return Fo({inputs:{x:s},backend:e});let b=new xf(y,"max",!1);return e.runWebGLProgram(b,[s],s.dtype)}let I9={kernelName:Ll,backendName:"webgl",kernelFunc:N9};function E9(n){let{inputs:t,backend:e,attrs:r}=n,{dy:s,input:u,output:l}=t,h=u;bf([u,l],"maxPoolBackprop");let{filterSize:p,strides:m,pad:y,dimRoundingMode:b}=r,x=tr(h.shape,p,m,1,y,b),S=!0,C=new xf(x,"max",S),I=e.runWebGLProgram(C,[h],h.dtype),D=new a7(x),R=e.runWebGLProgram(D,[s,I],h.dtype);return e.disposeIntermediateTensorInfo(I),R}let D9={kernelName:Ep,backendName:"webgl",kernelFunc:E9};function $9(n,t,e,r){let s=new xf(e,"max",!1),u=r.runWebGLProgram(s,[n],"float32");s=new xf(e,"max",!0,!0,t);let l=r.runWebGLProgram(s,[n],"float32");return[u,l]}let A9={kernelName:Dp,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{x:r}=n,{filterSize:s,strides:u,pad:l,includeBatchInIndex:h}=t,p=e;k(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let m=[1,1];k(wn(u,m),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${u} and dilations '${m}'`);let y=tr(r.shape,s,u,m,l),[b,x]=$9(r,h,y,p);return[b,x]}};function _9(n,t,e,r){let s=O(t),u=O(n.shape),l=u/s,h=Ro({inputs:{x:n},attrs:{shape:[l,s]},backend:r}),p=PD(h,"float32","mean",r),m=Ro({inputs:{x:p},attrs:{shape:e},backend:r});return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),m}let F9={kernelName:Yv,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{x:r}=n,{keepDims:s,axis:u}=t,l=e,h=r.shape.length,p=Et(u,r.shape),m=p,y=hr(m,h),b=y!=null,x=l.shouldExecuteOnCPU([r]),S=[],C=r;if(b){if(x){let L=l.texData.get(C.dataId),_=L.values,B=new Array(h);for(let j=0;j<B.length;j++)B[j]=r.shape[y[j]];let V=ix(_,r.shape,r.dtype,y,B);C=l.makeTensorInfo(B,r.dtype);let q=l.texData.get(C.dataId);q.values=V}else C=dx(r,y,l);S.push(C),m=Cr(m.length,h)}lr("sum",m,h);let[I,D]=Bn(C.shape,m),R=I;s&&(R=zn(I,p));let A=_9(C,D,R,l);for(let L of S)l.disposeIntermediateTensorInfo(L);return A}};class R9{constructor(t,e,r){this.variableNames=["x"],this.outputShape=e.map((y,b)=>y[0]+t[b]+y[1]);let s=t.length,u=We(s),l=e.map(y=>y[0]).join(","),h=e.map((y,b)=>y[0]+t[b]).join(","),p=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),m=r==="reflect"?0:1;if(s===1){this.userCode=`
int start = ${l};
int end = ${h};
2020-10-29 05:16:50 +01:00
void main() {
int outC = getOutputCoords();
if (outC < start) {
2020-11-25 14:30:53 +01:00
outC = start * 2 - outC - ${m};
2020-10-29 05:16:50 +01:00
} else if(outC >= end) {
2020-11-25 14:30:53 +01:00
outC = (end - 1) * 2 - outC + ${m};
2020-10-29 05:16:50 +01:00
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
2020-11-25 14:30:53 +01:00
${u} start = ${u}(${l});
${u} end = ${u}(${h});
2020-10-29 05:16:50 +01:00
void main() {
2020-11-25 14:30:53 +01:00
${u} outC = getOutputCoords();
2020-10-29 05:16:50 +01:00
for (int i = 0; i < ${s}; i++) {
if (outC[i] < start[i]) {
2020-11-25 14:30:53 +01:00
outC[i] = start[i] * 2 - outC[i] - ${m};
2020-10-29 05:16:50 +01:00
} else if(outC[i] >= end[i]) {
2020-11-25 14:30:53 +01:00
outC[i] = (end[i] - 1) * 2 - outC[i] + ${m};
2020-10-29 05:16:50 +01:00
}
}
2020-11-25 14:30:53 +01:00
${u} coords = outC - start;
setOutput(getX(${p}));
2020-10-29 05:16:50 +01:00
}
2020-11-25 14:30:53 +01:00
`}}class P9{constructor(t,e,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((C,I)=>C[0]+t[I]+C[1]);let s=t.length,u=We(s),l=e.map(C=>C[0]).join(","),h=e.map((C,I)=>C[0]+t[I]).join(","),p=nr("rc",s),m=nr("source",s),y=`${p[s-1]} < ${this.outputShape[s-1]}`,b=s===1?"source":`vec2(${m.slice(-2).join()})`,x=r==="reflect"?0:1,S="";if(s===1){let C=`
${u} source = rc;
2020-10-29 05:16:50 +01:00
if (source < start) {
2020-11-25 14:30:53 +01:00
source = start * 2 - source - ${x};
2020-10-29 05:16:50 +01:00
} else if (source >= end) {
2020-11-25 14:30:53 +01:00
source = (end - 1) * 2 - source + ${x};
2020-10-29 05:16:50 +01:00
}
source -= start;
2020-11-25 14:30:53 +01:00
`;S=`
${u} rc = outputLoc;
${C}
result[0] = getChannel(getX(${m.join()}), ${b});
${p[s-1]} += 1;
if(${y}) {
${C}
result[1] = getChannel(getX(${m.join()}), ${b});
2020-10-29 05:16:50 +01:00
}
2020-11-25 14:30:53 +01:00
`}else{let C=`
${u} source = rc;
${u} lt = ${u}(lessThan(source, start));
${u} gte = ${u}(greaterThanEqual(source, end));
${u} orig = 1 - (lt + gte);
2020-10-29 05:16:50 +01:00
source = orig * source +
2020-11-25 14:30:53 +01:00
lt * (start * 2 - source - ${x}) +
gte * ((end - 1) * 2 - source + ${x});
2020-10-29 05:16:50 +01:00
source -= start;
2020-11-25 14:30:53 +01:00
`;S=`
${u} rc = outputLoc;
${C}
result[0] = getChannel(getX(${m.join()}), ${b});
${p[s-1]} += 1;
if(${y}) {
${C}
result[1] = getChannel(getX(${m.join()}), ${b});
2020-10-29 05:16:50 +01:00
}
rc = outputLoc;
2020-11-25 14:30:53 +01:00
${p[s-2]} += 1;
if(${p[s-2]} < ${this.outputShape[s-2]}) {
${C}
result[2] = getChannel(getX(${m.join()}), ${b});
${p[s-1]} += 1;
if(${y}) {
${C}
result[3] = getChannel(getX(${m.join()}), ${b});
2020-10-29 05:16:50 +01:00
}
}
`}this.userCode=`
2020-11-25 14:30:53 +01:00
const ${u} start = ${u}(${l});
const ${u} end = ${u}(${h});
2020-10-29 05:16:50 +01:00
void main() {
2020-11-25 14:30:53 +01:00
${u} outputLoc = getOutputCoords();
2020-10-29 05:16:50 +01:00
vec4 result = vec4(0.);
2020-11-25 14:30:53 +01:00
${S}
2020-10-29 05:16:50 +01:00
setOutput(result);
}
2020-11-25 14:30:53 +01:00
`}}let O9=({inputs:n,backend:t,attrs:e})=>{let{x:r}=n,{paddings:s,mode:u}=e,l=ft().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new P9(r.shape,s,u):new R9(r.shape,s,u),h=t.runWebGLProgram(l,[r],r.dtype);return h},M9={kernelName:Bl,backendName:"webgl",kernelFunc:O9};let OD={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class MD{constructor(t,e,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=ve(e,r),this.userCode=`
2020-10-29 05:16:50 +01:00
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
2020-11-25 14:30:53 +01:00
${t}
2020-10-29 05:16:50 +01:00
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
2020-11-25 14:30:53 +01:00
`}}let LD="return a * b;";function L9(n){let{inputs:t,backend:e}=n,{a:r,b:s}=t,u=Qn(r.dtype,s.dtype);if(r.dtype==="complex64"){let h=e.texData.get(r.dataId),p=e.texData.get(s.dataId),m=new MD(OD.REAL,r.shape,s.shape),y=new MD(OD.IMAG,r.shape,s.shape),b=[{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:r.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:s.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:s.shape}],x=e.runWebGLProgram(m,b,"float32"),S=e.runWebGLProgram(y,b,"float32"),C=dc({inputs:{real:x,imag:S},backend:e});return e.disposeIntermediateTensorInfo(x),e.disposeIntermediateTensorInfo(S),C}if(e.shouldExecuteOnCPU([r,s])){let h=e.texData.get(r.dataId),p=e.texData.get(s.dataId),[m,y]=q8(r.shape,s.shape,h.values,p.values,u),b=e.makeTensorInfo(y,u),x=e.texData.get(b.dataId);return x.values=m,b}let l;return ft().getBool("WEBGL_PACK_BINARY_OPERATIONS")?l=new Ao(LD,r.shape,s.shape):l=new Yn(LD,r.shape,s.shape),e.runWebGLProgram(l,[r,s],u)}let B9={kernelName:gu,backendName:"webgl",kernelFunc:L9};let z9={kernelName:ey,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{Gu("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{boxes:r,scores:s}=n,{maxOutputSize:u,iouThreshold:l,scoreThreshold:h}=e,p=t,m=p.readSync(r.dataId),y=p.readSync(s.dataId),b=u,x=l,S=h;return Vd(m,y,b,x,S)}};let W9=Ud,V9={kernelName:$p,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{Gu("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{boxes:r,scores:s}=n,{maxOutputSize:u,iouThreshold:l,scoreThreshold:h,padToMaxOutputSize:p}=e,m=t,y=m.readSync(r.dataId),b=m.readSync(s.dataId),{selectedIndices:x,validOutputs:S}=W9(y,b,u,l,h,p);return[x,S]}};let U9=Gd,G9={kernelName:Ap,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{Gu("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{boxes:r,scores:s}=n,{maxOutputSize:u,iouThreshold:l,scoreThreshold:h,softNmsSigma:p}=e,m=t,y=m.readSync(r.dataId),b=m.readSync(s.dataId),x=u,S=l,C=h,I=p,{selectedIndices:D,selectedScores:R}=U9(y,b,x,S,C,I);return[D,R]}};class H9{constructor(t,e,r,s){this.variableNames=["Image"],this.outputShape=[];let u=t[1],l=t[2],h=Math.sin(e).toFixed(3),p=Math.cos(e).toFixed(3);this.outputShape=t;let[m,y]=Mb(s,u,l),b=m.toFixed(3),x=y.toFixed(3),S="";typeof r=="number"?S=`float outputValue = ${r.toFixed(2)};`:S=`
vec3 fill = vec3(${r.join(",")});
2020-10-15 12:48:39 +02:00
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
2020-11-25 14:30:53 +01:00
float coordXFloat = (float(x) - ${b}) * ${p} - (float(y) - ${x}) * ${h};
float coordYFloat = (float(x) - ${b}) * ${h} + (float(y) - ${x}) * ${p};
int coordX = int(round(coordXFloat + ${b}));
int coordY = int(round(coordYFloat + ${x}));
${S}
if(coordX >= 0 && coordX < ${l} && coordY >= 0 && coordY < ${u}) {
2020-10-15 12:48:39 +02:00
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
2020-11-25 14:30:53 +01:00
`}}let q9={kernelName:zp,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{image:r}=n,{radians:s,fillValue:u,center:l}=t,h=e,p=new H9(r.shape,s,u,l),m=h.runWebGLProgram(p,[r],r.dtype);return m}};let j9=ED+`
2020-10-15 12:48:39 +02:00
return sin(x);
2020-11-25 14:30:53 +01:00
`,K9=Km(j9),X9={kernelName:vu,backendName:"webgl",kernelFunc:K9};let Y9="return x * x;",J9=Km(Y9),Z9={kernelName:Mp,backendName:"webgl",kernelFunc:J9};let BD="return (a - b) * (a - b);",Q9=mc({opSnippet:BD,packedOpSnippet:BD}),tZ={kernelName:yu,backendName:"webgl",kernelFunc:Q9};let zD="return a - b;",eZ=mc({opSnippet:zD,packedOpSnippet:zD,supportsComplex:!0,cpuKernelImpl:X8}),nZ={kernelName:bu,backendName:"webgl",kernelFunc:eZ};let rZ="return tan(x);",sZ=Km(rZ),oZ={kernelName:wu,backendName:"webgl",kernelFunc:sZ};let aZ={kernelName:th,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{let{x:r}=n,{perm:s}=t,u=e,l=r.shape.length,h=new Array(l);for(let m=0;m<h.length;m++)h[m]=r.shape[s[m]];let p;if(u.shouldExecuteOnCPU([r])){let m=u.texData.get(r.dataId),y=m.values,b=ix(y,r.shape,r.dtype,s,h);p=u.makeTensorInfo(h,r.dtype);let x=u.texData.get(p.dataId);x.values=b}else p=dx(r,s,u);return p}};function iZ(n){let{inputs:t,attrs:e,backend:r}=n,{axis:s}=e,{x:u}=t;bf(u,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let l=r.readSync(u.dataId),{outputValues:h,outputShape:p,indices:m}=Y8(l,s,u.shape,u.dtype);return[r.makeTensorInfo(p,u.dtype,h),r.makeTensorInfo([m.length],"int32",m)]}let uZ={kernelName:Lp,backendName:"webgl",kernelFunc:iZ};let cZ=[AJ,PJ,MJ,BJ,UJ,XJ,IJ,n9,o9,c9,h9,p9,g9,NJ,b9,ZJ,C9,I9,D9,A9,F9,M9,B9,z9,V9,G9,HJ,qJ,t9,q9,X9,Z9,nZ,tZ,oZ,aZ,uZ];for(let n of cZ)Hp(n);let lZ="2.7.0";let hZ={"tfjs-core":PS,"tfjs-backend-cpu":I6,"tfjs-backend-webgl":SJ,"tfjs-data":uE,"tfjs-layers":bm,"tfjs-converter":VI,tfjs:lZ};o.Abs=hp,o.Acos=dl,o.Acosh=ml,o.AdadeltaOptimizer=Ah,o.AdagradOptimizer=_h,o.AdamOptimizer=Fh,o.AdamaxOptimizer=Rh,o.Add=ri,o.AddN=$v,o.All=T2,o.Any=k2,o.ArgMax=Av,o.ArgMin=_v,o.Asin=gl,o.Asinh=vl,o.Atan=yl,o.Atan2=fp,o.Atanh=bl,o.AvgPool=wl,o.AvgPool3D=Fv,o.AvgPool3DBackprop=S2,o.AvgPoolBackprop=pp,o.BatchMatMul=dp,o.BatchToSpaceND=Rv,o.BroadcastTo=Pv,o.Callback=II,o.CallbackList=xN,o.Cast=pu,o.Ceil=xl,o.ClipByValue=Tl,o.Complex=mp,o.Concat=kl,o.Conv2D=gp,o.Conv2DBackpropFilter=Ov,o.Conv2DBackpropInput=vp,o.Conv3D=yp,o.Conv3DBackpropFilterV2=Mv,o.Conv3DBackpropInputV2=Lv,o.Cos=du,o.Cosh=Sl,o.CropAndResize=C2,o.Cumsum=Bv,o.CustomCallback=kN,o.DataStorage=c,o.DepthToSpace=N2,o.DepthwiseConv2dNative=bp,o.DepthwiseConv2dNativeBackpropFilter=zv,o.DepthwiseConv2dNativeBackpropInput=Wv,o.Diag=I2,o.Dilation2D=wp,o.Dilation2DBackpropFilter=Tp,o.Dilation2DBackpropInput=xp,o.Div=mu,o.EarlyStopping=DI,o.Elu=Cl,o.EluGrad=E2,o.Environment=b2,o.Equal=D2,o.Erf=Nl,o.Exp=Il,o.Expm1=El,o.FFT=kp,o.Fill=Vv,o.FlipLeftRight=Sp,o.Floor=Dl,o.FloorDiv=Uv,o.FromPixels=Bp,o.FusedBatchNorm=$l,o.FusedConv2D=Vp,o.FusedDepthwiseConv2D=Up,o.GatherNd=$2,o.GatherV2=Gv,o.GraphModel=WI,o.Greater=A2,o.GreaterEqual=Hv,o.History=TN,o.IFFT=Cp,o.Identity=Al,o.Imag=Np,o.InputSpec=Fn,o.IsFinite=_l,o.IsInf=Fl,o.IsNan=Rl,o.KernelBackend=f,o.LRN=jv,o.LRNBackprop=M2,o.LayerVariable=Ts,o.LayersModel=Io,o.Less=_2,o.LessEqual=F2,o.LinSpace=R2,o.Log=Pl,o.Log1p=Ol,o.LogSoftmax=qv,o.LogicalAnd=P2,o.LogicalNot=Ip,o.LogicalOr=O2,o.Max=Ml,o.MaxPool=Ll,o.MaxPool3D=Xv,o.MaxPool3DBackprop=L2,o.MaxPoolBackprop=Ep,o.MaxPoolWithArgmax=Dp,o.Maximum=Kv,o.Mean=Yv,o.Min=Jv,o.Minimum=Zv,o.MirrorPad=Bl,o.Mod=Qv,o.MomentumOptimizer=Ph,o.Multiply=gu,o.Negate=ty,o.NonMaxSuppressionV3=ey,o.NonMaxSuppressionV4=$p,o.NonMaxSuppressionV5=Ap,o.NotEqual=zl,o.OP_SCOPE_SUFFIX=aS,o.OneHot=ry,o.OnesLike=ny,o.Optimizer=ko,o.PadV2=_p,o.Pool=UR,o.Pow=sy,o.Prelu=Fp,o.Prod=B2,o.RMSPropOptimizer=Oh,o.RNN=Is,o.Range=z2,o.Real=Rp,o.Reciprocal=Wl,o.Relu=Vl,o.Relu6=Gl,o.Reshape=Ul,o.ResizeBilinear=ay,o.ResizeBilinearGrad=V2,o.ResizeNearestNeighbor=oy,o.ResizeNearestNeighborGrad=W2,o.Reverse=iy,o.RotateWithOffset=zp,o.Round=Hl,o.Rsqrt=ql,o.SGDOptimizer=Uu,o.ScatterNd=U2,o.SelectV2=uy,o.Selu=jl,o.Sequential=Ii,o.Sigmoid=Yl,o.Sign=Xl,o.Sin=vu,o.Sinh=Kl,o.Slice=Pp,o.Softmax=hy,o.Softplus=Jl,o.SpaceToBatchND=Op,o.SparseToDense=G2,o.SplitV=ly,o.Sqrt=Zl,o.Square=Mp,o.SquaredDifference=yu,o.Step=eh,o.StridedSlice=H2,o.Sub=bu,o.Sum=cy,o.SymbolicTensor=k
`)),w.join(`
`)}function SQ(o,a,i,c){var f=mn(a),d=c[c.length-1],g=new Array(d).fill(0),v=a.length,w=i==="complex64"?Lf(o):o;if(v>1)for(var T=0;T<f/d;T++)for(var N=T*d,E=0;E<d;E++)g[E]=Math.max(g[E],Mf(w[N+E],0,i).length);return g}function Mf(o,a,i){var c;return Array.isArray(o)?c=parseFloat(o[0].toFixed(GT))+" + "+(parseFloat(o[1].toFixed(GT))+"j"):Oa(o)?c="'"+o+"'":i==="bool"?c=wA(o):c=parseFloat(o.toFixed(GT)).toString(),Rf(c,a)}function wA(o){return o===0?"false":"true"}function mg(o,a,i,c,f,d){d===void 0&&(d=!0);var g=i==="complex64"?2:1,v=a[0],w=a.length;if(w===0){if(i==="complex64"){var T=Lf(o);return[Mf(T[0],0,i)]}return i==="bool"?[wA(o[0])]:[o[0].toString()]}if(w===1){if(v>bA){var N=Of*g,E=Array.from(o.slice(0,N)),k=Array.from(o.slice((v-Of)*g,v*g));return i==="complex64"&&(E=Lf(E),k=Lf(k)),["["+E.map(function(St,It){return Mf(St,f[It],i)}).join(", ")+", ..., "+k.map(function(St,It){return Mf(St,f[v-Of+It],i)}).join(", ")+"]"]}var $=i==="complex64"?Lf(o):Array.from(o);return["["+$.map(function(St,It){return Mf(St,f[It],i)}).join(", ")+"]"]}var M=a.slice(1),G=c.slice(1),O=c[0]*g,H=[];if(v>bA){for(var K=0;K<Of;K++){var nt=K*O,ct=nt+O;H.push.apply(H,mg(o.slice(nt,ct),M,i,G,f,!1))}H.push("...");for(var K=v-Of;K<v;K++){var nt=K*O,ct=nt+O;H.push.apply(H,mg(o.slice(nt,ct),M,i,G,f,K===v-1))}}else for(var K=0;K<v;K++){var nt=K*O,ct=nt+O;H.push.apply(H,mg(o.slice(nt,ct),M,i,G,f,K===v-1))}var dt=w===2?",":"";H[0]="["+H[0]+dt;for(var K=1;K<H.length-1;K++)H[K]=" "+H[K]+dt;for(var Ct=`,
`,K=2;K<w;K++)Ct+=`
`;return H[H.length-1]=" "+H[H.length-1]+"]"+(d?"":Ct),H}function Lf(o){for(var a=[],i=0;i<o.length;i+=2)a.push([o[i],o[i+1]]);return a}var gg=function(){function o(a,i,c){var f=this;if(this.dtype=i,this.shape=a.slice(),this.size=mn(a),c!=null){var d=c.length;U(d===this.size,function(){return"Length of values '"+d+"' does not match the size "+("inferred by the shape '"+f.size+"'.")})}if(i==="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=c||i$(i,this.size),this.strides=Nc(a)}return o.prototype.set=function(a){for(var i=this,c=[],f=1;f<arguments.length;f++)c[f-1]=arguments[f];c.length===0&&(c=[0]),U(c.length===this.rank,function(){return"The number of provided coordinates ("+c.length+") must "+("match the rank ("+i.rank+")")});var d=this.locToIndex(c);this.values[d]=a},o.prototype.get=function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];a.length===0&&(a=[0]);for(var c=0,f=0,d=a;f<d.length;f++){var g=d[f];if(g<0||g>=this.shape[c]){var v="Requested out of range element at "+a+". "+(" Buffer shape="+this.shape);throw new Error(v)}c++}for(var w=a[a.length-1],T=0;T<a.length-1;++T)w+=this.strides[T]*a[T];return this.values[w]},o.prototype.locToIndex=function(a){if(this.rank===0)return 0;if(this.rank===1)return a[0];for(var i=a[a.length-1],c=0;c<a.length-1;++c)i+=this.strides[c]*a[c];return i},o.prototype.indexToLoc=function(a){if(this.rank===0)return[];if(this.rank===1)return[a];for(var i=new Array(this.shape.length),c=0;c<i.length-1;++c)i[c]=Math.floor(a/this.strides[c]),a-=i[c]*this.strides[c];return i[i.length-1]=a,i},Object.defineProperty(o.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),o.prototype.toTensor=function(){return io().makeTensor(this.values,this.shape,this.dtype)},o}(),io=null,$c=null;function NQ(o){io=o}function IQ(o){$c=o}var ut=function(){function o(a,i,c,f){this.kept=!1,this.isDisposedInternal=!1,this.shape=a.slice(),this.dtype=i||"float32",this.size=mn(a),this.strides=Nc(a),this.dataId=c,this.id=f,this.rankType=this.rank<5?this.rank.toString():"higher"}return Object.defineProperty(o.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),o.prototype.buffer=function(){return qt(this,void 0,void 0,function(){var a;return jt(this,function(i){switch(i.label){case 0:return[4,this.data()];case 1:return a=i.sent(),[2,$c.buffer(this.shape,this.dtype,a)]}})})},o.prototype.bufferSync=function(){return $c.buffer(this.shape,this.dtype,this.dataSync())},o.prototype.array=function(){return qt(this,void 0,void 0,function(){var a;return jt(this,function(i){switch(i.label){case 0:return[4,this.data()];case 1:return a=i.sent(),[2,Ic(this.shape,a)]}})})},o.prototype.arraySync=function(){return Ic(this.shape,this.dataSync())},o.prototype.data=function(){return qt(this,void 0,void 0,function(){var a,i;return jt(this,function(c){switch(c.label){case 0:return this.throwIfDisposed(),a=io().read(this.dataId),this.dtype==="string"?[4,a]:[3,2];case 1:i=c.sent();try{return[2,i.map(function(f){return UT(f)})]}catch(f){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}c.label=2;case 2:return[2,a]}})})},o.prototype.dataSync=function(){this.throwIfDisposed();var a=io().readSync(this.dataId);if(this.dtype==="string")try{return a.map(function(i){return UT(i)})}catch(i){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return a},o.prototype.bytes=function(){return qt(this,void 0,void 0,function(){var a;return jt(this,function(i){switch(i.label){case 0:return this.throwIfDisposed(),[4,io().read(this.dataId)];case 1:return a=i.sent(),this.dtype==="string"?[2,a]:[2,new Uint8Array(a.buffer)]}})})},o.prototype.dispose=function(){if(this.isDisposed)return;io().disposeTensor(this),this.isDisposedInternal=!0},Object.defineProperty(o.prototype,"isDisposed",{get:function(){return this.
`)+"Manifest JSON has weights with names: "+(w.join(", ")+"."));return N=d.reduce(function(O,H,K){return H&&O.push(K),O},[]),E=[],N.forEach(function(O){i[O].paths.forEach(function(H){var K=c+(c.endsWith("/")?"":"/")+H;E.push(K)})}),[4,o(E)];case 1:return k=G.sent(),$={},M=0,N.forEach(function(O){for(var H=i[O].paths.length,K=0,nt=0;nt<H;nt++)K+=k[M+nt].byteLength;for(var ct=new ArrayBuffer(K),dt=new Uint8Array(ct),Ct=0,St=0;St<H;St++){var It=new Uint8Array(k[M+St]);dt.set(It,Ct),Ct+=It.byteLength}var Gt=g[O];Gt.forEach(function(Et){var Wt=ct.slice(Et.groupOffset,Et.groupOffset+Et.sizeBytes),_t=DA(Wt,[Et.manifestEntry]);for(var Kt in _t)$[Kt]=_t[Kt]}),M+=H}),[2,$]}})})}}var Itt="application/octet-stream",Ett="application/json",UA=function(){function o(a,i){if(this.DEFAULT_METHOD="POST",i==null&&(i={}),this.weightPathPrefix=i.weightPathPrefix,this.onProgress=i.onProgress,this.weightUrlConverter=i.weightUrlConverter,i.fetchFunc!=null?(U(typeof i.fetchFunc=="function",function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"}),this.fetch=i.fetchFunc):this.fetch=Fe().platform.fetch,U(a!=null&&a.length>0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(a)&&U(a.length===2,function(){return"URL paths for http must have a length of 2, "+("(actual length is "+a.length+").")}),this.path=a,i.requestInit!=null&&i.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=i.requestInit||{}}return o.prototype.save=function(a){return qt(this,void 0,void 0,function(){var i,c,f,d;return jt(this,function(g){switch(g.label){case 0:if(a.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return i=Object.assign({method:this.DEFAULT_METHOD},this.requestInit),i.body=new FormData,c=[{paths:["./model.weights.bin"],weights:a.weightSpecs}],f={modelTopology:a.modelTopology,format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata,weightsManifest:c},i.body.append("model.json",new Blob([JSON.stringify(f)],{type:Ett}),"model.json"),a.weightData!=null&&i.body.append("model.weights.bin",new Blob([a.weightData],{type:Itt}),"model.weights.bin"),[4,this.fetch(this.path,i)];case 1:if(d=g.sent(),d.ok)return[2,{modelArtifactsInfo:Wf(a),responses:[d]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(d.status+"."))}})})},o.prototype.load=function(){return qt(this,void 0,void 0,function(){var a,i,c,f,d,g,v,w,T,N,E,k,$,M,G;return jt(this,function(O){switch(O.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(a=O.sent(),!a.ok)throw new Error("Request to "+this.path+" failed with status code "+(a.status+". Please verify this URL points to ")+"the model JSON of the model to load.");O.label=2;case 2:return O.trys.push([2,4,,5]),[4,a.json()];case 3:return i=O.sent(),[3,5];case 4:throw c=O.sent(),f="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?f+=" 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.":f+=" Please make sure the server is serving valid JSON for this request.",new Error(f);case 5:if(d=i.modelTopology,g=i.weightsManifest,v=i.generatedBy,w=i.convertedBy,T=i.format,N=i.userDefinedMetadata,d==null&&g==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return g!=null?[4,this.loadWeights(g)]:[3,7];case 6:$=O.sent(),E=$[0],k=$[1],O.label=7;case 7:return M={modelTopology:d,weightSpecs:E,weightData:k,userDefinedMetadata:N,generatedBy:v,convertedBy:w,format:T},G=i.modelInitializer,G&&(M.modelInitial
`)+("Actual: "+w+`.
`)+("Expected: "+T+"."));for(var N=0;N<T.length;++N){var E=w[N],k=T[N];if(!i(E,k))throw new Error("Arrays differ: actual["+N+"] = "+E+", expected["+N+"] = "+k+`.
`+("Actual: "+w+`.
`)+("Expected: "+T+"."))}}function Qtt(o,a){o().then(function(){return a.fail()},function(){return a()})}function tet(o,a){var i=typeof a=="string"||typeof a=="number"||typeof a=="boolean"?[a]:a;return Oa(o)||Oa(o[0])||Oa(a)||Oa(a[0])?hk(o,i,function(c,f){return c==f}):hk(o,a,function(c,f){return fk(c,f,0)})}function eet(o,a,i){if(i==null&&(i=lk()),!fk(o,a,i))throw new Error("Numbers differ: actual === "+o+", expected === "+a)}function fk(o,a,i){return!isFinite(o)&&!isFinite(a)?!0:!(isNaN(o)||isNaN(a)||Math.abs(o-a)>i)}function net(o,a,i){for(var c=0;c<o.length;c++)if(o[c]<a||o[c]>i)throw new Error("Value out of range:"+o[c]+" low: "+a+", high: "+i)}function ret(o,a){expect(new Float32Array(o)).toEqual(new Float32Array(a))}var set={__proto__:null,TEST_EPSILON_FLOAT16:u_,expectArraysClose:Ztt,testEpsilon:lk,expectPromiseToFail:Qtt,expectArraysEqual:tet,expectNumbersClose:eet,expectValuesInRange:net,expectArrayBuffersEqual:ret};var oet="2.7.0";function aet(){Fe().set("PROD",!0)}function iet(){Fe().set("DEBUG",!0)}function uet(){Fe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Mn(o){Fe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(o+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function cet(){Z.disposeVariables()}function het(){return Z}function fet(){return Z.memory()}function pet(o){return Z.profile(o)}function En(o,a){return Z.tidy(o,a)}function wr(o){var a=XT(o);a.forEach(function(i){return i.dispose()})}function c_(o){return Z.keep(o)}function det(o){return Z.time(o)}function met(o){return Z.setBackend(o)}function get(){return Z.ready()}function vet(){return Z.backendName}function yet(o){Z.removeBackend(o)}function bet(o){return Z.findBackend(o)}function wet(o){return Z.findBackendFactory(o)}function xet(o,a,i){return i===void 0&&(i=1),Z.registerBackend(o,a,i)}function Tet(){return Z.backend}function ket(o,a){Fe().setPlatform(o,a)}function Cet(o,a){var i,c=W(o,"a","add"),f=W(a,"b","add");i=pn(c,f),c=i[0],f=i[1];var d=function(v,w){var T=v.add(c,f);return w([c,f]),T},g={a:c,b:f};return Z.runKernelFunc(d,g,null,hg)}var Yt=Y({add_:Cet});function Net(o,a){var i,c=W(o,"a","floorDiv"),f=W(a,"b","floorDiv");i=pn(c,f),c=i[0],f=i[1];var d=function(v,w){var T=v.floorDiv(c,f);return w([c,f]),T},g={a:c,b:f};return Z.runKernelFunc(d,g,null,D1)}var pk=Y({floorDiv_:Net});function Iet(o,a){var i,c=W(o,"a","div"),f=W(a,"b","div");if(i=pn(c,f),c=i[0],f=i[1],c.dtype==="int32"&&f.dtype==="int32")return pk(c,f);var d=function(w,T){var N=w.realDivide(c,f);return T([c,f]),N},g={a:c,b:f},v={};return Z.runKernelFunc(d,g,null,k1,v)}var ae=Y({div_:Iet});function Eet(o,a){var i,c=W(o,"a","mul"),f=W(a,"b","mul");i=pn(c,f),c=i[0],f=i[1];var d=function(v,w){var T=v.multiply(c,f);return w([c,f]),T},g={a:c,b:f};return Z.runKernelFunc(d,g,null,X1)}var pt=Y({mul_:Eet});function Det(o){var a=W(o,"x","abs"),i={x:a};return Z.runKernelFunc(function(c,f){return f([a]),a.dtype==="complex64"?c.complexAbs(a):c.abs(a)},i,null,Yx)}var _r=Y({abs_:Det});function $et(o){var a=W(o,"x","acos"),i={x:a};return Z.runKernelFunc(function(c,f){var d=c.acos(a);return f([a]),d},i,null,Jx)}var l_=Y({acos_:$et});function Aet(o){var a=W(o,"x","acosh"),i={x:a};return Z.runKernelFunc(function(c,f){var d=c.acosh(a);return f([a]),d},i,null,Zx)}var h_=Y({acosh_:Aet});function _et(o){U(Array.isArray(o),function(){return"The argument passed to tf.addN() must be a list of tensors"}),U(o.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+(""+o.length)});var a=o.map(function(d,g){return W(d,"tensors"+g,"addN")}),i=a[0];a.forEach(function(d){if(d.dtype!==i.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),a.forEach(function(d){if(!Rs(d.shape,i.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var c=function(d,g){var v=d.addN(a);return g(a),v},f=a;return Z.runKernelFunc(c,f,null,Qx)}var Fet=Y({addN_:_et});function dk(o,a){for(var i=0;i<o.length;++i)if(o[o.length-i-1]!==a-1-i)
with dtype `+g.dtype+". ")});var c=function(g,v){var w=Qe(a,i[0].shape)[0],T=S_(i.map(function(k){return k.shape}),w);if(mn(T)===0)return za([],T);if(i=i.filter(function(k){return k.size>0}),i.length===1)return i[0];var N=i.map(function(k){return k.shape});k_(N,w);var E=g.concat(i,w);return v(i),E},f=i,d={axis:a};return Z.runKernelFunc(c,f,null,d1,d)}var qn=Y({concat_:Zet});function Qet(o){var a=W(o,"x","sigmoid"),i={x:a};return Z.runKernelFunc(function(c,f){var d=c.sigmoid(a);return f([d]),d},i,null,vT)}var Hi=Y({sigmoid_:Qet});function tnt(o,a,i){var c=W(o,"x","slice");if(c.rank===0)throw new Error("Slicing scalar is not possible");var f=function(v,w){var T=ck(c,a,i),N=T[0],E=T[1];return KA(c,N,E),w([c]),v.slice(c,N,E)},d={x:c},g={begin:a,size:i};return Z.runKernelFunc(f,d,null,pT,g)}var De=Y({slice_:tnt});function ent(o){var a=W(o,"x","tanh"),i={x:a};return Z.runKernelFunc(function(c,f){var d=c.tanh(a);return f([d]),d},i,null,IT)}var Sg=Y({tanh_:ent});function nnt(o,a,i,c,f,d){var g=W(o,"forgetBias","basicLSTMCell"),v=W(a,"lstmKernel","basicLSTMCell"),w=W(i,"lstmBias","basicLSTMCell"),T=W(c,"data","basicLSTMCell"),N=W(f,"c","basicLSTMCell"),E=W(d,"h","basicLSTMCell"),k=qn([T,E],1),$=Ce(k,v),M=Yt($,w),G=M.shape[0],O=M.shape[1]/4,H=[G,O],K=De(M,[0,0],H),nt=De(M,[0,O],H),ct=De(M,[0,O*2],H),dt=De(M,[0,O*3],H),Ct=Yt(pt(Hi(K),Sg(nt)),pt(N,Hi(Yt(g,ct)))),St=pt(Sg(Ct),Hi(dt));return[Ct,St]}var rnt=Y({basicLSTMCell_:nnt});function snt(o,a,i){var c=W(o,"x","batchToSpaceND"),f=a.reduce(function(w,T){return w*T});U(c.rank>=1+a.length,function(){return"input rank is "+c.rank+" but should be > than blockShape.length "+a.length}),U(i.length===a.length,function(){return"crops.length is "+i.length+" but should be equal to blockShape.length "+a.length}),U(c.shape[0]%f===0,function(){return"input tensor batch is "+c.shape[0]+" but is not divisible by the product of "+("the elements of blockShape "+a.join(" * ")+" === "+f)});var d=function(w){return w.batchToSpaceND(c,a,i)},g={x:c},v={blockShape:a,crops:i};return Z.runKernelFunc(d,g,null,l1,v)}var Cg=Y({batchToSpaceND_:snt});function ont(o){var a;return o.rank===0||o.rank===1?a=it(o,[1,1,1,o.size]):o.rank===2?a=it(o,[1,1,o.shape[0],o.shape[1]]):o.rank===3?a=it(o,[1,o.shape[0],o.shape[1],o.shape[2]]):a=o,a}function ant(o,a,i,c,f,d){d==null&&(d=.001);var g=W(o,"x","batchNorm"),v=W(a,"mean","batchNorm"),w=W(i,"variance","batchNorm"),T;f!=null&&(T=W(f,"scale","batchNorm"));var N;c!=null&&(N=W(c,"offset","batchNorm")),U(v.rank===w.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),U(N==null||v.rank===N.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),U(T==null||v.rank===T.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var E=ont(g),k=function(O,H){return H([E,v,w,T]),O.batchNorm(E,Ng(v),Ng(w),Ng(N),Ng(T),d)},$={x:E,scale:T,offset:N,mean:v,variance:w},M={varianceEpsilon:d},G=Z.runKernelFunc(k,$,null,$1,M);return it(G,g.shape)}function Ng(o){return o==null?null:o.rank===0?it(o,[o.size]):o.rank===1?o:o.rank===2?it(o,[1,1,o.shape[0],o.shape[1]]):o.rank===3?it(o,[1,o.shape[0],o.shape[1],o.shape[2]]):o}var Hf=Y({batchNorm_:ant});function int(o,a,i,c,f,d){var g=W(o,"x","batchNorm"),v=W(a,"mean","batchNorm"),w=W(i,"variance","batchNorm"),T;f!=null&&(T=W(f,"scale","batchNorm"));var N;return c!=null&&(N=W(c,"offset","batchNorm")),U(g.rank===2,function(){return"Error in batchNorm2D: x must be rank 2 but got rank "+(g.rank+".")}),U(v.rank===2||v.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but "+("got rank "+v.rank+".")}),U(w.rank===2||w.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 "+("but got rank "+w.rank+".")}),T!=null&&U(T.rank===2||T.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 "+("but got rank "+T.rank+".")}),N!=null&&U(N.rank===2||N.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 "+("but got ran
`+f+" and "+a+` for depthToSpace with input shape
`+c.shape}),U(d*a>=0,function(){return`Negative dimension size caused by overflow when multiplying
`+d+" and "+a+` for depthToSpace with input shape
`+c.shape}),U(g%(a*a)===0,function(){return"Dimension size must be evenly divisible by "+a*a+" but is "+g+" for depthToSpace with input shape "+c.shape});var v=function(N){return N.depthToSpace(c,a,i)},w={x:c},T={blockSize:a,dataFormat:i};return Z.runKernelFunc(v,w,null,D$,T)}var $_=Y({depthToSpace_:Ont});function Mnt(o,a,i,c,f,d,g){f===void 0&&(f="NHWC"),d===void 0&&(d=[1,1]);var v=W(o,"x","depthwiseConv2d"),w=W(a,"filter","depthwiseConv2d"),T=v,N=!1;v.rank===3&&(N=!0,T=it(v,[1,v.shape[0],v.shape[1],v.shape[2]])),U(T.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got "+("rank "+T.rank+".")}),U(w.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+(w.rank+".")}),U(T.shape[3]===w.shape[2],function(){return"Error in depthwiseConv2d: number of input channels "+("("+T.shape[3]+") must match the inChannels dimension in ")+("filter "+w.shape[2]+".")}),g!=null&&U(fn(c),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+g+" but got pad "+c+".")});var E=function(G,O){d==null&&(d=[1,1]),U(xr(i,d),function(){return"Error in depthwiseConv2d: Either strides or dilations must be "+("1. Got strides "+i+" and dilations '"+d+"'")});var H=Os(T.shape,w.shape,i,d,c,g,!0),K=G.depthwiseConv2D(T,w,H);return O([T,w]),K},k={x:T,filter:w},$={strides:i,pad:c,dataFormat:f,dilations:d,dimRoundingMode:g},M=Z.runKernelFunc(E,k,null,x1,$);return N?it(M,[M.shape[1],M.shape[2],M.shape[3]]):M}var qf=Y({depthwiseConv2d_:Mnt});function Lnt(o){var a=W(o,"x","diag"),i=function(f){var d=it(a,[a.size]),g=f.diag(d),v=o.shape.concat(o.shape);return it(g,v)},c={x:a};return Z.runKernelFunc(i,c,null,_$)}var Bnt=Y({diag_:Lnt});function znt(o,a,i,c,f,d){f===void 0&&(f=[1,1]),d===void 0&&(d="NHWC");var g=W(o,"x","dilation2d"),v=W(a,"filter","dilation2d");U(g.rank===3||g.rank===4,function(){return"Error in dilation2d: input must be rank 3 or 4, but got rank "+(g.rank+".")}),U(v.rank===3,function(){return"Error in dilation2d: filter must be rank 3, but got rank "+(v.rank+".")}),U(d==="NHWC",function(){return"Error in dilation2d: Only NHWC is currently supported, "+("but got dataFormat of "+d)});var w=g,T=!1;g.rank===3&&(w=it(g,[1,g.shape[0],g.shape[1],g.shape[2]]),T=!0);var N={x:w,filter:v},E={strides:i,pad:c,dilations:f},k=Z.runKernel(T1,N,E);return T?it(k,[k.shape[1],k.shape[2],k.shape[3]]):k}var A_=Y({dilation2d_:znt});function Wnt(o,a){for(var i=o.length,c=[],f=0;f<i;f++){var d=i-1-f,g=o[d]||1,v=a[a.length-1-f]||1;v>1&&g===1&&c.unshift(d)}return c}function Dn(o,a){for(var i=[],c=0;c<a.length;c++){var f=o[o.length-c-1],d=a.length-c-1,g=a[d];(f==null||f===1&&g>1)&&i.unshift(d)}return i}function tn(o,a){for(var i=[],c=Math.max(o.length,a.length),f=0;f<c;f++){var d=o[o.length-f-1];d==null&&(d=1);var g=a[a.length-f-1];if(g==null&&(g=1),d===1)i.unshift(g);else if(g===1)i.unshift(d);else if(d!==g){var v="Operands could not be broadcast together with shapes "+(o+" and "+a+".");throw Error(v)}else i.unshift(d)}return i}function Vnt(o,a){var i,c=W(o,"a","equal"),f=W(a,"b","equal");i=pn(c,f),c=i[0],f=i[1],tn(c.shape,f.shape);var d=function(v){return v.equal(c,f)},g={a:c,b:f};return Z.runKernelFunc(d,g,null,O$)}var jf=Y({equal_:Vnt});function Unt(o,a,i){var c=W(a,"a","where"),f=W(i,"b","where"),d=W(o,"condition","where","bool"),g=tn(c.shape,f.shape),v=Ig(c,g),w=Ig(f,g);d.rank===1&&U(d.shape[0]===c.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}),d.rank!==1&&Ee(d.shape,w.shape,"Error in where: ");var T=function(E,k){var $=E.select(d,v,w);return k([d]),$},N={condition:d,t:v,e:w};return Z.runKernelFunc(T,N,null,hT)}var Ms=Y({where_:Unt});function Gnt(o){var a=W(o,"x","zerosLike"),i={x:a};return Z.runKernelFunc(function(c){return c.zerosLike(a)},i,null,_T)}var ke=Y({zerosLike_:Gnt});function Hnt(o,a){var i,c=W(o,"a","div"),f=W(a,"b","div");i=pn(c,f),c=i[0],f=i[1];var d=ae(c,f),g=ke(d),v=jf(f,g);return Ms(v,g,d)}var __=Y({divNoNan_:Hnt});function qnt(o,a){var i=W(o,"t1","dot"),c=W(a,"t2","dot");U((i.rank===1||i.r
rank `+d.rank+"."}),U(fn(a),function(){return"Error in localResponseNormalization: depthRadius must be an "+("integer but got depthRadius "+a+".")});var g=d,v=!1;d.rank===3&&(v=!0,g=it(d,[1,d.shape[0],d.shape[1],d.shape[2]]));var w=function(k,$){var M=k.localResponseNormalization4D(g,a,i,c,f);return $([g,M]),M},T={x:g},N={depthRadius:a,bias:i,alpha:c,beta:f},E=Z.runKernelFunc(w,T,null,z1,N);return v?it(E,[E.shape[1],E.shape[2],E.shape[3]]):E}var V_=Y({localResponseNormalization_:vrt});function yrt(o){var a=W(o,"x","log"),i={x:a};return Z.runKernelFunc(function(c,f){var d=c.log(a);return f([a]),d},i,null,M1)}var Ki=Y({log_:yrt});function brt(o){var a=W(o,"x","log1p"),i={x:a};return Z.runKernelFunc(function(c,f){var d=c.log1p(a);return f([a]),d},i,null,L1)}var Sk=Y({log1p_:brt});function wrt(o){return U(Ma(o),function(){return"The f passed in grad(f) must be a function"}),function(a,i){var c=W(a,"x","tf.grad",null),f=i!=null?W(i,"dy","tf.grad"):null;return Z.tidy(function(){var d=Z.gradients(function(){return o(c)},[c],f),g=d.value,v=d.grads;return f!=null&&Ee(g.shape,f.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Fg(v),v[0]})}}function xrt(o){return U(Ma(o),function(){return"The f passed in grads(f) must be a function"}),function(a,i){U(Array.isArray(a),function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"});var c=zf(a,"args","tf.grads",null),f=i!=null?W(i,"dy","tf.grads"):null;return Z.tidy(function(){var d=Z.gradients(function(){return o.apply(void 0,c)},c,f),g=d.value,v=d.grads;return f!=null&&Ee(g.shape,f.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Fg(v),v})}}function Trt(o){return U(Ma(o),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(a,i){U(a instanceof ut,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),U(i==null||i instanceof ut,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var c=Z.gradients(function(){return o(a)},[a],i),f=c.grads,d=c.value;return Fg(f),{grad:f[0],value:d}}}function krt(o){return U(Ma(o),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(a,i){U(Array.isArray(a)&&a.every(function(f){return f instanceof ut}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),U(i==null||i instanceof ut,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var c=Z.gradients(function(){return o.apply(void 0,a)},a,i);return i!=null&&Ee(c.value.shape,i.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Fg(c.grads),c}}function U_(o,a){U(Ma(o),function(){return"The f passed in variableGrads(f) must be a function"}),U(a==null||Array.isArray(a)&&a.every(function(E){return E instanceof Bf}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var i=a!=null;if(!i){a=[];for(var c in Z.registeredVariables)a.push(Z.registeredVariables[c])}var f=i?a.filter(function(E){return!E.trainable}):null,d=a.length;a=a.filter(function(E){return E.trainable}),U(a.length>0,function(){return"variableGrads() expects at least one of the input variables to "+("be trainable, but none of the "+d+" variables is ")+"trainable."});var g=!0,v=Z.gradients(o,a,null,g),w=v.value,T=v.grads;U(T.some(function(E){return E!=null}),function(){return"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()."}),U(w.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it "+("returned a rank-"+w.rank+" tensor")});var N={};return a.forEach(function(E,k){T[k]!=null&&(N[E.name]=T[k])}),f!=null&&f.forEach(function(E){return N[E.name]=null}),{value:w,grads:N}}function ho(o){return Z.customGrad(o)}function Fg(o){var a=o.filter(function(i){return i==null}).length;
the f you passed encloses all operations that lead from x to y.`)}function Srt(o){var a=W(o,"x","neg"),i={x:a};return Z.runKernelFunc(function(c){return c.neg(a)},i,null,Y1)}var $n=Y({neg_:Srt});function Crt(o){var a=W(o,"x","softplus"),i={x:a};return Z.runKernelFunc(function(c,f){var d=c.softplus(a);return f([a]),d},i,null,yT)}var Ck=Y({softplus_:Crt});function Nrt(o){var a=W(o,"x","logSigmoid"),i=ho(function(c){var f=$n(Ck($n(c))),d=function(g){var v=pt(g,Hi($n(c)));return v};return{value:f,gradFunc:d}});return i(a)}var G_=Y({logSigmoid_:Nrt});function Irt(o,a,i){a===void 0&&(a=null),i===void 0&&(i=!1);var c=W(o,"x","max"),f=function(v,w){var T=Qe(a,c.shape),N=T,E=Ps(N,c.rank),k=c;E!=null&&(k=On(c,E),N=lo(N.length,k.rank));var $=v.max(k,N);E!=null&&k.dispose();var M=$;if(i){var G=Jr(M.shape,Qe(a,c.shape));M=it(M,G),$.dispose()}return w([c,M]),M},d={x:c},g={reductionIndices:a,keepDims:i};return Z.runKernelFunc(f,d,null,W1,g)}var Xi=Y({max_:Irt});function Ert(o,a){var i,c=W(o,"a","sub"),f=W(a,"b","sub");i=pn(c,f),c=i[0],f=i[1];var d=function(v,w){var T=v.subtract(c,f);return w([c,f]),T},g={a:c,b:f};return Z.runKernelFunc(d,g,null,CT)}var Qt=Y({sub_:Ert});function Drt(o,a,i){a===void 0&&(a=null),i===void 0&&(i=!1);var c=W(o,"x","sum");c.dtype==="bool"&&(c=Bt(c,"int32"));var f=function(v,w){w([c]);var T=Qe(a,c.shape),N=Ps(T,c.rank),E=T,k=c;N!=null&&(k=On(c,N),E=lo(E.length,c.rank));var $=v.sum(k,E);if(i){var M=Jr($.shape,T);$=it($,M)}return $},d={x:c},g={axis:a,keepDims:i};return Z.runKernelFunc(f,d,null,wT,g)}var ie=Y({sum_:Drt});function $rt(o,a){a===void 0&&(a=-1);var i=W(o,"logits","logSoftmax");if(a===-1&&(a=i.rank-1),a!==i.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. "+("Logits was rank "+i.rank+" and axis was "+a));var c=function(g,v){var w=!0,T=Xi(o,a,!0),N=Qt(o,T),E=Qt(Bt(N,"float32"),Ki(ie(Ls(N),a,w)));return v([E]),E},f={logits:i},d={axis:a};return Z.runKernelFunc(c,f,null,B1,d)}var H_=Y({logSoftmax_:$rt});function Art(o,a,i){a===void 0&&(a=null),i===void 0&&(i=!1);var c=W(o,"x","logSumExp"),f=Qe(a,c.shape),d=Xi(c,f,!0),g=Qt(c,d),v=Ls(g),w=ie(v,f),T=Ki(w),N=Yt(it(d,T.shape),T);if(i){var E=Jr(N.shape,f);return it(N,E)}return N}var Nk=Y({logSumExp_:Art});function _rt(o,a){var i=W(o,"a","logicalAnd","bool"),c=W(a,"b","logicalAnd","bool");tn(i.shape,c.shape);var f={a:i,b:c};return Z.runKernelFunc(function(d){return d.logicalAnd(i,c)},f,null,j$)}var Yi=Y({logicalAnd_:_rt});function Frt(o){var a=W(o,"x","logicalNot","bool"),i={x:a};return Z.runKernelFunc(function(c){return c.logicalNot(a)},i,null,K$)}var Rg=Y({logicalNot_:Frt});function Rrt(o,a){var i=W(o,"a","logicalOr","bool"),c=W(a,"b","logicalOr","bool");tn(i.shape,c.shape);var f={a:i,b:c};return Z.runKernelFunc(function(d){return d.logicalOr(i,c)},f,null,X$)}var Ik=Y({logicalOr_:Rrt});function Prt(o,a){var i=W(o,"a","logicalXor","bool"),c=W(a,"b","logicalXor","bool");return tn(i.shape,c.shape),Yi(Ik(o,a),Rg(Yi(o,a)))}var q_=Y({logicalXor_:Prt});function Ort(o,a,i,c,f){var d=W(o,"x","maxPool"),g=1,v=d,w=!1;d.rank===3&&(w=!0,v=it(d,[1,d.shape[0],d.shape[1],d.shape[2]])),U(v.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+v.rank+"."}),U(xr(i,g),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+i+" and dilations '"+g+"'")}),f!=null&&U(fn(c),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+f+" but got pad "+c+".")});var T=function($,M){var G=Oc(v.shape,a,i,1,c,f),O;return G.filterWidth===1&&G.filterHeight===1&&Rs(G.inShape,G.outShape)?O=v.clone():O=$.maxPool(v,G),M([v,O]),O},N={x:v},E={filterSize:a,strides:i,pad:c,dimRoundingMode:f},k=Z.runKernelFunc(T,N,null,U1,E);return w?it(k,[k.shape[1],k.shape[2],k.shape[3]]):k}var Ek=Y({maxPool_:Ort});function Mrt(o,a,i,c,f,d,g){a===void 0&&(a=[1,1,1]),d===void 0&&(d="NDHWC"),g==null?g=[1,1,1]:Mn("dilations is deprecated, this field will be gone in v3.0.0.");var v=W(o,"x","maxPool3d"),w=v,T=!1;v.rank===4&&(T=!0,w=it(v,[1,v.shape[0],v.shape[1],v.shape[2],v.shape[3]])),U(w
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
2020-10-15 12:48:39 +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.
* =============================================================================
*/
2020-11-25 14:30:53 +01: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.
* =============================================================================
*/
2020-10-15 12:48:39 +02:00
/** @license See the LICENSE file. */
2020-10-27 17:51:38 +01:00
//# sourceMappingURL=face-api.node.js.map