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

3982 lines
1.1 MiB
JavaScript
Raw Normal View History

2020-10-26 01:01:36 +01:00
var Nm=Object.defineProperty,gX=Object.prototype.hasOwnProperty,CS=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),jC=r=>Nm(r,"__esModule",{value:!0}),vc=(r,l)=>{jC(r);for(var h in l)Nm(r,h,{get:l[h],enumerable:!0})},yX=(r,l)=>{if(jC(r),typeof l=="object"||typeof l=="function")for(let h in l)!gX.call(r,h)&&h!=="default"&&Nm(r,h,{get:()=>l[h],enumerable:!0});return r},Ye=r=>r&&r.__esModule?r:yX(Nm({},"default",{value:r,enumerable:!0}),r);var i2=CS(bX=>{vc(bX,{FetchError:()=>Mn,Headers:()=>fi,Request:()=>Zo,Response:()=>Pi,default:()=>OX});const Ys=Ye(require("stream")),RS=Ye(require("http")),Cm=Ye(require("url")),KC=Ye(require("https")),no=Ye(require("zlib")),wX=Ys.default.Readable,pr=Symbol("buffer"),OS=Symbol("type");class fu{constructor(){this[OS]="";const r=arguments[0],l=arguments[1],h=[];let d=0;if(r){const g=r,S=Number(g.length);for(let L=0;L<S;L++){const x=g[L];let A;x instanceof Buffer?A=x:ArrayBuffer.isView(x)?A=Buffer.from(x.buffer,x.byteOffset,x.byteLength):x instanceof ArrayBuffer?A=Buffer.from(x):x instanceof fu?A=x[pr]:A=Buffer.from(typeof x=="string"?x:String(x)),d+=A.length,h.push(A)}}this[pr]=Buffer.concat(h);let f=l&&l.type!==void 0&&String(l.type).toLowerCase();f&&!/[^\u0020-\u007E]/.test(f)&&(this[OS]=f)}get size(){return this[pr].length}get type(){return this[OS]}text(){return Promise.resolve(this[pr].toString())}arrayBuffer(){const r=this[pr],l=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return Promise.resolve(l)}stream(){const r=new wX;return r._read=function(){},r.push(this[pr]),r.push(null),r}toString(){return"[object Blob]"}slice(){const r=this.size,l=arguments[0],h=arguments[1];let d,f;l===void 0?d=0:l<0?d=Math.max(r+l,0):d=Math.min(l,r),h===void 0?f=r:h<0?f=Math.max(r+h,0):f=Math.min(h,r);const g=Math.max(f-d,0),S=this[pr],L=S.slice(d,d+g),x=new fu([],{type:arguments[2]});return x[pr]=L,x}}Object.defineProperties(fu.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(fu.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});function Mn(r,l,h){Error.call(this,r),this.message=r,this.type=l,h&&(this.code=this.errno=h.code),Error.captureStackTrace(this,this.constructor)}Mn.prototype=Object.create(Error.prototype);Mn.prototype.constructor=Mn;Mn.prototype.name="FetchError";let ES;try{ES=require("encoding").convert}catch(r){}const mr=Symbol("Body internals"),XC=Ys.default.PassThrough;function xn(r){var l=this,h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=h.size;let f=d===void 0?0:d;var g=h.timeout;let S=g===void 0?0:g;r==null?r=null:JC(r)?r=Buffer.from(r.toString()):gu(r)||(Buffer.isBuffer(r)||(Object.prototype.toString.call(r)==="[object ArrayBuffer]"?r=Buffer.from(r):ArrayBuffer.isView(r)?r=Buffer.from(r.buffer,r.byteOffset,r.byteLength):r instanceof Ys.default||(r=Buffer.from(String(r))))),this[mr]={body:r,disturbed:!1,error:null},this.size=f,this.timeout=S,r instanceof Ys.default&&r.on("error",function(L){const x=L.name==="AbortError"?L:new Mn(`Invalid response body while trying to fetch ${l.url}: ${L.message}`,"system",L);l[mr].error=x})}xn.prototype={get body(){return this[mr].body},get bodyUsed(){return this[mr].disturbed},arrayBuffer(){return Nc.call(this).then(function(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)})},blob(){let r=this.headers&&this.headers.get("content-type")||"";return Nc.call(this).then(function(l){return Object.assign(new fu([],{type:r.toLowerCase()}),{[pr]:l})})},json(){var r=this;return Nc.call(this).then(function(l){try{return JSON.parse(l.toString())}catch(h){return xn.Promise.reject(new Mn(`invalid json response body at ${r.url} reason: ${h.message}`,"invalid-json"))}})},text(){return Nc.call(this).then(function(r){return r.toString()})},buffer(){return Nc.call(this)},textConverted(){var r=this;return Nc.call(this).then(function(l){return LX(l,r.headers)})}};Object.defineProperties(xn.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});x
2020-10-15 12:48:39 +02:00
`)),u.join(`
2020-10-26 01:01:36 +01:00
`)}function ck(e,t,n,s){const i=we(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,u=n==="complex64"?Kl(e):e;if(c>1)for(let p=0;p<i/o;p++){const m=p*o;for(let y=0;y<o;y++)a[y]=Math.max(a[y],jl(u[m+y],0,n).length)}return a}function jl(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(Ry))} + ${parseFloat(e[1].toFixed(Ry))}j`:Or(e)?s=`'${e}'`:n==="bool"?s=pT(e):s=parseFloat(e.toFixed(Ry)).toString(),Lo(s,t)}function pT(e){return e===0?"false":"true"}function Ad(e,t,n,s,i,o=!0){const a=n==="complex64"?2:1,c=t[0],u=t.length;if(u===0){if(n==="complex64"){const T=Kl(e);return[jl(T[0],0,n)]}return n==="bool"?[pT(e[0])]:[e[0].toString()]}if(u===1){if(c>dT){const v=ql*a;let N=Array.from(e.slice(0,v)),E=Array.from(e.slice((c-ql)*a,c*a));return n==="complex64"&&(N=Kl(N),E=Kl(E)),["["+N.map((D,F)=>jl(D,i[F],n)).join(", ")+", ..., "+E.map((D,F)=>jl(D,i[c-ql+F],n)).join(", ")+"]"]}const T=n==="complex64"?Kl(e):Array.from(e);return["["+T.map((v,N)=>jl(v,i[N],n)).join(", ")+"]"]}const p=t.slice(1),m=s.slice(1),y=s[0]*a,b=[];if(c>dT){for(let T=0;T<ql;T++){const v=T*y,N=v+y;b.push(...Ad(e.slice(v,N),p,n,m,i,!1))}b.push("...");for(let T=c-ql;T<c;T++){const v=T*y,N=v+y;b.push(...Ad(e.slice(v,N),p,n,m,i,T===c-1))}}else for(let T=0;T<c;T++){const v=T*y,N=v+y;b.push(...Ad(e.slice(v,N),p,n,m,i,T===c-1))}const w=u===2?",":"";b[0]="["+b[0]+w;for(let T=1;T<b.length-1;T++)b[T]=" "+b[T]+w;let I=`,
2020-10-15 12:48:39 +02:00
`;for(let T=2;T<u;T++)I+=`
2020-10-26 01:01:36 +01:00
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":I),b}function Kl(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class kr{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=we(e),n!=null){const s=n.length;k(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||So(t,this.size),this.strides=Ot(e)}set(e,...t){t.length===0&&(t=[0]),k(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const s of e){if(s<0||s>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let n=e[e.length-1];for(let s=0;s<e.length-1;++s)n+=this.strides[s]*e[s];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return vi().makeTensor(this.values,this.shape,this.dtype)}}let vi=null,ka=null,mT=null;function lk(e){vi=e}function hk(e){ka=e}function uk(e){mT=e}class Q{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=we(e),this.strides=Ot(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return ka.buffer(this.shape,this.dtype,e)}bufferSync(){return ka.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ls(this.shape,e)}arraySync(){return Ls(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=vi().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>Yl(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=vi().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Yl(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await vi().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;vi().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return ka.print(this,e)}clone(){return this.throwIfDisposed(),ka.clone(this)}toString(e=!1){const t=this.dataSync();return ak(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),ka.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),vi().makeVariable(this,e,t,n)}}Object.defineProperty(Q,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class Xl extends Q{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ot(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);vi().disposeTensor(this),this.dataId=e.dataId,vi().incRef(this,null)}dispose(){vi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Xl,Symbol.hasInstance,{value:e=>e instanceof Q&&e.assign!=null&&e.assign instanceof Function});(function(e){e.R0="R0",e.R1="R1",e.
Manifest JSON has weights with names: ${c.join(", ")}.`)}const u=i.reduce((w,I,T)=>(I&&w.push(T),w),[]),p=[];u.forEach(w=>{t[w].paths.forEach(I=>{const T=n+(n.endsWith("/")?"":"/")+I;p.push(T)})});const m=await e(p),y={};let b=0;return u.forEach(w=>{const I=t[w].paths.length;let T=0;for(let F=0;F<I;F++)T+=m[b+F].byteLength;const v=new ArrayBuffer(T),N=new Uint8Array(v);let E=0;for(let F=0;F<I;F++){const _=new Uint8Array(m[b+F]);N.set(_,E),E+=_.byteLength}const D=o[w];D.forEach(F=>{const _=v.slice(F.groupOffset,F.groupOffset+F.sizeBytes),B=Rd(_,[F.manifestEntry]);for(const U in B)y[U]=B[U]}),b+=I}),y}}const nF="application/octet-stream",sF="application/json";class Gy{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(k(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=C().platform.fetch,k(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&k(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(s)],{type:sF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:nF}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Ql(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(b){let w=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?w+=" 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.":w+=" Please make sure the server is serving valid JSON for this request.",new Error(w)}const n=t.modelTopology,s=t.weightsManifest,i=t.generatedBy,o=t.convertedBy,a=t.format,c=t.userDefinedMetadata;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let u,p;if(s!=null){const b=await this.loadWeights(s);[u,p]=b}const m={modelTopology:n,weightSpecs:u,weightData:p,userDefinedMetadata:c,generatedBy:i,convertedBy:o,format:a},y=t.modelInitializer;return y&&(m.modelInitializer=y),m}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=iF(t),i=this.weightPathPrefix||n,o=[];for(const p of e)o.push(...p.weights);const a=[],c=[];for(const p of e)for(const m of p.paths)this.weightUrlConverter!=null?c.push(this.weightUrlConverter(m)):a.push(i+m+s);this.weightUrlConverter&&a.push(...await Promise.all(c));const u=await FT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,Od(u)]}}Gy.URL_SCHEME_REGEX=/^https?:\/\//;function i
2020-10-15 12:48:39 +02:00
Actual: ${i}.
Expected: ${o}.`);for(let a=0;a<o.length;++a){const c=i[a],u=o[a];if(!n(c,u))throw new Error(`Arrays differ: actual[${a}] = ${c}, expected[${a}] = ${u}.
Actual: ${i}.
2020-10-26 01:01:36 +01:00
Expected: ${o}.`)}}function TF(e,t){e().then(()=>t.fail(),()=>t())}function AF(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Or(e)||Or(e[0])||Or(t)||Or(t[0])?Zy(e,n,(s,i)=>s==i):Zy(e,t,(s,i)=>eb(s,i,0))}function Qy(e,t,n){if(n==null&&(n=Ud()),!eb(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function eb(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function vF(e,t,n){for(let s=0;s<e.length;s++)if(e[s]<t||e[s]>n)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function NF(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var CF=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:XT,expectArraysClose:xF,testEpsilon:Ud,expectPromiseToFail:TF,expectArraysEqual:AF,expectNumbersClose:Qy,expectValuesInRange:vF,expectArrayBuffersEqual:NF});const JT="2.6.0";function RF(){C().set("PROD",!0)}function OF(){C().set("DEBUG",!0)}function EF(){C().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function sn(e){C().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}uk(sn);function DF(){V.disposeVariables()}function $s(){return V}function Bd(){return V.memory()}function kF(e){return V.profile(e)}function ee(e,t){return V.tidy(e,t)}function qe(e){const t=Zi(e);t.forEach(n=>n.dispose())}function Rn(e){return V.keep(e)}function FF(e){return V.time(e)}function ZT(e){return V.setBackend(e)}function _F(){return V.ready()}function WF(){return V.backendName}function $F(e){V.removeBackend(e)}function UF(e){return V.findBackend(e)}function BF(e){return V.findBackendFactory(e)}function tb(e,t,n=1){return V.registerBackend(e,t,n)}function QT(){return V.backend}function MF(e,t){C().setPlatform(e,t)}function PF(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.add(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,xe)}const be=P({add_:PF});function zF(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.floorDiv(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Wg)}const Md=P({floorDiv_:zF});function GF(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Bt(n,s),n.dtype==="int32"&&s.dtype==="int32")return Md(n,s);const i=(c,u)=>{const p=c.realDivide(n,s);return u([n,s]),p},o={a:n,b:s},a={};return V.runKernelFunc(i,o,null,Aa,a)}const _e=P({div_:GF});function VF(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.multiply(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Rl)}const X=P({mul_:VF});function HF(e){const t=W(e,"x","abs"),n={x:t};return V.runKernelFunc((s,i)=>(i([t]),t.dtype==="complex64"?s.complexAbs(t):s.abs(t)),n,null,fe)}const rn=P({abs_:HF});function YF(e){const t=W(e,"x","acos"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.acos(t);return i([t]),o},n,null,de)}const nb=P({acos_:YF});function qF(e){const t=W(e,"x","acosh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.acosh(t);return i([t]),o},n,null,Ae)}const sb=P({acosh_:qF});function jF(e){k(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),k(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((o,a)=>W(o,`tensors${a}`,"addN")),n=t[0];t.forEach(o=>{if(o.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!ot(o.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const s=(o,a)=>{const c=o.addN(t);return a(t),c},i=t;return V.runKernelFunc(s,i,null,Me)}const eA=P({addN_:jF});function ib(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function tA(e,t,n){const s=e.length+t.length,i=[];let o=0,a=0;for(let c=0;c<s;c++)n.indexOf(c)===-1?i.push(e[o++]):i.push(t[a++]);return i}function On(e,t){const n=[],s=e.length;for(let o=0;o<s;o++)t.indexOf(o)===-1&&n.pu
with dtype ${a.dtype}. `)});const s=(a,c)=>{const u=ft(t,n[0].shape)[0],p=Ur(n.map(b=>b.shape),u);if(we(p)===0)return en([],p);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);mb(m,u);const y=a.concat(n,u);return c(n),y},i=n,o={axis:t};return V.runKernelFunc(s,i,null,td,o)}const Mt=P({concat_:h_});function u_(e){const t=W(e,"x","sigmoid"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sigmoid(t);return i([o]),o},n,null,$l)}const Ei=P({sigmoid_:u_});function d_(e,t,n){const s=W(e,"x","slice");if(s.rank===0)throw new Error("Slicing scalar is not possible");const i=(c,u)=>{const[p,m]=$d(s,t,n);return Ky(s,p,m),u([s]),c.slice(s,p,m)},o={x:s},a={begin:t,size:n};return V.runKernelFunc(i,o,null,pd,a)}const st=P({slice_:d_});function p_(e){const t=W(e,"x","tanh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.tanh(t);return i([o]),o},n,null,Pl)}const Ma=P({tanh_:p_});function m_(e,t,n,s,i,o){const a=W(e,"forgetBias","basicLSTMCell"),c=W(t,"lstmKernel","basicLSTMCell"),u=W(n,"lstmBias","basicLSTMCell"),p=W(s,"data","basicLSTMCell"),m=W(i,"c","basicLSTMCell"),y=W(o,"h","basicLSTMCell"),b=Mt([p,y],1),w=at(b,c),I=be(w,u),T=I.shape[0],v=I.shape[1]/4,N=[T,v],E=st(I,[0,0],N),D=st(I,[0,v],N),F=st(I,[0,v*2],N),_=st(I,[0,v*3],N),B=be(X(Ei(E),Ma(D)),X(m,Ei(be(a,F)))),U=X(Ma(B),Ei(_));return[B,U]}const f_=P({basicLSTMCell_:m_});function g_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((u,p)=>u*p);k(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),k(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),k(s.shape[0]%i===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const o=u=>u.batchToSpaceND(s,t,n),a={x:s},c={blockShape:t,crops:n};return V.runKernelFunc(o,a,null,Ng,c)}const ah=P({batchToSpaceND_:g_});function y_(e){let t;return e.rank===0||e.rank===1?t=K(e,[1,1,1,e.size]):e.rank===2?t=K(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function b_(e,t,n,s,i,o){o==null&&(o=.001);const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),u=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;s!=null&&(m=W(s,"offset","batchNorm")),k(c.rank===u.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(m==null||c.rank===m.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(p==null||c.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const y=y_(a),b=(v,N)=>(N([y,c,u,p]),v.batchNorm(y,Vd(c),Vd(u),Vd(m),Vd(p),o)),w={x:y,scale:p,offset:m,mean:c,variance:u},I={varianceEpsilon:o},T=V.runKernelFunc(b,w,null,Ll,I);return K(T,a.shape)}function Vd(e){return e==null?null:e.rank===0?K(e,[e.size]):e.rank===1?e:e.rank===2?K(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?K(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const Ro=P({batchNorm_:b_});function w_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),u=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),k(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),k(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${c.rank}.`),k(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`),p!=null&&k(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),m!=null&&k(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${m.rank}.`),Ro(a,c,u,m,p,o)}const nA=P({batchNorm2d_:w_});function L_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),u=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),k(a.rank===3,()=>`Error in b
2020-10-15 12:48:39 +02:00
${i} and ${t} for depthToSpace with input shape
${s.shape}`),k(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
2020-10-26 01:01:36 +01:00
${s.shape}`),k(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${s.shape}`);const c=m=>m.depthToSpace(s,t,n),u={x:s},p={blockSize:t,dataFormat:n};return V.runKernelFunc(c,u,null,kx,p)}const bb=P({depthToSpace_:M_});function P_(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","depthwiseConv2d"),u=W(t,"filter","depthwiseConv2d");let p=c,m=!1;c.rank===3&&(m=!0,p=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),k(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),k(u.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`),k(p.shape[3]===u.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),a!=null&&k(Ut(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const y=(T,v)=>{o==null&&(o=[1,1]),k(on(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const N=Oi(p.shape,u.shape,n,o,s,a,!0),E=T.depthwiseConv2D(p,u,N);return v([p,u]),E},b={x:p,filter:u},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},I=V.runKernelFunc(y,b,null,Fg,w);return m?K(I,[I.shape[1],I.shape[2],I.shape[3]]):I}const Oo=P({depthwiseConv2d_:P_});function z_(e){const t=W(e,"x","diag"),n=i=>{const o=K(t,[t.size]),a=i.diag(o),c=[...e.shape,...e.shape];return K(a,c)},s={x:t};return V.runKernelFunc(n,s,null,Wx)}const G_=P({diag_:z_});function V_(e,t,n,s,i=[1,1],o="NHWC"){const a=W(e,"x","dilation2d"),c=W(t,"filter","dilation2d");k(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),k(c.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${c.rank}.`),k(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let u=a,p=!1;a.rank===3&&(u=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),p=!0);const m={x:u,filter:c},y={strides:n,pad:s,dilations:i},b=V.runKernel(nd,m,y);return p?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const wb=P({dilation2d_:V_});function Eo(e,t){const n=e.length,s=[];for(let i=0;i<n;i++){const o=n-1-i,a=e[o]||1,c=t[t.length-1-i]||1;c>1&&a===1&&s.unshift(o)}return s}function an(e,t){const n=[];for(let s=0;s<t.length;s++){const i=e[e.length-s-1],o=t.length-s-1,a=t[o];(i==null||i===1&&a>1)&&n.unshift(o)}return n}function nt(e,t){const n=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let o=e[e.length-i-1];o==null&&(o=1);let a=t[t.length-i-1];if(a==null&&(a=1),o===1)n.unshift(a);else if(a===1)n.unshift(o);else if(o!==a){const c=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(c)}else n.unshift(o)}return n}function H_(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Bt(n,s),nt(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,Ux)}const ni=P({equal_:H_});function Y_(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=nt(s.shape,i.shape),c=ch(s,a),u=ch(i,a);o.rank===1&&k(o.shape[0]===s.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&dt(o.shape,u.shape,"Error in where: ");const p=(y,b)=>{const w=y.select(o,c,u);return b([o]),w},m={condition:o,t:c,e:u};return V.runKernelFunc(p,m,null,oy)}const $n=P({where_:Y_});function q_(e){const t=W(e,"x","zerosLike"),n={x:t};return V.runKernelFunc(s=>s.zerosLike(t),n,null,py)}const et=P({zerosLike_:q_});function j_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Bt(n,s);const i=_e(n,s),o=et(i),a=ni(s,o);return $n(a,o,i)}const Lb=P({divNoNan_:j_});function K_(e,t){const n=W(e,"t1","dot"),s=W(t,"t2","dot");k((n.rank===1||n.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);const i=n.rank===1?n.size:n.shape[1],o=s.rank===1?s.size:s.shape[0];if(k(i===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${o}.`),n.rank=
2020-10-15 12:48:39 +02:00
rank ${o.rank}.`),k(Ut(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let a=o,c=!1;o.rank===3&&(c=!0,a=K(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const u=(b,w)=>{const I=b.localResponseNormalization4D(a,t,n,s,i);return w([a,I]),I},p={x:a},m={depthRadius:t,bias:n,alpha:s,beta:i},y=V.runKernelFunc(u,p,null,zg,m);return c?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const Tb=P({localResponseNormalization_:bW});function wW(e){const t=W(e,"x","log"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.log(t);return i([t]),o},n,null,Al)}const is=P({log_:wW});function LW(e){const t=W(e,"x","log1p"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.log1p(t);return i([t]),o},n,null,vl)}const Jd=P({log1p_:LW});function SW(e){return k(Er(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const s=W(t,"x","tf.grad",null),i=n!=null?W(n,"dy","tf.grad"):null;return V.tidy(()=>{const{value:o,grads:a}=V.gradients(()=>e(s),[s],i);return i!=null&&dt(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Zd(a),a[0]})}}function IW(e){return k(Er(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{k(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=Zl(t,"args","tf.grads",null),i=n!=null?W(n,"dy","tf.grads"):null;return V.tidy(()=>{const{value:o,grads:a}=V.gradients(()=>e(...s),s,i);return i!=null&&dt(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Zd(a),a})}}function xW(e){return k(Er(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{k(t instanceof Q,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),k(n==null||n instanceof Q,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=V.gradients(()=>e(t),[t],n);return Zd(s),{grad:s[0],value:i}}}function TW(e){return k(Er(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{k(Array.isArray(t)&&t.every(i=>i instanceof Q),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),k(n==null||n instanceof Q,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=V.gradients(()=>e(...t),t,n);return n!=null&&dt(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Zd(s.grads),s}}function Ab(e,t){k(Er(e),()=>"The f passed in variableGrads(f) must be a function"),k(t==null||Array.isArray(t)&&t.every(p=>p instanceof Xl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const p in V.registeredVariables)t.push(V.registeredVariables[p])}const s=n?t.filter(p=>!p.trainable):null,i=t.length;t=t.filter(p=>p.trainable),k(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const o=!0,{value:a,grads:c}=V.gradients(e,t,null,o);k(c.some(p=>p!=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(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const u={};return t.forEach((p,m)=>{c[m]!=null&&(u[p.name]=c[m])}),s!=null&&s.forEach(p=>u[p.name]=null),{value:a,grads:u}}function Di(e){return V.customGrad(e)}function Zd(e){const t=e.filter(n=>n==null).length;if(t>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
2020-10-26 01:01:36 +01:00
the f you passed encloses all operations that lead from x to y.`)}function AW(e){const t=W(e,"x","neg"),n={x:t};return V.runKernelFunc(s=>s.neg(t),n,null,jg)}const Pt=P({neg_:AW});function vW(e){const t=W(e,"x","softplus"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.softplus(t);return i([t]),o},n,null,Ul)}const Va=P({softplus_:vW});function NW(e){const t=W(e,"x","logSigmoid"),n=Di(s=>{const i=Pt(Va(Pt(s))),o=a=>{const c=X(a,Ei(Pt(s)));return c};return{value:i,gradFunc:o}});return n(t)}const gA=P({logSigmoid_:NW});function CW(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,u)=>{const p=ft(t,s.shape);let m=p;const y=_n(m,s.rank);let b=s;y!=null&&(b=Pe(s,y),m=Is(m.length,b.rank));const w=c.max(b,m);y!=null&&b.dispose();let I=w;if(n){const T=En(I.shape,ft(t,s.shape));I=K(I,T),w.dispose()}return u([s,I]),I},o={x:s},a={reductionIndices:t,keepDims:n};return V.runKernelFunc(i,o,null,Nl,a)}const Xn=P({max_:CW});function RW(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Bt(n,s);const i=(a,c)=>{const u=a.subtract(n,s);return c([n,s]),u},o={a:n,b:s};return V.runKernelFunc(i,o,null,Ml)}const Ce=P({sub_:RW});function OW(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=ve(s,"int32"));const i=(c,u)=>{u([s]);const p=ft(t,s.shape),m=_n(p,s.rank);let y=p,b=s;m!=null&&(b=Pe(s,m),y=Is(y.length,s.rank));let w=c.sum(b,y);if(n){const I=En(w.shape,p);w=K(w,I)}return w},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,ay,a)}const Ue=P({sum_:OW});function EW(e,t=-1){const n=W(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const s=(a,c)=>{const u=!0,p=Xn(e,t,!0),m=Ce(e,p),y=Ce(ve(m,"float32"),is(Ue(xs(m),t,u)));return c([y]),y},i={logits:n},o={axis:t};return V.runKernelFunc(s,i,null,Pg,o)}const Qd=P({logSoftmax_:EW});function DW(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=ft(t,s.shape),o=Xn(s,i,!0),a=Ce(s,o),c=xs(a),u=Ue(c,i),p=is(u),m=be(K(o,p.shape),p);if(n){const y=En(m.shape,i);return K(m,y)}return m}const vb=P({logSumExp_:DW});function kW(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");nt(n.shape,s.shape);const i={a:n,b:s};return V.runKernelFunc(o=>o.logicalAnd(n,s),i,null,Hx)}const Bs=P({logicalAnd_:kW});function FW(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return V.runKernelFunc(s=>s.logicalNot(t),n,null,od)}const ph=P({logicalNot_:FW});function _W(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");nt(n.shape,s.shape);const i={a:n,b:s};return V.runKernelFunc(o=>o.logicalOr(n,s),i,null,Yx)}const ep=P({logicalOr_:_W});function WW(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return nt(n.shape,s.shape),Bs(ep(e,t),ph(Bs(e,t)))}const yA=P({logicalXor_:WW});function $W(e,t,n,s,i){const o=W(e,"x","maxPool"),a=1;let c=o,u=!1;o.rank===3&&(u=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),k(c.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${c.rank}.`),k(on(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&k(Ut(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const p=(w,I)=>{const T=Wn(c.shape,t,n,1,s,i);let v;return T.filterWidth===1&&T.filterHeight===1&&ot(T.inShape,T.outShape)?v=c.clone():v=w.maxPool(c,T),I([c,v]),v},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=V.runKernelFunc(p,m,null,Cl,y);return u?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const mh=P({maxPool_:$W});function UW(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:sn("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","maxPool3d");let u=c,p=!1;c.rank===4&&(p=!0,u=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),k(u.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${u.rank}.`),k(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),k(on(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. G
2020-10-15 12:48:39 +02:00
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}else{const o=e;if(o.className==null||o.config==null)throw new j(`${s}: Improper config format: ${JSON.stringify(o)}.
'className' and 'config' must set.`);const a=o.className;let c,u;if(a in n?[c,u]=n[a]:a in Ms?[c,u]=Ms.className:a in t&&([c,u]=t[a]),c==null)throw new j(`Unknown ${s}: ${a}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2020-10-26 01:01:36 +01:00
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(u!=null){const p={};for(const w of Object.keys(Ms))p[w]=Ms[w];for(const w of Object.keys(n))p[w]=n[w];const m=o.config;m.customObjects=p;const y=Object.assign({},Ms);for(const w of Object.keys(n))Ms[w]=n[w];lw(o.config);const b=u(c,o.config,n,i);return Ms=Object.assign({},y),b}else{const p=Object.assign({},Ms);for(const y of Object.keys(n))Ms[y]=n[y];const m=new c(o.config);return Ms=Object.assign({},p),m}}}function dz(e,t){return e<t?-1:e>t?1:0}function vp(e,t){return-1*dz(e,t)}function BQ(e){switch(e){case"float32":return"float32";default:throw new j(`Invalid dtype: ${e}`)}}function MQ(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}function Hr(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function pz(e){if(e==null)throw new j(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function ec(e,t,n){if(n==null)return;if(e.indexOf(n)<0)throw new j(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function hw(e,t,n=0,s=Infinity){return vs(n>=0),vs(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function mn(e,t){Array.isArray(e)?(k(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>mn(n,`element ${s+1} of ${t}`))):k(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${yv(e)}.`)}function yv(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>yv(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function mz(e,t){let n=qn(),s;const i=(...o)=>{const a=qn();return a-n<t||(n=a,s=e(...o)),s};return i}function bv(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function PQ(...e){vs(e.length>0,"arrayOfValues is empty");for(const t of e)vs(Array.isArray(t),"one of the values is not an array"),vs(t.length>0,"one of the values is empty");return e.reduce((t,n)=>t.length===0?n.map(s=>[s]):n.map(s=>t.map(i=>[...i,s])).reduce((s,i)=>s.concat(i),[]),[])}function uw(e,t){return ee(()=>Sn(Ue(X(e,e),t,!0)))}class kh extends No{getConfig(){return{}}}class dw extends kh{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>{const t=uw(e,this.axis),n=jn(t,0,this.maxValue);return X(e,_e(n,be(cn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}dw.className="MaxNorm",ge(dw);class pw extends kh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>_e(e,be(cn(),uw(e,this.axis))))}getConfig(){return{axis:this.axis}}}pw.className="UnitNorm",ge(pw);class mw extends kh{apply(e){return Fi(e)}}mw.className="NonNeg",ge(mw);class fw extends kh{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>{const t=uw(e,this.axis),n=be(X(this.rate,jn(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,_e(n,be(cn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}fw.className="MinMaxNorm",ge(fw);const wv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ln(e){return cw(e)}function Lv(e,t={}){return Dh(e,Ws.getMap().classNameMap,t,"constraint")}function hn(e){if(e==null)return null;if(typeof e=="string"){const t=e in wv?wv[e]:e,n={className:t,config:{}};return Lv(n)}else return e instanceof kh?e:Lv(e)}function fz(e){return new dw(e)}function gz(e){return new pw(e)}function yz(){return new mw}function bz(e){return new fw(e)}var wz=Object.freeze({__pro
2020-10-15 12:48:39 +02:00
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Gs(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Rn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s<this.size();s++)e.push(s)}if(e.length===0)return en([],[0].concat(this.elementShape));const n=this.readMany(e);return Gs(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),as(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return en([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const n=this.readMany(t);return Gs(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Mt(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,_i(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const s=e.map(c=>(n+=c,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const i=n===0?0:t.size/n,o=[];ee(()=>{t=K(t,[1,n,i]);for(let c=0;c<e.length;++c){const u=c===0?0:s[c-1],p=[0,u,0],m=[1,e[c],i];o[c]=K(st(t,p,m),this.elementShape)}return o});const a=[];for(let c=0;c<e.length;c++)a[c]=c;this.writeMany(a,o)}}class tu{constructor(e,t,n,s=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(i=>{if(n!==i.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${i.dtype}`);Gs(t,i.shape,"TensorList shape mismatch: "),Rn(i)}),this.idTensor=Ne(0),this.maxNumElements=s,Rn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new tu([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);return Gs(e,this.elementShape,"TensorList shape mismatch: "),ee(()=>{const s=this.tensors.map(i=>K(i,e));return as(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");const n=this.tensors.pop();return Gs(n.shape,e,"TensorList shape mismatch: "),K(n,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Gs(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Rn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);return Gs(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Gs(this.elementShape,t.shape,"TensorList shape mismatch: "),Rn(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);return Gs(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?en([],[0].concat(this.elementShape)):ee(()=>{const s=e.map(i=>K(this.tensors[i],n));return as(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Gs(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?en([],[0].concat(this.elementShape)):ee(()=>{const n=this.tensors.map(s=>K(s,t));return Mt(n,0)})}}function WH(e,t,n){const s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);const i=e.s
tensor.shape[0], but sum of lengths is
2020-10-26 01:01:36 +01:00
${s}, and tensor's shape is: ${e.shape}`);const o=s===0?0:e.size/s,a=ee(()=>{const u=[];e=K(e,[1,s,o]);for(let p=0;p<t.length;++p){const m=p===0?0:i[p-1],y=[0,m,0],b=[1,t[p],o];u[p]=K(st(e,y,b),n)}return e.dispose(),u}),c=new tu([],n,e.dtype,t.length);for(let u=0;u<a.length;u++)c.setItem(u,a[u]);return c}const MH=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=R("thenBranch",e,t,n),i=R("elseBranch",e,t,n),o=R("cond",e,t,n),a=R("args",e,t,n),c=await o.data();return c[0]?n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap):n.functionMap[i].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const s=R("body",e,t,n),i=R("cond",e,t,n),o=R("args",e,t,n),a=await n.functionMap[i].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap),c=o.map(m=>m.id);let u=await a[0].data();a.forEach(m=>{!m.kept&&c.indexOf(m.id)===-1&&m.dispose()});let p=o;for(;u[0];){const m=p;p=await n.functionMap[s].executeFunctionAsync(p,n.tensorArrayMap,n.tensorListMap);const y=p.map(w=>w.id);m.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&y.indexOf(w.id)===-1&&w.dispose()});const b=await n.functionMap[i].executeFunctionAsync(p,n.tensorArrayMap,n.tensorListMap);u=await b[0].data(),b.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&y.indexOf(w.id)===-1&&w.dispose()})}return p}case"LoopCond":{const s=R("pred",e,t,n);return[hr(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=hr(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>Qn(i,t,n)!==void 0);if(s){const i=Qn(s,t,n);return[hr(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[hr(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[hr(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[hr(s)]}case"TensorArrayV3":{const s=R("size",e,t,n),i=R("dtype",e,t,n),o=R("elementShape",e,t,n),a=R("dynamicSize",e,t,n),c=R("clearAfterRead",e,t,n),u=R("identicalElementShapes",e,t,n),p=R("name",e,t,n),m=new _H(p,i,s,o,u,a,c);return n.addTensorArray(m),[m.idTensor,Ne(1)]}case"TensorArrayWriteV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.write(i,o),[a.idTensor]}case"TensorArrayReadV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=n.getTensorArray(s.id);return[o.read(i)]}case"TensorArrayGatherV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("dtype",e,t,n),a=n.getTensorArray(s.id);return[a.gather(i,o)]}case"TensorArrayScatterV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.scatter(i,o),[a.idTensor]}case"TensorArrayConcatV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id),o=R("dtype",e,t,n);return[i.concat(o)]}case"TensorArraySplitV3":{const s=R("tensorArrayId",e,t,n),i=R("tensor",e,t,n),o=R("lengths",e,t,n),a=n.getTensorArray(s.id);return a.split(o,i),[a.idTensor]}case"TensorArraySizeV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return[Ne(i.size(),"int32")]}case"TensorArrayCloseV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorList(s.id);return a.setItem(i,o),[a.idTensor]}case"TensorListGetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.getItem(i,o,a)]}case"TensorListScatterV2":case"TensorListScatter":{const s=R("indices",e,t,n),i=R("tensor",e,t,n),o=R("elementShape",e,t,n),a=R("numElements",e,t,n),c=UH(i,s,o,a);return n.addTensorList(c),[c.idTensor]}case"TensorListReserve":{const s=R("elementShape",e,t,n),i=R("elementDType",e,t,n),o=R("numElements",e,t,n),a=$H(s,i,o);return n.addTensorList(a),[a.idTensor]}case"TensorListGather":{const s=R("tensorListId",e,t,n),i=R("indices",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.gather(i
${e}`);let s;return this.size===Infinity||this.size==null?s=this.size:t?s=Math.ceil(this.size/e):s=Math.floor(this.size/e),hs(async()=>(await n.iterator()).columnMajorBatch(e,t,CY),s)}concatenate(e){const t=this;let n;return this.size===Infinity||e.size===Infinity?n=Infinity:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,hs(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,hs(async()=>(await t.iterator()).filter(s=>ee(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return hs(async()=>(await t.iterator()).map(n=>ee(()=>e(n))),this.size)}mapAsync(e){const t=this;return hs(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return hs(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=Infinity:n=null,hs(async()=>{const s=nu(async()=>({value:await t.iterator(),done:!1}));return u0(s.take(e))},n)}skip(e){const t=this;let n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,hs(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const s=this,i=qa(t||qn().toString());return hs(async()=>{let o=i.int32();return n&&(o+=i.int32()),(await s.iterator()).shuffle(e,o.toString())},this.size)}take(e){const t=this;let n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,hs(async()=>(await t.iterator()).take(e),n)}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()}}hc.MAX_BUFFER_SIZE=1e4;function hs(e,t=null){return new class extends hc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function vY(e){return hs(async()=>h0(e),e.length)}function NY(e){if(!lc(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=t==null?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(const n in e)t=t==null?e[n].size:Math.min(t,e[n].size);return hs(async()=>{const n=await c0(e,s=>{if(s instanceof hc)return{value:s.iterator(),recurse:!1};if(lc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return pY(n,Qr.SHORTEST)},t)}function CY(e){if(e===null)return null;const t=e[0];if(lY(t)){const n=RY(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function RY(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Q?as(e):en(e)}class f0 extends hc{constructor(e){super();this.input=e}async iterator(){const e=await this.input.iterator(),t=e.decodeUTF8(),n=t.split(`
`).map(s=>(s.endsWith("\r")&&(s=s.slice(0,-1)),s));return n}}const hm='"',su=Symbol("out"),g0=Symbol("field"),um=Symbol("quote"),sS=Symbol("quoteafterquote"),y0=Symbol("quoteinquote");class b0 extends hc{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new f0(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(k(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&k(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((s,i)=>(s[i]=s[i]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(k(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs)for(const s of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(s);if(i===-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){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value,s=this.parseRow(n,!1);return s}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),n={},s={};for(let i=0;i<this.fullColumnNames.length;i++){const o=this.fullColumnNames[i],a=this.columnConfigs?this.columnConfigs[o]:null;if(this.configuredColumnsOnly&&!a)continue;{const c=t[i];let u=null;if(c==="")if(a&&a.default!==void 0)u=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${o} is empty in this line: ${e}`);u=void 0}else{const p=Number(c);if(isNaN(p))a&&a.dtype==="bool"?u=this.getBoolean(c):u=c;else if(!a||!a.dtype)u=p;else switch(a.dtype){case"float32":u=p;break;case"int32":u=Math.floor(p);break;case"bool":u=this.getBoolean(c);break;default:u=p}}a&&a.isLabel?s[o]=u:n[o]=u}}return Object.keys(s).length===0?n:{xs:n,ys:s}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){const n=[];let s=0;const i=e.length;let o=su;for(let a=0;a<i;a++)switch(o){case su:switch(e.charAt(a)){case hm:s=a+1,o=um;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=su;break;default:o=g0,s=a;break}break;case g0:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=su,s=a+1;break;default:}break;case um:switch(e.charAt(a)){case hm:o=sS;break;default:}break;case sS:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=su,s=a+1;break;case hm:o=um;break;default:o=y0;break}break;case y0:switch(e.charAt(a)){case hm:o=um;break;default:}break;default:}if(o===sS?n.push(e.substring(s,i-1)):n.push(e.substring(s)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}}class w0 extends gn{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4|
2020-10-15 12:48:39 +02:00
============================
Hi there 👋. 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.
2020-10-26 01:01:36 +01:00
============================`));const s={};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){const s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,n,s){this.data.set(e,{values:t,dtype:s,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){const s=this.readSync(n.real.dataId),i=this.readSync(n.imag.dataId);return ir(s,i)}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if(e.dtype==="string")try{n=t.map(s=>Yl(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Qe(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return $s().makeTensorFromDataId(s,t,n,this)}disposeData(e){if(this.data.has(e)){const{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.data.has(t)){const n=this.data.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}async time(e){const t=qn();e();const n=qn()-t;return{kernelMs:n}}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(e,t,n,s){Te(e,"stridedSlice");const i=Wd(t,n,s);if(i.some(c=>c===0))return en([],i);const o=Qe(i,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;c++){const u=o.indexToLoc(c),p=new Array(u.length);for(let m=0;m<p.length;m++)p[m]=u[m]*s[m]+t[m];o.set(a.get(...p),...u)}return o.toTensor()}diag(e){const t=this.readSync(e.dataId),n=Qe([e.size,e.size],e.dtype),s=n.values;for(let i=0;i<t.length;i++)s[i*e.size+i]=t[i];return n.toTensor()}unstack(e,t){const n=e.shape[t],s=new Array(e.rank-1);let i=0;for(let u=0;u<e.rank;u++)u!==t&&(s[i++]=e.shape[u]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let u=0;u<c.length;u++)o[t]=u,c[u]=st(e,o,a).reshape(s);return c}reverse(e,t){Te(e,"reverse");const n=Qe(e.shape,e.dtype),s=this.bufferSync(e);for(let i=0;i<n.size;i++){const o=n.indexToLoc(i),a=o.slice();t.forEach(c=>a[c]=e.shape[c]-1-a[c]),n.set(s.get(...a),...o)}return n.toTensor()}neg(e){return Te(e,"neg"),X(Ne(-1),e)}addN(e){Te(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),n=Qe(e[0].shape,e[0].dtype),s=n.values;for(let i=0;i<e.length;i++){const o=t[i];for(let a=0;a<s.length;a++)s[a]+=o[a]}return n.toTensor()}softmax(e,t){const n=ft([t],e.shape),s=Xn(e,n),i=En(s.shape,n),o=Ce(e,s.reshape(i)),a=xs(o),c=this.sum(a,n).reshape(i);return _e(a,c)}pow(e,t){return Te([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.pow(n,s))}batchMatMul(e,t,n,s){Te([e,t],"matMul");const i=n?e.shape[1]:e.shape[2],o=n?e.shape[2]:e.shape[1],a=s?t.shape[1]:t.shape[2],c=e.shape[0],u=this.readSync(e.dataId),p=this.readSync(t.dataId),[m,y,b]=n?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],[w,I,T]=s?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],v=o*a,N=Qe([c,o,a],e.dtype),E=N.values,D=this.blockSize;for(let F=0;F<c;F++)for(let _=0;_<o;_+=D)for(let B=0;B<a;B+=D)for(let U=0;U<i;U+=D){const Y=Math.min(_+D,o),q=Math.min(B+D,a),J=Math.min(U+D,i);for(let oe=_;oe<Y;oe++)for(let ce=B;ce<q;ce++){let ue=0;for(let he=U;he<J;he++)ue+=u[F*m+oe*y+he*b]*p[he*w+ce*I+F*T];E[F*v+(oe*a+ce)]+=ue}}return N.toTensor()}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){let c=this.batchMatMul(e,t,n,s);return i&&(c=be(c,i)),o&&(c=iS(this,c,o,a)),c}floorDiv(e,t){Te([e,t],"floorDiv");const n=(i,o)=>Math.floor(i/o),s="int32";return this.broadcastedBinaryOp(e,t,s,n)}sum(e,t){Te(e,"sum"),ss("sum",t,e.rank);const[n,s]=On(e.shape,t),i=Cn(e.dtype,"int32"),o=ct(n,i),a=we(s),c=this.readSync(o.dataId),u=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=0;for(let b=0;b<a;++b)y+=u[m+b];c[p]
`),o=i.length.toString().length+2,a=i.map((y,b)=>Lo((b+1).toString(),o)+y);let c=0;for(let y=0;y<a.length;y++)c=Math.max(a[y].length,c);const u=a.slice(0,s-1),p=a.slice(s-1,s),m=a.slice(s);console.log(u.join(`
2020-10-15 12:48:39 +02:00
`)),console.log(t.split(`
2020-10-26 01:01:36 +01:00
`)[0]),console.log(`%c ${Lo(p[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
`))}function Pj(e){return ur(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function zj(e,t){if(Re(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function pS(e,t){if(Re(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Gj(e,t){const n=ur(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Re(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Vj(e,t){const n=ur(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Re(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Re(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function rte(){return C().getNumber("WEBGL_VERSION")===2?1:4}function Hj(e){return ur(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function Yj(e,t){const n=C().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const s=`[${e}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(e>n||t>n){const s=`[${e}x${t}]`,i=`[${n}x${n}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+i+".")}}function qj(e){return ur(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function K0(e,t,n,s,i,o,a){const c=e.getAttribLocation(t,n);return c===-1?!1:(Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Re(e,()=>e.vertexAttribPointer(c,i,e.FLOAT,!1,o,a)),Re(e,()=>e.enableVertexAttribArray(c)),!0)}function jj(e,t,n){J0(e,n),Re(e,()=>e.activeTexture(e.TEXTURE0+n)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function ote(e,t){J0(e,t),Re(e,()=>e.activeTexture(e.TEXTURE0+t)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Kj(e,t,n){return ur(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function Xj(e,t,n){return e.getUniformLocation(t,n)}function Jj(e,t,n,s){Re(e,()=>jj(e,t,s)),Re(e,()=>e.uniform1i(n,s))}function ate(e){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Re(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Re(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function mS(e,t,n){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Re(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function X0(e,t){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Re(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function mm(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Zj(e,t))}function Zj(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function ur(e,t,n){const s=Re(e,()=>t());if(s==null)throw new Error(n);return s}function J0(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(s<e.TEXTURE0||s>n){const i=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${i}.`)}}function gc(e,t=2){return we(e.slice(0,e.length-t))}function yc(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function fS(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[gc(e),...yc(e)]),t}function Qj(e,t=!1){let n=C().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?Sy(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=Rr(e);e=i.newShape}let s=we(e);if(e.length<=1&&s<=n)return[1,s];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e
2020-10-15 12:48:39 +02:00
void main() {
${n.join(`
`)}
float result = ${s};
setOutput(result);
}
`}}class SK{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((i,o)=>`T${o}`);const n=[];this.variableNames.forEach(i=>{n.push(`vec4 v${i} = get${i}AtOutCoords();`)});const s=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${n.join(`
`)}
vec4 result = ${s};
setOutput(result);
}
`}}class IK{constructor(e,t,n){this.variableNames=["A"];const{windowSize:s,batchSize:i,outSize:o}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[i,o];const a=t==="max"?">":"<",c=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${s}; i++) {
int inIdx = ${c};
float candidate = getA(batch, inIdx);
if (candidate ${a} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}}function eC(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function us(e,t){return t===1?[e]:eC(e,t)}function xK(e,t){if(e===1)return"rc";let n="";for(let s=0;s<e;s++)n+=t[s],s<e-1&&(n+=",");return n}function Un(){let e,t,n,s,i,o,a,c,u,p;return C().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",i="texture",o="outputColor",a="out vec4 outputColor;",c=`
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)
`,u="",p=`
#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)));
}
`):(e="",t="attribute",n="varying",s="varying",i="texture2D",o="gl_FragColor",a="",c=`
#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));
}
`,u=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,p=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-10-26 01:01:36 +01:00
`),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:i,output:o,defineOutput:a,defineSpecialNaN:c,defineSpecialInf:u,defineRound:p}}function Xo(e,t,n="index"){const s=Ot(t);return s.map((i,o)=>{const a=`int ${e[o]} = ${n} / ${i}`,c=o===s.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${i}`:`index -= ${e[o]} * ${i}`;return`${a}; ${c};`}).join("")}function wm(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function hte(e,t){if(e.length!==t.length)throw new Error(`Vectors to be dotted must be of the same length -got ${e.length} and ${t.length}`);const n=[],s=Math.floor(e.length/4),i=e.length%4;for(let o=0;o<s;o++){const a=e.slice(o*4,o*4+4),c=t.slice(o*4,o*4+4);n.push(`${wm(a)}, ${wm(c)}`)}if(i!==0){let o=e.slice(s*4),a=t.slice(s*4);o.length===1&&(o=o.map(c=>`float(${c})`),a=a.map(c=>`float(${c})`)),n.push(`${wm(o)}, ${wm(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function yS(e){const t=Ot(e).map(n=>n.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;
}
`}const tC=`
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;
}
`;const{getBroadcastDims:nC}=iw;function TK(e,t,n,s){const i=[];e.forEach(I=>{const T=we(I.shapeInfo.logicalShape);I.shapeInfo.isUniform?i.push(`uniform float ${I.name}${T>1?`[${T}]`:""};`):(i.push(`uniform sampler2D ${I.name};`),i.push(`uniform int offset${I.name};`))});const o=i.join(`
`),a=e.map(I=>AK(I,t,s)).join(`
`),c=t.texShape,u=Un(),p=CK(u);let m,y,b=EK(u);t.isPacked?(m=vK(t.logicalShape,c),y=OK(u)):(m=NK(t.logicalShape,c),y=RK(u)),s&&(b+=_K);const w=[b,p,y,o,m,a,n].join(`
2020-10-26 01:01:36 +01:00
`);return w}function bc(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return qK(e);case 1:return KK(e);case 2:return JK(e);case 3:return QK(e);case 4:return t5(e);case 5:return n5(e);case 6:return s5(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function sC(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return YK(e);case 1:return jK(e);case 2:return XK(e);case 3:return ZK(e);default:return e5(e)}}function AK(e,t,n=!1){let s="";n?s+=sC(e):s+=bc(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=i5(e,t):s+=r5(e,t)),s}function vK(e,t){switch(e.length){case 0:return iC();case 1:return WK(e,t);case 2:return VK(e,t);case 3:return UK(e,t);default:return MK(e,t)}}function NK(e,t){switch(e.length){case 0:return iC();case 1:return $K(e,t);case 2:return HK(e,t);case 3:return BK(e,t);case 4:return PK(e,t);case 5:return zK(e,t);case 6:return GK(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function CK(e){return`
2020-10-15 12:48:39 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function RK(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function OK(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function EK(e){const t=`${e.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
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);
}
${DK}
${kK}
${FK}
`;return t}const DK=`
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);
}
`,kK=`
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);
}
`,FK=`
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);
}
`,_K=`
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
`;function iC(){return`
int getOutputCoords() {
return 0;
}
`}function WK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?`
int getOutputCoords() {
return 2 * int(resultUV.x * ${n[1]}.0);
}
`:n[1]===1?`
int getOutputCoords() {
return 2 * int(resultUV.y * ${n[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
}
`}function $K(e,t){return t[0]===1?`
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;
}
`}function UK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),i=s*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec3(b, r, c);
}
2020-10-26 01:01:36 +01:00
`}function BK(e,t){const n=Xo(["r","c","d"],e);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;
${n}
return ivec3(r, c, d);
}
`}function MK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),i=s*Math.ceil(e[e.length-2]/2);let o=i,a="",c="b, r, c";for(let u=2;u<e.length-1;u++)o*=e[e.length-u-1],a=`
int b${u} = index / ${o};
index -= b${u} * ${o};
`+a,c=`b${u}, `+c;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
${a}
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec${e.length}(${c});
}
2020-10-26 01:01:36 +01:00
`}function PK(e,t){const n=Xo(["r","c","d","d2"],e);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;
${n}
return ivec4(r, c, d, d2);
}
2020-10-26 01:01:36 +01:00
`}function zK(e,t){const n=Xo(["r","c","d","d2","d3"],e);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;
${n}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
2020-10-26 01:01:36 +01:00
`}function GK(e,t){const n=Xo(["r","c","d","d2","d3","d4"],e);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;
${n}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function VK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ot(e,t))return`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
}
`;const s=Math.ceil(e[1]/2);return`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec2(r, c);
}
`}function HK(e,t){return ot(e,t)?`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
`:e[1]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
`:e[0]===1?`
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;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
}
2020-10-26 01:01:36 +01:00
`}function Jo(e){return`offset${e}`}function YK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Un();return`
2020-10-15 12:48:39 +02:00
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
}
`}function qK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${t};}`;const[s,i]=e.shapeInfo.texShape;if(s===1&&i===1)return`
float ${n}() {
return sampleTexture(${t}, halfCR);
}
2020-10-26 01:01:36 +01:00
`;const[o,a]=e.shapeInfo.texShape,c=Jo(t);return`
2020-10-15 12:48:39 +02:00
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
return sampleTexture(${t}, uv);
}
`}function jK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],o=Un();return`
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${o.texture2D}(${t}, uv);
}
`}function KK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${n}(int index) {
2020-10-26 01:01:36 +01:00
${wc(e)}
2020-10-15 12:48:39 +02:00
}
`;const s=e.shapeInfo.texShape,i=s[0],o=s[1];if(o===1&&i===1)return`
float ${n}(int index) {
return sampleTexture(${t}, halfCR);
}
2020-10-26 01:01:36 +01:00
`;const a=Jo(t);return o===1?`
2020-10-15 12:48:39 +02:00
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${i}.0);
return sampleTexture(${t}, uv);
}
`:i===1?`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${a}) + 0.5) / ${o}.0, 0.5);
return sampleTexture(${t}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = uvFromFlat(${i}, ${o}, index + ${a});
return sampleTexture(${t}, uv);
}
`}function XK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=i[0],a=i[1],c=Un();if(i!=null&&ot(t,i))return`
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${o}.0);
return ${c.texture2D}(${n}, uv);
}
`;const u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],p=Math.ceil(t[1]/2);return`
vec4 ${s}(int row, int col) {
vec2 uv = packedUVfrom2D(${p}, ${u[0]}, ${u[1]}, row, col);
return ${c.texture2D}(${n}, uv);
}
`}function JK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(i!=null&&ot(t,i)){const y=i[0],b=i[1];return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`}const{newShape:o,keptDims:a}=Rr(t),c=o;if(c.length<t.length){const y=Lc(e,c),b=["row","col"];return`
${bc(y)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col) {
2020-10-26 01:01:36 +01:00
return ${s}(${Sc(b,a)});
2020-10-15 12:48:39 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
2020-10-26 01:01:36 +01:00
${wc(e)}
2020-10-15 12:48:39 +02:00
}
2020-10-26 01:01:36 +01:00
`;const u=i[0],p=i[1],m=Jo(n);return p===1?`
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
return sampleTexture(${n}, uv);
}
`:u===1?`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5);
return sampleTexture(${n}, uv);
}
`:`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${t[1]} + col + ${m};
vec2 uv = uvFromFlat(${u}, ${p}, index);
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`}function ZK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const y=t.slice(1),b=[1,2],w=Lc(e,y),I=["b","row","col"];return`
2020-10-15 12:48:39 +02:00
${sC(w)}
vec4 ${s}(int b, int row, int col) {
2020-10-26 01:01:36 +01:00
return ${s}(${Sc(I,b)});
2020-10-15 12:48:39 +02:00
}
`}const a=o[0],c=o[1],u=Math.ceil(t[2]/2),p=u*Math.ceil(t[1]/2),m=Un();return`
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${a}, ${c}, ${p}, ${u}, b, row, col);
return ${m.texture2D}(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`}function QK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[1]*t[2],o=t[2],{newShape:a,keptDims:c}=Rr(t),u=a;if(u.length<t.length){const I=Lc(e,u),T=["row","col","depth"];return`
${bc(I)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth) {
2020-10-26 01:01:36 +01:00
return ${s}(${Sc(T,c)});
2020-10-15 12:48:39 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${i}, ${o}, 1)));
2020-10-26 01:01:36 +01:00
${wc(e)}
2020-10-15 12:48:39 +02:00
}
`;const p=e.shapeInfo.texShape,m=p[0],y=p[1],b=e.shapeInfo.flatOffset;if(y===i&&b==null)return`
float ${s}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${y}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`;if(y===o&&b==null)return`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${y}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`;const w=Jo(n);return`
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} + depth + ${w};
vec2 uv = uvFromFlat(${m}, ${y}, index);
return sampleTexture(${n}, uv);
}
`}function e5(e){const t=e.shapeInfo.logicalShape,n=t.length,s=e.name,i="get"+s.charAt(0).toUpperCase()+s.slice(1),o=e.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],c=a[0],u=a[1],p=Math.ceil(t[n-1]/2);let m=p*Math.ceil(t[n-2]/2),y="int b, int row, int col",b=`b * ${m} + (row / 2) * ${p} + (col / 2)`;for(let I=2;I<n-1;I++)y=`int b${I}, `+y,m*=t[n-I-1],b=`b${I} * ${m} + `+b;const w=Un();return`
vec4 ${i}(${y}) {
int index = ${b};
int texR = index / ${u};
int texC = index - texR * ${u};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${c});
return ${w.texture2D}(${s}, uv);
}
2020-10-26 01:01:36 +01:00
`}function t5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[3],o=t[2]*i,a=t[1]*o,{newShape:c,keptDims:u}=Rr(t);if(c.length<t.length){const I=Lc(e,c),T=["row","col","depth","depth2"];return`
${bc(I)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-26 01:01:36 +01:00
return ${s}(${Sc(T,u)});
2020-10-15 12:48:39 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${a}, ${o}, ${i}, 1)));
2020-10-26 01:01:36 +01:00
${wc(e)}
2020-10-15 12:48:39 +02:00
}
`;const p=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,y=m[0],b=m[1];if(b===a&&p==null)return`
float ${s}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${o}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
`;if(b===i&&p==null)return`
float ${s}(int row, int col, int depth, int depth2) {
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) /
vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`;const w=Jo(n);return`
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} +
depth * ${i} + depth2;
vec2 uv = uvFromFlat(${y}, ${b}, index + ${w});
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`}function n5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[4],o=t[3]*i,a=t[2]*o,c=t[1]*a,{newShape:u,keptDims:p}=Rr(t);if(u.length<t.length){const T=Lc(e,u),v=["row","col","depth","depth2","depth3"];return`
${bc(T)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-26 01:01:36 +01:00
return ${s}(${Sc(v,p)});
2020-10-15 12:48:39 +02:00
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${c}, ${a}, ${o}, ${i})) +
depth3;
2020-10-26 01:01:36 +01:00
${wc(e)}
2020-10-15 12:48:39 +02:00
}
`;const m=e.shapeInfo.flatOffset,y=e.shapeInfo.texShape,b=y[0],w=y[1];if(w===c&&m==null)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${a}, ${o}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${w}.0, ${b}.0);
return sampleTexture(${n}, uv);
}
`;if(w===i&&m==null)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${w}.0, ${b}.0);
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`;const I=Jo(n);return`
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${c} + col * ${a} + depth * ${o} +
depth2 * ${i} + depth3 + ${I};
vec2 uv = uvFromFlat(${b}, ${w}, index);
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`}function s5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=Rr(t);if(i.length<t.length){const v=Lc(e,i),N=["row","col","depth","depth2","depth3","depth4"];return`
${bc(v)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
2020-10-26 01:01:36 +01:00
return ${s}(${Sc(N,o)});
2020-10-15 12:48:39 +02:00
}
`}const a=t[5],c=t[4]*a,u=t[3]*c,p=t[2]*u,m=t[1]*p;if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${m}, ${p}, ${u}, ${c})) +
dot(
vec2(depth3, depth4),
vec2(${a}, 1)));
2020-10-26 01:01:36 +01:00
${wc(e)}
2020-10-15 12:48:39 +02:00
}
`;const y=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],I=b[1];if(I===m&&y==null)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${p}, ${u}, ${c}, ${a})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${I}.0, ${w}.0);
return sampleTexture(${n}, uv);
}
`;if(I===a&&y==null)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${I}.0, ${w}.0);
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`;const T=Jo(n);return`
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${m} + col * ${p} + depth * ${u} +
depth2 * ${c} + depth3 * ${a} + depth4 + ${T};
vec2 uv = uvFromFlat(${w}, ${I}, index);
return sampleTexture(${n}, uv);
}
2020-10-26 01:01:36 +01:00
`}function wc(e){const t=e.name,n=we(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
2020-10-15 12:48:39 +02:00
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function i5(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),i="get"+s+"AtOutCoords",o=e.shapeInfo.logicalShape.length,a=t.logicalShape.length,c=nC(e.shapeInfo.logicalShape,t.logicalShape),u=Et(a),p=a-o;let m;const y=["x","y","z","w","u","v"];o===0?m="":a<2&&c.length>=1?m="coords = 0;":m=c.map(E=>`coords.${y[E+p]} = 0;`).join(`
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((E,D)=>`coords.${y[D+p]}`).join(", ");let w="return outputValue;";const I=we(e.shapeInfo.logicalShape),T=I===1,v=we(t.logicalShape),N=v===1;if(o===1&&!T&&!N)w=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(T&&!N)a===1?w=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:w=`
return vec4(outputValue.x);
`;else if(c.length){const E=o-2,D=o-1;c.indexOf(E)>-1&&c.indexOf(D)>-1?w="return vec4(outputValue.x);":c.indexOf(E)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(D)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${i}() {
${u} coords = getOutputCoords();
${m}
vec4 outputValue = get${s}(${b});
${w}
}
`}function r5(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),i="get"+s+"AtOutCoords",o=t.texShape,a=e.shapeInfo.texShape,c=e.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&c===u&&e.shapeInfo.flatOffset==null&&ot(a,o))return`
float ${i}() {
return sampleTexture(${n}, resultUV);
}
`;const p=Et(u),m=nC(e.shapeInfo.logicalShape,t.logicalShape),y=u-c;let b;const w=["x","y","z","w","u","v"];c===0?b="":u<2&&m.length>=1?b="coords = 0;":b=m.map(T=>`coords.${w[T+y]} = 0;`).join(`
`);let I="";return u<2&&c>0?I="coords":I=e.shapeInfo.logicalShape.map((T,v)=>`coords.${w[v+y]}`).join(", "),`
float ${i}() {
${p} coords = getOutputCoords();
${b}
return get${s}(${I});
}
2020-10-26 01:01:36 +01:00
`}function Et(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function Lc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Sc(e,t){return t.map(n=>e[n]).join(", ")}class o5{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],o=Math.ceil(i/t);this.outputShape=e.slice(0,-1),o>1&&this.outputShape.push(o),s||this.variableNames.push("bestIndicesA");const a=this.outputShape,c=a.length,u=Et(c),p=us("coords",c);let m,y;if(o===1){y=c+1;const U=Et(y);m=`
2020-10-15 12:48:39 +02:00
${U} sourceLocR = ${U}(${p.join()}, 0);
++${p[c-1]};
${U} sourceLocG = ${U}(${p.join()}, 0);
++${p[c-2]};
${U} sourceLocA = ${U}(${p.join()}, 0);
--${p[c-1]};
${U} sourceLocB = ${U}(${p.join()}, 0);
--${p[c-2]};`}else y=c,m=`
${u} sourceLocR = coords;
++${p[c-1]};
${u} sourceLocG = coords;
++${p[c-2]};
${u} sourceLocA = coords;
--${p[c-1]};
${u} sourceLocB = coords;
--${p[c-2]};`;const b=["x","y","z","w","u","v"].slice(0,y),w="."+b[y-1],I=b.map(U=>"int "+U),T=us("sourceLocR",y-1).concat("inIdx.r"),v=us("sourceLocG",y-1).concat("inIdx.g"),N=us("sourceLocB",y-1).concat("inIdx.b"),E=us("sourceLocA",y-1).concat("inIdx.a"),D=n==="max"?"greaterThan":"lessThan",F=s?"":`
inIdx = round(vec4(getBestIndicesAChannel(${T.join()}),
getBestIndicesAChannel(${v.join()}),
getBestIndicesAChannel(${N.join()}),
getBestIndicesAChannel(${E.join()})));`,_=`vec4(
getAChannel(${T.join()}),
hasNextCol ? getAChannel(${v.join()}) : 0.,
hasNextRow ? getAChannel(${N.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${E.join()}) : 0.)`,B=s?"":`
float getBestIndicesAChannel(${I.join()}) {
return getChannel(getBestIndicesA(${b.join()}),
vec2(${b.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${I.join()}) {
return getChannel(getA(${b.join()}),
vec2(${b.slice(-2).join()}));
}
${B}
void main() {
${u} coords = getOutputCoords();
bool hasNextCol = ${p[c-1]} < ${a[c-1]-1};
bool hasNextRow = ${p[c-2]} < ${a[c-2]-1};
${m}
ivec4 srcIdx = ivec4(sourceLocR${w}, sourceLocG${w},
sourceLocB${w}, sourceLocA${w}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${_};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${F}
vec4 candidate = ${_};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${D}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`}}class a5{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,c=e.effectiveFilterHeight,u=e.effectiveFilterWidth,p=c-1-e.padInfo.top,m=u-1-e.padInfo.left,y=1/(t*n);this.userCode=`
const ivec2 pads = ivec2(${p}, ${m});
const float avgMultiplier = float(${y});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${c};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${u};
wC+= ${a}) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`}}class c5{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=e.dilationDepth,u=e.dilationHeight,p=e.dilationWidth,m=e.effectiveFilterDepth,y=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,I=y-1-e.padInfo.top,T=b-1-e.padInfo.left,v=1/(t*n*s);this.userCode=`
const ivec3 pads = ivec3(${w}, ${I}, ${T});
const float avgMultiplier = float(${v});
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;
for (int wD = 0; wD < ${m};
wD += ${c}) {
float dyD = float(dyDCorner + wD) / ${i}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${y};
wR += ${u}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${b};
wC += ${p}) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`}}const rC={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class oC{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=nt(t,n),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}}const aC=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,bS="return a + b;",wS="return a - b;",cC="return a * b;",l5=`
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;
}
`,h5=`
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);
`,ute="return (a - b) * (a - b);",u5="return float(a == b);",d5="return float(a != b);",p5="return float(a < b);",m5="return float(a <= b);",f5="return float(a > b);",g5="return float(a >= b);",y5="return float(a >= 1.0 && b >= 1.0);",b5="return float(a >= 1.0 || b >= 1.0);",w5=aC+`
return max(a, b);
`,L5=aC+`
return min(a, b);
`,S5=`if (b == 0.0) return NAN;
2020-10-26 01:01:36 +01:00
return mod(a, b);`,I5="return (b >= 1.0) ? a : a * (b + 1.0);",lC="return (a < 0.) ? b * a : a;";class un{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=nt(t,n),this.userCode=`
2020-10-15 12:48:39 +02:00
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}}const Lm=`
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;
`,x5=`
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);
`,T5=`
// 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));
`+Lm+`
return result;
`,hC=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,A5=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,v5=`
return vec4(equal(a, b));
`,N5=`
return vec4(notEqual(a, b));
`,C5=`
return vec4(lessThan(a, b));
`,R5=`
return vec4(lessThanEqual(a, b));
`,O5=`
return vec4(greaterThan(a, b));
`,E5=`
return vec4(greaterThanEqual(a, b));
`,D5=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,k5=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,F5=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Lm+`
return result;
`,_5=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Lm+`
return result;
`,W5=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+Lm+`
return result;
`;class to{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=nt(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||we(this.outputShape)===1)o=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{const a=Et(i);if(o=`
${a} coords = getOutputCoords();
`,i===1)o+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{const c=us("coords",i);o+=`
bool nextRowOutOfBounds =
(${c[i-2]} + 1) >= ${this.outputShape[i-2]};
bool nextColOutOfBounds =
(${c[i-1]} + 1) >= ${this.outputShape[i-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${o}
setOutput(result);
}
`}}class $5{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode=`
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`}getCustomSetupFunc(e,t){return(n,s)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class U5{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
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)));
}
`}getCustomSetupFunc(e,t){return(n,s)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class B5{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// 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))
);
}
`}}class M5{constructor(e){this.outputShape=[],this.outputShape=Ur(e,1),this.variableNames=e.map((o,a)=>`T${a}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let o=1;o<t.length;o++)t[o]=t[o-1]+e[o][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let o=1;o<t.length;o++){const a=t[o-1];n.push(`else if (yC < ${t[o]}) setOutput(getT${o}(yR, yC-${a}));`)}const s=t.length,i=t[t.length-1];n.push(`else setOutput(getT${s}(yR, yC-${i}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${n.join(`
`)}
}
`}}class P5{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Ur(e,t);const n=this.outputShape,s=n.length,i=Et(s),o=us("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((I,T)=>`T${T}`);const c=new Array(e.length-1);c[0]=e[0][t];for(let I=1;I<c.length;I++)c[I]=c[I-1]+e[I][t];const u=a[t],p=a.slice(-2),m=a.join();let y=`if (${u} < ${c[0]}) {
return getChannel(
getT0(${m}), vec2(${p.join()}));
}`;for(let I=1;I<c.length;I++){const T=c[I-1];y+=`
if (${u} < ${c[I]} && ${u} >= ${c[I-1]}) {
return getChannel(
getT${I}(${Sm(a,u,T)}),
vec2(${Sm(p,u,T)}));
}`}const b=c.length,w=c[c.length-1];y+=`
return getChannel(
getT${b}(${Sm(a,u,w)}),
vec2(${Sm(p,u,w)}));`,this.userCode=`
float getValue(${a.map(I=>"int "+I)}) {
${y}
}
void main() {
${i} coords = getOutputCoords();
vec4 result = vec4(getValue(${o}), 0., 0., 0.);
${o[s-1]} = ${o[s-1]} + 1;
if (${o[s-1]} < ${n[s-1]}) {
result.g = getValue(${o});
}
${o[s-2]} = ${o[s-2]} + 1;
if (${o[s-2]} < ${n[s-2]}) {
result.a = getValue(${o});
}
${o[s-1]} = ${o[s-1]} - 1;
if (${o[s-2]} < ${n[s-2]} &&
${o[s-1]} < ${n[s-1]}) {
result.b = getValue(${o});
}
setOutput(result);
}
`}}function Sm(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}class z5{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,i=e.padInfo.left,o=e.dataFormat==="channelsLast";this.userCode=`
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;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${o}) {
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);
}
`}}class G5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=e.dataFormat==="channelsLast",a=t-1-e.padInfo.top,c=n-1-e.padInfo.left,u=o?1:2,p=o?2:3,m=o?3:1;this.userCode=`
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${m}];
ivec2 dyCorner = ivec2(coords[${u}], coords[${p}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${o}) {
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);
}
`}}class V5{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,i=e.padInfo.front,o=e.padInfo.top,a=e.padInfo.left;this.userCode=`
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${n} - ${o};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${a};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class H5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=t-1-e.padInfo.front,u=n-1-e.padInfo.top,p=s-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${c}, ${u}, ${p});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${i}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${n} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class Y5{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,i=e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${o} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`}}class q5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.top,a=n-1-e.padInfo.left,c=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
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;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${c}; dm++) {
int d2 = d1 * ${c} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}}class uC{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,o=e.padInfo.left,a=e.strideHeight,c=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,m=e.filterHeight,y=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,I=e.dataFormat==="channelsLast",T=I?1:2,v=I?2:3,N=I?3:1;let E="",D="";n&&(s?E=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:E=`
float activation(float x) {
${n}
}
`,D="result = activation(result);");const F=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${E}
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${i}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${N}];
ivec2 xRCCorner =
ivec2(coords[${T}], coords[${v}]) * strides - pads;
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;
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${u};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${y}; wC++) {
int xC = xCCorner + wC * ${p};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${b}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${I}) {
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);
}
}
if (${w===1}) {
if (${I}) {
dotProd +=
getX(batch, xR, xC, ${b}) *
getW(wR, wC, ${b}, d2);
} else {
dotProd +=
getX(batch, ${b}, xR, xC) *
getW(wR, wC, ${b}, d2);
}
} else if (${w===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${b}, d2),
getW(wR, wC, ${b} + 1, d2)
);
if (${I}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${b}),
getX(batch, xR, xC, ${b} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${b}, xR, xC),
getX(batch, ${b} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${w===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${b}, d2),
getW(wR, wC, ${b} + 1, d2),
getW(wR, wC, ${b} + 2, d2)
);
if (${I}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${b}),
getX(batch, xR, xC, ${b} + 1),
getX(batch, xR, xC, ${b} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${b}, xR, xC),
getX(batch, ${b} + 1, xR, xC),
getX(batch, ${b} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${F}
${D}
setOutput(result);
}
`}}class j5{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=e.dilationDepth,u=e.dilationHeight,p=e.dilationWidth,m=e.filterDepth,y=e.filterHeight,b=e.filterWidth,w=Math.floor(e.inChannels/4)*4,I=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${i}, ${o}, ${a});
const ivec3 pads = ivec3(${t}, ${n}, ${s});
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;
for (int wF = 0; wF < ${m}; wF++) {
int xF = xFCorner + wF * ${c};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${y}; wR++) {
int xR = xRCorner + wR * ${u};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${b}; wC++) {
int xC = xCCorner + wC * ${p};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${w}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${I===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${w}) *
getW(wF, wR, wC, ${w}, d2);
} else if (${I===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${w}),
getX(batch, xF, xR, xC, ${w} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${w}, d2),
getW(wF, wR, wC, ${w} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${I===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${w}),
getX(batch, xF, xR, xC, ${w} + 1),
getX(batch, xF, xR, xC, ${w} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${w}, d2),
getW(wF, wR, wC, ${w} + 1, d2),
getW(wF, wR, wC, ${w} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`}}class dC{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.inHeight,o=e.inWidth,a=e.padInfo.top,c=e.padInfo.left,u=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,I=e.outChannels/e.inChannels;let T="",v="";n&&(s?T=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:T=`
float activation(float x) {
${n}
}
`,v="result = activation(result);");const N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${T}
const ivec2 strides = ivec2(${u}, ${p});
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${I};
int q = d2 - d1 * ${I};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${b}; wR++) {
int xR = xRCorner + wR * ${m};
if (xR < 0 || xR >= ${i}) {
continue;
}
for (int wC = 0; wC < ${w}; wC++) {
int xC = xCCorner + wC * ${y};
if (xC < 0 || xC >= ${o}) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${N}
${v}
setOutput(result);
}
`}}class pC{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const i=e.inHeight,o=e.inWidth,a=e.padInfo.top,c=e.padInfo.left,u=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,I=w;let T="int xR; int xC; int xCOffset;";for(let D=0;D<b;D++)for(let F=0;F<w;F++)T+=`
vec4 xTexelR${D}C${F*2} = vec4(0.);
vec4 wR${D}C${F} = vec4(0.);
vec4 xR${D}C${F} = vec4(0.);`;for(let D=0;D<b;D++)for(let F=0;F<I;F++){const _=F*2;if(T+=`
xR = xRCorner + ${D*m};
xC = xCCorner + ${_*y};
`,p===1){if(_<w&&(c%2===1?T+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${o}) {
xTexelR${D}C${_}.zw = vec2(0.);
}
} else {
xTexelR${D}C${_} = vec4(0.);
}
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${o}) {
previous.zw = vec2(0.);
}
xR${D}C${_} = vec4(previous.zw, xTexelR${D}C${_}.xy);
} else {
xR${D}C${_} = vec4(0, 0, xTexelR${D}C${_}.xy);
}
`:T+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xC, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
xR${D}C${_} = xTexelR${D}C${_};
`,_+1<w)){const B=c%2===0?Sy(y):y;y%2===0&&c%2===1||y%2!==0&&c%2!==1?(T+=`
xCOffset = xC + ${c%2} + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
}
`,y>1&&(T+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
`),T+=`
xR${D}C${_+1} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.xy);
`):T+=`
xCOffset = xC + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
}
xR${D}C${_+1} = xTexelR${D}C${_+2};
`}}else _<w&&(T+=`
if(xR >= 0 && xR < ${i}) {
`,c%2===1?(T+=`
xCOffset = xC + 1 - ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${D}C${_+2} = vec4(0.);
}
xR${D}C${_} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.zw);
`,_+1<w&&(T+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
final = getX(batch, xR, xCOffset, d1);
}
xR${D}C${_+1} = vec4(xTexelR${D}C${_+2}.xy, final.xy);
`)):(T+=`
if(xC >= 0 && xC < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xC, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
xCOffset = xC + ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_+2} = vec4(0.);
}
xR${D}C${_} = vec4(
xTexelR${D}C${_}.xy, xTexelR${D}C${_+2}.xy);
`,_+1<w&&(T+=`
xR${D}C${_+1} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.zw);
`)),T+="}");_<w&&(T+=`
vec4 wTexelR${D}C${_} = getW(${D}, ${_}, d1, q);
wR${D}C${_} = vec4(wTexelR${D}C${_}.xz, wTexelR${D}C${_}.xz);
`,_+1<w&&(T+=`
vec4 wTexelR${D}C${_+1} = getW(${D}, ${_+1}, d1, q);
wR${D}C${_+1} =
vec4(wTexelR${D}C${_+1}.xz, wTexelR${D}C${_+1}.xz);`))}for(let D=0;D<b;D++)for(let F=0;F<w;F++)T+=`dotProd += xR${D}C${F} * wR${D}C${F};`;let v="",N="";n&&(s?v=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:v=`vec4 activation(vec4 x) {
${n}
}`,N="result = activation(result);");const E=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${v}
const ivec2 strides = ivec2(${u}, ${p});
const ivec2 pads = ivec2(${a}, ${c});
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.);
${T}
vec4 result = dotProd;
${E}
${N}
setOutput(result);
}
`}}class K5{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,u]=e,[p]=t,[m,y]=n;this.outputShape=[p,m,y,u];const b=s==="bilinear"?1:0,[w,I]=[`${a-1}.0`,`${c-1}.0`],[T,v,N]=m>1?[`${(a-1)/(m-1)}`,"(y2-y1) * height_ratio",`y1*${w} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${w}`],[E,D,F]=y>1?[`${(c-1)/(y-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(${T});
const float width_ratio = float(${E});
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));
if(bInd < 0 || bInd >= ${o}) {
return;
}
float height_scale = ${v};
float width_scale = ${D};
float in_y = ${N};
if( in_y < 0.0 || in_y > ${w} ) {
setOutput(float(${i}));
return;
}
float in_x = ${F};
if( in_x < 0.0 || in_x > ${I} ) {
setOutput(float(${i}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${b} == 1) {
// 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);
}
}
`}}class mC{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${fC(s,"coords")})`,o=e[e.length-1];let a="",c="";t?(a=n?`end != ${o-1}`:"end != 0",c=n?"end + 1":"end - 1"):(a=n?`end + pow2 < ${o}`:"end >= pow2",c=n?"end + pow2":"end - pow2"),this.userCode=`
uniform float index;
void main() {
${Et(s)} coords = getOutputCoords();
int end = ${gC(s,"coords")};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${a}) {
int idx = ${c};
${gC(s,"coords")} = idx;
val += getX(${fC(s,"coords")});
}
setOutput(val);
}
`}getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}}function fC(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function gC(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}class X5{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=au.DENSE;const t=lu(e),n=Un();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-26 01:01:36 +01:00
${Xo(["r","c","d"],e)}
2020-10-15 12:48:39 +02:00
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
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);
}
${n.output} = result;
}
`}}class J5{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=au.DENSE;const t=lu(e),n=Un();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-26 01:01:36 +01:00
${Xo(["r","c","d"],e)}
2020-10-15 12:48:39 +02:00
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
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));
}
${n.output} = result;
}
`}}class Z5{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`}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 Q5{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`}}class e8{constructor(e){this.variableNames=["A"],this.outTexUsage=Cs.DOWNLOAD;const t=Un();this.outputShape=e,this.userCode=`
${tC}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}}class t8{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Cs.DOWNLOAD;const t=Un();this.outputShape=e,this.userCode=`
${tC}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}}class n8{constructor(e,t,n=!1){this.variableNames=["A"];const s=Un(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
${yS(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / ${o};
int c = imod(flatIndex, ${o});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${o}.0, ${i}.0);
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];
}
${s.output} = vec4(${a}, 0., 0., 0.);
}
`}}class s8{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Un(),[i,o]=t;this.outputShape=e;let a="",c="result";n&&(c="floor(result * 255. + 0.5)");for(let u=0;u<=1;u++)for(let p=0;p<=1;p++){const m=u*2+p;a+=`
localCoords = coords;
if(localCoords[2] + ${p} < ${e[2]}) {
localCoords[2] += ${p};
if(localCoords[1] + ${u} < ${e[1]}) {
localCoords[1] += ${u};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
r = flatIndex / ${o};
c = imod(flatIndex, ${o});
uv = (vec2(c, r) + halfCR) / vec2(${o}.0, ${i}.0);
values = ${s.texture2D}(A, uv);
if(offset == 0) {
result[${m}] = values[0];
} else if(offset == 1) {
result[${m}] = values[1];
} else if(offset == 2) {
result[${m}] = values[2];
} else {
result[${m}] = values[3];
}
}
}
`}this.userCode=`
${yS(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${a}
${s.output} = ${c};
}
`}}const yC={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"};class bC{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const i=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,o=n?`${s}.0`:"1.0";this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${e}
}
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 +=
unaryOpComplex(real, expR, imag, expI) / ${o};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}}class i8{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode=`
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class r8{constructor(e,t,n){this.variableNames=["A","indices"];const s=e.slice();s[n]=t,this.outputShape=s,this.rank=s.length;const i=Et(this.rank),o=o8(e,n);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${o}));
}
`}}function o8(e,t){const n=e.length;if(n>4)throw Error(`Gather for rank ${n} is not yet supported`);if(n===1)return"int(getIndices(resRC))";const s=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[];for(let o=0;o<e.length;o++)o===t?i.push(`int(getIndices(${s[o]}))`):i.push(`${s[o]}`);return i.join()}class a8{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=Et(t.length),i=Et(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${s} strides = ${s}(${this.strides});
void main() {
${i} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${o};
}
setOutput(getX(flattenIndex, coords[1]));
}
`}}function c8(e){const t=Un(),n=`${t.version}
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-10-26 01:01:36 +01:00
}`;return $j(e,n)}function l8(e){const t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return Gj(e,t)}function h8(e){const t=new Uint16Array([0,1,2,2,1,3]);return Vj(e,t)}function uu(e,t,n,s,i,o){Yj(t,n);const a=Hj(e),c=e.TEXTURE_2D;return Re(e,()=>e.bindTexture(c,a)),Re(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Re(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Re(e,()=>e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)),Re(e,()=>e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)),Re(e,()=>e.texImage2D(c,0,s,t,n,0,i,o,null)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null)),a}function wC(e){return e.internalFormatFloat}function u8(e,t,n,s){const[i,o]=cu(t,n);return uu(e,i,o,wC(s),s.textureFormatFloat,e.FLOAT)}function LC(e){return e.internalFormatHalfFloat}function d8(e,t,n,s){const[i,o]=cu(t,n);return uu(e,i,o,LC(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function SC(e){return e.downloadTextureFormat}function p8(e,t,n,s){const[i,o]=cu(t,n);return uu(e,i,o,SC(s),e.RGBA,e.UNSIGNED_BYTE)}function IC(e){return e.internalFormatPackedFloat}function m8(e,t,n,s){const[i,o]=fc(t,n);return uu(e,i,o,IC(s),e.RGBA,e.FLOAT)}function xC(e){return e.internalFormatPackedHalfFloat}function f8(e,t,n,s){const[i,o]=fc(t,n);return uu(e,i,o,xC(s),e.RGBA,s.textureTypeHalfFloat)}function g8(e,t,n){const s=0,i=3*4,o=3*4+2*4;Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=K0(e,t,"clipSpacePos",n,3,o,s);return a&&K0(e,t,"uv",n,2,o,i)}function y8(e,t,n,s,i,o){Re(e,()=>e.bindTexture(e.TEXTURE_2D,t));let a,c,u;i instanceof Uint8Array?(a=new Uint8Array(n*s*4),c=e.UNSIGNED_BYTE,u=e.RGBA):(a=new Float32Array(n*s*4),c=e.FLOAT,u=o.internalFormatPackedFloat),a.set(i),Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,u,n,s,0,e.RGBA,c,a)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function b8(e,t,n){Re(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function w8(e,t,n,s){const i=e.createBuffer();Re(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const o=4,a=4,c=o*a*t*n;return Re(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,c,e.STREAM_READ)),Re(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Re(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function L8(e,t,n){const s=e,i=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,i),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),i}function S8(e,t,n,s){const[i,o]=cu(t,n),a=4,c=new Uint8Array(Oj(t*n,a));return Re(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function I8(e,t,n,s,i,o,a,c){const u=e,p=new Float32Array(Ej(o,a));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,p),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),p}function x8(e,t,n){const s=new Float32Array(t*n*4);return Re(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}class T8{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=C().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Nj(t,e)):this.gl=Mi(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(C().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=pm(this.gl,i),Vs(this.gl,o))this.textureHalfFloatExtension=pm(this.gl,o);else if(C().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Vs(this.gl,s))this.colorBufferHalfFloatExtension=pm(this.gl,s);else if(C().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Vs(this.gl,n))this.colorBufferFloatExtensi
2020-10-15 12:48:39 +02:00
blockIndex = rc.y + ${_};
pos = rc.x + ${F};
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
offsetY = int(blockIndex / (${u})) * ${a} - ${w};
d0 = offsetY + ${m} * (pos / ${I});
if(d0 < ${t[N]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${u}.) * ${o}. - ${b}.);
d1 = offsetX + ${p} * (int(mod(float(pos), ${I}.) / ${i}.));
if(d1 < ${t[E]} && d1 >= 0) {
ch = int(mod(float(pos), ${i}.));
if (${v}) {
innerDims = vec2(d1, ch);
result[${F*2+_}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${F*2+_}] = getChannel(
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;
${D}
${T.output} = result;
}
`}}class O8{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[];const o=t,a=e[3]-1;this.outputShape=e;let c;const u=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${u})`:i===1?c=`1.0/(${u})`:c=`exp(log(${u}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${o}; j <= ${o}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${a}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${c};
setOutput(val);
}
`}}class E8{constructor(e,t,n,s,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=i,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${s}) * norm + float(${n});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${s})
* float(${i})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${i});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`}}class D8{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const o=t,a=e[3]-1;this.outputShape=e;let c;const u=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${u})`:i===1?c=`1.0/(${u})`:c=`exp(log(${u}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${o};
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);
for (int j = - ${o}; j <= ${o}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));
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;
}
}
vec4 result = xAtOutputCoords * ${c};
setOutput(result);
}
`}}class k8{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,i=e.effectiveFilterHeight,o=e.effectiveFilterWidth,a=i-1-e.padInfo.top,c=o-1-e.padInfo.left,u=i*o-1;this.userCode=`
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${i};
wR += ${s}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${o} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}}class F8{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,i=e.dilationDepth,o=e.dilationHeight,a=e.dilationWidth,c=e.effectiveFilterDepth,u=e.effectiveFilterHeight,p=e.effectiveFilterWidth,m=c-1-e.padInfo.front,y=u-1-e.padInfo.top,b=p-1-e.padInfo.left,w=c*u*p-1;this.userCode=`
const ivec3 pads = ivec3(${m}, ${y}, ${b});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${c};
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${u};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${p};
wC += ${a}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${w} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${u} * ${p} +
wR * ${p} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}}class LS{constructor(e,t,n=!1,s=!1,i=!1,o=null,a=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;const c=n?e[1]:e[2],u=Math.ceil(c/2),p=n?"i * 2, rc.y":"rc.y, i * 2",m=s?"rc.z, i * 2":"i * 2, rc.z",y=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],b=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let w="",I="";o&&(a?w=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
}`:w=`vec4 activation(vec4 x) {
${o}
}`,I="result = activation(result);");const T=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${w}
const float sharedDimension = ${u}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${u}; i++) {
vec4 a = getMatrixA(rc.x, ${p});
vec4 b = getMatrixB(rc.x, ${m});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${y[0]} * ${b[0]});
result += (${y[1]} * ${b[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${T}
${I}
setOutput(result);
}
`}}class _8{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode=`
uniform float seed;
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t-1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${t-1}));
}
`}getCustomSetupFunc(e){return(t,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class W8{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${s}), float(${n}),
float(index == coords.y)));
}
`}}class $8{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;const t=e.length;if(t===0)this.userCode=`
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{const n=us("rc",t),s=Et(t),i=B8(t,e,n),o=M8(t,e[e.length-1],e[e.length-2],n),a=P8(e,n);this.userCode=`
void main() {
${s} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${o}
setOutput(vec4(${a}));
}
}
`}}}function U8(e,t){const n=[];for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=`${s===0?"r":"rp1"}, ${i===0?"c":"cp1"}`;for(let a=2;a<e;a++)o=`${t[t.length-1-a]},`+o;n.push(o)}return n}function B8(e,t,n){if(e===1)return`rc > ${t[0]}`;let s="";for(let i=e-2;i<e;i++)s+=`${n[i]} >= ${t[i]}`,i<e-1&&(s+="||");return s}function M8(e,t,n,s){if(e===1)return"";const i=s.slice(-2);return`
int r = ${i[0]};
int c = ${i[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
bool rEdge = rp1 >= ${n};
`}function P8(e,t){const n=e.length,s=U8(n,t);return n===1?`getA(rc),
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${s[0]}),
cEdge ? 0. : getA(${s[1]}),
rEdge ? 0. : getA(${s[2]}),
rEdge || cEdge ? 0. : getA(${s[3]})`}class z8{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,p)=>u[0]+e[p]+u[1]);const s=e.length,i=Et(s),o=t.map(u=>u[0]).join(","),a=t.map((u,p)=>u[0]+e[p]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=`
int start = ${o};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(${n}));
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${i} start = ${i}(${o});
${i} end = ${i}(${a});
void main() {
${i} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(${n}));
} else {
${i} coords = outC - start;
setOutput(getX(${c}));
}
}
`}}class G8{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((I,T)=>I[0]+e[T]+I[1]);const s=e.length,i=Et(s),o=t.map(I=>I[0]).join(","),a=t.map((I,T)=>I[0]+e[T]).join(","),c=us("rc",s),u=us("source",s),p=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${u.slice(-2).join()})`,y=[`${i} rc = outputLoc;`,`${c[s-1]} += 1;
if(${p}) {
`,s===1?"":`}
rc = outputLoc;
${c[s-2]} += 1;
if(${c[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${c[s-1]} += 1;
if(${p}) {`],b=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let w="";for(let I=0,T=s===1?2:4;I<T;I++)w+=`
${y[I]}
if (${b}) {
result[${I}] = float(${n});
} else {
${i} source = rc - start;
result[${I}] = getChannel(getX(${u.join()}), ${m});
}
`;w+=s===1?"} ":"}}",this.userCode=`
const ${i} start = ${i}(${o});
const ${i} end = ${i}(${a});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${w}
setOutput(result);
}
`}}class du{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideHeight,c=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,m=e.effectiveFilterHeight,y=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const I=t==="avg",T=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,v=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let N="0.0";if(I||(N="-1.0 / 1e-20"),n){const U=">=";this.userCode=`
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
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;
for (int wR = 0; wR < ${m};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${y};
wC += ${p}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${U} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s?i?T:v:`wR * ${y} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const E="max";let D=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(D="avgValue / count");const F=Math.floor(o/4)*4,_=o%4,B=`
if (${I}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${E}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
const float initializationValue = ${N};
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) {
if (xC < 0 || xC >= ${e.inWidth}) {
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
vec4 minMaxValue = vec4(${N});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${m};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${F}; wC += 4) {
int xC = xCCorner + wC * ${p};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
getValue(batch, xR, xC + 2 * ${p}, d),
getValue(batch, xR, xC + 3 * ${p}, d)
);
${B}
}
int xC = xCCorner + ${F};
if (${_===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${B}
} else if (${_===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
initializationValue,
initializationValue
);
${B}
} else if (${_===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
getValue(batch, xR, xC + 2 * ${p}, d),
initializationValue
);
${B}
}
}
setOutput(${D});
}
`}}class SS{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideDepth,c=e.strideHeight,u=e.strideWidth,p=e.dilationDepth,m=e.dilationHeight,y=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,I=e.effectiveFilterWidth,T=e.padInfo.front,v=e.padInfo.top,N=e.padInfo.left;this.outputShape=e.outShape;const E=t==="avg";let D="0.0";if(E||(D="-1.0 / 1e-20"),n){const q=">=";this.userCode=`
const ivec3 strides =
ivec3(${a}, ${c}, ${u});
const ivec3 pads = ivec3(${T}, ${v}, ${N});
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;
for (int wD = 0; wD < ${b};
wD += ${p}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${w};
wR += ${m}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${I};
wC += ${y}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${q} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s?i?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${w} * ${I} +
wR * ${I} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const F="max";let _=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(_="avgValue / count");const B=Math.floor(o/4)*4,U=o%4,Y=`
if (${E}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${F}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${a}, ${c}, ${u});
const ivec3 pads = ivec3(${T}, ${v}, ${N});
const float initializationValue = ${D};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
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
vec4 minMaxValue = vec4(${D});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${b};
wD += ${p}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${w};
wR += ${m}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${B}; wC += 4) {
int xC = xCCorner + wC * ${y};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
getValue(batch, xD, xR, xC + 2 * ${y}, ch),
getValue(batch, xD, xR, xC + 3 * ${y}, ch)
);
${Y}
}
int xC = xCCorner + ${B};
if (${U===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${Y}
} else if (${U===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
initializationValue,
initializationValue
);
${Y}
} else if (${U===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
getValue(batch, xD, xR, xC + 2 * ${y}, ch),
initializationValue
);
${Y}
}
}
setOutput(${_});
}
}
`}}class AC{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:i,outSize:o}=e;this.outputShape=[s,o];let a="0.0",c="";t==="prod"?a="1.0":t==="min"?(a="1.0 / 1e-20",c="min"):t==="max"&&(a="-1.0 / 1e-20",c="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="anyValue");const p=Math.floor(n/4)*4,m=n%4;let y=`
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${c}(values, minMaxValue);
}
`,b="vec4";t==="all"?(a="1.0",y=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,b="bvec4"):t==="any"&&(a="0.0",y=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,b="bvec4");let w="";i%n>0&&(w=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${a};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${w}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
vec4 minMaxValue = vec4(${a});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${p}; i += 4) {
int inIdx = inOffset + i;
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${y}
}
int inIdx = inOffset + ${p};
if (${m===1}) {
${b} values = ${b}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${y}
} else if (${m===2}) {
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${y}
} else if (${m===3}) {
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${y}
}
setOutput(${u});
}
`}}class vC{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let n="";for(let s=0;s<4;s++){let i="thisRC = rc;";s%2===1&&(i+="thisRC.z += 1;"),s>1&&(i+="thisRC.y += 1;"),n+=`
${i}
${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=`
${V8(t)}
${yS(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${n}
setOutput(result);
}
2020-10-26 01:01:36 +01:00
`}}function V8(e){const t=Xo(["r","c","d"],e);return`
2020-10-15 12:48:39 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
`}class H8{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],u=[n&&o>1?o-1:o,n&&a>1?a-1:a],p=c[0]/u[0],m=c[1]/u[1],y=1/p,b=1/m,w=Math.ceil(y)*2+2,I=Math.ceil(b)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${p});
const float widthScale = float(${m});
const float invHeightScale = float(${y});
const float invWidthScale = float(${b});
const int winHeight = int(${w});
const int winWidth = int(${I});
// 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
if (dyR < 0 || dyR >= ${o}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${a}) {
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));
int rightDxCIndex = int(min(ceil(dxC), ${i-1}.0));
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);
}
`}}class Y8{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const u=[s&&t>1?o-1:o,s&&n>1?a-1:a],p=[s&&t>1?t-1:t,s&&n>1?n-1:n];this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0]/p[0]},
${u[1]/p[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${a}.0);
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);
}
`}}class q8{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const u=[s&&t>1?o-1:o,s&&n>1?a-1:a],p=[s&&t>1?t-1:t,s&&n>1?n-1:n];this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${u[0]/p[0]},
${u[1]/p[1]},
${u[1]/p[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${a}.0,
${a}.0);
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.
bool hasNextCol = d < ${c-1};
bool hasNextRow = coords.z < ${n-1};
// 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);
}
`}}class j8{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],u=[n&&o>1?o-1:o,n&&a>1?a-1:a],p=c[0]/u[0],m=c[1]/u[1],y=1/p,b=1/m,w=Math.ceil(y)*2+2,I=Math.ceil(b)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${p});
const float widthScale = float(${m});
const float invHeightScale = float(${y});
const float invWidthScale = float(${b});
const int winHeight = int(${w});
const int winWidth = int(${I});
// 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
if (dyR < 0 || dyR >= ${o}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${a}) {
continue;
}
float sourceFracRow =
float(${c[0]}) *
(float(dyR) / float(${u[0]}));
float sourceFracCol =
float(${c[1]}) *
(float(dyC) / float(${u[1]}));
int sourceNearestRow = int(min(
float(int(${s}) - 1),
${n} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${i}) - 1),
${n} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class K8{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const u=[s&&t>1?o-1:o,s&&n>1?a-1:a],p=[s&&t>1?t-1:t,s&&n>1?n-1:n],m=s?"0.5":"0.0";this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0]/p[0]},
${u[1]/p[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${a}.0);
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(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}}class X8{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;return}const s=a=>t.indexOf(a)!==-1&&e[a]!==1?`${e[a]} - coords[${a}] - 1`:`coords[${a}]`,i=e.map((a,c)=>s(c)).join(","),o=Et(n);this.userCode=`
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}}class J8{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const s=us("rc",n),i=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,o=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Et(n);n===1?this.userCode=`
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${i}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${a} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${c(s.slice())};
if(${i}){
result.g = ${u(s.slice())};
}
if(${o}) {
result.b = ${p(s.slice())};
if(${i}) {
result.a = ${m(s.slice())};
}
}
setOutput(result);
}
`;function c(w){return y(w)}function u(w){return w[n-1]="("+w[n-1]+" + 1)",y(w)}function p(w){return w[n-2]="("+w[n-2]+" + 1)",y(w)}function m(w){return w[n-1]="("+w[n-1]+" + 1)",w[n-2]="("+w[n-2]+" + 1)",y(w)}function y(w){const I=e.map((N,E)=>b(E,w)),T=I.join(","),v=I.slice(-2).join(",");return`getChannel(getX(${T}), vec2(${v}))`}function b(w,I){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${I[w]} - 1`:`${I[w]}`}}}class NC{constructor(e,t,n,s,i,o,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=Et(i.length),u=Et(o.length);let p="";n===1?p="i":n===2&&(p="i, j");const m=`getIndices(${p})`;let y="";s===1?y="i":s===2&&(y="i, coords[1]");const b=`getUpdates(${y})`,w=t>1?"strides[j]":"strides";this.userCode=`
${c} strides = ${c}(${i});
void main() {
${u} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${m});
flattenedIndex += index * ${w};
}
if (flattenedIndex == coords[0]) {
sum += ${b};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}}class Z8{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,s=e.batchSize,i=e.inSize,o=e.numSegments,a=o*Math.ceil(i/n);this.outputShape=[s,a];const c="0.0",u="sumValue",p=Math.floor(n/4)*4,m=n%4,y=`
sumValue += dot(values, segFilter);
`;let b="";i%n>0&&(b=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`);let w="";i%n>0&&(w=`
if (inIdx < 0 || inIdx >= ${i}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${c};
float getValue(int batch, int inIdx) {
${b}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${w}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${o})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${o})));
float sumValue = 0.0;
for (int i = 0; i < ${p}; i += 4) {
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
);
${y}
}
int inIdx = inOffset + ${p};
if (${m===1}) {
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
);
${y}
} else if (${m===2}) {
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
);
${y}
} else if (${m===3}) {
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
);
${y}
}
setOutput(${u});
}
`}}class Q8{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let s,i;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)i="resRC",s="resRC";else{const a=["resRC.x","resRC.y","resRC.z","resRC.w"],c=[],u=[];for(let p=0;p<t.length;p++)u.push(`${a[p]}`),p<e&&c.push(`${a[p]}`);s=c.join(),i=u.join()}const o=Et(n);this.userCode=`
void main() {
${o} resRC = getOutputCoords();
float cVal = getC(${s});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
`}}class e6{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Et(this.rank),n=`uniform int start[${this.rank}];`,s=t6(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${IS[c]} = start[${c}] + coords.${IS[c]};`);i=`
${t} sourceLoc;
${t} coords = getOutputCoords();
${o.join(`
`)}
`,this.userCode=`
${n}
void main() {
${i}
setOutput(getSource(${s}));
}
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}const IS=["x","y","z","w","u","v"];function t6(e){if(e===1)return"sourceLoc";if(e<=6)return IS.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class n6{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Et(this.rank),n=us("coords",this.rank),s=us("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,o=`getChannel(getSource(${s.join()}), ${i})`,a=`
result.x = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.y = ${o};
--${s[this.rank-1]};
}
`,c=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
++${s[this.rank-2]};
result.z = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.w = ${o};
}
}
`,u=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((p,m)=>`start[${m}]`).join()});`:e.map((p,m)=>`${s[m]} = ${n[m]} + start[${m}];`).join(`
`);this.userCode=`
uniform int start[${this.rank}];
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${u}
vec4 result = vec4(0.);
${a}
${c}
setOutput(result);
}
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}class s6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,i=Et(n.length),o=Et(n.length);let a="";if(s===1)a="coords * strides + begin";else{let c=0;a=n.map((u,p)=>(c++,n.length===1?`coords * strides[${p}] + begin[${p}]`:`coords[${c-1}] * strides[${p}] + begin[${p}]`)).join(",")}this.userCode=`
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${a}));
}
2020-10-26 01:01:36 +01:00
`}}class i6{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const s=RC(t,n),i=OC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=CC(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=o,this.log();const c=this.freeTextures[i].shift();return this.usedTextures[i].push(c),c}let a;return s===In.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===In.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===In.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===In.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===In.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(a),this.numUsedTextures++,this._numBytesAllocated+=o,this.log(),a}releaseTexture(e,t,n,s){if(this.freeTextures==null)return;const i=RC(n,s),o=OC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=CC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=C().get("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=a):(this.freeTextures[o].push(e),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const u=this.usedTextures[o],p=u.indexOf(e);if(p<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(p,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures==null)return;for(const e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(const e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}function r6(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function CC(e,t,n,s,i){const o=o6(t,s);let a;if(i){const[u,p]=fc(e[0],e[1]);a=u*p}else{const[u,p]=cu(e[0],e[1]);a=u*p}const c=r6(n,o);return a*c}function o6(e,t){switch(e){case In.PACKED_2X2_FLOAT32:return IC(t);case In.PACKED_2X2_FLOAT16:return xC(t);case In.UNPACKED_FLOAT32:return wC(t);case In.UNPACKED_FLOAT16:return LC(t);case In.PACKED_4X1_UNSIGNED_BYTE:return SC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function a6(e){return C().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?In.PACKED_2X2_FLOAT32:In.UNPACKED_FLOAT32:e?In.PACKED_2X2_FLOAT16:In.UNPACKED_FLOAT16}function RC(e,t){if(e===Cs.UPLOAD)return In.PACKED_2X2_FLOAT32;if(e===Cs.RENDER||e==null)return a6(t);if(e===Cs.DOWNLOAD||e===Cs.PIXELS)return In.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function OC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class c6{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[o]*t[o];this.outputShape=n,this.rank=n.length;const s=Et(this.rank),i=l6(e);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function l6(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let i=0;i<e.length;i++)s.push(`imod(${n[i]}, ${e[i]})`);return s.join()}class it{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=`
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}}const dr="if (isnan(x)) return x;",h6="return x;",EC="return abs(x);",DC=dr+`
return (x < 0.0) ? 0.0 : x;
`,kC=dr+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,FC="return (x >= 0.0) ? x : (exp(x) - 1.0);",u6=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${xp};
float scale = ${Tp};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;function d6(e=0){return dr+`
return x > 0.0 ? 1.0 : float(${e});
`}const _C="return -x;",WC="return ceil(x);",$C="return floor(x);",p6=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,m6="return float(isnan(x));",f6="return float(isinf(x));",g6="return float(!isnan(x) && !isinf(x));",y6=`
// 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;
}
}
`,UC="return exp(x);",BC="return exp(x) - 1.0;",b6=`if (x < 0.0) return NAN;
return log(x);`,w6="return log(1.0 + x);",L6="return sqrt(x);",S6="return inversesqrt(x);",I6="return 1.0 / (1.0 + exp(-1.0 * x));",x6=`
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;
`,T6=dr+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,A6=dr+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,v6=dr+`
return atan(x);
`,N6=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,C6=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,R6=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,O6=dr+"return log(x + sqrt(x * x + 1.0));",E6=dr+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,D6=dr+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,k6=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${Xb};
float a1 = ${Jb};
float a2 = ${Zb};
float a3 = ${Qb};
float a4 = ${ew};
float a5 = ${tw};
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));
`,F6="return 1.0 / x;",_6="return float(!(x >= 1.0));",W6="return float(int(x));",Im="return x;";const $6="return x;",U6=`
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;
`,MC=`
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;
`,PC=`
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;
`,zC=`
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;
`;class pu{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`}}class B6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=us("rc",t),s=Et(t),i=xK(t,n),o=n.slice(-2),a=t<=1?"rc":`vec2(${o.join(",")})`;this.userCode=`
void main() {
${s} rc = getOutputCoords();
vec4 packedInput = getA(${i});
setOutput(getChannel(packedInput, ${a}));
}
2020-10-26 01:01:36 +01:00
`}}const{segment_util:GC}=iw,M6=rw,P6=ow,z6=aw,G6=dp,V6=1e-7,H6=1e-4,xm={};function Y6(e){return e in xm||(xm[e]={}),xm[e]}function Tm(e,t=!1){if(e==="linear")return t?$6:h6;if(e==="relu")return t?MC:DC;if(e==="elu")return t?zC:FC;if(e==="relu6")return t?PC:kC;if(e==="prelu")return t?hC:lC;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const q6=128,j6=600;function K6(){return C().global.screen==null?1024:C().global.screen.height*C().global.screen.width*window.devicePixelRatio*j6/1024/1024}const VC=1e3;class X6 extends f{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!C().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Mi(C().getNumber("WEBGL_VERSION"));this.binaryCache=Y6(C().getNumber("WEBGL_VERSION")),this.gpgpu=new T8(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new i6(this.gpgpu),this.numMBBeforeWarning=K6(),this.texData=new d(this,$s())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((C().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||C().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:Cs.UPLOAD,refCount:1}),s}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,n,s){if(C().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:Cs.UPLOAD,refCount:1})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const n=this.texData.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:n,dtype:s,complexTensors:i,slice:o,shape:a,isPacked:c}=t;if(o!=null){let y;c?y=new pu(a,Im):y=new it(a,Im);const b=this.runWebGLProgram(y,[{dataId:e,shape:a,dtype:s}],s),w=this.readSync(b.dataId);return this.disposeIntermediateTensorInfo(b),w}if(n!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return n;const u=this.activeTimers!=null;let p;u&&(p=qn());let m;if(s==="complex64"){const y=i.real.dataSync(),b=i.imag.dataSync();m=ir(y,b)}else m=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=qn()-p),this.convertAndCacheOnCPU(e,m)}async read(e){if(this.pendingRead.has(e)){const w=this.pendingRead.get(e);return new Promise(I=>w.push(I))}const t=this.texData.get(e),{values:n,shape:s,slice:i,dtype:o,complexTensors:a,isPacked:c}=t;if(i!=null){let w;c?w=new pu(s,Im):w=new it(s,Im);const I=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),T=this.read(I.dataId);return this.disposeIntermediateTensorInfo(I),T}if(n!=null)return this.convertAndCacheOnCPU(e);if(!C().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&C().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,p;if(o!=="complex64"&&C().get("WEBGL_BUFFER_SUPPORTED")){p=this.decode(e);const w=this.texData.get(p.dataId);u=this.gpgpu.createBufferFromTexture(w.texture,...lu(s))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let m;if(o==="complex64"){const w=await Promise.all([a.real.data(),a.imag.data()]),I=w[0],T=w[1];m=ir(I,T)}else if(u==null)m=this.getValuesFromTexture(e);else{const w=we(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(u,w)}p!=null&&this.disposeIntermediateTensorInfo(p);const y=this.convertAndCacheOnCPU(e,m),b=this.pendingRead.get(e);return this.pe
2020-10-15 12:48:39 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
`,t7=`
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-10-26 01:01:36 +01:00
`;function Am(e){return({inputs:t,backend:n})=>{const{x:s}=t,i=n,o=new it(s.shape,e);return i.runWebGLProgram(o,[s],s.dtype)}}function xS(e,t,n,s){return({inputs:i,backend:o})=>{const{a,b:c}=i,u=o,p=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new to(t,a.shape,c.shape,!!n):new un(e,a.shape,c.shape),m=s||a.dtype,y=u.runWebGLProgram(p,[a,c],m);return y}}const n7=e7+`
2020-10-15 12:48:39 +02:00
return atan(a, b);
`,s7=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+t7+`
return result;
2020-10-26 01:01:36 +01:00
`,i7=xS(n7,s7),r7={kernelName:Ai,backendName:"webgl",kernelFunc:i7};function TS(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const o7={kernelName:Sl,backendName:"webgl",kernelFunc:TS};function a7(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;hu(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:u}=s,p=1;k(on(a,p),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Wn(i.shape,o,a,p,c,u);if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))return TS({inputs:{x:i},backend:n});const y=new du(m,"avg",!1);return n.runWebGLProgram(y,[i],"float32")}const c7={kernelName:ei,backendName:"webgl",kernelFunc:a7};function l7(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;hu([i,o],"avgPoolBackprop");const{filterSize:c,strides:u,pad:p}=s,m=Wn(a.shape,c,u,1,p),y=new a5(m);return n.runWebGLProgram(y,[i],a.dtype)}const h7={kernelName:xa,backendName:"webgl",kernelFunc:l7};class u7{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="0.0";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(nt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${a};
float scale = ${c};
float inv = scale * inversesqrt(variance + float(${o}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}}class d7{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="vec4(0.0)";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(nt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
vec4 offset = ${a};
vec4 scale = ${c};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${o}));
setOutput((x - mean) * inv + offset);
}
`}}const p7=({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:i,variance:o,offset:a,scale:c}=e;k(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(c==null||i.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:u}=n;u==null&&(u=.001);const p=[s,i,o];let m=null;a!=null&&(m=a.shape,p.push(a));let y=null;c!=null&&(y=c.shape,p.push(c));const b=C().getBool("WEBGL_PACK_NORMALIZATION")?new d7(s.shape,i.shape,o.shape,m,y,u):new u7(s.shape,i.shape,o.shape,m,y,u),w=t.runWebGLProgram(b,p,p[0].dtype);return w},m7={kernelName:Ll,backendName:"webgl",kernelFunc:p7};const f7=HC+`
return cos(x);
2020-10-26 01:01:36 +01:00
`,g7=Am(f7),y7={kernelName:Ta,backendName:"webgl",kernelFunc:g7};const b7=`
2020-10-15 12:48:39 +02:00
if (a == b) {
return 1.0;
};
return a / b;`,w7=`
// 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-10-26 01:01:36 +01:00
`,L7=xS(b7,w7,!0),S7={kernelName:Aa,backendName:"webgl",kernelFunc:L7};class I7{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
`}}const x7={kernelName:rd,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new I7(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class T7{constructor(e){this.variableNames=["A"];const t=Un(),[n,s]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`}}class A7{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Un(),[n,s]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
}
2020-10-26 01:01:36 +01:00
`}}const v7={kernelName:yd,backendName:"webgl",kernelFunc:N7};let Ic;function N7(e){const{inputs:t,backend:n,attrs:s}=e;let{pixels:i}=t;const{numChannels:o}=s,a=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,c=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,[u,p]=a?[i.videoWidth,i.videoHeight]:[i.width,i.height],m=[p,u],y=[p,u,o];(c||a)&&(Ic==null&&(Ic=document.createElement("canvas").getContext("2d")),Ic.canvas.width=u,Ic.canvas.height=p,Ic.drawImage(i,0,0,u,p),i=Ic.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=Cs.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=C().getBool("WEBGL_PACK")?new A7(y):new T7(y),I=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),I}function C7(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const n=t.length?t[t.length-1].outSize:e[1],s=uh(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function R7(e,t,n,s){const i=C7(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:u,outSize:p}=i[a],m=new AC({windowSize:u,inSize:c,batchSize:e.shape[0],outSize:p},n),y=o;o=s.runWebGLProgram(m,[o],t),y.dataId!==e.dataId&&s.disposeData(y.dataId)}return o}function O7(e,t,n){const s=[gc(e.shape),...yc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[gc(t),...yc(t)],a=new vC(o,s),c=!0,u=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function AS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=we(i.shape),u=Id(o,c),p=we(u);k(c===p,()=>`The new shape (${u}) has ${p} elements and the old shape (${i.shape}) has ${c} elements. The new shape and old shape must have the same number of elements.`);const m=a.texData.get(i.dataId);return m.isPacked&&!gm(i.shape,u)&&!(m.texture!==null&&gm(m.shape,u))?O7(i,u,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:u,dtype:i.dtype})}const E7={kernelName:El,backendName:"webgl",kernelFunc:AS};function D7(e,t,n,s){const i=we(t),o=we(e.shape),a=o/i,c=AS({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),u=R7(c,e.dtype,"max",s),p=AS({inputs:{x:u},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(u),p}class k7{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[t[o]];this.outputShape=n,this.rank=n.length;const s=Et(this.rank),i=F7(t);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function F7(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let i=0;i<e.length;i++)s[e[i]]=n[i];return s.join()}class _7{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let p=0;p<n.length;p++)n[p]=e[t[p]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=Et(this.rank),i=eC("rc",this.rank),o=new Array(this.rank);for(let p=0;p<t.length;p++)o[t[p]]=i[p];const a=`vec2(${o.slice(-2).join()})`,c=`++${i[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${o.join()}), ${a})`;this.userCode=`
void main() {
${s} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${u};
if(${c}) {
result[1] = ${u};
}
--${i[this.rank-1]};
if(++${i[this.rank-2]} < ${n[this.rank-2]}) {
result[2] = ${u};
if(${c}) {
result[3] = ${u};
}
}
setOutput(result);
}
2020-10-26 01:01:36 +01:00
`}}function YC(e,t,n){const s=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _7(e.shape,t):new k7(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const W7={kernelName:Nl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{reductionIndices:i,keepDims:o}=t,a=n,c=s.shape.length,u=ft(i,s.shape);let p=u;const m=_n(p,c),y=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(y){if(b){const E=a.texData.get(w.dataId),D=E.values,F=new Array(c);for(let U=0;U<F.length;U++)F[U]=s.shape[m[U]];const _=Q0(D,s.shape,s.dtype,m,F);w=a.makeTensorInfo(F,s.dtype);const B=a.texData.get(w.dataId);B.values=_}else w=YC(s,m,a);p=Is(p.length,c)}ss("max",p,c);const[I,T]=On(w.shape,p);let v=I;o&&(v=En(I,u));let N;if(b){const E=a.texData.get(w.dataId),D=E.values,F=mK(D,we(T),v,s.dtype);N=a.makeTensorInfo(v,s.dtype);const _=a.texData.get(N.dataId);_.values=F}else N=D7(w,T,v,a);return y&&a.disposeIntermediateTensorInfo(w),N}};function $7(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;hu(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:u}=s,p=1;k(on(a,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Wn(i.shape,o,a,p,c,u);if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))return TS({inputs:{x:i},backend:n});const y=new du(m,"max",!1);return n.runWebGLProgram(y,[i],i.dtype)}const U7={kernelName:Cl,backendName:"webgl",kernelFunc:$7};function B7(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;hu([o,a],"maxPoolBackprop");const{filterSize:u,strides:p,pad:m,dimRoundingMode:y}=s,b=Wn(c.shape,u,p,1,m,y),w=!0,I=new du(b,"max",w),T=n.runWebGLProgram(I,[c],c.dtype),v=new k8(b),N=n.runWebGLProgram(v,[i,T],c.dtype);return n.disposeIntermediateTensorInfo(T),N}const M7={kernelName:ad,backendName:"webgl",kernelFunc:B7};function P7(e,t,n,s){let i=new du(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new du(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const z7={kernelName:cd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,u=n;k(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const p=[1,1];k(on(o,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);const m=Wn(s.shape,i,o,p,a),[y,b]=P7(s,c,m,u);return[y,b]}};const G7={kernelName:Kg,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Qa("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=n,u=t,p=u.readSync(s.dataId),m=u.readSync(i.dataId),y=o,b=a,w=c;return wp(p,m,y,b,w)}};const V7=Lp,H7={kernelName:hd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Qa("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:u}=n,p=t,m=p.readSync(s.dataId),y=p.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=V7(m,y,o,a,c,u);return[b,w]}};const Y7=Sp,q7={kernelName:ud,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Qa("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:u}=n,p=t,m=p.readSync(s.dataId),y=p.readSync(i.dataId),b=o,w=a,I=c,T=u,{selectedIndices:v,selectedScores:N}=Y7(m,y,b,w,I,T);return[v,N]}};class j7{constructor(e,t,n,s){this.variableNames=["Image"],this.outputShape=[];const i=e[1],o=e[2],a=Math.sin(t).toFixed(3),c=Math.cos(t).toFixed(3);this.outputShape=e;const[u,p]=qb(s,i,o),m=u.toFixed(3),y=p.toFixed(3);let b="";typeof n=="number"?b=`float outputValue = ${n.toFixed(2)};`:b=`
2020-10-15 12:48:39 +02:00
vec3 fill = vec3(${n.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - ${m}) * ${c} - (float(y) - ${y}) * ${a};
float coordYFloat = (float(x) - ${m}) * ${a} + (float(y) - ${y}) * ${c};
int coordX = int(round(coordXFloat + ${m}));
int coordY = int(round(coordYFloat + ${y}));
${b}
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${i}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}}const K7={kernelName:bd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,u=new j7(s.shape,i,o,a),p=c.runWebGLProgram(u,[s],s.dtype);return p}};const X7=HC+`
return sin(x);
2020-10-26 01:01:36 +01:00
`,J7=Am(X7),Z7={kernelName:va,backendName:"webgl",kernelFunc:J7};const Q7="return x * x;",eX=Am(Q7),tX={kernelName:fd,backendName:"webgl",kernelFunc:eX};const qC="return (a - b) * (a - b);",nX=xS(qC,qC),sX={kernelName:Na,backendName:"webgl",kernelFunc:nX};const iX="return tan(x);",rX=Am(iX),oX={kernelName:Ca,backendName:"webgl",kernelFunc:rX};const aX={kernelName:zl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{perm:i}=t,o=n,a=s.shape.length,c=new Array(a);for(let p=0;p<c.length;p++)c[p]=s.shape[i[p]];let u;if(o.shouldExecuteOnCPU([s])){const p=o.texData.get(s.dataId),m=p.values,y=Q0(m,s.shape,s.dtype,i,c);u=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(u.dataId);b.values=y}else u=YC(s,i,o);return u}};function cX(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;hu(o,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const a=s.readSync(o.dataId),{outputValues:c,outputShape:u,indices:p}=wK(a,i,o.shape,o.dtype);return[s.makeTensorInfo(u,o.dtype,c),s.makeTensorInfo([p.length],"int32",p)]}const lX={kernelName:gd,backendName:"webgl",kernelFunc:cX};const hX=[r7,c7,h7,m7,y7,S7,x7,v7,o7,W7,U7,M7,z7,G7,H7,q7,E7,K7,Z7,tX,sX,oX,aX,lX];for(const e of hX)Ld(e);const uX="2.6.0";const dX={"tfjs-core":JT,"tfjs-backend-cpu":Sq,"tfjs-backend-webgl":Z6,"tfjs-data":N0,"tfjs-layers":Xp,"tfjs-converter":r0,tfjs:uX};r.Abs=fe,r.Acos=de,r.Acosh=Ae,r.AdadeltaOptimizer=xh,r.AdagradOptimizer=Th,r.AdamOptimizer=Ah,r.AdamaxOptimizer=vh,r.Add=xe,r.AddN=Me,r.All=Ke,r.Any=wt,r.ArgMax=$t,r.ArgMin=Kt,r.Asin=Fn,r.Asinh=vn,r.Atan=Nn,r.Atan2=Ai,r.Atanh=Qs,r.AvgPool=ei,r.AvgPool3D=hl,r.AvgPool3DBackprop=Cx,r.AvgPoolBackprop=xa,r.BatchMatMul=vg,r.BatchToSpaceND=Ng,r.BroadcastTo=Cg,r.Callback=VN,r.CallbackList=Uv,r.Cast=ul,r.Ceil=dl,r.ClipByValue=pl,r.Complex=Rg,r.Concat=td,r.Conv2D=Og,r.Conv2DBackpropFilter=Rx,r.Conv2DBackpropInput=Eg,r.Conv3D=Dg,r.Conv3DBackpropFilterV2=Ox,r.Conv3DBackpropInputV2=Ex,r.Cos=Ta,r.Cosh=ml,r.CropAndResize=Dx,r.Cumsum=kg,r.CustomCallback=Mv,r.DataStorage=d,r.DepthToSpace=kx,r.DepthwiseConv2dNative=Fg,r.DepthwiseConv2dNativeBackpropFilter=Fx,r.DepthwiseConv2dNativeBackpropInput=_x,r.Diag=Wx,r.Dilation2D=nd,r.Dilation2DBackpropFilter=id,r.Dilation2DBackpropInput=sd,r.Div=Aa,r.EarlyStopping=YN,r.Elu=fl,r.EluGrad=$x,r.Environment=L,r.Equal=Ux,r.Erf=gl,r.Exp=yl,r.Expm1=bl,r.FFT=_g,r.Fill=Bx,r.FlipLeftRight=rd,r.Floor=wl,r.FloorDiv=Wg,r.FromPixels=yd,r.FusedBatchNorm=Ll,r.FusedConv2D=fy,r.FusedDepthwiseConv2D=gy,r.GatherNd=Mx,r.GatherV2=$g,r.GraphModel=i0,r.Greater=Px,r.GreaterEqual=Ug,r.History=Bv,r.IFFT=Bg,r.Identity=Sl,r.Imag=Mg,r.InputSpec=fn,r.IsFinite=Il,r.IsInf=xl,r.IsNan=Tl,r.KernelBackend=f,r.LRN=zg,r.LRNBackprop=qx,r.LayerVariable=ci,r.LayersModel=cr,r.Less=zx,r.LessEqual=Gx,r.LinSpace=Vx,r.Log=Al,r.Log1p=vl,r.LogSoftmax=Pg,r.LogicalAnd=Hx,r.LogicalNot=od,r.LogicalOr=Yx,r.Max=Nl,r.MaxPool=Cl,r.MaxPool3D=Vg,r.MaxPool3DBackprop=jx,r.MaxPoolBackprop=ad,r.MaxPoolWithArgmax=cd,r.Maximum=Gg,r.Mean=VD,r.Min=Hg,r.Minimum=Yg,r.Mod=qg,r.MomentumOptimizer=Nh,r.Multiply=Rl,r.Negate=jg,r.NonMaxSuppressionV3=Kg,r.NonMaxSuppressionV4=hd,r.NonMaxSuppressionV5=ud,r.NotEqual=ld,r.OP_SCOPE_SUFFIX=IT,r.OneHot=Jg,r.OnesLike=Xg,r.Optimizer=sr,r.PadV2=dd,r.Pool=HD,r.Pow=Zg,r.Prelu=Qg,r.Prod=Kx,r.RMSPropOptimizer=Ch,r.RNN=Bi,r.Range=Xx,r.Real=ey,r.Reciprocal=Ol,r.Relu=ty,r.Relu6=iy,r.Reshape=El,r.ResizeBilinear=sy,r.ResizeBilinearGrad=Zx,r.ResizeNearestNeighbor=ny,r.ResizeNearestNeighborGrad=Jx,r.Reverse=ry,r.RotateWithOffset=bd,r.Round=Dl,r.Rsqrt=kl,r.SGDOptimizer=Za,r.ScatterNd=Qx,r.SelectV2=oy,r.Selu=Fl,r.Sequential=oc,r.Sigmoid=$l,r.Sign=Wl,r.Sin=va,r.Sinh=_l,r.Slice=pd,r.Softmax=ly,r.Softplus=Ul,r.SpaceToBatchND=md,r.SparseToDense=eT,r.SplitV=cy,r.Sqrt=Bl,r.Square=fd,r.SquaredDifference=Na,r.Step=Gl,r.StridedSlice=tT,r.Sub=Ml,r.Sum=ay,r.SymbolicTensor=li,r.Tan=Ca,r.Tanh=Pl,r.Tensor=Q,r.TensorBuffer=kr,r.Tile=hy,r.TopK=nT,r.Transpose=zl,r.Unique=gd,r.Unpack=uy,r.UnsortedSegmentSum=dy,r.Variable=Xl,r.ZerosLike=py,r._FusedMatMul=my,r.abs=rn,r.acos=nb,r.acosh=s
2020-10-15 12:48:39 +02:00
`)),x.join(`
2020-10-26 01:01:36 +01:00
`)}function sJ(r,l,h,d){const f=qt(l),g=d[d.length-1],S=new Array(g).fill(0),L=l.length,x=h==="complex64"?Ou(r):r;if(L>1)for(let A=0;A<f/g;A++){const O=A*g;for(let C=0;C<g;C++)S[C]=Math.max(S[C],Ru(x[O+C],0,h).length)}return S}function Ru(r,l,h){let d;return Array.isArray(r)?d=`${parseFloat(r[0].toFixed(pI))} + ${parseFloat(r[1].toFixed(pI))}j`:Au(r)?d=`'${r}'`:h==="bool"?d=QR(r):d=parseFloat(r.toFixed(pI)).toString(),$c(d,l)}function QR(r){return r===0?"false":"true"}function Mf(r,l,h,d,f,g=!0){const S=h==="complex64"?2:1,L=l[0],x=l.length;if(x===0){if(h==="complex64"){const te=Ou(r);return[Ru(te[0],0,h)]}return h==="bool"?[QR(r[0])]:[r[0].toString()]}if(x===1){if(L>JR){const se=Cu*S;let fe=Array.from(r.slice(0,se)),de=Array.from(r.slice((L-Cu)*S,L*S));return h==="complex64"&&(fe=Ou(fe),de=Ou(de)),["["+fe.map((Ae,xe)=>Ru(Ae,f[xe],h)).join(", ")+", ..., "+de.map((Ae,xe)=>Ru(Ae,f[L-Cu+xe],h)).join(", ")+"]"]}const te=h==="complex64"?Ou(r):Array.from(r);return["["+te.map((se,fe)=>Ru(se,f[fe],h)).join(", ")+"]"]}const A=l.slice(1),O=d.slice(1),C=d[0]*S,$=[];if(L>JR){for(let te=0;te<Cu;te++){const se=te*C,fe=se+C;$.push(...Mf(r.slice(se,fe),A,h,O,f,!1))}$.push("...");for(let te=L-Cu;te<L;te++){const se=te*C,fe=se+C;$.push(...Mf(r.slice(se,fe),A,h,O,f,te===L-1))}}else for(let te=0;te<L;te++){const se=te*C,fe=se+C;$.push(...Mf(r.slice(se,fe),A,h,O,f,te===L-1))}const z=x===2?",":"";$[0]="["+$[0]+z;for(let te=1;te<$.length-1;te++)$[te]=" "+$[te]+z;let ne=`,
2020-10-15 12:48:39 +02:00
`;for(let te=2;te<x;te++)ne+=`
2020-10-26 01:01:36 +01:00
`;return $[$.length-1]=" "+$[$.length-1]+"]"+(g?"":ne),$}function Ou(r){const l=[];for(let h=0;h<r.length;h+=2)l.push([r[h],r[h+1]]);return l}class eO{constructor(r,l,h){if(this.dtype=l,this.shape=r.slice(),this.size=qt(r),h!=null){const d=h.length;Z(d===this.size,()=>`Length of values '${d}' does not match the size inferred by the shape '${this.size}'.`)}if(l==="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=h||zR(l,this.size),this.strides=Nu(r)}set(r,...l){l.length===0&&(l=[0]),Z(l.length===this.rank,()=>`The number of provided coordinates (${l.length}) must match the rank (${this.rank})`);const h=this.locToIndex(l);this.values[h]=r}get(...r){r.length===0&&(r=[0]);let l=0;for(const d of r){if(d<0||d>=this.shape[l]){const f=`Requested out of range element at ${r}. Buffer shape=${this.shape}`;throw new Error(f)}l++}let h=r[r.length-1];for(let d=0;d<r.length-1;++d)h+=this.strides[d]*r[d];return this.values[h]}locToIndex(r){if(this.rank===0)return 0;if(this.rank===1)return r[0];let l=r[r.length-1];for(let h=0;h<r.length-1;++h)l+=this.strides[h]*r[h];return l}indexToLoc(r){if(this.rank===0)return[];if(this.rank===1)return[r];const l=new Array(this.shape.length);for(let h=0;h<l.length-1;++h)l[h]=Math.floor(r/this.strides[h]),r-=l[h]*this.strides[h];return l[l.length-1]=r,l}get rank(){return this.shape.length}toTensor(){return Yi().makeTensor(this.values,this.shape,this.dtype)}}let Yi=null,Uc=null,iJ=null;function tO(r){Yi=r}function nO(r){Uc=r}function sO(r){iJ=r}class Tn{constructor(r,l,h,d){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=qt(r),this.strides=Nu(r),this.dataId=h,this.id=d,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const r=await this.data();return Uc.buffer(this.shape,this.dtype,r)}bufferSync(){return Uc.buffer(this.shape,this.dtype,this.dataSync())}async array(){const r=await this.data();return hI(this.shape,r)}arraySync(){return hI(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const r=Yi().read(this.dataId);if(this.dtype==="string"){const l=await r;try{return l.map(h=>dI(h))}catch(h){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return r}dataSync(){this.throwIfDisposed();const r=Yi().readSync(this.dataId);if(this.dtype==="string")try{return r.map(l=>dI(l))}catch(l){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return r}async bytes(){this.throwIfDisposed();const r=await Yi().read(this.dataId);return this.dtype==="string"?r:new Uint8Array(r.buffer)}dispose(){if(this.isDisposed)return;Yi().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(r=!1){return Uc.print(this,r)}clone(){return this.throwIfDisposed(),Uc.clone(this)}toString(r=!1){const l=this.dataSync();return ZR(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),Uc.cast(this,r)}variable(r=!0,l,h){return this.throwIfDisposed(),Yi().makeVariable(this,r,l,h)}}Object.defineProperty(Tn,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class Pf extends Tn{constructor(r,l,h,d){super(r.shape,r.dtype,r.dataId,d);this.trainable=l,this.name=h}assign(r){if(r.dtype!==this.dtype)throw new Error(`dtype of the new value (${r.dtype}) and previous value (${this.dtype}) must match`);if(!oa(r.shape,this.shape))throw new Error(`shape of the new value (${r.shape}) and previous value (${this.shape}) must match`);Yi().disposeTensor(this),this.dataId=r.dataId,Yi().incRef(this,null)}dispose(){Yi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Pf,Symbol.hasInstance,{value:r=>r instanceof Tn&&r.assign!=null&&r.assign instanceof Function});var iO;(function(r){r.R0="R0",
2020-10-27 21:35:40 +01:00
with dtype ${S.dtype}. `)});const d=(S,L)=>{const x=ht(l,h[0].shape)[0],A=bO(h.map($=>$.shape),x);if(qt(A)===0)return wI([],A);if(h=h.filter($=>$.size>0),h.length===1)return h[0];const O=h.map($=>$.shape);yO(O,x);const C=S.concat(h,x);return L(h),C},f=h,g={axis:l};return H.runKernelFunc(d,f,null,Gm,g)}const bn=G({concat_:EJ});function DJ(r){const l=M(r,"x","sigmoid"),h={x:l};return H.runKernelFunc((d,f)=>{const g=d.sigmoid(l);return f([g]),g},h,null,xf)}const AI=G({sigmoid_:DJ});function kJ(r,l,h){const d=M(r,"x","slice");if(d.rank===0)throw new Error("Slicing scalar is not possible");const f=(L,x)=>{const[A,O]=Vf(d,l,h);return dO(d,A,O),x([d]),L.slice(d,A,O)},g={x:d},S={begin:l,size:h};return H.runKernelFunc(f,g,null,Lf,S)}const At=G({slice_:kJ});function FJ(r,l,h){const d=M(r,"x","batchToSpaceND"),f=l.reduce((x,A)=>x*A);Z(d.rank>=1+l.length,()=>`input rank is ${d.rank} but should be > than blockShape.length ${l.length}`),Z(h.length===l.length,()=>`crops.length is ${h.length} but should be equal to blockShape.length ${l.length}`),Z(d.shape[0]%f===0,()=>`input tensor batch is ${d.shape[0]} but is not divisible by the product of the elements of blockShape ${l.join(" * ")} === ${f}`);const g=x=>x.batchToSpaceND(d,l,h),S={x:d},L={blockShape:l,crops:h};return H.runKernelFunc(g,S,null,Pm,L)}const vI=G({batchToSpaceND_:FJ});function _J(r,l){let h=M(r,"broadcastTo","x");const d=h.shape;if(l.some(O=>!(O>0)||O%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${l}].`);if(l.length<h.rank)throw new Error(`broadcastTo(): shape.length=${l.length} < input.rank=${h.rank}.`);if(l.length>h.rank){const O=h.shape.slice();for(;O.length<l.length;)O.unshift(1);h=re(h,O)}const f=h.shape,g=Array.from(l);for(let O=l.length-1;O>=0;O--)if(f[O]===l[O])g[O]=1;else if(h.shape[O]!==1)throw new Error(`broadcastTo(): [${d}] cannot be broadcast to [${l}].`);const S=g.map((O,C)=>O>1?C:-1).filter(O=>O>=0);if(S.length===0)return bi(h);const L=O=>O.tile(h,g),x={x:h},A={shape:l,inputShape:f};return H.runKernelFunc(L,x,null,zm,A)}const jf=G({broadcastTo_:_J});function WJ(r,l,h,d,f="NHWC",g=[1,1],S){const L=M(r,"x","conv2d"),x=M(l,"filter","conv2d");let A=L,O=!1;L.rank===3&&(O=!0,A=re(L,[1,L.shape[0],L.shape[1],L.shape[2]])),Z(A.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${A.rank}.`),Z(x.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${x.rank}.`),S!=null&&Z(Qt(d),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${S} but got pad ${d}.`);const C=f==="NHWC"?A.shape[3]:A.shape[1];Z(C===x.shape[2],()=>`Error in conv2d: depth of input (${C}) must match input depth for filter ${x.shape[2]}.`),Z(co(h,g),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${h} and dilations '${g}'`);const $=(se,fe)=>{const de=zc(f),Ae=Lr(A.shape,x.shape,h,g,d,S,!1,de),xe=se.conv2d(A,x,Ae);return fe([A,x]),xe},z={x:A,filter:x},ne={strides:h,pad:d,dataFormat:f,dilations:g,dimRoundingMode:S},te=H.runKernelFunc($,z,null,Vm,ne);return O?re(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const NI=G({conv2d_:WJ});function $J(r,l,h,d,f,g="NHWC",S){Z(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let L=r,x=l,A=!1;l.rank===3&&(A=!0,x=re(l,[1,l.shape[0],l.shape[1],l.shape[2]]),L=[1,r[0],r[1],r[2]]),Z(L.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${L.length}.`),Z(x.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${x.rank}`),Z(h.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${h.rank}`);const O=g==="NHWC"?L[3]:L[1],C=g==="NHWC"?x.shape[3]:x.shape[1];Z(O===h.shape[2],()=>`Error in conv2dDerInput: depth of input (${O}) must match input depth for filter ${h.shape[2]}.`),Z(C===h.shape[3],()=>`Error in conv2dDerInput: depth of output (${C}) must match output depth for filter ${h.shape[3]}.`),S!=null&&Z(Qt(f),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${S} but got pad ${f}.`);const $=(se,fe)=>{const de=1,Ae=zc(g),xe=Lr(L,h.s
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.
* =============================================================================
*/
/** @license See the LICENSE file. */
2020-10-27 17:51:38 +01:00
//# sourceMappingURL=face-api.node.js.map