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

4122 lines
1.1 MiB
JavaScript
Raw Normal View History

2020-10-29 05:16:50 +01:00
var rf=Object.defineProperty,n9=Object.prototype.hasOwnProperty,XS=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),T2=r=>rf(r,"__esModule",{value:!0}),$c=(r,l)=>{T2(r);for(var u in l)rf(r,u,{get:l[u],enumerable:!0})},s9=(r,l)=>{if(T2(r),typeof l=="object"||typeof l=="function")for(let u in l)!n9.call(r,u)&&u!=="default"&&rf(r,u,{get:()=>l[u],enumerable:!0});return r},He=r=>r&&r.__esModule?r:s9(rf({},"default",{value:r,enumerable:!0}),r);var F2=XS(i9=>{$c(i9,{FetchError:()=>Gn,Headers:()=>fi,Request:()=>ra,Response:()=>Mi,default:()=>g9});const qs=He(require("stream")),JS=He(require("http")),of=He(require("url")),A2=He(require("https")),uo=He(require("zlib")),r9=qs.default.Readable,Lr=Symbol("buffer"),ZS=Symbol("type");class Ou{constructor(){this[ZS]="";const r=arguments[0],l=arguments[1],u=[];let d=0;if(r){const g=r,I=Number(g.length);for(let S=0;S<I;S++){const x=g[S];let N;x instanceof Buffer?N=x:ArrayBuffer.isView(x)?N=Buffer.from(x.buffer,x.byteOffset,x.byteLength):x instanceof ArrayBuffer?N=Buffer.from(x):x instanceof Ou?N=x[Lr]:N=Buffer.from(typeof x=="string"?x:String(x)),d+=N.length,u.push(N)}}this[Lr]=Buffer.concat(u);let f=l&&l.type!==void 0&&String(l.type).toLowerCase();f&&!/[^\u0020-\u007E]/.test(f)&&(this[ZS]=f)}get size(){return this[Lr].length}get type(){return this[ZS]}text(){return Promise.resolve(this[Lr].toString())}arrayBuffer(){const r=this[Lr],l=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return Promise.resolve(l)}stream(){const r=new r9;return r._read=function(){},r.push(this[Lr]),r.push(null),r}toString(){return"[object Blob]"}slice(){const r=this.size,l=arguments[0],u=arguments[1];let d,f;l===void 0?d=0:l<0?d=Math.max(r+l,0):d=Math.min(l,r),u===void 0?f=r:u<0?f=Math.max(r+u,0):f=Math.min(u,r);const g=Math.max(f-d,0),I=this[Lr],S=I.slice(d,d+g),x=new Ou([],{type:arguments[2]});return x[Lr]=S,x}}Object.defineProperties(Ou.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Object.defineProperty(Ou.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0});function Gn(r,l,u){Error.call(this,r),this.message=r,this.type=l,u&&(this.code=this.errno=u.code),Error.captureStackTrace(this,this.constructor)}Gn.prototype=Object.create(Error.prototype);Gn.prototype.constructor=Gn;Gn.prototype.name="FetchError";let QS;try{QS=require("encoding").convert}catch(r){}const Sr=Symbol("Body internals"),v2=qs.default.PassThrough;function Dn(r){var l=this,u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=u.size;let f=d===void 0?0:d;var g=u.timeout;let I=g===void 0?0:g;r==null?r=null:N2(r)?r=Buffer.from(r.toString()):Eu(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 qs.default||(r=Buffer.from(String(r))))),this[Sr]={body:r,disturbed:!1,error:null},this.size=f,this.timeout=I,r instanceof qs.default&&r.on("error",function(S){const x=S.name==="AbortError"?S:new Gn(`Invalid response body while trying to fetch ${l.url}: ${S.message}`,"system",S);l[Sr].error=x})}Dn.prototype={get body(){return this[Sr].body},get bodyUsed(){return this[Sr].disturbed},arrayBuffer(){return Uc.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 Uc.call(this).then(function(l){return Object.assign(new Ou([],{type:r.toLowerCase()}),{[Lr]:l})})},json(){var r=this;return Uc.call(this).then(function(l){try{return JSON.parse(l.toString())}catch(u){return Dn.Promise.reject(new Gn(`invalid json response body at ${r.url} reason: ${u.message}`,"invalid-json"))}})},text(){return Uc.call(this).then(function(r){return r.toString()})},buffer(){return Uc.call(this)},textConverted(){var r=this;return Uc.call(this).then(function(l){return o9(l,r.headers)})}};Object.defineProperties(Dn.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});D
`)),h.join(`
`)}function Pk(e,t,n,s){const i=M(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,h=n==="complex64"?dh(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],uh(h[m+y],0,n).length)}return a}function uh(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(Zy))} + ${parseFloat(e[1].toFixed(Zy))}j`:Ji(e)?s=`'${e}'`:n==="bool"?s=DT(e):s=parseFloat(e.toFixed(Zy)).toString(),ct(s,t)}function DT(e){return e===0?"false":"true"}function tp(e,t,n,s,i,o=!0){const a=n==="complex64"?2:1,c=t[0],h=t.length;if(h===0){if(n==="complex64"){const T=dh(e);return[uh(T[0],0,n)]}return n==="bool"?[DT(e[0])]:[e[0].toString()]}if(h===1){if(c>ET){const v=hh*a;let C=Array.from(e.slice(0,v)),O=Array.from(e.slice((c-hh)*a,c*a));return n==="complex64"&&(C=dh(C),O=dh(O)),["["+C.map((D,k)=>uh(D,i[k],n)).join(", ")+", ..., "+O.map((D,k)=>uh(D,i[c-hh+k],n)).join(", ")+"]"]}const T=n==="complex64"?dh(e):Array.from(e);return["["+T.map((v,C)=>uh(v,i[C],n)).join(", ")+"]"]}const p=t.slice(1),m=s.slice(1),y=s[0]*a,b=[];if(c>ET){for(let T=0;T<hh;T++){const v=T*y,C=v+y;b.push(...tp(e.slice(v,C),p,n,m,i,!1))}b.push("...");for(let T=c-hh;T<c;T++){const v=T*y,C=v+y;b.push(...tp(e.slice(v,C),p,n,m,i,T===c-1))}}else for(let T=0;T<c;T++){const v=T*y,C=v+y;b.push(...tp(e.slice(v,C),p,n,m,i,T===c-1))}const w=h===2?",":"";b[0]="["+b[0]+w;for(let T=1;T<b.length-1;T++)b[T]=" "+b[T]+w;let L=`,
`;for(let T=2;T<h;T++)L+=`
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":L),b}function dh(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class an{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=M(e),n!=null){const s=n.length;A(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||Is(t,this.size),this.strides=Ke(e)}set(e,...t){t.length===0&&(t=[0]),A(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,za=null,kT=null;function zk(e){vi=e}function Vk(e){za=e}function Gk(e){kT=e}class te{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=M(e),this.strides=Ke(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 za.buffer(this.shape,this.dtype,e)}bufferSync(){return za.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return xs(this.shape,e)}arraySync(){return xs(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=>lh(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=>lh(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 za.print(this,e)}clone(){return this.throwIfDisposed(),za.clone(this)}toString(e=!1){const t=this.dataSync();return Mk(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),za.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),vi().makeVariable(this,e,t,n)}}Object.defineProperty(te,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class ph extends te{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(!ie(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(ph,Symbol.hasInstance,{value:e=>e instanceof te&&e.assign!=null&&e.assign instanceof Function});(function(e){e.R0="R0",e.R1="R1",
Manifest JSON has weights with names: ${c.join(", ")}.`)}const h=i.reduce((w,L,T)=>(L&&w.push(T),w),[]),p=[];h.forEach(w=>{t[w].paths.forEach(L=>{const T=n+(n.endsWith("/")?"":"/")+L;p.push(T)})});const m=await e(p),y={};let b=0;return h.forEach(w=>{const L=t[w].paths.length;let T=0;for(let k=0;k<L;k++)T+=m[b+k].byteLength;const v=new ArrayBuffer(T),C=new Uint8Array(v);let O=0;for(let k=0;k<L;k++){const F=new Uint8Array(m[b+k]);C.set(F,O),O+=F.byteLength}const D=o[w];D.forEach(k=>{const F=v.slice(k.groupOffset,k.groupOffset+k.sizeBytes),B=rp(F,[k.manifestEntry]);for(const $ in B)y[$]=B[$]}),b+=L}),y}}const _F="application/octet-stream",WF="application/json";class db{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?(A(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=ae().platform.fetch,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(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:WF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:_F}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:gh(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 h,p;if(s!=null){const b=await this.loadWeights(s);[h,p]=b}const m={modelTopology:n,weightSpecs:h,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]=$F(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 h=await QT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,op(h)]}}db.URL_SCHEME_REGEX=/^https?:\/\//;function
2020-10-15 12:48:39 +02:00
Actual: ${i}.
2020-10-29 05:16:50 +01:00
Expected: ${o}.`);for(let a=0;a<o.length;++a){const c=i[a],h=o[a];if(!n(c,h))throw new Error(`Arrays differ: actual[${a}] = ${c}, expected[${a}] = ${h}.
2020-10-15 12:48:39 +02:00
Actual: ${i}.
2020-10-29 05:16:50 +01:00
Expected: ${o}.`)}}function s_(e,t){e().then(()=>t.fail(),()=>t())}function i_(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ji(e)||Ji(e[0])||Ji(t)||Ji(t[0])?Sb(e,n,(s,i)=>s==i):Sb(e,t,(s,i)=>xb(s,i,0))}function Ib(e,t,n){if(n==null&&(n=mp()),!xb(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function xb(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function r_(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 o_(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var a_=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:fA,expectArraysClose:n_,testEpsilon:mp,expectPromiseToFail:s_,expectArraysEqual:i_,expectNumbersClose:Ib,expectValuesInRange:r_,expectArrayBuffersEqual:o_});const gA="2.7.0";function c_(){ae().set("PROD",!0)}function l_(){ae().set("DEBUG",!0)}function h_(){ae().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function dn(e){ae().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}Gk(dn);function u_(){G.disposeVariables()}function tr(){return G}function fp(){return G.memory()}function d_(e){return G.profile(e)}function ee(e,t){return G.tidy(e,t)}function qe(e){const t=Zi(e);t.forEach(n=>n.dispose())}function wn(e){return G.keep(e)}function p_(e){return G.time(e)}function yA(e){return G.setBackend(e)}function m_(){return G.ready()}function f_(){return G.backendName}function g_(e){G.removeBackend(e)}function y_(e){return G.findBackend(e)}function b_(e){return G.findBackendFactory(e)}function Tb(e,t,n=1){return G.registerBackend(e,t,n)}function bA(){return G.backend}function w_(e,t){ae().setPlatform(e,t)}function L_(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.add(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Oo)}const be=z({add_:L_});function S_(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.floorDiv(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Iy)}const gp=z({floorDiv_:S_});function I_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Gt(n,s),n.dtype==="int32"&&s.dtype==="int32")return gp(n,s);const i=(c,h)=>{const p=c.realDivide(n,s);return h([n,s]),p},o={a:n,b:s},a={};return G.runKernelFunc(i,o,null,_a,a)}const We=z({div_:I_});function x_(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.multiply(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Wa)}const X=z({mul_:x_});function T_(e){const t=W(e,"x","abs"),n={x:t};return G.runKernelFunc((s,i)=>(i([t]),t.dtype==="complex64"?s.complexAbs(t):s.abs(t)),n,null,wd)}const pn=z({abs_:T_});function A_(e){const t=W(e,"x","acos"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.acos(t);return i([t]),o},n,null,Ll)}const Ab=z({acos_:A_});function v_(e){const t=W(e,"x","acosh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.acosh(t);return i([t]),o},n,null,Sl)}const vb=z({acosh_:v_});function N_(e){A(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),A(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(!ie(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 G.runKernelFunc(s,i,null,ly)}const wA=z({addN_:N_});function Nb(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function LA(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 vn(e,t){const n=[],s=e.length;for(let o=0;o<s;o++)t.indexOf(o)===-1&
with dtype ${a.dtype}. `)});const s=(a,c)=>{const h=je(t,n[0].shape)[0],p=nr(n.map(b=>b.shape),h);if(M(p)===0)return sn([],p);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);Lp(m,h);const y=a.concat(n,h);return c(n),y},i=n,o={axis:t};return G.runKernelFunc(s,i,null,Rl,o)}const Yt=z({concat_:V_});function G_(e){const t=W(e,"x","sigmoid"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sigmoid(t);return i([o]),o},n,null,nh)}const Ri=z({sigmoid_:G_});function Y_(e,t,n){const s=W(e,"x","slice");if(s.rank===0)throw new Error("Slicing scalar is not possible");const i=(c,h)=>{const[p,m]=pp(s,t,n);return bb(s,p,m),h([s]),c.slice(s,p,m)},o={x:s},a={begin:t,size:n};return G.runKernelFunc(i,o,null,Vd,a)}const nt=z({slice_:Y_});function H_(e){const t=W(e,"x","tanh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.tanh(t);return i([o]),o},n,null,rh)}const Ka=z({tanh_:H_});function q_(e,t,n,s,i,o){const a=W(e,"forgetBias","basicLSTMCell"),c=W(t,"lstmKernel","basicLSTMCell"),h=W(n,"lstmBias","basicLSTMCell"),p=W(s,"data","basicLSTMCell"),m=W(i,"c","basicLSTMCell"),y=W(o,"h","basicLSTMCell"),b=Yt([p,y],1),w=lt(b,c),L=be(w,h),T=L.shape[0],v=L.shape[1]/4,C=[T,v],O=nt(L,[0,0],C),D=nt(L,[0,v],C),k=nt(L,[0,v*2],C),F=nt(L,[0,v*3],C),B=be(X(Ri(O),Ka(D)),X(m,Ri(be(a,k)))),$=X(Ka(B),Ri(F));return[B,$]}const j_=z({basicLSTMCell_:q_});function K_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((h,p)=>h*p);A(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),A(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),A(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=h=>h.batchToSpaceND(s,t,n),a={x:s},c={blockShape:t,crops:n};return G.runKernelFunc(o,a,null,py,c)}const Ih=z({batchToSpaceND_:K_});function X_(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 J_(e,t,n,s,i,o){o==null&&(o=.001);const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;s!=null&&(m=W(s,"offset","batchNorm")),A(c.rank===h.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(m==null||c.rank===m.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(p==null||c.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const y=X_(a),b=(v,C)=>(C([y,c,h,p]),v.batchNorm(y,Sp(c),Sp(h),Sp(m),Sp(p),o)),w={x:y,scale:p,offset:m,mean:c,variance:h},L={varianceEpsilon:o},T=G.runKernelFunc(b,w,null,Wl,L);return K(T,a.shape)}function Sp(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 Uo=z({batchNorm_:J_});function Z_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),A(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),A(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${c.rank}.`),A(h.rank===2||h.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${h.rank}.`),p!=null&&A(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),m!=null&&A(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${m.rank}.`),Uo(a,c,h,m,p,o)}const SA=z({batchNorm2d_:Z_});function Q_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let p;i!=null&&(p=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),A(a.rank===3,()=>`Error in ba
2020-10-15 12:48:39 +02:00
${i} and ${t} for depthToSpace with input shape
2020-10-29 05:16:50 +01:00
${s.shape}`),A(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
2020-10-15 12:48:39 +02:00
${o} and ${t} for depthToSpace with input shape
2020-10-29 05:16:50 +01:00
${s.shape}`),A(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),h={x:s},p={blockSize:t,dataFormat:n};return G.runKernelFunc(c,h,null,aT,p)}const Mb=z({depthToSpace_:wW});function LW(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","depthwiseConv2d"),h=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]])),A(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),A(h.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),A(p.shape[3]===h.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),a!=null&&A(we(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]),A(cn(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const C=_n(p.shape,h.shape,n,o,s,a,!0),O=T.depthwiseConv2D(p,h,C);return v([p,h]),O},b={x:p,filter:h},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},L=G.runKernelFunc(y,b,null,Nd,w);return m?K(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const Bo=z({depthwiseConv2d_:LW});function SW(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 G.runKernelFunc(n,s,null,cT)}const IW=z({diag_:SW});function xW(e,t,n,s,i=[1,1],o="NHWC"){const a=W(e,"x","dilation2d"),c=W(t,"filter","dilation2d");A(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),A(c.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${c.rank}.`),A(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let h=a,p=!1;a.rank===3&&(h=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),p=!0);const m={x:h,filter:c},y={strides:n,pad:s,dilations:i},b=G.runKernel(Cd,m,y);return p?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Pb=z({dilation2d_:xW});function Mo(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 mn(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 st(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 TW(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Gt(n,s),st(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,hT)}const ei=z({equal_:TW});function AW(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=st(s.shape,i.shape),c=xh(s,a),h=xh(i,a);o.rank===1&&A(o.shape[0]===s.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&U(o.shape,h.shape,"Error in where: ");const p=(y,b)=>{const w=y.select(o,c,h);return b([o]),w},m={condition:o,t:c,e:h};return G.runKernelFunc(p,m,null,Py)}const Pn=z({where_:AW});function vW(e){const t=W(e,"x","zerosLike"),n={x:t};return G.runKernelFunc(s=>s.zerosLike(t),n,null,jy)}const tt=z({zerosLike_:vW});function NW(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Gt(n,s);const i=We(n,s),o=tt(i),a=ei(s,o);return Pn(a,o,i)}const zb=z({divNoNan_:NW});function CW(e,t){const n=W(e,"t1","dot"),s=W(t,"t2","dot");A((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(A(i===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${o}.`),n.rank==
rank ${o.rank}.`),A(we(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 h=(b,w)=>{const L=b.localResponseNormalization4D(a,t,n,s,i);return w([a,L]),L},p={x:a},m={depthRadius:t,bias:n,alpha:s,beta:i},y=G.runKernelFunc(h,p,null,vy,m);return c?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const Hb=z({localResponseNormalization_:JW});function ZW(e){const t=W(e,"x","log"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.log(t);return i([t]),o},n,null,Pl)}const us=z({log_:ZW});function QW(e){const t=W(e,"x","log1p"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.log1p(t);return i([t]),o},n,null,zl)}const Cp=z({log1p_:QW});function e$(e){return A($r(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 G.tidy(()=>{const{value:o,grads:a}=G.gradients(()=>e(s),[s],i);return i!=null&&U(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Rp(a),a[0]})}}function t$(e){return A($r(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=fh(t,"args","tf.grads",null),i=n!=null?W(n,"dy","tf.grads"):null;return G.tidy(()=>{const{value:o,grads:a}=G.gradients(()=>e(...s),s,i);return i!=null&&U(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rp(a),a})}}function n$(e){return A($r(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof te,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof te,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=G.gradients(()=>e(t),[t],n);return Rp(s),{grad:s[0],value:i}}}function s$(e){return A($r(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(i=>i instanceof te),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof te,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=G.gradients(()=>e(...t),t,n);return n!=null&&U(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rp(s.grads),s}}function qb(e,t){A($r(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(p=>p instanceof ph),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const p in G.registeredVariables)t.push(G.registeredVariables[p])}const s=n?t.filter(p=>!p.trainable):null,i=t.length;t=t.filter(p=>p.trainable),A(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}=G.gradients(e,t,null,o);A(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()."),A(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const h={};return t.forEach((p,m)=>{c[m]!=null&&(h[p.name]=c[m])}),s!=null&&s.forEach(p=>h[p.name]=null),{value:a,grads:h}}function Oi(e){return G.customGrad(e)}function Rp(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
the f you passed encloses all operations that lead from x to y.`)}function i$(e){const t=W(e,"x","neg"),n={x:t};return G.runKernelFunc(s=>s.neg(t),n,null,ky)}const Ht=z({neg_:i$});function r$(e){const t=W(e,"x","softplus"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.softplus(t);return i([t]),o},n,null,sh)}const ec=z({softplus_:r$});function o$(e){const t=W(e,"x","logSigmoid"),n=Oi(s=>{const i=Ht(ec(Ht(s))),o=a=>{const c=X(a,Ri(Ht(s)));return c};return{value:i,gradFunc:o}});return n(t)}const _A=z({logSigmoid_:o$});function a$(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,h)=>{const p=je(t,s.shape);let m=p;const y=Qn(m,s.rank);let b=s;y!=null&&(b=Ye(s,y),m=hs(m.length,b.rank));const w=c.max(b,m);y!=null&&b.dispose();let L=w;if(n){const T=Nn(L.shape,je(t,s.shape));L=K(L,T),w.dispose()}return h([s,L]),L},o={x:s},a={reductionIndices:t,keepDims:n};return G.runKernelFunc(i,o,null,Vl,a)}const ns=z({max_:a$});function c$(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Gt(n,s);const i=(a,c)=>{const h=a.subtract(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Ba)}const Re=z({sub_:c$});function l$(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=ve(s,"int32"));const i=(c,h)=>{h([s]);const p=je(t,s.shape),m=Qn(p,s.rank);let y=p,b=s;m!=null&&(b=Ye(s,m),y=hs(y.length,s.rank));let w=c.sum(b,y);if(n){const L=Nn(w.shape,p);w=K(w,L)}return w},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,zy,a)}const $e=z({sum_:l$});function h$(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 h=!0,p=ns(e,t,!0),m=Re(e,p),y=Re(ve(m,"float32"),us($e(As(m),t,h)));return c([y]),y},i={logits:n},o={axis:t};return G.runKernelFunc(s,i,null,Ay,o)}const Op=z({logSoftmax_:h$});function u$(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=je(t,s.shape),o=ns(s,i,!0),a=Re(s,o),c=As(a),h=$e(c,i),p=us(h),m=be(K(o,p.shape),p);if(n){const y=Nn(m.shape,i);return K(m,y)}return m}const jb=z({logSumExp_:u$});function d$(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");st(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalAnd(n,s),i,null,gT)}const Ps=z({logicalAnd_:d$});function p$(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return G.runKernelFunc(s=>s.logicalNot(t),n,null,_d)}const Ch=z({logicalNot_:p$});function m$(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");st(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalOr(n,s),i,null,yT)}const Ep=z({logicalOr_:m$});function f$(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return st(n.shape,s.shape),Ps(Ep(e,t),Ch(Ps(e,t)))}const WA=z({logicalXor_:f$});function g$(e,t,n,s,i){const o=W(e,"x","maxPool"),a=1;let c=o,h=!1;o.rank===3&&(h=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(c.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${c.rank}.`),A(cn(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&A(we(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const p=(w,L)=>{const T=Mn(c.shape,t,n,1,s,i);let v;return T.filterWidth===1&&T.filterHeight===1&&ie(T.inShape,T.outShape)?v=c.clone():v=w.maxPool(c,T),L([c,v]),v},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=G.runKernelFunc(p,m,null,Gl,y);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Rh=z({maxPool_:g$});function y$(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:dn("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","maxPool3d");let h=c,p=!1;c.rank===4&&(p=!0,h=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),A(h.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${h.rank}.`),A(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),A(cn(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.
2020-10-29 05:16:50 +01:00
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 q(`${s}: Improper config format: ${JSON.stringify(o)}.
'className' and 'config' must set.`);const a=o.className;let c,h;if(a in n?[c,h]=n[a]:a in zs?[c,h]=zs.className:a in t&&([c,h]=t[a]),c==null)throw new q(`Unknown ${s}: ${a}. This may be due to one of the following reasons:
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.
2020-10-29 05:16:50 +01:00
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(h!=null){const p={};for(const w of Object.keys(zs))p[w]=zs[w];for(const w of Object.keys(n))p[w]=n[w];const m=o.config;m.customObjects=p;const y=Object.assign({},zs);for(const w of Object.keys(n))zs[w]=n[w];Dw(o.config);const b=h(c,o.config,n,i);return zs=Object.assign({},y),b}else{const p=Object.assign({},zs);for(const y of Object.keys(n))zs[y]=n[y];const m=new c(o.config);return zs=Object.assign({},p),m}}}function jz(e,t){return e<t?-1:e>t?1:0}function sm(e,t){return-1*jz(e,t)}function Tte(e){switch(e){case"float32":return"float32";default:throw new q(`Invalid dtype: ${e}`)}}function Ate(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 Jr(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function Kz(e){if(e==null)throw new q(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function uc(e,t,n){if(n==null)return;if(e.indexOf(n)<0)throw new q(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function kw(e,t,n=0,s=Infinity){return Cs(n>=0),Cs(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function Ln(e,t){Array.isArray(e)?(A(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>Ln(n,`element ${s+1} of ${t}`))):A(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${_v(e)}.`)}function _v(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>_v(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function Xz(e,t){let n=Jn(),s;const i=(...o)=>{const a=Jn();return a-n<t||(n=a,s=e(...o)),s};return i}function Wv(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function vte(...e){Cs(e.length>0,"arrayOfValues is empty");for(const t of e)Cs(Array.isArray(t),"one of the values is not an array"),Cs(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 Fw(e,t){return ee(()=>Cn($e(X(e,e),t,!0)))}class jh extends Wo{getConfig(){return{}}}class _w extends jh{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=Fw(e,this.axis),n=es(t,0,this.maxValue);return X(e,We(n,be(fn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}_w.className="MaxNorm",ge(_w);class Ww extends jh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>We(e,be(fn(),Fw(e,this.axis))))}getConfig(){return{axis:this.axis}}}Ww.className="UnitNorm",ge(Ww);class $w extends jh{apply(e){return Di(e)}}$w.className="NonNeg",ge($w);class Uw extends jh{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=Fw(e,this.axis),n=be(X(this.rate,es(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,We(n,be(fn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Uw.className="MinMaxNorm",ge(Uw);const $v={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function gn(e){return Ew(e)}function Uv(e,t={}){return qh(e,Bs.getMap().classNameMap,t,"constraint")}function yn(e){if(e==null)return null;if(typeof e=="string"){const t=e in $v?$v[e]:e,n={className:t,config:{}};return Uv(n)}else return e instanceof jh?e:Uv(e)}function Jz(e){return new _w(e)}function Zz(e){return new Ww(e)}function Qz(){return new $w}function e3(e){return new Uw(e)}var t3=Object.freeze({__
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),Ys(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,wn(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 sn([],[0].concat(this.elementShape));const n=this.readMany(e);return Ys(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),ss(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 sn([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const n=this.readMany(t);return Ys(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Yt(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,si(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
2020-10-15 12:48:39 +02:00
tensor.shape[0], but sum of lengths is
2020-10-29 05:16:50 +01:00
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);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 h=c===0?0:s[c-1],p=[0,h,0],m=[1,e[c],i];o[c]=K(nt(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 gu{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}`);Ys(t,i.shape,"TensorList shape mismatch: "),wn(i)}),this.idTensor=Ce(0),this.maxNumElements=s,wn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new gu([...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 Ys(e,this.elementShape,"TensorList shape mismatch: "),ee(()=>{const s=this.tensors.map(i=>K(i,e));return ss(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 Ys(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(Ys(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");wn(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 Ys(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.`);Ys(this.elementShape,t.shape,"TensorList shape mismatch: "),wn(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 Ys(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?sn([],[0].concat(this.elementShape)):ee(()=>{const s=e.map(i=>K(this.tensors[i],n));return ss(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Ys(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?sn([],[0].concat(this.elementShape)):ee(()=>{const n=this.tensors.map(s=>K(s,t));return Yt(n,0)})}}function LH(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
2020-10-15 12:48:39 +02:00
tensor.shape[0], but sum of lengths is
2020-10-29 05:16:50 +01:00
${s}, and tensor's shape is: ${e.shape}`);const o=s===0?0:e.size/s,a=ee(()=>{const h=[];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];h[p]=K(nt(e,y,b),n)}return e.dispose(),h}),c=new gu([],n,e.dtype,t.length);for(let h=0;h<a.length;h++)c.setItem(h,a[h]);return c}const TH=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 h=await a[0].data();a.forEach(m=>{!m.kept&&c.indexOf(m.id)===-1&&m.dispose()});let p=o;for(;h[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);h=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[pr(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=pr(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>os(i,t,n)!==void 0);if(s){const i=os(s,t,n);return[pr(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[pr(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[pr(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[pr(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),h=R("identicalElementShapes",e,t,n),p=R("name",e,t,n),m=new wH(p,i,s,o,h,a,c);return n.addTensorArray(m),[m.idTensor,Ce(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[Ce(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=IH(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=SH(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),gs(async()=>(await n.iterator()).columnMajorBatch(e,t,yq),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,gs(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,gs(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 gs(async()=>(await t.iterator()).map(n=>ee(()=>e(n))),this.size)}mapAsync(e){const t=this;return gs(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 gs(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,gs(async()=>{const s=yu(async()=>({value:await t.iterator(),done:!1}));return R0(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,gs(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=ic(t||Jn().toString());return gs(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,gs(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()}}Sc.MAX_BUFFER_SIZE=1e4;function gs(e,t=null){return new class extends Sc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function fq(e){return gs(async()=>C0(e),e.length)}function gq(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 gs(async()=>{const n=await v0(e,s=>{if(s instanceof Sc)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 nq(n,ro.SHORTEST)},t)}function yq(e){if(e===null)return null;const t=e[0];if(ZH(t)){const n=bq(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function bq(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof te?ss(e):sn(e)}class k0 extends Sc{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 Pm='"',bu=Symbol("out"),F0=Symbol("field"),zm=Symbol("quote"),vS=Symbol("quoteafterquote"),_0=Symbol("quoteinquote");class W0 extends Sc{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 k0(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(A(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&&A(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(A(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 h=null;if(c==="")if(a&&a.default!==void 0)h=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${o} is empty in this line: ${e}`);h=void 0}else{const p=Number(c);if(isNaN(p))a&&a.dtype==="bool"?h=this.getBoolean(c):h=c;else if(!a||!a.dtype)h=p;else switch(a.dtype){case"float32":h=p;break;case"int32":h=Math.floor(p);break;case"bool":h=this.getBoolean(c);break;default:h=p}}a&&a.isLabel?s[o]=h:n[o]=h}}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=bu;for(let a=0;a<i;a++)switch(o){case bu:switch(e.charAt(a)){case Pm:s=a+1,o=zm;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=bu;break;default:o=F0,s=a;break}break;case F0:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=bu,s=a+1;break;default:}break;case zm:switch(e.charAt(a)){case Pm:o=vS;break;default:}break;case vS:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=bu,s=a+1;break;case Pm:o=zm;break;default:o=_0;break}break;case _0:switch(e.charAt(a)){case Pm:o=zm;break;default:}break;default:}if(o===vS?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 $0 extends In{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-29 05:16:50 +01:00
============================`));const s={};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&Ji(n[0])){const i=n.map(o=>ep(o));s=this.write(i,e,t)}else 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 ar(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=>lh(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return tr().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=Jn();e();const n=Jn()-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=dp(t,n,s);if(i.some(c=>c===0))return sn([],i);const o=wt(i,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;c++){const h=o.indexToLoc(c),p=new Array(h.length);for(let m=0;m<p.length;m++)p[m]=h[m]*s[m]+t[m];o.set(a.get(...p),...h)}return o.toTensor()}diag(e){const t=this.readSync(e.dataId),n=wt([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 h=0;h<e.rank;h++)h!==t&&(s[i++]=e.shape[h]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let h=0;h<c.length;h++)o[t]=h,c[h]=nt(e,o,a).reshape(s);return c}reverse(e,t){Te(e,"reverse");const n=wt(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(Ce(-1),e)}addN(e){Te(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),n=wt(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=je([t],e.shape),s=ns(e,n),i=Nn(s.shape,n),o=Re(e,s.reshape(i)),a=As(o),c=this.sum(a,n).reshape(i);return We(a,c)}pow(e,t){return Te([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.pow(n,s))}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"),Zn("sum",t,e.rank);const[n,s]=vn(e.shape,t),i=Bn(e.dtype,"int32"),o=pt(n,i),a=M(s),c=this.readSync(o.dataId),h=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+=h[m+b];c[p]=y}return o}prod(e,t){Te(e,"sum");const[n,s]=vn(e.shape,t),i=Bn(e.dtype,"int32"),o=pt(n,i),a=M(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=1;for(let b=0;b<a;++b)y*=h[m+b];c[p]=y}return o}unsortedSegmentSum(e,t,n){Te(e,"unsortedSegmentSum");const s=[],i=e.rank-t.rank;for(let o=0;o<i;++o)t=t.expandDims(o+1);for(let o=0;o<n;++o){const a=Ce(o,"int32"),c=ei(a,t).asType("float32"),h=c.mul(e).sum(0);s.push(h)}return ss(s)}argMin(e,t){Te(e,"argMin");const n=[t];Zn("argMin",n,e.rank);const[s,i]=vn(e.shape,n),o=pt(s,"int32"),a=M(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let p=0;p<c.length;++p){const m=p*a;let y=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L<y&&(y=L,b=w)}c[p]=b}return o}argMax(e,t
`),o=i.length.toString().length+2,a=i.map((y,b)=>ct((b+1).toString(),o)+y);let c=0;for(let y=0;y<a.length;y++)c=Math.max(a[y].length,c);const h=a.slice(0,s-1),p=a.slice(s-1,s),m=a.slice(s);console.log(h.join(`
2020-10-15 12:48:39 +02:00
`)),console.log(t.split(`
2020-10-29 05:16:50 +01:00
`)[0]),console.log(`%c ${ct(p[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
`))}function r5(e){return mr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function o5(e,t){if(Ee(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 WS(e,t){if(Ee(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function a5(e,t){const n=mr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Ee(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function c5(e,t){const n=mr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ee(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Ee(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Hne(){return ae().getNumber("WEBGL_VERSION")===2?1:4}function l5(e){return mr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function h5(e,t){const n=ae().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 u5(e){return mr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function SC(e,t,n,s,i,o,a){const c=e.getAttribLocation(t,n);return c===-1?!1:(Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Ee(e,()=>e.vertexAttribPointer(c,i,e.FLOAT,!1,o,a)),Ee(e,()=>e.enableVertexAttribArray(c)),!0)}function d5(e,t,n){xC(e,n),Ee(e,()=>e.activeTexture(e.TEXTURE0+n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function qne(e,t){xC(e,t),Ee(e,()=>e.activeTexture(e.TEXTURE0+t)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function p5(e,t,n){return mr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function m5(e,t,n){return e.getUniformLocation(t,n)}function f5(e,t,n,s){Ee(e,()=>d5(e,t,s)),Ee(e,()=>e.uniform1i(n,s))}function jne(e){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ee(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Ee(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function $S(e,t,n){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function IC(e,t){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Ym(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+g5(e,t))}function g5(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 mr(e,t,n){const s=Ee(e,()=>t());if(s==null)throw new Error(n);return s}function xC(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 vc(e,t=2){return M(e.slice(0,e.length-t))}function Nc(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 US(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[vc(e),...Nc(e)]),t}function y5(e,t=!1){let n=ae().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?x(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=hn(e);e=i.newShape}let s=M(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);
}
2020-10-29 05:16:50 +01:00
`}}class B5{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=`
2020-10-15 12:48:39 +02:00
void main() {
${n.join(`
`)}
vec4 result = ${s};
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class M5{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=`
2020-10-15 12:48:39 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${s}; i++) {
int inIdx = ${c};
float candidate = getA(batch, inIdx);
if (candidate ${a} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
2020-10-29 05:16:50 +01:00
`}}function AC(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function zn(e,t){return t===1?[e]:AC(e,t)}function P5(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 Vn(){let e,t,n,s,i,o,a,c,h,p;return ae().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",i="texture",o="outputColor",a="out vec4 outputColor;",c=`
2020-10-15 12:48:39 +02:00
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
2020-10-29 05:16:50 +01:00
`,h="",p=`
2020-10-15 12:48:39 +02:00
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`):(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));
}
2020-10-29 05:16:50 +01:00
`,h=`
2020-10-15 12:48:39 +02:00
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,p=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-10-29 05:16:50 +01:00
`),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:i,output:o,defineOutput:a,defineSpecialNaN:c,defineSpecialInf:h,defineRound:p}}function na(e,t,n="index"){const s=Ke(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 Xm(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function Jne(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(`${Xm(a)}, ${Xm(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(`${Xm(o)}, ${Xm(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function PS(e){const t=Ke(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;
}
2020-10-29 05:16:50 +01:00
`}const vC=`
2020-10-15 12:48:39 +02:00
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
2020-10-29 05:16:50 +01:00
`;const{getBroadcastDims:NC}=Nw;function z5(e,t,n,s){const i=[];e.forEach(L=>{const T=M(L.shapeInfo.logicalShape);L.shapeInfo.isUniform?i.push(`uniform float ${L.name}${T>1?`[${T}]`:""};`):(i.push(`uniform sampler2D ${L.name};`),i.push(`uniform int offset${L.name};`))});const o=i.join(`
`),a=e.map(L=>V5(L,t,s)).join(`
`),c=t.texShape,h=Vn(),p=H5(h);let m,y,b=K5(h);t.isPacked?(m=G5(t.logicalShape,c),y=j5(h)):(m=Y5(t.logicalShape,c),y=q5(h)),s&&(b+=Q5);const w=[b,p,y,o,m,a,n].join(`
`);return w}function Cc(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return u8(e);case 1:return p8(e);case 2:return f8(e);case 3:return y8(e);case 4:return w8(e);case 5:return L8(e);case 6:return S8(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function CC(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return h8(e);case 1:return d8(e);case 2:return m8(e);case 3:return g8(e);default:return b8(e)}}function V5(e,t,n=!1){let s="";n?s+=CC(e):s+=Cc(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=I8(e,t):s+=x8(e,t)),s}function G5(e,t){switch(e.length){case 0:return RC();case 1:return e8(e,t);case 2:return c8(e,t);case 3:return n8(e,t);default:return i8(e,t)}}function Y5(e,t){switch(e.length){case 0:return RC();case 1:return t8(e,t);case 2:return l8(e,t);case 3:return s8(e,t);case 4:return r8(e,t);case 5:return o8(e,t);case 6:return a8(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function H5(e){return`
2020-10-15 12:48:39 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
2020-10-29 05:16:50 +01:00
`}function q5(e){return`
2020-10-15 12:48:39 +02:00
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
2020-10-29 05:16:50 +01:00
`}function j5(e){return`
2020-10-15 12:48:39 +02:00
void setOutput(vec4 val) {
${e.output} = val;
}
2020-10-29 05:16:50 +01:00
`}function K5(e){const t=`${e.version}
2020-10-15 12:48:39 +02:00
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
2020-10-29 05:16:50 +01:00
${X5}
${J5}
${Z5}
`;return t}const X5=`
2020-10-15 12:48:39 +02:00
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-10-29 05:16:50 +01:00
`,J5=`
2020-10-15 12:48:39 +02:00
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-10-29 05:16:50 +01:00
`,Z5=`
2020-10-15 12:48:39 +02:00
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
2020-10-29 05:16:50 +01:00
`,Q5=`
2020-10-15 12:48:39 +02:00
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
2020-10-29 05:16:50 +01:00
`;function RC(){return`
2020-10-15 12:48:39 +02:00
int getOutputCoords() {
return 0;
}
2020-10-29 05:16:50 +01:00
`}function e8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?`
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}function t8(e,t){return t[0]===1?`
2020-10-15 12:48:39 +02:00
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
2020-10-29 05:16:50 +01:00
`}function n8(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`
2020-10-15 12:48:39 +02:00
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-29 05:16:50 +01:00
`}function s8(e,t){const n=na(["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);
}
2020-10-29 05:16:50 +01:00
`}function i8(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 h=2;h<e.length-1;h++)o*=e[e.length-h-1],a=`
int b${h} = index / ${o};
index -= b${h} * ${o};
`+a,c=`b${h}, `+c;return`
2020-10-15 12:48:39 +02:00
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-29 05:16:50 +01:00
`}function r8(e,t){const n=na(["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-29 05:16:50 +01:00
`}function o8(e,t){const n=na(["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-29 05:16:50 +01:00
`}function a8(e,t){const n=na(["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;
}
2020-10-29 05:16:50 +01:00
`}function c8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ie(e,t))return`
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}function l8(e,t){return ie(e,t)?`
2020-10-15 12:48:39 +02:00
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-29 05:16:50 +01:00
`}function sa(e){return`offset${e}`}function h8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Vn();return`
2020-10-15 12:48:39 +02:00
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
}
2020-10-29 05:16:50 +01:00
`}function u8(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`
2020-10-15 12:48:39 +02:00
float ${n}() {
return sampleTexture(${t}, halfCR);
}
2020-10-29 05:16:50 +01:00
`;const[o,a]=e.shapeInfo.texShape,c=sa(t);return`
2020-10-15 12:48:39 +02:00
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
return sampleTexture(${t}, uv);
}
2020-10-29 05:16:50 +01:00
`}function d8(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=Vn();return`
2020-10-15 12:48:39 +02:00
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${o.texture2D}(${t}, uv);
}
2020-10-29 05:16:50 +01:00
`}function p8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
2020-10-15 12:48:39 +02:00
float ${n}(int index) {
2020-10-29 05:16:50 +01:00
${Rc(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-29 05:16:50 +01:00
`;const a=sa(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);
}
2020-10-29 05:16:50 +01:00
`}function m8(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=Vn();if(i!=null&&ie(t,i))return`
2020-10-15 12:48:39 +02:00
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${o}.0);
return ${c.texture2D}(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`;const h=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],p=Math.ceil(t[1]/2);return`
2020-10-15 12:48:39 +02:00
vec4 ${s}(int row, int col) {
2020-10-29 05:16:50 +01:00
vec2 uv = packedUVfrom2D(${p}, ${h[0]}, ${h[1]}, row, col);
2020-10-15 12:48:39 +02:00
return ${c.texture2D}(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`}function f8(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&&ie(t,i)){const y=i[0],b=i[1];return`
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`}const{newShape:o,keptDims:a}=hn(t),c=o;if(c.length<t.length){const y=Oc(e,c),b=["row","col"];return`
${Cc(y)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ec(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-29 05:16:50 +01:00
${Rc(e)}
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
`;const h=i[0],p=i[1],m=sa(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));
2020-10-29 05:16:50 +01:00
vec2 uv = vec2(0.5, (index + 0.5) / ${h}.0);
2020-10-15 12:48:39 +02:00
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`:h===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((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};
2020-10-29 05:16:50 +01:00
vec2 uv = uvFromFlat(${h}, ${p}, index);
2020-10-15 12:48:39 +02:00
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`}function g8(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=Oc(e,y),L=["b","row","col"];return`
${CC(w)}
2020-10-15 12:48:39 +02:00
vec4 ${s}(int b, int row, int col) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ec(L,b)});
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
`}const a=o[0],c=o[1],h=Math.ceil(t[2]/2),p=h*Math.ceil(t[1]/2),m=Vn();return`
2020-10-15 12:48:39 +02:00
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
2020-10-29 05:16:50 +01:00
${a}, ${c}, ${p}, ${h}, b, row, col);
2020-10-15 12:48:39 +02:00
return ${m.texture2D}(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`}function y8(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}=hn(t),h=a;if(h.length<t.length){const L=Oc(e,h),T=["row","col","depth"];return`
${Cc(L)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ec(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-29 05:16:50 +01:00
${Rc(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-29 05:16:50 +01:00
`;const w=sa(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);
}
2020-10-29 05:16:50 +01:00
`}function b8(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],h=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 L=2;L<n-1;L++)y=`int b${L}, `+y,m*=t[n-L-1],b=`b${L} * ${m} + `+b;const w=Vn();return`
2020-10-15 12:48:39 +02:00
vec4 ${i}(${y}) {
int index = ${b};
2020-10-29 05:16:50 +01:00
int texR = index / ${h};
int texC = index - texR * ${h};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}, ${c});
2020-10-15 12:48:39 +02:00
return ${w.texture2D}(${s}, uv);
}
2020-10-29 05:16:50 +01:00
`}function w8(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:h}=hn(t);if(c.length<t.length){const L=Oc(e,c),T=["row","col","depth","depth2"];return`
${Cc(L)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ec(T,h)});
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-29 05:16:50 +01:00
${Rc(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-29 05:16:50 +01:00
`;const w=sa(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-29 05:16:50 +01:00
`}function L8(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:h,keptDims:p}=hn(t);if(h.length<t.length){const T=Oc(e,h),v=["row","col","depth","depth2","depth3"];return`
${Cc(T)}
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ec(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-29 05:16:50 +01:00
${Rc(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-29 05:16:50 +01:00
`;const L=sa(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} +
2020-10-29 05:16:50 +01:00
depth2 * ${i} + depth3 + ${L};
2020-10-15 12:48:39 +02:00
vec2 uv = uvFromFlat(${b}, ${w}, index);
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`}function S8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=hn(t);if(i.length<t.length){const v=Oc(e,i),C=["row","col","depth","depth2","depth3","depth4"];return`
${Cc(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-29 05:16:50 +01:00
return ${s}(${Ec(C,o)});
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
`}const a=t[5],c=t[4]*a,h=t[3]*c,p=t[2]*h,m=t[1]*p;if(e.shapeInfo.isUniform)return`
2020-10-15 12:48:39 +02:00
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
2020-10-29 05:16:50 +01:00
vec4(${m}, ${p}, ${h}, ${c})) +
2020-10-15 12:48:39 +02:00
dot(
vec2(depth3, depth4),
vec2(${a}, 1)));
2020-10-29 05:16:50 +01:00
${Rc(e)}
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
`;const y=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],L=b[1];if(L===m&&y==null)return`
2020-10-15 12:48:39 +02:00
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),
2020-10-29 05:16:50 +01:00
vec4(${p}, ${h}, ${c}, ${a})) +
2020-10-15 12:48:39 +02:00
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-29 05:16:50 +01:00
vec2(${L}.0, ${w}.0);
2020-10-15 12:48:39 +02:00
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`;if(L===a&&y==null)return`
2020-10-15 12:48:39 +02:00
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) /
2020-10-29 05:16:50 +01:00
vec2(${L}.0, ${w}.0);
2020-10-15 12:48:39 +02:00
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`;const T=sa(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.
2020-10-29 05:16:50 +01:00
int index = row * ${m} + col * ${p} + depth * ${h} +
2020-10-15 12:48:39 +02:00
depth2 * ${c} + depth3 * ${a} + depth4 + ${T};
2020-10-29 05:16:50 +01:00
vec2 uv = uvFromFlat(${w}, ${L}, index);
2020-10-15 12:48:39 +02:00
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`}function Rc(e){const t=e.name,n=M(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];
}
}
2020-10-29 05:16:50 +01:00
`}function I8(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),h=Rt(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(O=>`coords.${y[O+p]} = 0;`).join(`
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((O,D)=>`coords.${y[D+p]}`).join(", ");let w="return outputValue;";const L=M(e.shapeInfo.logicalShape),T=L===1,v=M(t.logicalShape),C=v===1;if(o===1&&!T&&!C)w=`
2020-10-15 12:48:39 +02:00
return vec4(outputValue.xy, outputValue.xy);
2020-10-29 05:16:50 +01:00
`;else if(T&&!C)a===1?w=`
2020-10-15 12:48:39 +02:00
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:w=`
return vec4(outputValue.x);
2020-10-29 05:16:50 +01:00
`;else if(c.length){const O=o-2,D=o-1;c.indexOf(O)>-1&&c.indexOf(D)>-1?w="return vec4(outputValue.x);":c.indexOf(O)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(D)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
2020-10-15 12:48:39 +02:00
vec4 ${i}() {
2020-10-29 05:16:50 +01:00
${h} coords = getOutputCoords();
2020-10-15 12:48:39 +02:00
${m}
vec4 outputValue = get${s}(${b});
${w}
}
2020-10-29 05:16:50 +01:00
`}function x8(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,h=t.logicalShape.length;if(!e.shapeInfo.isUniform&&c===h&&e.shapeInfo.flatOffset==null&&ie(a,o))return`
2020-10-15 12:48:39 +02:00
float ${i}() {
return sampleTexture(${n}, resultUV);
}
2020-10-29 05:16:50 +01:00
`;const p=Rt(h),m=NC(e.shapeInfo.logicalShape,t.logicalShape),y=h-c;let b;const w=["x","y","z","w","u","v"];c===0?b="":h<2&&m.length>=1?b="coords = 0;":b=m.map(T=>`coords.${w[T+y]} = 0;`).join(`
`);let L="";return h<2&&c>0?L="coords":L=e.shapeInfo.logicalShape.map((T,v)=>`coords.${w[v+y]}`).join(", "),`
2020-10-15 12:48:39 +02:00
float ${i}() {
${p} coords = getOutputCoords();
${b}
2020-10-29 05:16:50 +01:00
return get${s}(${L});
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
`}function Rt(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 Oc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Ec(e,t){return t.map(n=>e[n]).join(", ")}class T8{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,A(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,h=Rt(c),p=zn("coords",c);let m,y;if(o===1){y=c+1;const $=Rt(y);m=`
${$} sourceLocR = ${$}(${p.join()}, 0);
2020-10-15 12:48:39 +02:00
++${p[c-1]};
2020-10-29 05:16:50 +01:00
${$} sourceLocG = ${$}(${p.join()}, 0);
2020-10-15 12:48:39 +02:00
++${p[c-2]};
2020-10-29 05:16:50 +01:00
${$} sourceLocA = ${$}(${p.join()}, 0);
2020-10-15 12:48:39 +02:00
--${p[c-1]};
2020-10-29 05:16:50 +01:00
${$} sourceLocB = ${$}(${p.join()}, 0);
2020-10-15 12:48:39 +02:00
--${p[c-2]};`}else y=c,m=`
2020-10-29 05:16:50 +01:00
${h} sourceLocR = coords;
2020-10-15 12:48:39 +02:00
++${p[c-1]};
2020-10-29 05:16:50 +01:00
${h} sourceLocG = coords;
2020-10-15 12:48:39 +02:00
++${p[c-2]};
2020-10-29 05:16:50 +01:00
${h} sourceLocA = coords;
2020-10-15 12:48:39 +02:00
--${p[c-1]};
2020-10-29 05:16:50 +01:00
${h} sourceLocB = coords;
--${p[c-2]};`;const b=["x","y","z","w","u","v"].slice(0,y),w="."+b[y-1],L=b.map($=>"int "+$),T=zn("sourceLocR",y-1).concat("inIdx.r"),v=zn("sourceLocG",y-1).concat("inIdx.g"),C=zn("sourceLocB",y-1).concat("inIdx.b"),O=zn("sourceLocA",y-1).concat("inIdx.a"),D=n==="max"?"greaterThan":"lessThan",k=s?"":`
2020-10-15 12:48:39 +02:00
inIdx = round(vec4(getBestIndicesAChannel(${T.join()}),
getBestIndicesAChannel(${v.join()}),
2020-10-29 05:16:50 +01:00
getBestIndicesAChannel(${C.join()}),
getBestIndicesAChannel(${O.join()})));`,F=`vec4(
2020-10-15 12:48:39 +02:00
getAChannel(${T.join()}),
hasNextCol ? getAChannel(${v.join()}) : 0.,
2020-10-29 05:16:50 +01:00
hasNextRow ? getAChannel(${C.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${O.join()}) : 0.)`,B=s?"":`
float getBestIndicesAChannel(${L.join()}) {
2020-10-15 12:48:39 +02:00
return getChannel(getBestIndicesA(${b.join()}),
vec2(${b.slice(-2).join()}));
}`;this.userCode=`
2020-10-29 05:16:50 +01:00
float getAChannel(${L.join()}) {
2020-10-15 12:48:39 +02:00
return getChannel(getA(${b.join()}),
vec2(${b.slice(-2).join()}));
}
${B}
void main() {
2020-10-29 05:16:50 +01:00
${h} coords = getOutputCoords();
2020-10-15 12:48:39 +02:00
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);
2020-10-29 05:16:50 +01:00
vec4 bestValue = ${F};
2020-10-15 12:48:39 +02:00
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
2020-10-29 05:16:50 +01:00
${k}
vec4 candidate = ${F};
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class A8{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,h=e.effectiveFilterWidth,p=c-1-e.padInfo.top,m=h-1-e.padInfo.left,y=1/(t*n);this.userCode=`
2020-10-15 12:48:39 +02:00
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);
2020-10-29 05:16:50 +01:00
for (int wC = 0; wC < ${h};
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class v8{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,h=e.dilationHeight,p=e.dilationWidth,m=e.effectiveFilterDepth,y=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,L=y-1-e.padInfo.top,T=b-1-e.padInfo.left,v=1/(t*n*s);this.userCode=`
const ivec3 pads = ivec3(${w}, ${L}, ${T});
2020-10-15 12:48:39 +02:00
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};
2020-10-29 05:16:50 +01:00
wR += ${h}) {
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}const OC=`
2020-10-15 12:48:39 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-29 05:16:50 +01:00
`,N8=`
2020-10-15 12:48:39 +02:00
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
2020-10-29 05:16:50 +01:00
`,C8=`
2020-10-15 12:48:39 +02:00
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
2020-10-29 05:16:50 +01:00
`,Zne="return (a - b) * (a - b);",R8="return float(a == b);",O8="return float(a < b);",E8="return float(a <= b);",D8="return float(a > b);",k8="return float(a >= b);",F8="return float(a >= 1.0 && b >= 1.0);",_8="return float(a >= 1.0 || b >= 1.0);",W8=OC+`
2020-10-15 12:48:39 +02:00
return max(a, b);
2020-10-29 05:16:50 +01:00
`,$8=OC+`
2020-10-15 12:48:39 +02:00
return min(a, b);
2020-10-29 05:16:50 +01:00
`,U8=`if (b == 0.0) return NAN;
return mod(a, b);`,B8="return (b >= 1.0) ? a : a * (b + 1.0);",EC="return (a < 0.) ? b * a : a;";class $n{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=st(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));
}
2020-10-29 05:16:50 +01:00
`}}const Jm=`
2020-10-15 12:48:39 +02:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2020-10-29 05:16:50 +01:00
`,M8=`
2020-10-15 12:48:39 +02:00
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
2020-10-29 05:16:50 +01:00
`,P8=`
2020-10-15 12:48:39 +02:00
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
2020-10-29 05:16:50 +01:00
`+Jm+`
2020-10-15 12:48:39 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,DC=`
2020-10-15 12:48:39 +02:00
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
2020-10-29 05:16:50 +01:00
`,z8=`
2020-10-15 12:48:39 +02:00
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
2020-10-29 05:16:50 +01:00
`,V8=`
2020-10-15 12:48:39 +02:00
return vec4(equal(a, b));
2020-10-29 05:16:50 +01:00
`,Qne=`
2020-10-15 12:48:39 +02:00
return vec4(notEqual(a, b));
2020-10-29 05:16:50 +01:00
`,G8=`
2020-10-15 12:48:39 +02:00
return vec4(lessThan(a, b));
2020-10-29 05:16:50 +01:00
`,Y8=`
2020-10-15 12:48:39 +02:00
return vec4(lessThanEqual(a, b));
2020-10-29 05:16:50 +01:00
`,H8=`
2020-10-15 12:48:39 +02:00
return vec4(greaterThan(a, b));
2020-10-29 05:16:50 +01:00
`,q8=`
2020-10-15 12:48:39 +02:00
return vec4(greaterThanEqual(a, b));
2020-10-29 05:16:50 +01:00
`,j8=`
2020-10-15 12:48:39 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2020-10-29 05:16:50 +01:00
`,K8=`
2020-10-15 12:48:39 +02:00
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
2020-10-29 05:16:50 +01:00
`,X8=`
2020-10-15 12:48:39 +02:00
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-29 05:16:50 +01:00
`+Jm+`
2020-10-15 12:48:39 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,J8=`
2020-10-15 12:48:39 +02:00
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-29 05:16:50 +01:00
`+Jm+`
2020-10-15 12:48:39 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,Z8=`
2020-10-15 12:48:39 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2020-10-29 05:16:50 +01:00
`+Jm+`
2020-10-15 12:48:39 +02:00
return result;
2020-10-29 05:16:50 +01:00
`;class fr{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=st(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||M(this.outputShape)===1)o=`
2020-10-15 12:48:39 +02:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
2020-10-29 05:16:50 +01:00
`;else{const a=Rt(i);if(o=`
2020-10-15 12:48:39 +02:00
${a} coords = getOutputCoords();
`,i===1)o+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
2020-10-29 05:16:50 +01:00
`;else{const c=zn("coords",i);o+=`
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class Q8{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
2020-10-29 05:16:50 +01:00
`}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 e6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float minVal;
uniform float maxVal;
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
2020-10-29 05:16:50 +01:00
`}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 t6{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
2020-10-29 05:16:50 +01:00
`}}class n6{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=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
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);
}
2020-10-29 05:16:50 +01:00
`}}class s6{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,h=o?1:2,p=o?2:3,m=o?3:1;this.userCode=`
2020-10-15 12:48:39 +02:00
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${m}];
2020-10-29 05:16:50 +01:00
ivec2 dyCorner = ivec2(coords[${h}], coords[${p}]) - pads;
2020-10-15 12:48:39 +02:00
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
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);
}
2020-10-29 05:16:50 +01:00
`}}class i6{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=`
2020-10-15 12:48:39 +02:00
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
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);
}
2020-10-29 05:16:50 +01:00
`}}class r6{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,h=n-1-e.padInfo.top,p=s-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${c}, ${h}, ${p});
2020-10-15 12:48:39 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
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);
}
2020-10-29 05:16:50 +01:00
`}}class o6{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=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
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);
}
2020-10-29 05:16:50 +01:00
`}}class a6{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=`
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class kC{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,h=e.dilationHeight,p=e.dilationWidth,m=e.filterHeight,y=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,L=e.dataFormat==="channelsLast",T=L?1:2,v=L?2:3,C=L?3:1;let O="",D="";n&&(s?O=`float activation(float a) {
2020-10-15 12:48:39 +02:00
float b = getPreluActivationWeightsAtOutCoords();
${n}
2020-10-29 05:16:50 +01:00
}`:O=`
2020-10-15 12:48:39 +02:00
float activation(float x) {
${n}
}
2020-10-29 05:16:50 +01:00
`,D="result = activation(result);");const k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${O}
2020-10-15 12:48:39 +02:00
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${i}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
2020-10-29 05:16:50 +01:00
int d2 = coords[${C}];
2020-10-15 12:48:39 +02:00
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++) {
2020-10-29 05:16:50 +01:00
int xR = xRCorner + wR * ${h};
2020-10-15 12:48:39 +02:00
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)
);
2020-10-29 05:16:50 +01:00
if (${L}) {
2020-10-15 12:48:39 +02:00
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${w===1}) {
2020-10-29 05:16:50 +01:00
if (${L}) {
2020-10-15 12:48:39 +02:00
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)
);
2020-10-29 05:16:50 +01:00
if (${L}) {
2020-10-15 12:48:39 +02:00
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)
);
2020-10-29 05:16:50 +01:00
if (${L}) {
2020-10-15 12:48:39 +02:00
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;
2020-10-29 05:16:50 +01:00
${k}
2020-10-15 12:48:39 +02:00
${D}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class c6{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,h=e.dilationHeight,p=e.dilationWidth,m=e.filterDepth,y=e.filterHeight,b=e.filterWidth,w=Math.floor(e.inChannels/4)*4,L=e.inChannels%4;this.userCode=`
2020-10-15 12:48:39 +02:00
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++) {
2020-10-29 05:16:50 +01:00
int xR = xRCorner + wR * ${h};
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
if (${L===1}) {
2020-10-15 12:48:39 +02:00
dotProd +=
getX(batch, xF, xR, xC, ${w}) *
getW(wF, wR, wC, ${w}, d2);
2020-10-29 05:16:50 +01:00
} else if (${L===2}) {
2020-10-15 12:48:39 +02:00
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);
2020-10-29 05:16:50 +01:00
} else if (${L===3}) {
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class FC{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,h=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=e.outChannels/e.inChannels;let T="",v="";n&&(s?T=`float activation(float a) {
2020-10-15 12:48:39 +02:00
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:T=`
float activation(float x) {
${n}
}
2020-10-29 05:16:50 +01:00
`,v="result = activation(result);");const C=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
2020-10-15 12:48:39 +02:00
${T}
2020-10-29 05:16:50 +01:00
const ivec2 strides = ivec2(${h}, ${p});
2020-10-15 12:48:39 +02:00
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;
2020-10-29 05:16:50 +01:00
int d1 = d2 / ${L};
int q = d2 - d1 * ${L};
2020-10-15 12:48:39 +02:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
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;
2020-10-29 05:16:50 +01:00
${C}
2020-10-15 12:48:39 +02:00
${v}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class _C{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,h=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=w;let T="int xR; int xC; int xCOffset;";for(let D=0;D<b;D++)for(let k=0;k<w;k++)T+=`
vec4 xTexelR${D}C${k*2} = vec4(0.);
vec4 wR${D}C${k} = vec4(0.);
vec4 xR${D}C${k} = vec4(0.);`;for(let D=0;D<b;D++)for(let k=0;k<L;k++){const F=k*2;if(T+=`
2020-10-15 12:48:39 +02:00
xR = xRCorner + ${D*m};
2020-10-29 05:16:50 +01:00
xC = xCCorner + ${F*y};
`,p===1){if(F<w&&(c%2===1?T+=`
2020-10-15 12:48:39 +02:00
xCOffset = xC + 1;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F}.zw = vec2(0.);
2020-10-15 12:48:39 +02:00
}
} else {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
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.);
}
2020-10-29 05:16:50 +01:00
xR${D}C${F} = vec4(previous.zw, xTexelR${D}C${F}.xy);
2020-10-15 12:48:39 +02:00
} else {
2020-10-29 05:16:50 +01:00
xR${D}C${F} = vec4(0, 0, xTexelR${D}C${F}.xy);
2020-10-15 12:48:39 +02:00
}
`:T+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = getX(batch, xR, xC, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
xR${D}C${F} = xTexelR${D}C${F};
`,F+1<w)){const B=c%2===0?x(y):y;y%2===0&&c%2===1||y%2!==0&&c%2!==1?(T+=`
2020-10-15 12:48:39 +02:00
xCOffset = xC + ${c%2} + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
}
`,y>1&&(T+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
`),T+=`
2020-10-29 05:16:50 +01:00
xR${D}C${F+1} = vec4(
xTexelR${D}C${F}.zw, xTexelR${D}C${F+2}.xy);
2020-10-15 12:48:39 +02:00
`):T+=`
xCOffset = xC + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
xR${D}C${F+1} = xTexelR${D}C${F+2};
`}}else F<w&&(T+=`
2020-10-15 12:48:39 +02:00
if(xR >= 0 && xR < ${i}) {
`,c%2===1?(T+=`
xCOffset = xC + 1 - ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
if(xC + 1 >= 0 && xC + 1 < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F+2} = getX(batch, xR, xC + 1, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F+2} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
xR${D}C${F} = vec4(
xTexelR${D}C${F}.zw, xTexelR${D}C${F+2}.zw);
`,F+1<w&&(T+=`
2020-10-15 12:48:39 +02:00
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
final = getX(batch, xR, xCOffset, d1);
}
2020-10-29 05:16:50 +01:00
xR${D}C${F+1} = vec4(xTexelR${D}C${F+2}.xy, final.xy);
2020-10-15 12:48:39 +02:00
`)):(T+=`
if(xC >= 0 && xC < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = getX(batch, xR, xC, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
xCOffset = xC + ${p};
if(xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-15 12:48:39 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${D}C${F+2} = vec4(0.);
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
xR${D}C${F} = vec4(
xTexelR${D}C${F}.xy, xTexelR${D}C${F+2}.xy);
`,F+1<w&&(T+=`
xR${D}C${F+1} = vec4(
xTexelR${D}C${F}.zw, xTexelR${D}C${F+2}.zw);
`)),T+="}");F<w&&(T+=`
vec4 wTexelR${D}C${F} = getW(${D}, ${F}, d1, q);
wR${D}C${F} = vec4(wTexelR${D}C${F}.xz, wTexelR${D}C${F}.xz);
`,F+1<w&&(T+=`
vec4 wTexelR${D}C${F+1} = getW(${D}, ${F+1}, d1, q);
wR${D}C${F+1} =
vec4(wTexelR${D}C${F+1}.xz, wTexelR${D}C${F+1}.xz);`))}for(let D=0;D<b;D++)for(let k=0;k<w;k++)T+=`dotProd += xR${D}C${k} * wR${D}C${k};`;let v="",C="";n&&(s?v=`vec4 activation(vec4 a) {
2020-10-15 12:48:39 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:v=`vec4 activation(vec4 x) {
${n}
2020-10-29 05:16:50 +01:00
}`,C="result = activation(result);");const O=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
2020-10-15 12:48:39 +02:00
${v}
2020-10-29 05:16:50 +01:00
const ivec2 strides = ivec2(${h}, ${p});
2020-10-15 12:48:39 +02:00
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;
2020-10-29 05:16:50 +01:00
${O}
${C}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class l6{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,h]=e,[p]=t,[m,y]=n;this.outputShape=[p,m,y,h];const b=s==="bilinear"?1:0,[w,L]=[`${a-1}.0`,`${c-1}.0`],[T,v,C]=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}`],[O,D,k]=y>1?[`${(c-1)/(y-1)}`,"(x2-x1) * width_ratio",`x1*${L} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${L}`];this.userCode=`
2020-10-15 12:48:39 +02:00
const float height_ratio = float(${T});
2020-10-29 05:16:50 +01:00
const float width_ratio = float(${O});
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${o}) {
return;
}
float height_scale = ${v};
float width_scale = ${D};
2020-10-29 05:16:50 +01:00
float in_y = ${C};
2020-10-15 12:48:39 +02:00
if( in_y < 0.0 || in_y > ${w} ) {
setOutput(float(${i}));
return;
}
2020-10-29 05:16:50 +01:00
float in_x = ${k};
if( in_x < 0.0 || in_x > ${L} ) {
2020-10-15 12:48:39 +02:00
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);
}
}
2020-10-29 05:16:50 +01:00
`}}class WC{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${$C(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=`
2020-10-15 12:48:39 +02:00
uniform float index;
void main() {
2020-10-29 05:16:50 +01:00
${Rt(s)} coords = getOutputCoords();
int end = ${UC(s,"coords")};
2020-10-15 12:48:39 +02:00
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${a}) {
int idx = ${c};
2020-10-29 05:16:50 +01:00
${UC(s,"coords")} = idx;
val += getX(${$C(s,"coords")});
2020-10-15 12:48:39 +02:00
}
setOutput(val);
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}}function $C(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 UC(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 h6{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=xu.DENSE;const t=Au(e),n=Vn();this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-29 05:16:50 +01:00
${na(["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;
}
2020-10-29 05:16:50 +01:00
`}}class u6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=xu.DENSE;const t=Au(e),n=Vn();this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-29 05:16:50 +01:00
${na(["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;
}
2020-10-29 05:16:50 +01:00
`}}class d6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
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);
}
2020-10-29 05:16:50 +01:00
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}class p6{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
2020-10-29 05:16:50 +01:00
`}}class m6{constructor(e){this.variableNames=["A"],this.outTexUsage=Os.DOWNLOAD;const t=Vn();this.outputShape=e,this.userCode=`
${vC}
2020-10-15 12:48:39 +02:00
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
2020-10-29 05:16:50 +01:00
`}}class f6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Os.DOWNLOAD;const t=Vn();this.outputShape=e,this.userCode=`
${vC}
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
2020-10-29 05:16:50 +01:00
`}}class g6{constructor(e,t,n=!1){this.variableNames=["A"];const s=Vn(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
${PS(e)}
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
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.);
}
2020-10-29 05:16:50 +01:00
`}}class y6{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Vn(),[i,o]=t;this.outputShape=e;let a="",c="result";n&&(c="floor(result * 255. + 0.5)");for(let h=0;h<=1;h++)for(let p=0;p<=1;p++){const m=h*2+p;a+=`
2020-10-15 12:48:39 +02:00
localCoords = coords;
if(localCoords[2] + ${p} < ${e[2]}) {
localCoords[2] += ${p};
2020-10-29 05:16:50 +01:00
if(localCoords[1] + ${h} < ${e[1]}) {
localCoords[1] += ${h};
2020-10-15 12:48:39 +02:00
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=`
2020-10-29 05:16:50 +01:00
${PS(e)}
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${a}
${s.output} = ${c};
}
2020-10-29 05:16:50 +01:00
`}}class b6{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class w6{constructor(e,t,n){this.variableNames=["A","indices"];const s=e.slice();s[n]=t,this.outputShape=s,this.rank=s.length;const i=Rt(this.rank),o=L6(e,n);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${o}));
}
2020-10-29 05:16:50 +01:00
`}}function L6(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 S6{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=Rt(t.length),i=Rt(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
2020-10-15 12:48:39 +02:00
${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]));
}
2020-10-29 05:16:50 +01:00
`}}function I6(e){const t=Vn(),n=`${t.version}
2020-10-15 12:48:39 +02:00
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
2020-10-29 05:16:50 +01:00
}`;return t5(e,n)}function x6(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 a5(e,t)}function T6(e){const t=new Uint16Array([0,1,2,2,1,3]);return c5(e,t)}function Nu(e,t,n,s,i,o){h5(t,n);const a=l5(e),c=e.TEXTURE_2D;return Ee(e,()=>e.bindTexture(c,a)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)),Ee(e,()=>e.texImage2D(c,0,s,t,n,0,i,o,null)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null)),a}function BC(e){return e.internalFormatFloat}function A6(e,t,n,s){const[i,o]=Tu(t,n);return Nu(e,i,o,BC(s),s.textureFormatFloat,e.FLOAT)}function MC(e){return e.internalFormatHalfFloat}function v6(e,t,n,s){const[i,o]=Tu(t,n);return Nu(e,i,o,MC(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function PC(e){return e.downloadTextureFormat}function N6(e,t,n,s){const[i,o]=Tu(t,n);return Nu(e,i,o,PC(s),e.RGBA,e.UNSIGNED_BYTE)}function zC(e){return e.internalFormatPackedFloat}function C6(e,t,n,s){const[i,o]=Ac(t,n);return Nu(e,i,o,zC(s),e.RGBA,e.FLOAT)}function VC(e){return e.internalFormatPackedHalfFloat}function R6(e,t,n,s){const[i,o]=Ac(t,n);return Nu(e,i,o,VC(s),e.RGBA,s.textureTypeHalfFloat)}function O6(e,t,n){const s=0,i=3*4,o=3*4+2*4;Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=SC(e,t,"clipSpacePos",n,3,o,s);return a&&SC(e,t,"uv",n,2,o,i)}function E6(e,t,n,s,i,o){Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t));let a,c,h;i instanceof Uint8Array?(a=new Uint8Array(n*s*4),c=e.UNSIGNED_BYTE,h=e.RGBA):(a=new Float32Array(n*s*4),c=e.FLOAT,h=o.internalFormatPackedFloat),a.set(i),Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,h,n,s,0,e.RGBA,c,a)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function D6(e,t,n){Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function k6(e,t,n,s){const i=e.createBuffer();Ee(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const o=4,a=4,c=o*a*t*n;return Ee(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,c,e.STREAM_READ)),Ee(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Ee(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function F6(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 _6(e,t,n,s){const[i,o]=Tu(t,n),a=4,c=new Uint8Array(jK(t*n,a));return Ee(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function W6(e,t,n,s,i,o,a,c){const h=e,p=new Float32Array(KK(o,a));return h.bindBuffer(h.PIXEL_PACK_BUFFER,t),h.getBufferSubData(h.PIXEL_PACK_BUFFER,0,p),h.bindBuffer(h.PIXEL_PACK_BUFFER,null),p}function $6(e,t,n){const s=new Float32Array(t*n*4);return Ee(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}class U6{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=ae().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,YK(t,e)):this.gl=Ui(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(ae().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=Gm(this.gl,i),Hs(this.gl,o))this.textureHalfFloatExtension=Gm(this.gl,o);else if(ae().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),Hs(this.gl,s))this.colorBufferHalfFloatExtension=Gm(this.gl,s);else if(ae().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",Hs(this.gl,n))this.colorBufferFloatExt
blockIndex = rc.y + ${F};
pos = rc.x + ${k};
2020-10-15 12:48:39 +02:00
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
2020-10-29 05:16:50 +01:00
offsetY = int(blockIndex / (${h})) * ${a} - ${w};
d0 = offsetY + ${m} * (pos / ${L});
2020-10-15 12:48:39 +02:00
2020-10-29 05:16:50 +01:00
if(d0 < ${t[C]} && d0 >= 0) {
2020-10-15 12:48:39 +02:00
2020-10-29 05:16:50 +01:00
offsetX = int(mod(float(blockIndex), ${h}.) * ${o}. - ${b}.);
d1 = offsetX + ${p} * (int(mod(float(pos), ${L}.) / ${i}.));
2020-10-15 12:48:39 +02:00
2020-10-29 05:16:50 +01:00
if(d1 < ${t[O]} && d1 >= 0) {
2020-10-15 12:48:39 +02:00
ch = int(mod(float(pos), ${i}.));
if (${v}) {
innerDims = vec2(d1, ch);
2020-10-29 05:16:50 +01:00
result[${k*2+F}] = getChannel(
2020-10-15 12:48:39 +02:00
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
2020-10-29 05:16:50 +01:00
result[${k*2+F}] = getChannel(
2020-10-15 12:48:39 +02:00
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${D}
${T.output} = result;
}
2020-10-29 05:16:50 +01:00
`}}class G6{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[];const o=t,a=e[3]-1;this.outputShape=e;let c;const h=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${h})`:i===1?c=`1.0/(${h})`:c=`exp(log(${h}) * float(-${i}));`,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
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);
}
2020-10-29 05:16:50 +01:00
`}}class Y6{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=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
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);
}
2020-10-29 05:16:50 +01:00
`}}class H6{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 h=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${h})`:i===1?c=`1.0/(${h})`:c=`exp(log(${h}) * float(-${i}));`,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
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);
}
2020-10-29 05:16:50 +01:00
`}}class q6{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,h=i*o-1;this.userCode=`
2020-10-15 12:48:39 +02:00
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);
2020-10-29 05:16:50 +01:00
int maxPosValue = ${h} - int(getMaxPos(b, idyR, idyC, d));
2020-10-15 12:48:39 +02:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${o} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class j6{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,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,m=c-1-e.padInfo.front,y=h-1-e.padInfo.top,b=p-1-e.padInfo.left,w=c*h*p-1;this.userCode=`
2020-10-15 12:48:39 +02:00
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);
2020-10-29 05:16:50 +01:00
for (int wR = 0; wR < ${h};
2020-10-15 12:48:39 +02:00
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 =
2020-10-29 05:16:50 +01:00
wD * ${h} * ${p} +
2020-10-15 12:48:39 +02:00
wR * ${p} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class zS{constructor(e,t,n,s=!1,i=!1,o=!1,a=null,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;const h=s?e[1]:e[2],p=Math.ceil(h/2),m=s?"i * 2, rc.y":"rc.y, i * 2",y=i?"rc.z, i * 2":"i * 2, rc.z",b=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],w=i?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let L="",T="";a&&(c?L=`vec4 activation(vec4 a) {
2020-10-15 12:48:39 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-10-29 05:16:50 +01:00
${a}
}`:L=`vec4 activation(vec4 x) {
${a}
}`,T="result = activation(result);");const v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights");let C="rc.x",O="rc.x";e[0]<t[0]?C=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(O=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
${L}
2020-10-15 12:48:39 +02:00
2020-10-29 05:16:50 +01:00
const float sharedDimension = ${p}.0;
2020-10-15 12:48:39 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
2020-10-29 05:16:50 +01:00
for (int i = 0; i < ${p}; i++) {
int batchA = ${C};
int batchB = ${O};
vec4 a = getMatrixA(batchA, ${m});
vec4 b = getMatrixB(batchB, ${y});
2020-10-15 12:48:39 +02:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
2020-10-29 05:16:50 +01:00
result += (${b[0]} * ${w[0]});
result += (${b[1]} * ${w[1]});
2020-10-15 12:48:39 +02:00
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2020-10-29 05:16:50 +01:00
${v}
2020-10-15 12:48:39 +02:00
2020-10-29 05:16:50 +01:00
${T}
2020-10-15 12:48:39 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class K6{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode=`
2020-10-15 12:48:39 +02:00
uniform float seed;
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
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}));
}
2020-10-29 05:16:50 +01:00
`}getCustomSetupFunc(e){return(t,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class X6{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${s}), float(${n}),
float(index == coords.y)));
}
2020-10-29 05:16:50 +01:00
`}}class J6{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;const t=e.length;if(t===0)this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2020-10-29 05:16:50 +01:00
`;else{const n=zn("rc",t),s=Rt(t),i=Q6(t,e,n),o=e7(t,e[e.length-1],e[e.length-2],n),a=t7(e,n);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${o}
setOutput(vec4(${a}));
}
}
2020-10-29 05:16:50 +01:00
`}}}function Z6(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 Q6(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 e7(e,t,n,s){if(e===1)return"";const i=s.slice(-2);return`
2020-10-15 12:48:39 +02:00
int r = ${i[0]};
int c = ${i[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
bool rEdge = rp1 >= ${n};
2020-10-29 05:16:50 +01:00
`}function t7(e,t){const n=e.length,s=Z6(n,t);return n===1?`getA(rc),
2020-10-15 12:48:39 +02:00
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${s[0]}),
cEdge ? 0. : getA(${s[1]}),
rEdge ? 0. : getA(${s[2]}),
2020-10-29 05:16:50 +01:00
rEdge || cEdge ? 0. : getA(${s[3]})`}class n7{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((h,p)=>h[0]+e[p]+h[1]);const s=e.length,i=Rt(s),o=t.map(h=>h[0]).join(","),a=t.map((h,p)=>h[0]+e[p]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=`
2020-10-15 12:48:39 +02:00
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}));
}
}
2020-10-29 05:16:50 +01:00
`}}class s7{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((L,T)=>L[0]+e[T]+L[1]);const s=e.length,i=Rt(s),o=t.map(L=>L[0]).join(","),a=t.map((L,T)=>L[0]+e[T]).join(","),c=zn("rc",s),h=zn("source",s),p=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,y=[`${i} rc = outputLoc;`,`${c[s-1]} += 1;
2020-10-15 12:48:39 +02:00
if(${p}) {
`,s===1?"":`}
rc = outputLoc;
${c[s-2]} += 1;
if(${c[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${c[s-1]} += 1;
2020-10-29 05:16:50 +01:00
if(${p}) {`],b=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let w="";for(let L=0,T=s===1?2:4;L<T;L++)w+=`
${y[L]}
2020-10-15 12:48:39 +02:00
if (${b}) {
2020-10-29 05:16:50 +01:00
result[${L}] = float(${n});
2020-10-15 12:48:39 +02:00
} else {
${i} source = rc - start;
2020-10-29 05:16:50 +01:00
result[${L}] = getChannel(getX(${h.join()}), ${m});
2020-10-15 12:48:39 +02:00
}
`;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);
}
2020-10-29 05:16:50 +01:00
`}}class Cu{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,h=e.dilationHeight,p=e.dilationWidth,m=e.effectiveFilterHeight,y=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const L=t==="avg",T=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,v=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let C="0.0";if(L||(C="-1.0 / 1e-20"),n){const $=">=";this.userCode=`
2020-10-15 12:48:39 +02:00
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};
2020-10-29 05:16:50 +01:00
wR += ${h}) {
2020-10-15 12:48:39 +02:00
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);
2020-10-29 05:16:50 +01:00
if (value ${$} currMinMaxValue) {
2020-10-15 12:48:39 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s?i?T:v:`wR * ${y} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
2020-10-29 05:16:50 +01:00
`;return}const O="max";let D=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(D="avgValue / count");const k=Math.floor(o/4)*4,F=o%4,B=`
if (${L}) {
2020-10-15 12:48:39 +02:00
avgValue += dot(values, ones);
} else {
2020-10-29 05:16:50 +01:00
minMaxValue = ${O}(values, minMaxValue);
2020-10-15 12:48:39 +02:00
}
`;this.userCode=`
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
2020-10-29 05:16:50 +01:00
const float initializationValue = ${C};
2020-10-15 12:48:39 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
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
2020-10-29 05:16:50 +01:00
vec4 minMaxValue = vec4(${C});
2020-10-15 12:48:39 +02:00
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${m};
2020-10-29 05:16:50 +01:00
wR += ${h}) {
2020-10-15 12:48:39 +02:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-10-29 05:16:50 +01:00
for (int wC = 0; wC < ${k}; wC += 4) {
2020-10-15 12:48:39 +02:00
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}
}
2020-10-29 05:16:50 +01:00
int xC = xCCorner + ${k};
if (${F===1}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${B}
2020-10-29 05:16:50 +01:00
} else if (${F===2}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
initializationValue,
initializationValue
);
${B}
2020-10-29 05:16:50 +01:00
} else if (${F===3}) {
2020-10-15 12:48:39 +02:00
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});
}
2020-10-29 05:16:50 +01:00
`}}class VS{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,h=e.strideWidth,p=e.dilationDepth,m=e.dilationHeight,y=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,L=e.effectiveFilterWidth,T=e.padInfo.front,v=e.padInfo.top,C=e.padInfo.left;this.outputShape=e.outShape;const O=t==="avg";let D="0.0";if(O||(D="-1.0 / 1e-20"),n){const j=">=";this.userCode=`
2020-10-15 12:48:39 +02:00
const ivec3 strides =
2020-10-29 05:16:50 +01:00
ivec3(${a}, ${c}, ${h});
const ivec3 pads = ivec3(${T}, ${v}, ${C});
2020-10-15 12:48:39 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
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;
}
2020-10-29 05:16:50 +01:00
for (int wC = 0; wC < ${L};
2020-10-15 12:48:39 +02:00
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);
2020-10-29 05:16:50 +01:00
if (value ${j} currMinMaxValue) {
2020-10-15 12:48:39 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
2020-10-29 05:16:50 +01:00
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} * ${L} +
wR * ${L} + wC`};
2020-10-15 12:48:39 +02:00
}
}
}
}
setOutput(float(minMaxPosition));
}
2020-10-29 05:16:50 +01:00
`;return}const k="max";let F=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(F="avgValue / count");const B=Math.floor(o/4)*4,$=o%4,Y=`
if (${O}) {
2020-10-15 12:48:39 +02:00
avgValue += dot(values, ones);
} else {
2020-10-29 05:16:50 +01:00
minMaxValue = ${k}(values, minMaxValue);
2020-10-15 12:48:39 +02:00
}
`;this.userCode=`
const ivec3 strides =
2020-10-29 05:16:50 +01:00
ivec3(${a}, ${c}, ${h});
const ivec3 pads = ivec3(${T}, ${v}, ${C});
2020-10-15 12:48:39 +02:00
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};
2020-10-29 05:16:50 +01:00
if (${$===1}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${Y}
2020-10-29 05:16:50 +01:00
} else if (${$===2}) {
2020-10-15 12:48:39 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
initializationValue,
initializationValue
);
${Y}
2020-10-29 05:16:50 +01:00
} else if (${$===3}) {
2020-10-15 12:48:39 +02:00
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}
}
}
2020-10-29 05:16:50 +01:00
setOutput(${F});
2020-10-15 12:48:39 +02:00
}
}
2020-10-29 05:16:50 +01:00
`}}class YC{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 h=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?h="sumValue":t==="prod"?h="prodValue":t==="all"?h="allValue":t==="any"&&(h="anyValue");const p=Math.floor(n/4)*4,m=n%4;let y=`
2020-10-15 12:48:39 +02:00
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${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}
}
2020-10-29 05:16:50 +01:00
setOutput(${h});
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class HC{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+=`
2020-10-15 12:48:39 +02:00
${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=`
2020-10-29 05:16:50 +01:00
${i7(t)}
${PS(e)}
2020-10-15 12:48:39 +02:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${n}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}function i7(e){const t=na(["r","c","d"],e);return`
2020-10-15 12:48:39 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
2020-10-29 05:16:50 +01:00
`}class r7{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],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],p=c[0]/h[0],m=c[1]/h[1],y=1/p,b=1/m,w=Math.ceil(y)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
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});
2020-10-29 05:16:50 +01:00
const int winWidth = int(${L});
2020-10-15 12:48:39 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
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);
}
2020-10-29 05:16:50 +01:00
`}}class o7{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const h=[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=`
2020-10-15 12:48:39 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2020-10-29 05:16:50 +01:00
${h[0]/p[0]},
${h[1]/p[1]});
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class a7{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 h=[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=`
2020-10-15 12:48:39 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
2020-10-29 05:16:50 +01:00
${h[0]/p[0]},
${h[1]/p[1]},
${h[1]/p[1]});
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class c7{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],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],p=c[0]/h[0],m=c[1]/h[1],y=1/p,b=1/m,w=Math.ceil(y)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
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});
2020-10-29 05:16:50 +01:00
const int winWidth = int(${L});
2020-10-15 12:48:39 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
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]}) *
2020-10-29 05:16:50 +01:00
(float(dyR) / float(${h[0]}));
2020-10-15 12:48:39 +02:00
float sourceFracCol =
float(${c[1]}) *
2020-10-29 05:16:50 +01:00
(float(dyC) / float(${h[1]}));
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class l7{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const h=[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=`
2020-10-15 12:48:39 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2020-10-29 05:16:50 +01:00
${h[0]/p[0]},
${h[1]/p[1]});
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}class h7{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=`
2020-10-15 12:48:39 +02:00
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
2020-10-29 05:16:50 +01:00
`;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=Rt(n);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${i}));
}
2020-10-29 05:16:50 +01:00
`}}class u7{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=zn("rc",n),i=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,o=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Rt(n);n===1?this.userCode=`
2020-10-15 12:48:39 +02:00
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}){
2020-10-29 05:16:50 +01:00
result.g = ${h(s.slice())};
2020-10-15 12:48:39 +02:00
}
if(${o}) {
result.b = ${p(s.slice())};
if(${i}) {
result.a = ${m(s.slice())};
}
}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`;function c(w){return y(w)}function h(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 L=e.map((C,O)=>b(O,w)),T=L.join(","),v=L.slice(-2).join(",");return`getChannel(getX(${T}), vec2(${v}))`}function b(w,L){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${L[w]} - 1`:`${L[w]}`}}}class qC{constructor(e,t,n,s,i,o,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=Rt(i.length),h=Rt(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=`
2020-10-15 12:48:39 +02:00
${c} strides = ${c}(${i});
void main() {
2020-10-29 05:16:50 +01:00
${h} coords = getOutputCoords();
2020-10-15 12:48:39 +02:00
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${m});
flattenedIndex += index * ${w};
}
if (flattenedIndex == coords[0]) {
sum += ${b};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
2020-10-29 05:16:50 +01:00
`}}class d7{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",h="sumValue",p=Math.floor(n/4)*4,m=n%4,y=`
2020-10-15 12:48:39 +02:00
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}
}
2020-10-29 05:16:50 +01:00
setOutput(${h});
2020-10-15 12:48:39 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class p7{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=[],h=[];for(let p=0;p<t.length;p++)h.push(`${a[p]}`),p<e&&c.push(`${a[p]}`);s=c.join(),i=h.join()}const o=Rt(n);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${o} resRC = getOutputCoords();
float cVal = getC(${s});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
2020-10-29 05:16:50 +01:00
`}}class m7{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=`uniform int start[${this.rank}];`,s=f7(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${GS[c]} = start[${c}] + coords.${GS[c]};`);i=`
2020-10-15 12:48:39 +02:00
${t} sourceLoc;
${t} coords = getOutputCoords();
${o.join(`
`)}
`,this.userCode=`
${n}
void main() {
${i}
setOutput(getSource(${s}));
}
2020-10-29 05:16:50 +01:00
`}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 GS=["x","y","z","w","u","v"];function f7(e){if(e===1)return"sourceLoc";if(e<=6)return GS.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class g7{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=zn("coords",this.rank),s=zn("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,o=`getChannel(getSource(${s.join()}), ${i})`,a=`
2020-10-15 12:48:39 +02:00
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};
}
}
2020-10-29 05:16:50 +01:00
`,h=this.rank<=4?`sourceLoc = coords +
2020-10-15 12:48:39 +02:00
${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;
2020-10-29 05:16:50 +01:00
${h}
2020-10-15 12:48:39 +02:00
vec4 result = vec4(0.);
${a}
${c}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}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 y7{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,i=Rt(n.length),o=Rt(n.length);let a="";if(s===1)a="coords * strides + begin";else{let c=0;a=n.map((h,p)=>(c++,n.length===1?`coords * strides[${p}] + begin[${p}]`:`coords[${c-1}] * strides[${p}] + begin[${p}]`)).join(",")}this.userCode=`
2020-10-15 12:48:39 +02:00
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${a}));
}
2020-10-29 05:16:50 +01:00
`}}class b7{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=KC(t,n),i=XC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=jC(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===Rn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Rn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Rn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Rn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Rn.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=KC(n,s),o=XC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=jC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=ae().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 h=this.usedTextures[o],p=h.indexOf(e);if(p<0)throw new Error("Cannot release a texture that was never provided by this texture manager");h.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 w7(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 jC(e,t,n,s,i){const o=L7(t,s);let a;if(i){const[h,p]=Ac(e[0],e[1]);a=h*p}else{const[h,p]=Tu(e[0],e[1]);a=h*p}const c=w7(n,o);return a*c}function L7(e,t){switch(e){case Rn.PACKED_2X2_FLOAT32:return zC(t);case Rn.PACKED_2X2_FLOAT16:return VC(t);case Rn.UNPACKED_FLOAT32:return BC(t);case Rn.UNPACKED_FLOAT16:return MC(t);case Rn.PACKED_4X1_UNSIGNED_BYTE:return PC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function S7(e){return ae().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Rn.PACKED_2X2_FLOAT32:Rn.UNPACKED_FLOAT32:e?Rn.PACKED_2X2_FLOAT16:Rn.UNPACKED_FLOAT16}function KC(e,t){if(e===Os.UPLOAD)return Rn.PACKED_2X2_FLOAT32;if(e===Os.RENDER||e==null)return S7(t);if(e===Os.DOWNLOAD||e===Os.PIXELS)return Rn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function XC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class I7{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=Rt(this.rank),i=x7(e);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
2020-10-29 05:16:50 +01:00
`}}function x7(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=`
2020-10-15 12:48:39 +02:00
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
2020-10-29 05:16:50 +01:00
`}}const gr="if (isnan(x)) return x;",T7="return x;",JC="return abs(x);",ZC=gr+`
2020-10-15 12:48:39 +02:00
return (x < 0.0) ? 0.0 : x;
2020-10-29 05:16:50 +01:00
`,QC=gr+`
2020-10-15 12:48:39 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2020-10-29 05:16:50 +01:00
`,e2="return (x >= 0.0) ? x : (exp(x) - 1.0);",A7=`
2020-10-15 12:48:39 +02:00
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
2020-10-29 05:16:50 +01:00
float scaleAlpha = ${em};
float scale = ${tm};
2020-10-15 12:48:39 +02:00
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2020-10-29 05:16:50 +01:00
`;function v7(e=0){return gr+`
2020-10-15 12:48:39 +02:00
return x > 0.0 ? 1.0 : float(${e});
2020-10-29 05:16:50 +01:00
`}const t2="return -x;",n2="return ceil(x);",s2="return floor(x);",N7=`
2020-10-15 12:48:39 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2020-10-29 05:16:50 +01:00
`,C7="return float(isnan(x));",R7="return float(isinf(x));",O7="return float(!isnan(x) && !isinf(x));",E7=`
2020-10-15 12:48:39 +02:00
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
2020-10-29 05:16:50 +01:00
`,i2="return exp(x);",r2="return exp(x) - 1.0;",D7=`if (x < 0.0) return NAN;
return log(x);`,k7="return log(1.0 + x);",F7="return sqrt(x);",_7="return inversesqrt(x);",W7="return 1.0 / (1.0 + exp(-1.0 * x));",$7=`
2020-10-15 12:48:39 +02:00
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
2020-10-29 05:16:50 +01:00
`,U7=gr+`
2020-10-15 12:48:39 +02:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
2020-10-29 05:16:50 +01:00
`,B7=gr+`
2020-10-15 12:48:39 +02:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
2020-10-29 05:16:50 +01:00
`,M7=gr+`
2020-10-15 12:48:39 +02:00
return atan(x);
2020-10-29 05:16:50 +01:00
`,P7=`
2020-10-15 12:48:39 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2020-10-29 05:16:50 +01:00
`,z7=`
2020-10-15 12:48:39 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2020-10-29 05:16:50 +01:00
`,V7=`
2020-10-15 12:48:39 +02:00
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
2020-10-29 05:16:50 +01:00
`,G7=gr+"return log(x + sqrt(x * x + 1.0));",Y7=gr+`
2020-10-15 12:48:39 +02:00
if (x < 1.0) return NAN;
2020-10-29 05:16:50 +01:00
return log(x + sqrt(x * x - 1.0));`,H7=gr+`
2020-10-15 12:48:39 +02:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2020-10-29 05:16:50 +01:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,q7=`
2020-10-15 12:48:39 +02:00
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
2020-10-29 05:16:50 +01:00
float p = ${ww};
float a1 = ${Lw};
float a2 = ${Sw};
float a3 = ${Iw};
float a4 = ${xw};
float a5 = ${Tw};
2020-10-15 12:48:39 +02:00
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
2020-10-29 05:16:50 +01:00
`,j7="return 1.0 / x;",K7="return float(!(x >= 1.0));",Zm="return x;";const X7="return x;",J7=`
2020-10-15 12:48:39 +02:00
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
2020-10-29 05:16:50 +01:00
`,o2=`
2020-10-15 12:48:39 +02:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2020-10-29 05:16:50 +01:00
`,a2=`
2020-10-15 12:48:39 +02:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2020-10-29 05:16:50 +01:00
`,c2=`
2020-10-15 12:48:39 +02:00
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
2020-10-29 05:16:50 +01:00
`;class Ru{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
2020-10-29 05:16:50 +01:00
`}}class Z7{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=zn("rc",t),s=Rt(t),i=P5(t,n),o=n.slice(-2),a=t<=1?"rc":`vec2(${o.join(",")})`;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} rc = getOutputCoords();
vec4 packedInput = getA(${i});
setOutput(getChannel(packedInput, ${a}));
}
2020-10-29 05:16:50 +01:00
`}}const{segment_util:l2}=Nw,Q7=Cw,eX=Rw,tX=Ow,nX=Vp,sX=1e-7,iX=1e-4,Qm={};function rX(e){return e in Qm||(Qm[e]={}),Qm[e]}function ef(e,t=!1){if(e==="linear")return t?X7:T7;if(e==="relu")return t?o2:ZC;if(e==="elu")return t?c2:e2;if(e==="relu6")return t?a2:QC;if(e==="prelu")return t?DC:EC;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const oX=128,aX=600;function cX(){return ae().global.screen==null?1024:ae().global.screen.height*ae().global.screen.width*window.devicePixelRatio*aX/1024/1024}const h2=1e3;class lX 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,!ae().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Ui(ae().getNumber("WEBGL_VERSION"));this.binaryCache=rX(ae().getNumber("WEBGL_VERSION")),this.gpgpu=new U6(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 b7(this.gpgpu),this.numMBBeforeWarning=cX(),this.texData=new d(this,tr())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((ae().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||ae().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:Os.UPLOAD,refCount:1,complexParentRefCount:0}),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(ae().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:Os.UPLOAD,refCount:1,complexParentRefCount:0})}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,complexTensorInfos:i,slice:o,shape:a,isPacked:c}=t;if(o!=null){let y;c?y=new Ru(a,Zm):y=new it(a,Zm);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 h=this.activeTimers!=null;let p;h&&(p=Jn());let m;if(s==="complex64"){const y=this.readSync(i.real.dataId),b=this.readSync(i.imag.dataId);m=ar(y,b)}else m=this.getValuesFromTexture(e);return h&&(this.downloadWaitMs+=Jn()-p),this.convertAndCacheOnCPU(e,m)}async read(e){if(this.pendingRead.has(e)){const w=this.pendingRead.get(e);return new Promise(L=>w.push(L))}const t=this.texData.get(e),{values:n,shape:s,slice:i,dtype:o,complexTensorInfos:a,isPacked:c}=t;if(i!=null){let w;c?w=new Ru(s,Zm):w=new it(s,Zm);const L=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),T=this.read(L.dataId);return this.disposeIntermediateTensorInfo(L),T}if(n!=null)return this.convertAndCacheOnCPU(e);if(!ae().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&ae().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let h=null,p;if(o!=="complex64"&&ae().get("WEBGL_BUFFER_SUPPORTED")){p=this.decode(e);const w=this.texData.get(p.dataId);h=this.gpgpu.createBufferFromTexture(w.texture,...Au(s))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let m;if(o==="complex64"){const w=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),L=w[0],T=w[1];m=ar(L,T)}else if(h==null)m=this.getValuesFromTexture(e);else{const w=M(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(h,w)}p!=null&&this.d
2020-10-15 12:48:39 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-29 05:16:50 +01:00
`,gX=`
2020-10-15 12:48:39 +02:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2020-10-29 05:16:50 +01:00
`;function tf(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 kc({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:i,dtype:o}){return({inputs:a,backend:c})=>{const{a:h,b:p}=a,m=c;if(s&&h.dtype==="complex64"){const L=m.texData.get(h.dataId),T=m.texData.get(p.dataId),[v,C]=[[L.complexTensorInfos.real,T.complexTensorInfos.real],[L.complexTensorInfos.imag,T.complexTensorInfos.imag]].map(D=>{const[k,F]=D,B={dataId:k.dataId,dtype:k.dtype,shape:h.shape},$={dataId:F.dataId,dtype:F.dtype,shape:p.shape},Y=new $n(e,h.shape,p.shape);return m.runWebGLProgram(Y,[B,$],Bn(k.dtype,F.dtype))}),O=Dc({inputs:{real:v,imag:C},backend:m});return m.disposeIntermediateTensorInfo(v),m.disposeIntermediateTensorInfo(C),O}const y=o||Bn(h.dtype,p.dtype);if(m.shouldExecuteOnCPU([h,p])&&i!=null){const L=m.texData.get(h.dataId),T=m.texData.get(p.dataId),[v,C]=i(h.shape,p.shape,L.values,T.values,y),O=m.makeTensorInfo(C,y),D=m.texData.get(O.dataId);return D.values=v,O}const b=ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null;let w;return b?w=new fr(t,h.shape,p.shape,n):w=new $n(e,h.shape,p.shape),m.runWebGLProgram(w,[h,p],y)}}const d2="return a + b;",yX=kc({opSnippet:d2,packedOpSnippet:d2,supportsComplex:!0,cpuKernelImpl:v5}),bX={kernelName:Oo,backendName:"webgl",kernelFunc:yX};const wX=fX+`
2020-10-15 12:48:39 +02:00
return atan(a, b);
2020-10-29 05:16:50 +01:00
`,LX=`
2020-10-15 12:48:39 +02:00
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
2020-10-29 05:16:50 +01:00
`+gX+`
2020-10-15 12:48:39 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,SX=kc({opSnippet:wX,packedOpSnippet:LX}),IX={kernelName:Ld,backendName:"webgl",kernelFunc:SX};function xX(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;vu(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,p=1;A(cn(a,p),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Mn(i.shape,o,a,p,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ie(m.inShape,m.outShape))return yr({inputs:{x:i},backend:n});const y=new Cu(m,"avg",!1);return n.runWebGLProgram(y,[i],"float32")}const TX={kernelName:vl,backendName:"webgl",kernelFunc:xX};function AX(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;vu([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:p}=s,m=Mn(a.shape,c,h,1,p),y=new A8(m);return n.runWebGLProgram(y,[i],a.dtype)}const vX={kernelName:Sd,backendName:"webgl",kernelFunc:AX};class NX{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],st(e,t),st(e,n);let a="0.0";s!=null&&(st(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(st(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)));
}
2020-10-29 05:16:50 +01:00
`}}class CX{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],st(e,t),st(e,n);let a="vec4(0.0)";s!=null&&(st(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(st(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
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);
}
2020-10-29 05:16:50 +01:00
`}}const RX=({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:i,variance:o,offset:a,scale:c}=e;A(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(c==null||i.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:h}=n;h==null&&(h=.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=ae().getBool("WEBGL_PACK_NORMALIZATION")?new CX(s.shape,i.shape,o.shape,m,y,h):new NX(s.shape,i.shape,o.shape,m,y,h),w=t.runWebGLProgram(b,p,p[0].dtype);return w},OX={kernelName:Wl,backendName:"webgl",kernelFunc:RX};const EX="return float(a != b);",p2=kc({opSnippet:EX,dtype:"bool"}),DX={kernelName:Hl,backendName:"webgl",kernelFunc:p2};function YS(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return yr({inputs:{x:i.complexTensorInfos.real},backend:n})}const kX={kernelName:zd,backendName:"webgl",kernelFunc:YS};const FX="return float(int(x));";function _X(e,t){const n=new it(e.shape,FX),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function HS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return yr({inputs:{x:i},backend:n});const a=pt(i.shape),c=HS({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),h=Dc({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),h}if(i.dtype==="complex64"){const a=YS({inputs:{input:i},backend:n}),c=HS({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!Oa(i.dtype,o)){const a=yr({inputs:{x:i},backend:n});return{dataId:a.dataId,shape:a.shape,dtype:o}}if(o==="int32")return _X(i,n);if(o==="bool"){const a=n.makeTensorInfo([],"bool",bt("bool",1)),c={a:i,b:a},h=p2({inputs:c,backend:n});return n.disposeIntermediateTensorInfo(a),h}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}const WX={kernelName:ka,backendName:"webgl",kernelFunc:HS};class $X{constructor(e){this.outputShape=[],this.outputShape=nr(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 UX{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=nr(e,t);const n=this.outputShape,s=n.length,i=Rt(s),o=zn("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((L,T)=>`T${T}`);const c=new Array(e.length-1);c[0]=e[0][t];for(let L=1;L<c.length;L++)c[L]=c[L-1]+e[L][t];const h=a[t],p=a.slice(-2),m=a.join();let y=`if (${h} < ${c[0]}) {
return getChannel(
getT0(${m}), vec2(${p.join()}));
}`;for(let L=1;L<c.length;L++){const T=c[L-1];y+=`
if (${h} < ${c[L]} && ${h} >= ${c[L-1]}) {
return getChannel(
getT${L}(${nf(a,h,T)}),
vec2(${nf(p,h,T)}));
}`}const b=c.length,w=c[c.length-1];y+=`
return getChannel(
getT${b}(${nf(a,h,w)}),
vec2(${nf(p,h,w)}));`,this.userCode=`
float getValue(${a.map(L=>"int "+L)}) {
${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 nf(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}function m2(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return yr({inputs:{x:i.complexTensorInfos.imag},backend:n})}const BX={kernelName:Fd,backendName:"webgl",kernelFunc:m2};function MX(e,t,n){const s=[vc(e.shape),...Nc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[vc(t),...Nc(t)],a=new HC(o,s),c=!0,h=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:h.dataId,shape:t,dtype:h.dtype}}function br(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=M(i.shape),h=Vt(o,c),p=M(h);A(c===p,()=>`The new shape (${h}) 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&&!qm(i.shape,h)&&!(m.texture!==null&&qm(m.shape,h))?MX(i,h,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:h,dtype:i.dtype})}const PX={kernelName:Kl,backendName:"webgl",kernelFunc:br};function Fc(e,t,n){const s=e[0].dtype;if(s==="complex64"){const p=e.map(L=>YS({inputs:{input:L},backend:n})),m=e.map(L=>m2({inputs:{input:L},backend:n})),y=Fc(p,t,n),b=Fc(m,t,n),w=Dc({inputs:{real:y,imag:b},backend:n});return p.forEach(L=>n.disposeIntermediateTensorInfo(L)),m.forEach(L=>n.disposeIntermediateTensorInfo(L)),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),w}if(e.length>ae().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const p=Math.floor(e.length/2),m=Fc(e.slice(0,p),t,n),y=Fc(e.slice(p),t,n),b=Fc([m,y],t,n);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),b}if(ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const p=new UX(e.map(m=>m.shape),t);return n.runWebGLProgram(p,e,s)}const i=nr(e.map(p=>p.shape),t),o=e.map(p=>br({inputs:{x:p},attrs:{shape:[-1,M(p.shape.slice(t))]},backend:n})),a=new $X(o.map(p=>p.shape)),c=n.runWebGLProgram(a,o,s);o.forEach(p=>n.disposeIntermediateTensorInfo(p));const h=br({inputs:{x:c},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(c),h}function zX(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=je(i,t[0].shape)[0],a=nr(t.map(p=>p.shape),o);if(M(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(p=>M(p.shape)>0);if(c.length===1)return c[0];const h=c.map(p=>p.shape);return Lp(h,o),Fc(c,o,n)}const VX={kernelName:Rl,backendName:"webgl",kernelFunc:zX};const GX=u2+`
2020-10-15 12:48:39 +02:00
return cos(x);
2020-10-29 05:16:50 +01:00
`,YX=tf(GX),HX={kernelName:Fa,backendName:"webgl",kernelFunc:YX};const qX=`
2020-10-15 12:48:39 +02:00
if (a == b) {
return 1.0;
};
2020-10-29 05:16:50 +01:00
return a / b;`,jX=`
2020-10-15 12:48:39 +02:00
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
2020-10-29 05:16:50 +01:00
`,KX=kc({opSnippet:qX,packedOpSnippet:jX,checkOutOfBounds:!0}),XX={kernelName:_a,backendName:"webgl",kernelFunc:KX};class f2{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";let a;if(e==="real")a="return real * expR - imag * expI;";else if(e==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${a}
}
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]));
}
`}}function g2(e,t,n){const s=n.texData.get(e.dataId),i=M(e.shape),o=e.shape[e.shape.length-1],a=i/o,c=br({inputs:{x:e},backend:n,attrs:{shape:[a,o]}}),h=c.shape,p=new f2("real",h,t),m=new f2("imag",h,t),y=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:h},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:h}],b=n.runWebGLProgram(p,y,"float32"),w=n.runWebGLProgram(m,y,"float32"),L=Dc({inputs:{real:b,imag:w},backend:n});n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w);const T=br({inputs:{x:L},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(T),T}function JX(e){const{inputs:t,backend:n}=e,{input:s}=t;return g2(s,!1,n)}const ZX={kernelName:Ed,backendName:"webgl",kernelFunc:JX};class QX{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);
}
2020-10-29 05:16:50 +01:00
`}}const eJ={kernelName:Dd,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new QX(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class tJ{constructor(e){this.variableNames=["A"];const t=Vn(),[n,s]=e;this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
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));
}
2020-10-29 05:16:50 +01:00
`}}class nJ{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Vn(),[n,s]=e;this.outputShape=e,this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
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-29 05:16:50 +01:00
`}}const sJ={kernelName:qd,backendName:"webgl",kernelFunc:iJ};let _c;function iJ(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,[h,p]=a?[i.videoWidth,i.videoHeight]:[i.width,i.height],m=[p,h],y=[p,h,o];(c||a)&&(_c==null&&(_c=document.createElement("canvas").getContext("2d")),_c.canvas.width=h,_c.canvas.height=p,_c.drawImage(i,0,0,h,p),i=_c.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=Os.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=ae().getBool("WEBGL_PACK")?new nJ(y):new tJ(y),L=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),L}function rJ(e){const{inputs:t,backend:n}=e,{input:s}=t;return g2(s,!0,n)}const oJ={kernelName:kd,backendName:"webgl",kernelFunc:rJ};class y2{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:i,outSize:o}=e;this.outputShape=[s,o];const a=Math.floor(n/4)*4,c=n%4;let h="sumValue += dot(values, ones);";if(t!=null){const m=1/t;h=`sumValue += dot(values * ${we(m)?m.toPrecision(2):m}, ones);`}let p="";i%n>0&&(p=`
if (inIdx < 0 || inIdx >= ${i}) {
return 0.0;
}
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${p}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
float sumValue = 0.0;
for (int i = 0; i < ${a}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${h}
}
int inIdx = inOffset + ${a};
if (${c===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${h}
} else if (${c===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${h}
} else if (${c===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${h}
}
setOutput(sumValue);
}
`}}function aJ(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=Ah(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function b2(e,t,n,s){const i=aJ(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:h,outSize:p}=i[a];let m,y;n==="mean"?m=a===0?new y2({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:p},c):new y2({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:p}):m=new YC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:p},n),y=o,o=s.runWebGLProgram(m,[o],t),y.dataId!==e.dataId&&s.disposeIntermediateTensorInfo(y)}return o}function cJ(e,t,n,s){const i=M(t),o=M(e.shape),a=o/i,c=br({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=b2(c,e.dtype,"max",s),p=br({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),p}class lJ{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=Rt(this.rank),i=hJ(t);this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
2020-10-29 05:16:50 +01:00
`}}function hJ(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 uJ{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=Rt(this.rank),i=AC("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]}`,h=`getChannel(getA(${o.join()}), ${a})`;this.userCode=`
2020-10-15 12:48:39 +02:00
void main() {
${s} rc = getOutputCoords();
vec4 result = vec4(0.);
2020-10-29 05:16:50 +01:00
result[0] = ${h};
2020-10-15 12:48:39 +02:00
if(${c}) {
2020-10-29 05:16:50 +01:00
result[1] = ${h};
2020-10-15 12:48:39 +02:00
}
--${i[this.rank-1]};
if(++${i[this.rank-2]} < ${n[this.rank-2]}) {
2020-10-29 05:16:50 +01:00
result[2] = ${h};
2020-10-15 12:48:39 +02:00
if(${c}) {
2020-10-29 05:16:50 +01:00
result[3] = ${h};
2020-10-15 12:48:39 +02:00
}
}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}function qS(e,t,n){const s=ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new uJ(e.shape,t):new lJ(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const dJ={kernelName:Vl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{reductionIndices:i,keepDims:o}=t,a=n,c=s.shape.length,h=je(i,s.shape);let p=h;const m=Qn(p,c),y=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(y){if(b){const O=a.texData.get(w.dataId),D=O.values,k=new Array(c);for(let $=0;$<k.length;$++)k[$]=s.shape[m[$]];const F=MS(D,s.shape,s.dtype,m,k);w=a.makeTensorInfo(k,s.dtype);const B=a.texData.get(w.dataId);B.values=F}else w=qS(s,m,a);p=hs(p.length,c)}Zn("max",p,c);const[L,T]=vn(w.shape,p);let v=L;o&&(v=Nn(L,h));let C;if(b){const O=a.texData.get(w.dataId),D=O.values,k=D5(D,M(T),v,s.dtype);C=a.makeTensorInfo(v,s.dtype);const F=a.texData.get(C.dataId);F.values=k}else C=cJ(w,T,v,a);return y&&a.disposeIntermediateTensorInfo(w),C}};function pJ(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;vu(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,p=1;A(cn(a,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${p}'`);const m=Mn(i.shape,o,a,p,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ie(m.inShape,m.outShape))return yr({inputs:{x:i},backend:n});const y=new Cu(m,"max",!1);return n.runWebGLProgram(y,[i],i.dtype)}const mJ={kernelName:Gl,backendName:"webgl",kernelFunc:pJ};function fJ(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;vu([o,a],"maxPoolBackprop");const{filterSize:h,strides:p,pad:m,dimRoundingMode:y}=s,b=Mn(c.shape,h,p,1,m,y),w=!0,L=new Cu(b,"max",w),T=n.runWebGLProgram(L,[c],c.dtype),v=new q6(b),C=n.runWebGLProgram(v,[i,T],c.dtype);return n.disposeIntermediateTensorInfo(T),C}const gJ={kernelName:Wd,backendName:"webgl",kernelFunc:fJ};function yJ(e,t,n,s){let i=new Cu(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new Cu(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const bJ={kernelName:$d,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;A(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const p=[1,1];A(cn(o,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);const m=Mn(s.shape,i,o,p,a),[y,b]=yJ(s,c,m,h);return[y,b]}};function wJ(e,t,n,s){const i=M(t),o=M(e.shape),a=o/i,c=br({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=b2(c,"float32","mean",s),p=br({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),p}const LJ={kernelName:Ry,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{keepDims:i,axis:o}=t,a=n,c=s.shape.length,h=je(o,s.shape);let p=h;const m=Qn(p,c),y=m!=null,b=a.shouldExecuteOnCPU([s]),w=[];let L=s;if(y){if(b){const D=a.texData.get(L.dataId),k=D.values,F=new Array(c);for(let Y=0;Y<F.length;Y++)F[Y]=s.shape[m[Y]];const B=MS(k,s.shape,s.dtype,m,F);L=a.makeTensorInfo(F,s.dtype);const $=a.texData.get(L.dataId);$.values=B}else L=qS(s,m,a);w.push(L),p=hs(p.length,c)}Zn("sum",p,c);const[T,v]=vn(L.shape,p);let C=T;i&&(C=Nn(T,h));const O=wJ(L,v,C,a);for(const D of w)a.disposeIntermediateTensorInfo(D);return O}};class SJ{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((p,m)=>p[0]+e[m]+p[1]);const s=e.length,i=Rt(s),o=t.map(p=>p[0]).join(","),a=t.map((p,m)=>p[0]+e[m]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),h=n==="reflect"?0:1;if(s===1){this.userCode=`
int start = ${o};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${h};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${h};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${i} start = ${i}(${o});
${i} end = ${i}(${a});
void main() {
${i} outC = getOutputCoords();
for (int i = 0; i < ${s}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${h};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${h};
}
}
${i} coords = outC - start;
setOutput(getX(${c}));
}
`}}class IJ{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((w,L)=>w[0]+e[L]+w[1]);const s=e.length,i=Rt(s),o=t.map(w=>w[0]).join(","),a=t.map((w,L)=>w[0]+e[L]).join(","),c=zn("rc",s),h=zn("source",s),p=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,y=n==="reflect"?0:1;let b="";if(s===1){const w=`
${i} source = rc;
if (source < start) {
source = start * 2 - source - ${y};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${y};
}
source -= start;
`;b=`
${i} rc = outputLoc;
${w}
result[0] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${p}) {
${w}
result[1] = getChannel(getX(${h.join()}), ${m});
}
`}else{const w=`
${i} source = rc;
${i} lt = ${i}(lessThan(source, start));
${i} gte = ${i}(greaterThanEqual(source, end));
${i} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${y}) +
gte * ((end - 1) * 2 - source + ${y});
source -= start;
`;b=`
${i} rc = outputLoc;
${w}
result[0] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${p}) {
${w}
result[1] = getChannel(getX(${h.join()}), ${m});
}
rc = outputLoc;
${c[s-2]} += 1;
if(${c[s-2]} < ${this.outputShape[s-2]}) {
${w}
result[2] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${p}) {
${w}
result[3] = getChannel(getX(${h.join()}), ${m});
}
}
`}this.userCode=`
const ${i} start = ${i}(${o});
const ${i} end = ${i}(${a});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${b}
setOutput(result);
}
`}}const xJ=({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:i,mode:o}=n,a=ae().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new IJ(s.shape,i,o):new SJ(s.shape,i,o),c=t.runWebGLProgram(a,[s],s.dtype);return c},TJ={kernelName:Yl,backendName:"webgl",kernelFunc:xJ};const w2={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class L2{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=st(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 S2="return a * b;";function AJ(e){const{inputs:t,backend:n}=e,{a:s,b:i}=t,o=Bn(s.dtype,i.dtype);if(s.dtype==="complex64"){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),p=new L2(w2.REAL,s.shape,i.shape),m=new L2(w2.IMAG,s.shape,i.shape),y=[{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape},{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:i.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:i.shape}],b=n.runWebGLProgram(p,y,"float32"),w=n.runWebGLProgram(m,y,"float32"),L=Dc({inputs:{real:b,imag:w},backend:n});return n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),L}if(n.shouldExecuteOnCPU([s,i])){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),[p,m]=k5(s.shape,i.shape,c.values,h.values,o),y=n.makeTensorInfo(m,o),b=n.texData.get(y.dataId);return b.values=p,y}let a;return ae().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new fr(S2,s.shape,i.shape):a=new $n(S2,s.shape,i.shape),n.runWebGLProgram(a,[s,i],o)}const vJ={kernelName:Wa,backendName:"webgl",kernelFunc:AJ};const NJ={kernelName:Fy,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{hc("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,h=t,p=h.readSync(s.dataId),m=h.readSync(i.dataId),y=o,b=a,w=c;return Xp(p,m,y,b,w)}};const CJ=Jp,RJ={kernelName:Ud,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{hc("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:h}=n,p=t,m=p.readSync(s.dataId),y=p.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=CJ(m,y,o,a,c,h);return[b,w]}};const OJ=Zp,EJ={kernelName:Bd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{hc("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:h}=n,p=t,m=p.readSync(s.dataId),y=p.readSync(i.dataId),b=o,w=a,L=c,T=h,{selectedIndices:v,selectedScores:C}=OJ(m,y,b,w,L,T);return[v,C]}};class DJ{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[h,p]=gw(s,i,o),m=h.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);
}
2020-10-29 05:16:50 +01:00
`}}const kJ={kernelName:jd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=new DJ(s.shape,i,o,a),p=c.runWebGLProgram(h,[s],s.dtype);return p}};const FJ=u2+`
2020-10-15 12:48:39 +02:00
return sin(x);
2020-10-29 05:16:50 +01:00
`,_J=tf(FJ),WJ={kernelName:$a,backendName:"webgl",kernelFunc:_J};const $J="return x * x;",UJ=tf($J),BJ={kernelName:Yd,backendName:"webgl",kernelFunc:UJ};const I2="return (a - b) * (a - b);",MJ=kc({opSnippet:I2,packedOpSnippet:I2}),PJ={kernelName:Ua,backendName:"webgl",kernelFunc:MJ};const x2="return a - b;",zJ=kc({opSnippet:x2,packedOpSnippet:x2,supportsComplex:!0,cpuKernelImpl:W5}),VJ={kernelName:Ba,backendName:"webgl",kernelFunc:zJ};const GJ="return tan(x);",YJ=tf(GJ),HJ={kernelName:Ma,backendName:"webgl",kernelFunc:YJ};const qJ={kernelName:oh,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 h;if(o.shouldExecuteOnCPU([s])){const p=o.texData.get(s.dataId),m=p.values,y=MS(m,s.shape,s.dtype,i,c);h=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(h.dataId);b.values=y}else h=qS(s,i,o);return h}};function jJ(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;vu(o,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const a=s.readSync(o.dataId),{outputValues:c,outputShape:h,indices:p}=$5(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([p.length],"int32",p)]}const KJ={kernelName:Hd,backendName:"webgl",kernelFunc:jJ};const XJ=[bX,IX,TX,vX,OX,WX,mX,VX,HX,XX,ZX,eJ,sJ,pX,oJ,BX,dJ,mJ,gJ,bJ,LJ,TJ,vJ,NJ,RJ,EJ,DX,kX,PX,kJ,WJ,BJ,VJ,PJ,HJ,qJ,KJ];for(const e of XJ)Qd(e);const JJ="2.7.0";const ZJ={"tfjs-core":gA,"tfjs-backend-cpu":m4,"tfjs-backend-webgl":uX,"tfjs-data":Y0,"tfjs-layers":Nm,"tfjs-converter":x0,tfjs:JJ};r.Abs=wd,r.Acos=Ll,r.Acosh=Sl,r.AdadeltaOptimizer=Uh,r.AdagradOptimizer=Bh,r.AdamOptimizer=Mh,r.AdamaxOptimizer=Ph,r.Add=Oo,r.AddN=ly,r.All=sT,r.Any=iT,r.ArgMax=hy,r.ArgMin=uy,r.Asin=Il,r.Asinh=xl,r.Atan=Tl,r.Atan2=Ld,r.Atanh=Al,r.AvgPool=vl,r.AvgPool3D=dy,r.AvgPool3DBackprop=rT,r.AvgPoolBackprop=Sd,r.BatchMatMul=Id,r.BatchToSpaceND=py,r.BroadcastTo=my,r.Callback=c0,r.CallbackList=nN,r.Cast=ka,r.Ceil=Nl,r.ClipByValue=Cl,r.Complex=xd,r.Concat=Rl,r.Conv2D=Td,r.Conv2DBackpropFilter=fy,r.Conv2DBackpropInput=Ad,r.Conv3D=vd,r.Conv3DBackpropFilterV2=gy,r.Conv3DBackpropInputV2=yy,r.Cos=Fa,r.Cosh=Ol,r.CropAndResize=oT,r.Cumsum=by,r.CustomCallback=iN,r.DataStorage=d,r.DepthToSpace=aT,r.DepthwiseConv2dNative=Nd,r.DepthwiseConv2dNativeBackpropFilter=wy,r.DepthwiseConv2dNativeBackpropInput=Ly,r.Diag=cT,r.Dilation2D=Cd,r.Dilation2DBackpropFilter=Od,r.Dilation2DBackpropInput=Rd,r.Div=_a,r.EarlyStopping=h0,r.Elu=El,r.EluGrad=lT,r.Environment=eT,r.Equal=hT,r.Erf=Dl,r.Exp=kl,r.Expm1=Fl,r.FFT=Ed,r.Fill=Sy,r.FlipLeftRight=Dd,r.Floor=_l,r.FloorDiv=Iy,r.FromPixels=qd,r.FusedBatchNorm=Wl,r.FusedConv2D=Xd,r.FusedDepthwiseConv2D=Jd,r.GatherNd=uT,r.GatherV2=xy,r.GraphModel=I0,r.Greater=dT,r.GreaterEqual=Ty,r.History=sN,r.IFFT=kd,r.Identity=$l,r.Imag=Fd,r.InputSpec=Sn,r.IsFinite=Ul,r.IsInf=Bl,r.IsNan=Ml,r.KernelBackend=f,r.LRN=vy,r.LRNBackprop=bT,r.LayerVariable=ai,r.LayersModel=ur,r.Less=pT,r.LessEqual=mT,r.LinSpace=fT,r.Log=Pl,r.Log1p=zl,r.LogSoftmax=Ay,r.LogicalAnd=gT,r.LogicalNot=_d,r.LogicalOr=yT,r.Max=Vl,r.MaxPool=Gl,r.MaxPool3D=Cy,r.MaxPool3DBackprop=wT,r.MaxPoolBackprop=Wd,r.MaxPoolWithArgmax=$d,r.Maximum=Ny,r.Mean=Ry,r.Min=Oy,r.Minimum=Ey,r.MirrorPad=Yl,r.Mod=Dy,r.MomentumOptimizer=zh,r.Multiply=Wa,r.Negate=ky,r.NonMaxSuppressionV3=Fy,r.NonMaxSuppressionV4=Ud,r.NonMaxSuppressionV5=Bd,r.NotEqual=Hl,r.OP_SCOPE_SUFFIX=PT,r.OneHot=Wy,r.OnesLike=_y,r.Optimizer=or,r.PadV2=Md,r.Pool=Rk,r.Pow=$y,r.Prelu=Pd,r.Prod=LT,r.RMSPropOptimizer=Vh,r.RNN=Wi,r.Range=ST,r.Real=zd,r.Reciprocal=ql,r.Relu=jl,r.Relu6=Xl,r.Reshape=Kl,r.ResizeBilinear=By,r.ResizeBilinearGrad=xT,r.ResizeNearestNeighbor=Uy,r.ResizeNearestNeighborGrad=IT,r.Reverse=My,r.RotateWithOffset=jd,r.Round=Jl,r.Rsqrt=Zl,r.SGDOptimizer=lc,r.ScatterNd=TT,r.SelectV2=Py,r.Selu=Ql,r.Sequential=yc,r.Sigmoid=nh,r.Sign=th,r.Sin=$a,r.Sinh=eh,r.Slice=Vd,r.Softmax=Gy,r.Softplus=sh,r.SpaceToBatchND=Gd,r.SparseToDense=AT,r.SplitV=Vy,r.Sqrt=ih,r.Square=Yd,r.SquaredDifference=Ua,r.Step=ah,r.StridedSlice=vT,r.Sub=
2020-10-15 12:48:39 +02:00
`)),x.join(`
2020-10-29 05:16:50 +01:00
`)}function z9(r,l,u,d){const f=Zt(l),g=d[d.length-1],I=new Array(g).fill(0),S=l.length,x=u==="complex64"?Hu(r):r;if(S>1)for(let N=0;N<f/g;N++){const E=N*g;for(let _=0;_<g;_++)I[_]=Math.max(I[_],Yu(x[E+_],0,u).length)}return I}function Yu(r,l,u){let d;return Array.isArray(r)?d=`${parseFloat(r[0].toFixed(_I))} + ${parseFloat(r[1].toFixed(_I))}j`:Pu(r)?d=`'${r}'`:u==="bool"?d=DO(r):d=parseFloat(r.toFixed(_I)).toString(),Yc(d,l)}function DO(r){return r===0?"false":"true"}function bg(r,l,u,d,f,g=!0){const I=u==="complex64"?2:1,S=l[0],x=l.length;if(x===0){if(u==="complex64"){const Q=Hu(r);return[Yu(Q[0],0,u)]}return u==="bool"?[DO(r[0])]:[r[0].toString()]}if(x===1){if(S>OO){const M=Gu*I;let fe=Array.from(r.slice(0,M)),ie=Array.from(r.slice((S-Gu)*I,S*I));return u==="complex64"&&(fe=Hu(fe),ie=Hu(ie)),["["+fe.map((we,Ae)=>Yu(we,f[Ae],u)).join(", ")+", ..., "+ie.map((we,Ae)=>Yu(we,f[S-Gu+Ae],u)).join(", ")+"]"]}const Q=u==="complex64"?Hu(r):Array.from(r);return["["+Q.map((M,fe)=>Yu(M,f[fe],u)).join(", ")+"]"]}const N=l.slice(1),E=d.slice(1),_=d[0]*I,A=[];if(S>OO){for(let Q=0;Q<Gu;Q++){const M=Q*_,fe=M+_;A.push(...bg(r.slice(M,fe),N,u,E,f,!1))}A.push("...");for(let Q=S-Gu;Q<S;Q++){const M=Q*_,fe=M+_;A.push(...bg(r.slice(M,fe),N,u,E,f,Q===S-1))}}else for(let Q=0;Q<S;Q++){const M=Q*_,fe=M+_;A.push(...bg(r.slice(M,fe),N,u,E,f,Q===S-1))}const U=x===2?",":"";A[0]="["+A[0]+U;for(let Q=1;Q<A.length-1;Q++)A[Q]=" "+A[Q]+U;let ne=`,
`;for(let Q=2;Q<x;Q++)ne+=`
`;return A[A.length-1]=" "+A[A.length-1]+"]"+(g?"":ne),A}function Hu(r){const l=[];for(let u=0;u<r.length;u+=2)l.push([r[u],r[u+1]]);return l}class kO{constructor(r,l,u){if(this.dtype=l,this.shape=r.slice(),this.size=Zt(r),u!=null){const d=u.length;J(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=u||V2(l,this.size),this.strides=Vu(r)}set(r,...l){l.length===0&&(l=[0]),J(l.length===this.rank,()=>`The number of provided coordinates (${l.length}) must match the rank (${this.rank})`);const u=this.locToIndex(l);this.values[u]=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 u=r[r.length-1];for(let d=0;d<r.length-1;++d)u+=this.strides[d]*r[d];return this.values[u]}locToIndex(r){if(this.rank===0)return 0;if(this.rank===1)return r[0];let l=r[r.length-1];for(let u=0;u<r.length-1;++u)l+=this.strides[u]*r[u];return l}indexToLoc(r){if(this.rank===0)return[];if(this.rank===1)return[r];const l=new Array(this.shape.length);for(let u=0;u<l.length-1;++u)l[u]=Math.floor(r/this.strides[u]),r-=l[u]*this.strides[u];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,jc=null,V9=null;function FO(r){Yi=r}function _O(r){jc=r}function WO(r){V9=r}class kn{constructor(r,l,u,d){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=Zt(r),this.strides=Vu(r),this.dataId=u,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 jc.buffer(this.shape,this.dtype,r)}bufferSync(){return jc.buffer(this.shape,this.dtype,this.dataSync())}async array(){const r=await this.data();return AI(this.shape,r)}arraySync(){return AI(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(u=>FI(u))}catch(u){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=>FI(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 jc.print(this,r)}clone(){return this.throwIfDisposed(),jc.clone(this)}toString(r=!1){const l=this.dataSync();return EO(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),jc.cast(this,r)}variable(r=!0,l,u){return this.throwIfDisposed(),Yi().makeVariable(this,r,l,u)}}Object.defineProperty(kn,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class wg extends kn{constructor(r,l,u,d){super(r.shape,r.dtype,r.dataId,d);this.trainable=l,this.name=u}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(!Mu(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(wg,Symbol.hasInstance,{value:r=>r instanceof kn&&r.assign!=null&&r.assign instanceof Function});var $O;(function(r){r.R0="R0",
with dtype ${I.dtype}. `)});const d=(I,S)=>{const x=ft(l,u[0].shape)[0],N=JO(u.map(A=>A.shape),x);if(Zt(N)===0)return PI([],N);if(u=u.filter(A=>A.size>0),u.length===1)return u[0];const E=u.map(A=>A.shape);XO(E,x);const _=I.concat(u,x);return S(u),_},f=u,g={axis:l};return H.runKernelFunc(d,f,null,Tf,g)}const An=V({concat_:gZ});function yZ(r){const l=P(r,"x","sigmoid"),u={x:l};return H.runKernelFunc((d,f)=>{const g=d.sigmoid(l);return f([g]),g},u,null,sg)}const qI=V({sigmoid_:yZ});function bZ(r,l,u){const d=P(r,"x","slice");if(d.rank===0)throw new Error("Slicing scalar is not possible");const f=(S,x)=>{const[N,E]=Ig(d,l,u);return YO(d,N,E),x([d]),S.slice(d,N,E)},g={x:d},I={begin:l,size:u};return H.runKernelFunc(f,g,null,eg,I)}const Tt=V({slice_:bZ});function wZ(r,l,u){const d=P(r,"x","batchToSpaceND"),f=l.reduce((x,N)=>x*N);J(d.rank>=1+l.length,()=>`input rank is ${d.rank} but should be > than blockShape.length ${l.length}`),J(u.length===l.length,()=>`crops.length is ${u.length} but should be equal to blockShape.length ${l.length}`),J(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,u),I={x:d},S={blockShape:l,crops:u};return H.runKernelFunc(g,I,null,If,S)}const jI=V({batchToSpaceND_:wZ});function LZ(r,l){let u=P(r,"broadcastTo","x");const d=u.shape;if(l.some(E=>!(E>0)||E%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${l}].`);if(l.length<u.rank)throw new Error(`broadcastTo(): shape.length=${l.length} < input.rank=${u.rank}.`);if(l.length>u.rank){const E=u.shape.slice();for(;E.length<l.length;)E.unshift(1);u=oe(u,E)}const f=u.shape,g=Array.from(l);for(let E=l.length-1;E>=0;E--)if(f[E]===l[E])g[E]=1;else if(u.shape[E]!==1)throw new Error(`broadcastTo(): [${d}] cannot be broadcast to [${l}].`);const I=g.map((E,_)=>E>1?_:-1).filter(E=>E>=0);if(I.length===0)return bi(u);const S=E=>E.tile(u,g),x={x:u},N={shape:l,inputShape:f};return H.runKernelFunc(S,x,null,xf,N)}const vg=V({broadcastTo_:LZ});function SZ(r,l,u,d,f="NHWC",g=[1,1],I){const S=P(r,"x","conv2d"),x=P(l,"filter","conv2d");let N=S,E=!1;S.rank===3&&(E=!0,N=oe(S,[1,S.shape[0],S.shape[1],S.shape[2]])),J(N.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${N.rank}.`),J(x.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${x.rank}.`),I!=null&&J(nn(d),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${d}.`);const _=f==="NHWC"?N.shape[3]:N.shape[1];J(_===x.shape[2],()=>`Error in conv2d: depth of input (${_}) must match input depth for filter ${x.shape[2]}.`),J(bo(u,g),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${u} and dilations '${g}'`);const A=(M,fe)=>{const ie=Zc(f),we=wi(N.shape,x.shape,u,g,d,I,!1,ie),Ae=M.conv2d(N,x,we);return fe([N,x]),Ae},U={x:N,filter:x},ne={strides:u,pad:d,dataFormat:f,dilations:g,dimRoundingMode:I},Q=H.runKernelFunc(A,U,null,Af,ne);return E?oe(Q,[Q.shape[1],Q.shape[2],Q.shape[3]]):Q}const KI=V({conv2d_:SZ});function IZ(r,l,u,d,f,g="NHWC",I){J(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let S=r,x=l,N=!1;l.rank===3&&(N=!0,x=oe(l,[1,l.shape[0],l.shape[1],l.shape[2]]),S=[1,r[0],r[1],r[2]]),J(S.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${S.length}.`),J(x.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${x.rank}`),J(u.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${u.rank}`);const E=g==="NHWC"?S[3]:S[1],_=g==="NHWC"?x.shape[3]:x.shape[1];J(E===u.shape[2],()=>`Error in conv2dDerInput: depth of input (${E}) must match input depth for filter ${u.shape[2]}.`),J(_===u.shape[3],()=>`Error in conv2dDerInput: depth of output (${_}) must match output depth for filter ${u.shape[3]}.`),I!=null&&J(nn(f),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${I} but got pad ${f}.`);const A=(M,fe)=>{const ie=1,we=Zc(g),Ae=wi(S,u.shape,d,ie
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