face-api/dist/face-api.js

4122 lines
1.1 MiB
JavaScript
Raw Normal View History

2020-10-29 05:16:50 +01:00
var faceapi=(()=>{var Xm=Object.defineProperty,s9=Object.prototype.hasOwnProperty,Jm=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),s2=r=>Xm(r,"__esModule",{value:!0}),vu=(r,l)=>{s2(r);for(var u in l)Xm(r,u,{get:l[u],enumerable:!0})},i9=(r,l)=>{if(s2(r),typeof l=="object"||typeof l=="function")for(let u in l)!s9.call(r,u)&&u!=="default"&&Xm(r,u,{get:()=>l[u],enumerable:!0});return r},Ze=r=>r&&r.__esModule?r:i9(Xm({},"default",{value:r,enumerable:!0}),r);var r2=Jm((Ec,i2)=>{"use strict";var r9=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof gr!="undefined")return gr;throw new Error("unable to locate global object")},gr=r9();i2.exports=Ec=gr.fetch;gr.fetch&&(Ec.default=gr.fetch.bind(gr));Ec.Headers=gr.Headers;Ec.Request=gr.Request;Ec.Response=gr.Response});var Qe=Jm((Zm,o2)=>{(function(r,l){typeof Zm=="object"&&typeof o2!="undefined"?l(Zm):typeof define=="function"&&define.amd?define(["exports"],l):(r=r||self,l(r.tf=r.tf||{}))})(Zm,function(r){"use strict";const l=1e-7,u=1e-4;class p{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class y{time(e){return g("time")}read(e){return g("read")}readSync(e){return g("readSync")}numDataIds(){return g("numDataIds")}disposeData(e){return g("disposeData")}write(e,t,n){return g("write")}move(e,t,n,s){return g("move")}memory(){return g("memory")}floatPrecision(){return g("floatPrecision")}epsilon(){return this.floatPrecision()===32?l:u}batchMatMul(e,t,n,s){return g("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){return g("fusedBatchMatMul")}slice(e,t,n){return g("slice")}stridedSlice(e,t,n,s){return g("stridedSlice")}unstack(e,t){return g("unstack")}reverse(e,t){return g("reverse")}concat(e,t){return g("concat")}neg(e){return g("neg")}add(e,t){return g("add")}addN(e){return g("addN")}subtract(e,t){return g("subtract")}multiply(e,t){return g("multiply")}realDivide(e,t){return g("realDivide")}floorDiv(e,t){return g("floorDiv")}sum(e,t){return g("sum")}prod(e,t){return g("prod")}unsortedSegmentSum(e,t,n){return g("unsortedSegmentSum")}argMin(e,t){return g("argMin")}argMax(e,t){return g("argMax")}equal(e,t){return g("equal")}notEqual(e,t){return g("notEqual")}less(e,t){return g("less")}lessEqual(e,t){return g("lessEqual")}greater(e,t){return g("greater")}greaterEqual(e,t){return g("greaterEqual")}logicalNot(e){return g("logicalNot")}logicalAnd(e,t){return g("logicalAnd")}logicalOr(e,t){return g("logicalOr")}where(e){return g("where")}select(e,t,n){return g("select")}topk(e,t,n){return g("topk")}min(e,t){return g("min")}minimum(e,t){return g("minimum")}mod(e,t){return g("mod")}max(e,t){return g("max")}maximum(e,t){return g("maximum")}all(e,t){return g("all")}any(e,t){return g("any")}squaredDifference(e,t){return g("squaredDifference")}ceil(e){return g("ceil")}floor(e){return g("floor")}round(e){return g("round")}sign(e){return g("sign")}isNaN(e){return g("isNaN")}isInf(e){return g("isInf")}isFinite(e){return g("isFinite")}pow(e,t){return g("pow")}exp(e){return g("exp")}expm1(e){return g("expm1")}softmax(e,t){return g("softmax")}log(e){return g("log")}log1p(e){return g("log1p")}sqrt(e){return g("sqrt")}rsqrt(e){return g("rsqrt")}square(e){return g("square")}reciprocal(e){return g("reciprocal")}relu(e){return g("relu")}relu6(e){return g("relu6")}prelu(e,t){return g("prelu")}elu(e){return g("elu")}eluDer(e,t){return g("eluDer")}selu(e){return g("selu")}int(e){return g("int")}clip(e,t,n){return g("clip")}abs(e){return g("abs")}complexAbs(e){return g("complexAbs")}sigmoid(e){return g("sigmoid")}softplus(e){return g("softplus")}sin(e){return g("sin")}cos(e){return g("cos")}tan(e){return g("tan")}asin(e){return g("asin")}acos(e){return g("acos")}atan(e){return g("a
2020-10-13 22:57:06 +02:00
`)),h.join(`
2020-10-29 05:16:50 +01:00
`)}function zk(e,t,n,s){const i=P(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,h=n==="complex64"?ch(e):e;if(c>1)for(let d=0;d<i/o;d++){const m=d*o;for(let f=0;f<o;f++)a[f]=Math.max(a[f],ah(h[m+f],0,n).length)}return a}function ah(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(ab))} + ${parseFloat(e[1].toFixed(ab))}j`:qi(e)?s=`'${e}'`:n==="bool"?s=uT(e):s=parseFloat(e.toFixed(ab)).toString(),pt(s,t)}function uT(e){return e===0?"false":"true"}function qd(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 x=ch(e);return[ah(x[0],0,n)]}return n==="bool"?[uT(e[0])]:[e[0].toString()]}if(h===1){if(c>hT){const v=oh*a;let N=Array.from(e.slice(0,v)),O=Array.from(e.slice((c-oh)*a,c*a));return n==="complex64"&&(N=ch(N),O=ch(O)),["["+N.map((E,k)=>ah(E,i[k],n)).join(", ")+", ..., "+O.map((E,k)=>ah(E,i[c-oh+k],n)).join(", ")+"]"]}const x=n==="complex64"?ch(e):Array.from(e);return["["+x.map((v,N)=>ah(v,i[N],n)).join(", ")+"]"]}const d=t.slice(1),m=s.slice(1),f=s[0]*a,b=[];if(c>hT){for(let x=0;x<oh;x++){const v=x*f,N=v+f;b.push(...qd(e.slice(v,N),d,n,m,i,!1))}b.push("...");for(let x=c-oh;x<c;x++){const v=x*f,N=v+f;b.push(...qd(e.slice(v,N),d,n,m,i,x===c-1))}}else for(let x=0;x<c;x++){const v=x*f,N=v+f;b.push(...qd(e.slice(v,N),d,n,m,i,x===c-1))}const w=h===2?",":"";b[0]="["+b[0]+w;for(let x=1;x<b.length-1;x++)b[x]=" "+b[x]+w;let L=`,
`;for(let x=2;x<h;x++)L+=`
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":L),b}function ch(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=P(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||ws(t,this.size),this.strides=je(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 Ii().makeTensor(this.values,this.shape,this.dtype)}}let Ii=null,Wa=null,dT=null;function Vk(e){Ii=e}function Gk(e){Wa=e}function Yk(e){dT=e}class ee{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=P(e),this.strides=je(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 Wa.buffer(this.shape,this.dtype,e)}bufferSync(){return Wa.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ls(this.shape,e)}arraySync(){return Ls(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=Ii().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>rh(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=Ii().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>rh(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 Ii().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;Ii().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Wa.print(this,e)}clone(){return this.throwIfDisposed(),Wa.clone(this)}toString(e=!1){const t=this.dataSync();return Pk(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Wa.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ii().makeVariable(this,e,t,n)}}Object.defineProperty(ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class lh extends ee{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(!ae(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Ii().disposeTensor(this),this.dataId=e.dataId,Ii().incRef(this,null)}dispose(){Ii().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(lh,Symbol.hasInstance,{value:e=>e instanceof ee&&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,x)=>(L&&w.push(x),w),[]),d=[];h.forEach(w=>{t[w].paths.forEach(L=>{const x=n+(n.endsWith("/")?"":"/")+L;d.push(x)})});const m=await e(d),f={};let b=0;return h.forEach(w=>{const L=t[w].paths.length;let x=0;for(let k=0;k<L;k++)x+=m[b+k].byteLength;const v=new ArrayBuffer(x),N=new Uint8Array(v);let O=0;for(let k=0;k<L;k++){const F=new Uint8Array(m[b+k]);N.set(F,O),O+=F.byteLength}const E=o[w];E.forEach(k=>{const F=v.slice(k.groupOffset,k.groupOffset+k.sizeBytes),U=Jd(F,[k.manifestEntry]);for(const $ in U)f[$]=U[$]}),b+=L}),f}}const WF="application/octet-stream",$F="application/json";class Sb{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=oe().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:$F}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:WF}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:dh(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,d;if(s!=null){const b=await this.loadWeights(s);[h,d]=b}const m={modelTopology:n,weightSpecs:h,weightData:d,userDefinedMetadata:c,generatedBy:i,convertedBy:o,format:a},f=t.modelInitializer;return f&&(m.modelInitializer=f),m}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=UF(t),i=this.weightPathPrefix||n,o=[];for(const d of e)o.push(...d.weights);const a=[],c=[];for(const d of e)for(const m of d.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 DT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,Zd(h)]}}Sb.URL_SCHEME_REGEX=/^https?:\/\//;function
2020-10-11 18:41:17 +02:00
Actual: ${i}.
2020-10-13 22:57:06 +02: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-11 18:41:17 +02:00
Actual: ${i}.
2020-10-29 05:16:50 +01:00
Expected: ${o}.`)}}function i_(e,t){e().then(()=>t.fail(),()=>t())}function r_(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return qi(e)||qi(e[0])||qi(t)||qi(t[0])?Ob(e,n,(s,i)=>s==i):Ob(e,t,(s,i)=>Db(s,i,0))}function Eb(e,t,n){if(n==null&&(n=op()),!Db(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Db(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function o_(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 a_(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var c_=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:jT,expectArraysClose:s_,testEpsilon:op,expectPromiseToFail:i_,expectArraysEqual:r_,expectNumbersClose:Eb,expectValuesInRange:o_,expectArrayBuffersEqual:a_});const KT="2.7.0";function l_(){oe().set("PROD",!0)}function h_(){oe().set("DEBUG",!0)}function u_(){oe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function un(e){oe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}Yk(un);function d_(){G.disposeVariables()}function Ji(){return G}function ap(){return G.memory()}function p_(e){return G.profile(e)}function Q(e,t){return G.tidy(e,t)}function He(e){const t=ji(e);t.forEach(n=>n.dispose())}function bn(e){return G.keep(e)}function m_(e){return G.time(e)}function XT(e){return G.setBackend(e)}function f_(){return G.ready()}function g_(){return G.backendName}function y_(e){G.removeBackend(e)}function b_(e){return G.findBackend(e)}function w_(e){return G.findBackendFactory(e)}function kb(e,t,n=1){return G.registerBackend(e,t,n)}function JT(){return G.backend}function L_(e,t){oe().setPlatform(e,t)}function S_(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Yt(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,Co)}const be=z({add_:S_});function I_(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Yt(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,Ey)}const cp=z({floorDiv_:I_});function x_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Yt(n,s),n.dtype==="int32"&&s.dtype==="int32")return cp(n,s);const i=(c,h)=>{const d=c.realDivide(n,s);return h([n,s]),d},o={a:n,b:s},a={};return G.runKernelFunc(i,o,null,Ra,a)}const We=z({div_:x_});function T_(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Yt(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,Oa)}const X=z({mul_:T_});function A_(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,ud)}const dn=z({abs_:A_});function v_(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,gl)}const Fb=z({acos_:v_});function N_(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,yl)}const _b=z({acosh_:N_});function C_(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(!ae(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,by)}const ZT=z({addN_:C_});function Wb(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function QT(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 An(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=qe(t,n[0].shape)[0],d=Zi(n.map(b=>b.shape),h);if(P(d)===0)return sn([],d);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);dp(m,h);const f=a.concat(n,h);return c(n),f},i=n,o={axis:t};return G.runKernelFunc(s,i,null,Al,o)}const Ht=z({concat_:G_});function Y_(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,Zl)}const Ai=z({sigmoid_:Y_});function H_(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[d,m]=rp(s,t,n);return Nb(s,d,m),h([s]),c.slice(s,d,m)},o={x:s},a={begin:t,size:n};return G.runKernelFunc(i,o,null,_d,a)}const tt=z({slice_:H_});function q_(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,th)}const Va=z({tanh_:q_});function j_(e,t,n,s,i,o){const a=W(e,"forgetBias","basicLSTMCell"),c=W(t,"lstmKernel","basicLSTMCell"),h=W(n,"lstmBias","basicLSTMCell"),d=W(s,"data","basicLSTMCell"),m=W(i,"c","basicLSTMCell"),f=W(o,"h","basicLSTMCell"),b=Ht([d,f],1),w=ct(b,c),L=be(w,h),x=L.shape[0],v=L.shape[1]/4,N=[x,v],O=tt(L,[0,0],N),E=tt(L,[0,v],N),k=tt(L,[0,v*2],N),F=tt(L,[0,v*3],N),U=be(X(Ai(O),Va(E)),X(m,Ai(be(a,k)))),$=X(Va(U),Ai(F));return[U,$]}const K_=z({basicLSTMCell_:j_});function X_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((h,d)=>h*d);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,Iy,c)}const bh=z({batchToSpaceND_:X_});function J_(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 Z_(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 d;i!=null&&(d=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(d==null||c.rank===d.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const f=J_(a),b=(v,N)=>(N([f,c,h,d]),v.batchNorm(f,pp(c),pp(h),pp(m),pp(d),o)),w={x:f,scale:d,offset:m,mean:c,variance:h},L={varianceEpsilon:o},x=G.runKernelFunc(b,w,null,Dl,L);return K(x,a.shape)}function pp(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 Wo=z({batchNorm_: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 d;i!=null&&(d=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}.`),d!=null&&A(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${d.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}.`),Wo(a,c,h,m,d,o)}const eA=z({batchNorm2d_:Q_});function eW(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let d;i!=null&&(d=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),A(a.rank===3,()=>`Error in ba
2020-10-11 18:41:17 +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-13 22:57:06 +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},d={blockSize:t,dataFormat:n};return G.runKernelFunc(c,h,null,Mx,d)}const Kb=z({depthToSpace_:LW});function SW(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","depthwiseConv2d"),h=W(t,"filter","depthwiseConv2d");let d=c,m=!1;c.rank===3&&(m=!0,d=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),A(d.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`),A(h.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),A(d.shape[3]===h.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),a!=null&&A(Le(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const f=(x,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 N=Fn(d.shape,h.shape,n,o,s,a,!0),O=x.depthwiseConv2D(d,h,N);return v([d,h]),O},b={x:d,filter:h},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},L=G.runKernelFunc(f,b,null,wd,w);return m?K(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const $o=z({depthwiseConv2d_:SW});function IW(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,Px)}const xW=z({diag_:IW});function TW(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,d=!1;a.rank===3&&(h=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),d=!0);const m={x:h,filter:c},f={strides:n,pad:s,dilations:i},b=G.runKernel(Ld,m,f);return d?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Xb=z({dilation2d_:TW});function Uo(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 pn(e,t){const n=[];for(let s=0;s<t.length;s++){const i=e[e.length-s-1],o=t.length-s-1,a=t[o];(i==null||i===1&&a>1)&&n.unshift(o)}return n}function nt(e,t){const n=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let o=e[e.length-i-1];o==null&&(o=1);let a=t[t.length-i-1];if(a==null&&(a=1),o===1)n.unshift(a);else if(a===1)n.unshift(o);else if(o!==a){const c=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(c)}else n.unshift(o)}return n}function AW(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Yt(n,s),nt(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,Vx)}const Qs=z({equal_:AW});function vW(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=nt(s.shape,i.shape),c=wh(s,a),h=wh(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&&B(o.shape,h.shape,"Error in where: ");const d=(f,b)=>{const w=f.select(o,c,h);return b([o]),w},m={condition:o,t:c,e:h};return G.runKernelFunc(d,m,null,Xy)}const Bn=z({where_:vW});function NW(e){const t=W(e,"x","zerosLike"),n={x:t};return G.runKernelFunc(s=>s.zerosLike(t),n,null,sb)}const et=z({zerosLike_:NW});function CW(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Yt(n,s);const i=We(n,s),o=et(i),a=Qs(s,o);return Bn(a,o,i)}const Jb=z({divNoNan_:CW});function RW(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(Le(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},d={x:a},m={depthRadius:t,bias:n,alpha:s,beta:i},f=G.runKernelFunc(h,d,null,_y,m);return c?K(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const tw=z({localResponseNormalization_:ZW});function QW(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,$l)}const ls=z({log_:QW});function e$(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,Ul)}const Lp=z({log1p_:e$});function t$(e){return A(Or(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&&B(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Sp(a),a[0]})}}function n$(e){return A(Or(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=uh(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&&B(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Sp(a),a})}}function s$(e){return A(Or(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=G.gradients(()=>e(t),[t],n);return Sp(s),{grad:s[0],value:i}}}function i$(e){return A(Or(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(i=>i instanceof ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=G.gradients(()=>e(...t),t,n);return n!=null&&B(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Sp(s.grads),s}}function nw(e,t){A(Or(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(d=>d instanceof lh),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const d in G.registeredVariables)t.push(G.registeredVariables[d])}const s=n?t.filter(d=>!d.trainable):null,i=t.length;t=t.filter(d=>d.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(d=>d!=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((d,m)=>{c[m]!=null&&(h[d.name]=c[m])}),s!=null&&s.forEach(d=>h[d.name]=null),{value:a,grads:h}}function vi(e){return G.customGrad(e)}function Sp(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 r$(e){const t=W(e,"x","neg"),n={x:t};return G.runKernelFunc(s=>s.neg(t),n,null,zy)}const qt=z({neg_:r$});function o$(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,Ql)}const ja=z({softplus_:o$});function a$(e){const t=W(e,"x","logSigmoid"),n=vi(s=>{const i=qt(ja(qt(s))),o=a=>{const c=X(a,Ai(qt(s)));return c};return{value:i,gradFunc:o}});return n(t)}const mA=z({logSigmoid_:a$});function c$(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,h)=>{const d=qe(t,s.shape);let m=d;const f=Jn(m,s.rank);let b=s;f!=null&&(b=Ye(s,f),m=cs(m.length,b.rank));const w=c.max(b,m);f!=null&&b.dispose();let L=w;if(n){const x=vn(L.shape,qe(t,s.shape));L=K(L,x),w.dispose()}return h([s,L]),L},o={x:s},a={reductionIndices:t,keepDims:n};return G.runKernelFunc(i,o,null,Bl,a)}const es=z({max_:c$});function l$(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Yt(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,ka)}const Re=z({sub_:l$});function h$(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=Ae(s,"int32"));const i=(c,h)=>{h([s]);const d=qe(t,s.shape),m=Jn(d,s.rank);let f=d,b=s;m!=null&&(b=Ye(s,m),f=cs(f.length,s.rank));let w=c.sum(b,f);if(n){const L=vn(w.shape,d);w=K(w,L)}return w},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,Jy,a)}const $e=z({sum_:h$});function u$(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,d=es(e,t,!0),m=Re(e,d),f=Re(Ae(m,"float32"),ls($e(Is(m),t,h)));return c([f]),f},i={logits:n},o={axis:t};return G.runKernelFunc(s,i,null,Fy,o)}const Ip=z({logSoftmax_:u$});function d$(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=qe(t,s.shape),o=es(s,i,!0),a=Re(s,o),c=Is(a),h=$e(c,i),d=ls(h),m=be(K(o,d.shape),d);if(n){const f=vn(m.shape,i);return K(m,f)}return m}const sw=z({logSumExp_:d$});function p$(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");nt(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalAnd(n,s),i,null,Kx)}const Bs=z({logicalAnd_:p$});function m$(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return G.runKernelFunc(s=>s.logicalNot(t),n,null,Nd)}const Th=z({logicalNot_:m$});function f$(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");nt(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalOr(n,s),i,null,Xx)}const xp=z({logicalOr_:f$});function g$(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return nt(n.shape,s.shape),Bs(xp(e,t),Th(Bs(e,t)))}const fA=z({logicalXor_:g$});function y$(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(Le(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const d=(w,L)=>{const x=Un(c.shape,t,n,1,s,i);let v;return x.filterWidth===1&&x.filterHeight===1&&ae(x.inShape,x.outShape)?v=c.clone():v=w.maxPool(c,x),L([c,v]),v},m={x:c},f={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=G.runKernelFunc(d,m,null,Ml,f);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Ah=z({maxPool_:y$});function b$(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:un("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","maxPool3d");let h=c,d=!1;c.rank===4&&(d=!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-13 22:57:06 +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 Ms?[c,h]=Ms.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-13 22:57:06 +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 d={};for(const w of Object.keys(Ms))d[w]=Ms[w];for(const w of Object.keys(n))d[w]=n[w];const m=o.config;m.customObjects=d;const f=Object.assign({},Ms);for(const w of Object.keys(n))Ms[w]=n[w];Pw(o.config);const b=h(c,o.config,n,i);return Ms=Object.assign({},f),b}else{const d=Object.assign({},Ms);for(const f of Object.keys(n))Ms[f]=n[f];const m=new c(o.config);return Ms=Object.assign({},d),m}}}function Kz(e,t){return e<t?-1:e>t?1:0}function Kp(e,t){return-1*Kz(e,t)}function Dee(e){switch(e){case"float32":return"float32";default:throw new q(`Invalid dtype: ${e}`)}}function kee(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 Gr(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function Xz(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 rc(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 zw(e,t,n=0,s=Infinity){return As(n>=0),As(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function wn(e,t){Array.isArray(e)?(A(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>wn(n,`element ${s+1} of ${t}`))):A(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${mv(e)}.`)}function mv(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>mv(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function Jz(e,t){let n=Kn(),s;const i=(...o)=>{const a=Kn();return a-n<t||(n=a,s=e(...o)),s};return i}function fv(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Fee(...e){As(e.length>0,"arrayOfValues is empty");for(const t of e)As(Array.isArray(t),"one of the values is not an array"),As(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 Vw(e,t){return Q(()=>Nn($e(X(e,e),t,!0)))}class Gh extends Fo{getConfig(){return{}}}class Gw extends Gh{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 Q(()=>{const t=Vw(e,this.axis),n=Zn(t,0,this.maxValue);return X(e,We(n,be(mn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Gw.className="MaxNorm",fe(Gw);class Yw extends Gh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return Q(()=>We(e,be(mn(),Vw(e,this.axis))))}getConfig(){return{axis:this.axis}}}Yw.className="UnitNorm",fe(Yw);class Hw extends Gh{apply(e){return Ci(e)}}Hw.className="NonNeg",fe(Hw);class qw extends Gh{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 Q(()=>{const t=Vw(e,this.axis),n=be(X(this.rate,Zn(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,We(n,be(mn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}qw.className="MinMaxNorm",fe(qw);const gv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function fn(e){return Mw(e)}function yv(e,t={}){return Vh(e,$s.getMap().classNameMap,t,"constraint")}function gn(e){if(e==null)return null;if(typeof e=="string"){const t=e in gv?gv[e]:e,n={className:t,config:{}};return yv(n)}else return e instanceof Gh?e:yv(e)}function Zz(e){return new Gw(e)}function Qz(e){return new Yw(e)}function e3(){return new Hw}function t3(e){return new qw(e)}var n3=Object.freeze({__prot
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),Vs(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,bn(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 Vs(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),ts(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 Vs(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Ht(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,ni(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-11 18:41:17 +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=[];Q(()=>{t=K(t,[1,n,i]);for(let c=0;c<e.length;++c){const h=c===0?0:s[c-1],d=[0,h,0],m=[1,e[c],i];o[c]=K(tt(t,d,m),this.elementShape)}return o});const a=[];for(let c=0;c<e.length;c++)a[c]=c;this.writeMany(a,o)}}class du{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}`);Vs(t,i.shape,"TensorList shape mismatch: "),bn(i)}),this.idTensor=Ce(0),this.maxNumElements=s,bn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new du([...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 Vs(e,this.elementShape,"TensorList shape mismatch: "),Q(()=>{const s=this.tensors.map(i=>K(i,e));return ts(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 Vs(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(Vs(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");bn(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 Vs(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.`);Vs(this.elementShape,t.shape,"TensorList shape mismatch: "),bn(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 Vs(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?sn([],[0].concat(this.elementShape)):Q(()=>{const s=e.map(i=>K(this.tensors[i],n));return ts(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Vs(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?sn([],[0].concat(this.elementShape)):Q(()=>{const n=this.tensors.map(s=>K(s,t));return Ht(n,0)})}}function SH(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.shape
2020-10-11 18:41:17 +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=Q(()=>{const h=[];e=K(e,[1,s,o]);for(let d=0;d<t.length;++d){const m=d===0?0:i[d-1],f=[0,m,0],b=[1,t[d],o];h[d]=K(tt(e,f,b),n)}return e.dispose(),h}),c=new du([],n,e.dtype,t.length);for(let h=0;h<a.length;h++)c.setItem(h,a[h]);return c}const AH=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 d=o;for(;h[0];){const m=d;d=await n.functionMap[s].executeFunctionAsync(d,n.tensorArrayMap,n.tensorListMap);const f=d.map(w=>w.id);m.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&f.indexOf(w.id)===-1&&w.dispose()});const b=await n.functionMap[i].executeFunctionAsync(d,n.tensorArrayMap,n.tensorListMap);h=await b[0].data(),b.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&f.indexOf(w.id)===-1&&w.dispose()})}return d}case"LoopCond":{const s=R("pred",e,t,n);return[lr(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=lr(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>is(i,t,n)!==void 0);if(s){const i=is(s,t,n);return[lr(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[lr(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[lr(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[lr(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),d=R("name",e,t,n),m=new LH(d,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=xH(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=IH(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),ms(async()=>(await n.iterator()).columnMajorBatch(e,t,bq),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,ms(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,ms(async()=>(await t.iterator()).filter(s=>Q(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return ms(async()=>(await t.iterator()).map(n=>Q(()=>e(n))),this.size)}mapAsync(e){const t=this;return ms(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 ms(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,ms(async()=>{const s=pu(async()=>({value:await t.iterator(),done:!1}));return c0(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,ms(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=Za(t||Kn().toString());return ms(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,ms(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()}}fc.MAX_BUFFER_SIZE=1e4;function ms(e,t=null){return new class extends fc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function gq(e){return ms(async()=>a0(e),e.length)}function yq(e){if(!mc(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 ms(async()=>{const n=await r0(e,s=>{if(s instanceof fc)return{value:s.iterator(),recurse:!1};if(mc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return sq(n,Zr.SHORTEST)},t)}function bq(e){if(e===null)return null;const t=e[0];if(QH(t)){const n=wq(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function wq(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof ee?ts(e):sn(e)}class d0 extends fc{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 km='"',mu=Symbol("out"),p0=Symbol("field"),Fm=Symbol("quote"),_S=Symbol("quoteafterquote"),m0=Symbol("quoteinquote");class f0 extends fc{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 d0(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 d=Number(c);if(isNaN(d))a&&a.dtype==="bool"?h=this.getBoolean(c):h=c;else if(!a||!a.dtype)h=d;else switch(a.dtype){case"float32":h=d;break;case"int32":h=Math.floor(d);break;case"bool":h=this.getBoolean(c);break;default:h=d}}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=mu;for(let a=0;a<i;a++)switch(o){case mu:switch(e.charAt(a)){case km:s=a+1,o=Fm;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=mu;break;default:o=p0,s=a;break}break;case p0:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=mu,s=a+1;break;default:}break;case Fm:switch(e.charAt(a)){case km:o=_S;break;default:}break;case _S:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=mu,s=a+1;break;case km:o=Fm;break;default:o=m0;break}break;case m0:switch(e.charAt(a)){case km:o=Fm;break;default:}break;default:}if(o===_S?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 g0 extends Sn{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-11 18:41:17 +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&&qi(n[0])){const i=n.map(o=>Hd(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 sr(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=>rh(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 Ji().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=Kn();e();const n=Kn()-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=ip(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),d=new Array(h.length);for(let m=0;m<d.length;m++)d[m]=h[m]*s[m]+t[m];o.set(a.get(...d),...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]=tt(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=qe([t],e.shape),s=es(e,n),i=vn(s.shape,n),o=Re(e,s.reshape(i)),a=Is(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"),Xn("sum",t,e.rank);const[n,s]=An(e.shape,t),i=$n(e.dtype,"int32"),o=dt(n,i),a=P(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=0;for(let b=0;b<a;++b)f+=h[m+b];c[d]=f}return o}prod(e,t){Te(e,"sum");const[n,s]=An(e.shape,t),i=$n(e.dtype,"int32"),o=dt(n,i),a=P(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=1;for(let b=0;b<a;++b)f*=h[m+b];c[d]=f}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=Qs(a,t).asType("float32"),h=c.mul(e).sum(0);s.push(h)}return ts(s)}argMin(e,t){Te(e,"argMin");const n=[t];Xn("argMin",n,e.rank);const[s,i]=An(e.shape,n),o=dt(s,"int32"),a=P(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L<f&&(f=L,b=w)}c[d]=b}return o}argMax(e,t
`),o=i.length.toString().length+2,a=i.map((f,b)=>pt((b+1).toString(),o)+f);let c=0;for(let f=0;f<a.length;f++)c=Math.max(a[f].length,c);const h=a.slice(0,s-1),d=a.slice(s-1,s),m=a.slice(s);console.log(h.join(`
2020-10-11 18:41:17 +02:00
`)),console.log(t.split(`
2020-10-29 05:16:50 +01:00
`)[0]),console.log(`%c ${pt(d[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
`))}function o5(e){return hr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function a5(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 YS(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 c5(e,t){const n=hr(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 l5(e,t){const n=hr(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 ene(){return oe().getNumber("WEBGL_VERSION")===2?1:4}function h5(e){return hr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function u5(e,t){const n=oe().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 d5(e){return hr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function eC(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 p5(e,t,n){nC(e,n),Ee(e,()=>e.activeTexture(e.TEXTURE0+n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function tne(e,t){nC(e,t),Ee(e,()=>e.activeTexture(e.TEXTURE0+t)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function m5(e,t,n){return hr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function f5(e,t,n){return e.getUniformLocation(t,n)}function g5(e,t,n,s){Ee(e,()=>p5(e,t,s)),Ee(e,()=>e.uniform1i(n,s))}function nne(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 HS(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 tC(e,t){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function $m(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+y5(e,t))}function y5(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 hr(e,t,n){const s=Ee(e,()=>t());if(s==null)throw new Error(n);return s}function nC(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 Lc(e,t=2){return P(e.slice(0,e.length-t))}function Sc(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 qS(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[Lc(e),...Sc(e)]),t}function b5(e,t=!1){let n=oe().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?T(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=ln(e);e=i.newShape}let s=P(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-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${n.join(`
2020-10-11 18:41:17 +02:00
`)}
2020-10-13 22:57:06 +02:00
float result = ${s};
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class M5{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-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${n.join(`
2020-10-11 18:41:17 +02:00
`)}
2020-10-13 22:57:06 +02:00
vec4 result = ${s};
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class P5{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-11 18:41:17 +02:00
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
2020-10-13 22:57:06 +02:00
int inOffset = outIdx * ${s};
2020-10-11 18:41:17 +02:00
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
2020-10-13 22:57:06 +02:00
for (int i = 0; i < ${s}; i++) {
int inIdx = ${c};
2020-10-11 18:41:17 +02:00
float candidate = getA(batch, inIdx);
2020-10-13 22:57:06 +02:00
if (candidate ${a} bestValue) {
2020-10-11 18:41:17 +02:00
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
2020-10-29 05:16:50 +01:00
`}}function iC(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function Mn(e,t){return t===1?[e]:iC(e,t)}function z5(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 Pn(){let e,t,n,s,i,o,a,c,h,d;return oe().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-11 18:41:17 +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-13 22:57:06 +02:00
`,h="",d=`
2020-10-11 18:41:17 +02:00
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-10-13 22:57:06 +02:00
`):(e="",t="attribute",n="varying",s="varying",i="texture2D",o="gl_FragColor",a="",c=`
2020-10-11 18:41:17 +02:00
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
2020-10-13 22:57:06 +02:00
`,h=`
2020-10-11 18:41:17 +02:00
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
2020-10-13 22:57:06 +02:00
`,d=`
2020-10-11 18:41:17 +02:00
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:d}}function ea(e,t,n="index"){const s=je(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 zm(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function rne(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(`${zm(a)}, ${zm(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(`${zm(o)}, ${zm(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function XS(e){const t=je(e).map(n=>n.toString());return`
2020-10-11 18:41:17 +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 rC=`
2020-10-11 18:41:17 +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:oC}=Ww;function V5(e,t,n,s){const i=[];e.forEach(L=>{const x=P(L.shapeInfo.logicalShape);L.shapeInfo.isUniform?i.push(`uniform float ${L.name}${x>1?`[${x}]`:""};`):(i.push(`uniform sampler2D ${L.name};`),i.push(`uniform int offset${L.name};`))});const o=i.join(`
`),a=e.map(L=>G5(L,t,s)).join(`
`),c=t.texShape,h=Pn(),d=q5(h);let m,f,b=X5(h);t.isPacked?(m=Y5(t.logicalShape,c),f=K5(h)):(m=H5(t.logicalShape,c),f=j5(h)),s&&(b+=e8);const w=[b,d,f,o,m,a,n].join(`
`);return w}function Ic(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return d8(e);case 1:return m8(e);case 2:return g8(e);case 3:return b8(e);case 4:return L8(e);case 5:return S8(e);case 6:return I8(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function aC(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);default:return w8(e)}}function G5(e,t,n=!1){let s="";n?s+=aC(e):s+=Ic(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=x8(e,t):s+=T8(e,t)),s}function Y5(e,t){switch(e.length){case 0:return cC();case 1:return t8(e,t);case 2:return l8(e,t);case 3:return s8(e,t);default:return r8(e,t)}}function H5(e,t){switch(e.length){case 0:return cC();case 1:return n8(e,t);case 2:return h8(e,t);case 3:return i8(e,t);case 4:return o8(e,t);case 5:return a8(e,t);case 6:return c8(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function q5(e){return`
2020-10-11 18:41:17 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
2020-10-29 05:16:50 +01:00
`}function j5(e){return`
2020-10-11 18:41:17 +02:00
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
2020-10-29 05:16:50 +01:00
`}function K5(e){return`
2020-10-11 18:41:17 +02:00
void setOutput(vec4 val) {
${e.output} = val;
}
2020-10-29 05:16:50 +01:00
`}function X5(e){const t=`${e.version}
2020-10-11 18:41:17 +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
${J5}
${Z5}
${Q5}
`;return t}const J5=`
2020-10-11 18:41:17 +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
`,Z5=`
2020-10-11 18:41:17 +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
`,Q5=`
2020-10-11 18:41:17 +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
`,e8=`
2020-10-11 18:41:17 +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 cC(){return`
2020-10-11 18:41:17 +02:00
int getOutputCoords() {
return 0;
}
2020-10-29 05:16:50 +01:00
`}function t8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?`
2020-10-11 18:41:17 +02:00
int getOutputCoords() {
2020-10-13 22:57:06 +02:00
return 2 * int(resultUV.x * ${n[1]}.0);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`:n[1]===1?`
2020-10-11 18:41:17 +02:00
int getOutputCoords() {
2020-10-13 22:57:06 +02:00
return 2 * int(resultUV.y * ${n[0]}.0);
2020-10-11 18:41:17 +02:00
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-10-13 22:57:06 +02:00
vec2(${n[0]}, ${n[1]}));
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}function n8(e,t){return t[0]===1?`
2020-10-11 18:41:17 +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 s8(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-11 18:41:17 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-10-13 22:57:06 +02:00
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
2020-10-11 18:41:17 +02:00
int b = index / ${i};
index -= b * ${i};
2020-10-13 22:57:06 +02:00
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
2020-10-11 18:41:17 +02:00
return ivec3(b, r, c);
}
2020-10-29 05:16:50 +01:00
`}function i8(e,t){const n=ea(["r","c","d"],e);return`
2020-10-11 18:41:17 +02:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-10-13 22:57:06 +02:00
${n}
2020-10-11 18:41:17 +02:00
return ivec3(r, c, d);
}
2020-10-29 05:16:50 +01:00
`}function r8(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=`
2020-10-13 22:57:06 +02:00
int b${h} = index / ${o};
index -= b${h} * ${o};
`+a,c=`b${h}, `+c;return`
2020-10-11 18:41:17 +02:00
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-10-13 22:57:06 +02:00
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
${a}
2020-10-11 18:41:17 +02:00
int b = index / ${i};
index -= b * ${i};
2020-10-13 22:57:06 +02:00
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
return ivec${e.length}(${c});
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}function o8(e,t){const n=ea(["r","c","d","d2"],e);return`
2020-10-11 18:41:17 +02:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-10-13 22:57:06 +02:00
${n}
2020-10-11 18:41:17 +02:00
return ivec4(r, c, d, d2);
}
2020-10-29 05:16:50 +01:00
`}function a8(e,t){const n=ea(["r","c","d","d2","d3"],e);return`
2020-10-11 18:41:17 +02:00
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-10-13 22:57:06 +02:00
${n}
2020-10-11 18:41:17 +02:00
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
2020-10-29 05:16:50 +01:00
`}function c8(e,t){const n=ea(["r","c","d","d2","d3","d4"],e);return`
2020-10-11 18:41:17 +02:00
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
2020-10-13 22:57:06 +02:00
${n}
2020-10-11 18:41:17 +02:00
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
2020-10-29 05:16:50 +01:00
`}function l8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ae(e,t))return`
2020-10-11 18:41:17 +02:00
ivec2 getOutputCoords() {
2020-10-13 22:57:06 +02:00
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const s=Math.ceil(e[1]/2);return`
2020-10-11 18:41:17 +02:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
2020-10-13 22:57:06 +02:00
vec2(${n[0]}, ${n[1]}));
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
2020-10-11 18:41:17 +02:00
return ivec2(r, c);
}
2020-10-29 05:16:50 +01:00
`}function h8(e,t){return ae(e,t)?`
2020-10-11 18:41:17 +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 ta(e){return`offset${e}`}function u8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Pn();return`
2020-10-13 22:57:06 +02:00
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}function d8(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-13 22:57:06 +02:00
float ${n}() {
2020-10-11 18:41:17 +02:00
return sampleTexture(${t}, halfCR);
}
2020-10-29 05:16:50 +01:00
`;const[o,a]=e.shapeInfo.texShape,c=ta(t);return`
2020-10-13 22:57:06 +02:00
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
2020-10-11 18:41:17 +02:00
return sampleTexture(${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),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],o=Pn();return`
2020-10-13 22:57:06 +02:00
vec4 ${n}(int index) {
2020-10-11 18:41:17 +02:00
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
2020-10-13 22:57:06 +02:00
return ${o.texture2D}(${t}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}function m8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
2020-10-13 22:57:06 +02:00
float ${n}(int index) {
2020-10-29 05:16:50 +01:00
${xc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const s=e.shapeInfo.texShape,i=s[0],o=s[1];if(o===1&&i===1)return`
float ${n}(int index) {
2020-10-11 18:41:17 +02:00
return sampleTexture(${t}, halfCR);
}
2020-10-29 05:16:50 +01:00
`;const a=ta(t);return o===1?`
2020-10-13 22:57:06 +02:00
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${i}.0);
2020-10-11 18:41:17 +02:00
return sampleTexture(${t}, uv);
}
`:i===1?`
2020-10-13 22:57:06 +02:00
float ${n}(int index) {
vec2 uv = vec2((float(index + ${a}) + 0.5) / ${o}.0, 0.5);
2020-10-11 18:41:17 +02:00
return sampleTexture(${t}, uv);
}
`:`
2020-10-13 22:57:06 +02:00
float ${n}(int index) {
vec2 uv = uvFromFlat(${i}, ${o}, index + ${a});
2020-10-11 18:41:17 +02:00
return sampleTexture(${t}, 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,o=i[0],a=i[1],c=Pn();if(i!=null&&ae(t,i))return`
2020-10-13 22:57:06 +02:00
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${o}.0);
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
return ${c.texture2D}(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const h=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],d=Math.ceil(t[1]/2);return`
vec4 ${s}(int row, int col) {
vec2 uv = packedUVfrom2D(${d}, ${h[0]}, ${h[1]}, row, col);
return ${c.texture2D}(${n}, uv);
2020-10-11 18:41:17 +02:00
}
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;if(i!=null&&ae(t,i)){const f=i[0],b=i[1];return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
2020-10-29 05:16:50 +01:00
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${f}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}const{newShape:o,keptDims:a}=ln(t),c=o;if(c.length<t.length){const f=Tc(e,c),b=["row","col"];return`
${Ic(f)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ac(b,a)});
2020-10-11 18:41:17 +02:00
}
`}if(e.shapeInfo.isUniform)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
2020-10-11 18:41:17 +02:00
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
2020-10-29 05:16:50 +01:00
${xc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const h=i[0],d=i[1],m=ta(n);return d===1?`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${h}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`:h===1?`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
`:`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col) {
2020-10-11 18:41:17 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-10-13 22:57:06 +02:00
int index = row * ${t[1]} + col + ${m};
vec2 uv = uvFromFlat(${h}, ${d}, index);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
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=e.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const f=t.slice(1),b=[1,2],w=Tc(e,f),L=["b","row","col"];return`
${aC(w)}
2020-10-13 22:57:06 +02:00
vec4 ${s}(int b, int row, int col) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ac(L,b)});
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}const a=o[0],c=o[1],h=Math.ceil(t[2]/2),d=h*Math.ceil(t[1]/2),m=Pn();return`
2020-10-13 22:57:06 +02:00
vec4 ${s}(int b, int row, int col) {
2020-10-11 18:41:17 +02:00
vec2 uv = packedUVfrom3D(
2020-10-13 22:57:06 +02:00
${a}, ${c}, ${d}, ${h}, b, row, col);
return ${m.texture2D}(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}function b8(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}=ln(t),h=a;if(h.length<t.length){const L=Tc(e,h),x=["row","col","depth"];return`
${Ic(L)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ac(x,c)});
2020-10-11 18:41:17 +02:00
}
`}if(e.shapeInfo.isUniform)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-11 18:41:17 +02:00
int index = round(dot(vec3(row, col, depth),
2020-10-13 22:57:06 +02:00
vec3(${i}, ${o}, 1)));
2020-10-29 05:16:50 +01:00
${xc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const d=e.shapeInfo.texShape,m=d[0],f=d[1],b=e.shapeInfo.flatOffset;if(f===i&&b==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-11 18:41:17 +02:00
float texR = float(row);
2020-10-13 22:57:06 +02:00
float texC = dot(vec2(col, depth), vec2(${o}, 1));
2020-10-11 18:41:17 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-29 05:16:50 +01:00
vec2(${f}.0, ${m}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;if(f===o&&b==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-11 18:41:17 +02:00
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
2020-10-29 05:16:50 +01:00
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${f}.0, ${m}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const w=ta(n);return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth) {
2020-10-11 18:41:17 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-10-13 22:57:06 +02:00
int index = row * ${i} + col * ${o} + depth + ${w};
2020-10-29 05:16:50 +01:00
vec2 uv = uvFromFlat(${m}, ${f}, index);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
}
2020-10-29 05:16:50 +01:00
`}function w8(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],d=Math.ceil(t[n-1]/2);let m=d*Math.ceil(t[n-2]/2),f="int b, int row, int col",b=`b * ${m} + (row / 2) * ${d} + (col / 2)`;for(let L=2;L<n-1;L++)f=`int b${L}, `+f,m*=t[n-L-1],b=`b${L} * ${m} + `+b;const w=Pn();return`
vec4 ${i}(${f}) {
2020-10-13 22:57:06 +02:00
int index = ${b};
int texR = index / ${h};
int texC = index - texR * ${h};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}, ${c});
return ${w.texture2D}(${s}, uv);
2020-10-11 18:41:17 +02:00
}
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[3],o=t[2]*i,a=t[1]*o,{newShape:c,keptDims:h}=ln(t);if(c.length<t.length){const L=Tc(e,c),x=["row","col","depth","depth2"];return`
${Ic(L)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ac(x,h)});
2020-10-11 18:41:17 +02:00
}
`}if(e.shapeInfo.isUniform)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-11 18:41:17 +02:00
int index = round(dot(vec4(row, col, depth, depth2),
2020-10-13 22:57:06 +02:00
vec4(${a}, ${o}, ${i}, 1)));
2020-10-29 05:16:50 +01:00
${xc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const d=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,f=m[0],b=m[1];if(b===a&&d==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-11 18:41:17 +02:00
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
2020-10-13 22:57:06 +02:00
vec3(${o}, ${i}, 1));
2020-10-11 18:41:17 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-29 05:16:50 +01:00
vec2(${b}.0, ${f}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;if(b===i&&d==null)return`
float ${s}(int row, int col, int depth, int depth2) {
2020-10-11 18:41:17 +02:00
float texR = dot(vec3(row, col, depth),
vec3(${t[1]*t[2]}, ${t[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-29 05:16:50 +01:00
vec2(${b}.0, ${f}.0);
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const w=ta(n);return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2) {
2020-10-11 18:41:17 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-10-13 22:57:06 +02:00
int index = row * ${a} + col * ${o} +
2020-10-11 18:41:17 +02:00
depth * ${i} + depth2;
2020-10-29 05:16:50 +01:00
vec2 uv = uvFromFlat(${f}, ${b}, index + ${w});
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
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),i=t[4],o=t[3]*i,a=t[2]*o,c=t[1]*a,{newShape:h,keptDims:d}=ln(t);if(h.length<t.length){const x=Tc(e,h),v=["row","col","depth","depth2","depth3"];return`
${Ic(x)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ac(v,d)});
2020-10-11 18:41:17 +02:00
}
`}if(e.shapeInfo.isUniform)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-11 18:41:17 +02:00
float index = dot(
vec4(row, col, depth, depth2),
2020-10-13 22:57:06 +02:00
vec4(${c}, ${a}, ${o}, ${i})) +
2020-10-11 18:41:17 +02:00
depth3;
2020-10-29 05:16:50 +01:00
${xc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const m=e.shapeInfo.flatOffset,f=e.shapeInfo.texShape,b=f[0],w=f[1];if(w===c&&m==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-11 18:41:17 +02:00
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
2020-10-13 22:57:06 +02:00
vec4(${a}, ${o}, ${i}, 1));
2020-10-11 18:41:17 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-13 22:57:06 +02:00
vec2(${w}.0, ${b}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;if(w===i&&m==null)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-11 18:41:17 +02:00
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-13 22:57:06 +02:00
vec2(${w}.0, ${b}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const L=ta(n);return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth, int depth2, int depth3) {
2020-10-11 18:41:17 +02:00
// Explicitly use integer operations as dot() only works on floats.
2020-10-13 22:57:06 +02:00
int index = row * ${c} + col * ${a} + depth * ${o} +
depth2 * ${i} + depth3 + ${L};
vec2 uv = uvFromFlat(${b}, ${w}, index);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}function I8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=ln(t);if(i.length<t.length){const v=Tc(e,i),N=["row","col","depth","depth2","depth3","depth4"];return`
${Ic(v)}
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth,
2020-10-11 18:41:17 +02:00
int depth2, int depth3, int depth4) {
2020-10-29 05:16:50 +01:00
return ${s}(${Ac(N,o)});
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`}const a=t[5],c=t[4]*a,h=t[3]*c,d=t[2]*h,m=t[1]*d;if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth,
2020-10-11 18:41:17 +02:00
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
2020-10-13 22:57:06 +02:00
vec4(${m}, ${d}, ${h}, ${c})) +
2020-10-11 18:41:17 +02:00
dot(
vec2(depth3, depth4),
2020-10-13 22:57:06 +02:00
vec2(${a}, 1)));
2020-10-29 05:16:50 +01:00
${xc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const f=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],L=b[1];if(L===m&&f==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth,
2020-10-11 18:41:17 +02:00
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
2020-10-13 22:57:06 +02:00
vec4(${d}, ${h}, ${c}, ${a})) +
2020-10-11 18:41:17 +02:00
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-13 22:57:06 +02:00
vec2(${L}.0, ${w}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;if(L===a&&f==null)return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth,
2020-10-11 18:41:17 +02:00
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-13 22:57:06 +02:00
vec2(${L}.0, ${w}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const x=ta(n);return`
2020-10-13 22:57:06 +02:00
float ${s}(int row, int col, int depth,
2020-10-11 18:41:17 +02:00
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
2020-10-13 22:57:06 +02:00
int index = row * ${m} + col * ${d} + depth * ${h} +
2020-10-29 05:16:50 +01:00
depth2 * ${c} + depth3 * ${a} + depth4 + ${x};
2020-10-13 22:57:06 +02:00
vec2 uv = uvFromFlat(${w}, ${L}, index);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}function xc(e){const t=e.name,n=P(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
2020-10-13 22:57:06 +02:00
for (int i = 0; i < ${n}; i++) {
2020-10-11 18:41:17 +02:00
if (i == index) {
return ${t}[i];
}
}
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=e.shapeInfo.logicalShape.length,a=t.logicalShape.length,c=oC(e.shapeInfo.logicalShape,t.logicalShape),h=Rt(a),d=a-o;let m;const f=["x","y","z","w","u","v"];o===0?m="":a<2&&c.length>=1?m="coords = 0;":m=c.map(O=>`coords.${f[O+d]} = 0;`).join(`
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((O,E)=>`coords.${f[E+d]}`).join(", ");let w="return outputValue;";const L=P(e.shapeInfo.logicalShape),x=L===1,v=P(t.logicalShape),N=v===1;if(o===1&&!x&&!N)w=`
2020-10-11 18:41:17 +02:00
return vec4(outputValue.xy, outputValue.xy);
2020-10-29 05:16:50 +01:00
`;else if(x&&!N)a===1?w=`
2020-10-11 18:41:17 +02:00
return vec4(outputValue.x, outputValue.x, 0., 0.);
2020-10-13 22:57:06 +02:00
`:w=`
2020-10-11 18:41:17 +02:00
return vec4(outputValue.x);
2020-10-29 05:16:50 +01:00
`;else if(c.length){const O=o-2,E=o-1;c.indexOf(O)>-1&&c.indexOf(E)>-1?w="return vec4(outputValue.x);":c.indexOf(O)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(E)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
2020-10-11 18:41:17 +02:00
vec4 ${i}() {
2020-10-13 22:57:06 +02:00
${h} coords = getOutputCoords();
${m}
vec4 outputValue = get${s}(${b});
${w}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}function T8(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&&ae(a,o))return`
2020-10-11 18:41:17 +02:00
float ${i}() {
2020-10-13 22:57:06 +02:00
return sampleTexture(${n}, resultUV);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`;const d=Rt(h),m=oC(e.shapeInfo.logicalShape,t.logicalShape),f=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(x=>`coords.${w[x+f]} = 0;`).join(`
`);let L="";return h<2&&c>0?L="coords":L=e.shapeInfo.logicalShape.map((x,v)=>`coords.${w[v+f]}`).join(", "),`
2020-10-11 18:41:17 +02:00
float ${i}() {
2020-10-13 22:57:06 +02:00
${d} coords = getOutputCoords();
${b}
return get${s}(${L});
2020-10-11 18:41:17 +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 Tc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Ac(e,t){return t.map(n=>e[n]).join(", ")}class A8{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),d=Mn("coords",c);let m,f;if(o===1){f=c+1;const $=Rt(f);m=`
2020-10-13 22:57:06 +02:00
${$} sourceLocR = ${$}(${d.join()}, 0);
++${d[c-1]};
${$} sourceLocG = ${$}(${d.join()}, 0);
++${d[c-2]};
${$} sourceLocA = ${$}(${d.join()}, 0);
--${d[c-1]};
${$} sourceLocB = ${$}(${d.join()}, 0);
2020-10-29 05:16:50 +01:00
--${d[c-2]};`}else f=c,m=`
2020-10-13 22:57:06 +02:00
${h} sourceLocR = coords;
++${d[c-1]};
${h} sourceLocG = coords;
++${d[c-2]};
${h} sourceLocA = coords;
--${d[c-1]};
${h} sourceLocB = coords;
2020-10-29 05:16:50 +01:00
--${d[c-2]};`;const b=["x","y","z","w","u","v"].slice(0,f),w="."+b[f-1],L=b.map($=>"int "+$),x=Mn("sourceLocR",f-1).concat("inIdx.r"),v=Mn("sourceLocG",f-1).concat("inIdx.g"),N=Mn("sourceLocB",f-1).concat("inIdx.b"),O=Mn("sourceLocA",f-1).concat("inIdx.a"),E=n==="max"?"greaterThan":"lessThan",k=s?"":`
inIdx = round(vec4(getBestIndicesAChannel(${x.join()}),
getBestIndicesAChannel(${v.join()}),
2020-10-13 22:57:06 +02:00
getBestIndicesAChannel(${N.join()}),
2020-10-29 05:16:50 +01:00
getBestIndicesAChannel(${O.join()})));`,F=`vec4(
getAChannel(${x.join()}),
hasNextCol ? getAChannel(${v.join()}) : 0.,
2020-10-13 22:57:06 +02:00
hasNextRow ? getAChannel(${N.join()}) : 0.,
2020-10-29 05:16:50 +01:00
hasNextRow && hasNextCol ? getAChannel(${O.join()}) : 0.)`,U=s?"":`
2020-10-13 22:57:06 +02:00
float getBestIndicesAChannel(${L.join()}) {
return getChannel(getBestIndicesA(${b.join()}),
vec2(${b.slice(-2).join()}));
2020-10-11 18:41:17 +02:00
}`;this.userCode=`
2020-10-13 22:57:06 +02:00
float getAChannel(${L.join()}) {
return getChannel(getA(${b.join()}),
vec2(${b.slice(-2).join()}));
}
2020-10-29 05:16:50 +01:00
${U}
2020-10-13 22:57:06 +02:00
void main() {
${h} coords = getOutputCoords();
bool hasNextCol = ${d[c-1]} < ${a[c-1]-1};
bool hasNextRow = ${d[c-2]} < ${a[c-2]-1};
${m}
ivec4 srcIdx = ivec4(sourceLocR${w}, sourceLocG${w},
sourceLocB${w}, sourceLocA${w}) * ${t};
2020-10-11 18:41:17 +02:00
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
2020-10-29 05:16:50 +01:00
vec4 bestValue = ${F};
2020-10-11 18:41:17 +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-11 18:41:17 +02:00
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
2020-10-29 05:16:50 +01:00
vec4(${E}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2020-10-11 18:41:17 +02:00
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
2020-10-29 05:16:50 +01:00
`}}class v8{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,d=c-1-e.padInfo.top,m=h-1-e.padInfo.left,f=1/(t*n);this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 pads = ivec2(${d}, ${m});
2020-10-29 05:16:50 +01:00
const float avgMultiplier = float(${f});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${c};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
2020-10-11 18:41:17 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${h};
wC+= ${a}) {
2020-10-11 18:41:17 +02:00
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 N8{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,d=e.dilationWidth,m=e.effectiveFilterDepth,f=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,L=f-1-e.padInfo.top,x=b-1-e.padInfo.left,v=1/(t*n*s);this.userCode=`
const ivec3 pads = ivec3(${w}, ${L}, ${x});
const float avgMultiplier = float(${v});
2020-10-11 18:41:17 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-10-13 22:57:06 +02:00
for (int wD = 0; wD < ${m};
wD += ${c}) {
2020-10-11 18:41:17 +02:00
float dyD = float(dyDCorner + wD) / ${i}.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 < ${f};
2020-10-13 22:57:06 +02:00
wR += ${h}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
2020-10-11 18:41:17 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${b};
wC += ${d}) {
float dyC = float(dyCCorner + wC) / ${a}.0;
2020-10-11 18:41:17 +02:00
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 lC=`
2020-10-11 18:41:17 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-29 05:16:50 +01:00
`,C8=`
2020-10-11 18:41:17 +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
`,R8=`
2020-10-11 18:41:17 +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
`,one="return (a - b) * (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 >= b);",_8="return float(a >= 1.0 && b >= 1.0);",W8="return float(a >= 1.0 || b >= 1.0);",$8=lC+`
2020-10-11 18:41:17 +02:00
return max(a, b);
2020-10-29 05:16:50 +01:00
`,U8=lC+`
2020-10-11 18:41:17 +02:00
return min(a, b);
2020-10-29 05:16:50 +01:00
`,B8=`if (b == 0.0) return NAN;
return mod(a, b);`,M8="return (b >= 1.0) ? a : a * (b + 1.0);",hC="return (a < 0.) ? b * a : a;";class Wn{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=nt(t,n),this.userCode=`
2020-10-11 18:41:17 +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 Vm=`
2020-10-11 18:41:17 +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
`,P8=`
2020-10-11 18:41:17 +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
`,z8=`
2020-10-11 18:41:17 +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
`+Vm+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,uC=`
2020-10-11 18:41:17 +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
`,V8=`
2020-10-11 18:41:17 +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
`,G8=`
2020-10-11 18:41:17 +02:00
return vec4(equal(a, b));
2020-10-29 05:16:50 +01:00
`,ane=`
2020-10-11 18:41:17 +02:00
return vec4(notEqual(a, b));
2020-10-29 05:16:50 +01:00
`,Y8=`
2020-10-11 18:41:17 +02:00
return vec4(lessThan(a, b));
2020-10-29 05:16:50 +01:00
`,H8=`
2020-10-11 18:41:17 +02:00
return vec4(lessThanEqual(a, b));
2020-10-29 05:16:50 +01:00
`,q8=`
2020-10-11 18:41:17 +02:00
return vec4(greaterThan(a, b));
2020-10-29 05:16:50 +01:00
`,j8=`
2020-10-11 18:41:17 +02:00
return vec4(greaterThanEqual(a, b));
2020-10-29 05:16:50 +01:00
`,K8=`
2020-10-11 18:41:17 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2020-10-29 05:16:50 +01:00
`,X8=`
2020-10-11 18:41:17 +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
`,J8=`
2020-10-11 18:41:17 +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
`+Vm+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,Z8=`
2020-10-11 18:41:17 +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
`+Vm+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,Q8=`
2020-10-11 18:41:17 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2020-10-29 05:16:50 +01:00
`+Vm+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-29 05:16:50 +01:00
`;class ur{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=nt(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||P(this.outputShape)===1)o=`
2020-10-11 18:41:17 +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-13 22:57:06 +02:00
${a} coords = getOutputCoords();
`,i===1)o+=`
2020-10-11 18:41:17 +02:00
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=Mn("coords",i);o+=`
2020-10-11 18:41:17 +02:00
bool nextRowOutOfBounds =
2020-10-13 22:57:06 +02:00
(${c[i-2]} + 1) >= ${this.outputShape[i-2]};
2020-10-11 18:41:17 +02:00
bool nextColOutOfBounds =
2020-10-13 22:57:06 +02:00
(${c[i-1]} + 1) >= ${this.outputShape[i-1]};
2020-10-11 18:41:17 +02:00
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
2020-10-13 22:57:06 +02:00
${o}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class e6{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +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 t6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +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 n6{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +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 s6{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-11 18:41:17 +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++) {
2020-10-13 22:57:06 +02:00
int xR = wR + yR * ${t} - ${s};
2020-10-11 18:41:17 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
2020-10-13 22:57:06 +02:00
int xC = wC + yC * ${n} - ${i};
2020-10-11 18:41:17 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2020-10-13 22:57:06 +02:00
if (${o}) {
2020-10-11 18:41:17 +02:00
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class i6{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,d=o?2:3,m=o?3:1;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 pads = ivec2(${a}, ${c});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
2020-10-13 22:57:06 +02:00
int d1 = coords[${m}];
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
ivec2 dyCorner = ivec2(coords[${h}], coords[${d}]) - pads;
2020-10-11 18:41:17 +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++) {
2020-10-13 22:57:06 +02:00
float dyR = float(dyRCorner + wR) / ${s}.0;
2020-10-11 18:41:17 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${n}; wC++) {
2020-10-11 18:41:17 +02:00
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-10-13 22:57:06 +02:00
int wCPerm = ${n} - 1 - wC;
2020-10-11 18:41:17 +02:00
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
2020-10-13 22:57:06 +02:00
if (${o}) {
2020-10-11 18:41:17 +02:00
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class r6{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-11 18:41:17 +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++) {
2020-10-13 22:57:06 +02:00
int xR = wR + yR * ${n} - ${o};
2020-10-11 18:41:17 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
2020-10-13 22:57:06 +02:00
int xC = wC + yC * ${s} - ${a};
2020-10-11 18:41:17 +02:00
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 o6{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,d=s-1-e.padInfo.left;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec3 pads = ivec3(${c}, ${h}, ${d});
2020-10-11 18:41:17 +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;
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
2020-10-11 18:41:17 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-10-13 22:57:06 +02:00
int wRPerm = ${n} - 1 - wR;
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
2020-10-11 18:41:17 +02:00
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-10-13 22:57:06 +02:00
int wCPerm = ${s} - 1 - wC;
2020-10-11 18:41:17 +02:00
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 a6{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-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
2020-10-13 22:57:06 +02:00
int d2 = d1 * ${o} + dm;
2020-10-11 18:41:17 +02:00
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++) {
2020-10-13 22:57:06 +02:00
int xR = wR + yR * ${t} - ${s};
2020-10-11 18:41:17 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
2020-10-13 22:57:06 +02:00
int xC = wC + yC * ${n} - ${i};
2020-10-11 18:41:17 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class c6{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-13 22:57:06 +02:00
const ivec2 pads = ivec2(${o}, ${a});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
2020-10-13 22:57:06 +02:00
float dyR = float(dyRCorner + wR) / ${s}.0;
2020-10-11 18:41:17 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${n}; wC++) {
2020-10-11 18:41:17 +02:00
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-10-13 22:57:06 +02:00
int wCPerm = ${n} - 1 - wC;
2020-10-11 18:41:17 +02:00
// TO DO: Vec4 over the channelMul
2020-10-13 22:57:06 +02:00
for (int dm = 0; dm < ${c}; dm++) {
int d2 = d1 * ${c} + dm;
2020-10-11 18:41:17 +02:00
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 dC{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,d=e.dilationWidth,m=e.filterHeight,f=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,L=e.dataFormat==="channelsLast",x=L?1:2,v=L?2:3,N=L?3:1;let O="",E="";n&&(s?O=`float activation(float a) {
2020-10-11 18:41:17 +02:00
float b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
2020-10-29 05:16:50 +01:00
}`:O=`
2020-10-11 18:41:17 +02:00
float activation(float x) {
2020-10-13 22:57:06 +02:00
${n}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`,E="result = activation(result);");const k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${O}
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${i}, ${o});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
2020-10-13 22:57:06 +02:00
int d2 = coords[${N}];
2020-10-11 18:41:17 +02:00
ivec2 xRCCorner =
2020-10-29 05:16:50 +01:00
ivec2(coords[${x}], coords[${v}]) * strides - pads;
2020-10-11 18:41:17 +02:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${h};
2020-10-11 18:41:17 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-10-29 05:16:50 +01:00
for (int wC = 0; wC < ${f}; wC++) {
2020-10-13 22:57:06 +02:00
int xC = xCCorner + wC * ${d};
2020-10-11 18:41:17 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2020-10-13 22:57:06 +02:00
for (int d1 = 0; d1 < ${b}; d1 += 4) {
2020-10-11 18:41:17 +02:00
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-11 18:41:17 +02:00
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
2020-10-13 22:57:06 +02:00
if (${w===1}) {
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-11 18:41:17 +02:00
dotProd +=
2020-10-13 22:57:06 +02:00
getX(batch, xR, xC, ${b}) *
getW(wR, wC, ${b}, d2);
2020-10-11 18:41:17 +02:00
} else {
dotProd +=
2020-10-13 22:57:06 +02:00
getX(batch, ${b}, xR, xC) *
getW(wR, wC, ${b}, d2);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
} else if (${w===2}) {
2020-10-11 18:41:17 +02:00
vec2 wValues = vec2(
2020-10-13 22:57:06 +02:00
getW(wR, wC, ${b}, d2),
getW(wR, wC, ${b} + 1, d2)
2020-10-11 18:41:17 +02:00
);
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-11 18:41:17 +02:00
vec2 xValues = vec2(
2020-10-13 22:57:06 +02:00
getX(batch, xR, xC, ${b}),
getX(batch, xR, xC, ${b} + 1)
2020-10-11 18:41:17 +02:00
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
2020-10-13 22:57:06 +02:00
getX(batch, ${b}, xR, xC),
getX(batch, ${b} + 1, xR, xC)
2020-10-11 18:41:17 +02:00
);
dotProd += dot(xValues, wValues);
}
2020-10-13 22:57:06 +02:00
} else if (${w===3}) {
2020-10-11 18:41:17 +02:00
vec3 wValues = vec3(
2020-10-13 22:57:06 +02:00
getW(wR, wC, ${b}, d2),
getW(wR, wC, ${b} + 1, d2),
getW(wR, wC, ${b} + 2, d2)
2020-10-11 18:41:17 +02:00
);
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-11 18:41:17 +02:00
vec3 xValues = vec3(
2020-10-13 22:57:06 +02:00
getX(batch, xR, xC, ${b}),
getX(batch, xR, xC, ${b} + 1),
getX(batch, xR, xC, ${b} + 2)
2020-10-11 18:41:17 +02:00
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
2020-10-13 22:57:06 +02:00
getX(batch, ${b}, xR, xC),
getX(batch, ${b} + 1, xR, xC),
getX(batch, ${b} + 2, xR, xC)
2020-10-11 18:41:17 +02:00
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
2020-10-29 05:16:50 +01:00
${k}
${E}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class l6{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,d=e.dilationWidth,m=e.filterDepth,f=e.filterHeight,b=e.filterWidth,w=Math.floor(e.inChannels/4)*4,L=e.inChannels%4;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec3 strides = ivec3(${i}, ${o}, ${a});
const ivec3 pads = ivec3(${t}, ${n}, ${s});
2020-10-11 18:41:17 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
2020-10-13 22:57:06 +02:00
for (int wF = 0; wF < ${m}; wF++) {
int xF = xFCorner + wF * ${c};
2020-10-11 18:41:17 +02:00
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
2020-10-29 05:16:50 +01:00
for (int wR = 0; wR < ${f}; wR++) {
2020-10-13 22:57:06 +02:00
int xR = xRCorner + wR * ${h};
2020-10-11 18:41:17 +02:00
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${b}; wC++) {
int xC = xCCorner + wC * ${d};
2020-10-11 18:41:17 +02:00
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
2020-10-13 22:57:06 +02:00
for (int d1 = 0; d1 < ${w}; d1 += 4) {
2020-10-11 18:41:17 +02:00
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
2020-10-13 22:57:06 +02:00
if (${L===1}) {
2020-10-11 18:41:17 +02:00
dotProd +=
2020-10-13 22:57:06 +02:00
getX(batch, xF, xR, xC, ${w}) *
getW(wF, wR, wC, ${w}, d2);
} else if (${L===2}) {
2020-10-11 18:41:17 +02:00
vec2 xValues = vec2(
2020-10-13 22:57:06 +02:00
getX(batch, xF, xR, xC, ${w}),
getX(batch, xF, xR, xC, ${w} + 1)
2020-10-11 18:41:17 +02:00
);
vec2 wValues = vec2(
2020-10-13 22:57:06 +02:00
getW(wF, wR, wC, ${w}, d2),
getW(wF, wR, wC, ${w} + 1, d2)
2020-10-11 18:41:17 +02:00
);
dotProd += dot(xValues, wValues);
2020-10-13 22:57:06 +02:00
} else if (${L===3}) {
2020-10-11 18:41:17 +02:00
vec3 xValues = vec3(
2020-10-13 22:57:06 +02:00
getX(batch, xF, xR, xC, ${w}),
getX(batch, xF, xR, xC, ${w} + 1),
getX(batch, xF, xR, xC, ${w} + 2)
2020-10-11 18:41:17 +02:00
);
vec3 wValues = vec3(
2020-10-13 22:57:06 +02:00
getW(wF, wR, wC, ${w}, d2),
getW(wF, wR, wC, ${w} + 1, d2),
getW(wF, wR, wC, ${w} + 2, d2)
2020-10-11 18:41:17 +02:00
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class pC{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,d=e.strideWidth,m=e.dilationHeight,f=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=e.outChannels/e.inChannels;let x="",v="";n&&(s?x=`float activation(float a) {
2020-10-11 18:41:17 +02:00
float b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
2020-10-29 05:16:50 +01:00
}`:x=`
2020-10-11 18:41:17 +02:00
float activation(float x) {
2020-10-13 22:57:06 +02:00
${n}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`,v="result = activation(result);");const N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${x}
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${h}, ${d});
const ivec2 pads = ivec2(${a}, ${c});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
2020-10-13 22:57:06 +02:00
int d1 = d2 / ${L};
int q = d2 - d1 * ${L};
2020-10-11 18:41:17 +02:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${b}; wR++) {
int xR = xRCorner + wR * ${m};
2020-10-11 18:41:17 +02:00
if (xR < 0 || xR >= ${i}) {
continue;
}
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${w}; wC++) {
2020-10-29 05:16:50 +01:00
int xC = xCCorner + wC * ${f};
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
if (xC < 0 || xC >= ${o}) {
2020-10-11 18:41:17 +02:00
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
2020-10-13 22:57:06 +02:00
${N}
2020-10-29 05:16:50 +01:00
${v}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class mC{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,d=e.strideWidth,m=e.dilationHeight,f=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=w;let x="int xR; int xC; int xCOffset;";for(let E=0;E<b;E++)for(let k=0;k<w;k++)x+=`
vec4 xTexelR${E}C${k*2} = vec4(0.);
vec4 wR${E}C${k} = vec4(0.);
vec4 xR${E}C${k} = vec4(0.);`;for(let E=0;E<b;E++)for(let k=0;k<L;k++){const F=k*2;if(x+=`
xR = xRCorner + ${E*m};
xC = xCCorner + ${F*f};
`,d===1){if(F<w&&(c%2===1?x+=`
2020-10-11 18:41:17 +02:00
xCOffset = xC + 1;
2020-10-13 22:57:06 +02:00
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2020-10-13 22:57:06 +02:00
if(xCOffset + 1 >= ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F}.zw = vec2(0.);
2020-10-11 18:41:17 +02:00
}
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
xCOffset = xC + 1 - 2;
2020-10-13 22:57:06 +02:00
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
2020-10-11 18:41:17 +02:00
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
2020-10-13 22:57:06 +02:00
if(xCOffset + 1 >= ${o}) {
2020-10-11 18:41:17 +02:00
previous.zw = vec2(0.);
}
2020-10-29 05:16:50 +01:00
xR${E}C${F} = vec4(previous.zw, xTexelR${E}C${F}.xy);
2020-10-11 18:41:17 +02:00
} else {
2020-10-29 05:16:50 +01:00
xR${E}C${F} = vec4(0, 0, xTexelR${E}C${F}.xy);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`:x+=`
2020-10-13 22:57:06 +02:00
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xC, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
xR${E}C${F} = xTexelR${E}C${F};
`,F+1<w)){const U=c%2===0?T(f):f;f%2===0&&c%2===1||f%2!==0&&c%2!==1?(x+=`
xCOffset = xC + ${c%2} + ${U};
2020-10-11 18:41:17 +02:00
if(xR >= 0 && xR < ${i} &&
2020-10-13 22:57:06 +02:00
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`,f>1&&(x+=`
2020-10-11 18:41:17 +02:00
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
2020-10-13 22:57:06 +02:00
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`),x+=`
xR${E}C${F+1} = vec4(
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.xy);
`):x+=`
xCOffset = xC + ${U};
2020-10-11 18:41:17 +02:00
if(xR >= 0 && xR < ${i} &&
2020-10-13 22:57:06 +02:00
xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
xR${E}C${F+1} = xTexelR${E}C${F+2};
`}}else F<w&&(x+=`
2020-10-11 18:41:17 +02:00
if(xR >= 0 && xR < ${i}) {
2020-10-29 05:16:50 +01:00
`,c%2===1?(x+=`
2020-10-13 22:57:06 +02:00
xCOffset = xC + 1 - ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
if(xC + 1 >= 0 && xC + 1 < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = getX(batch, xR, xC + 1, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
xR${E}C${F} = vec4(
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.zw);
`,F+1<w&&(x+=`
2020-10-11 18:41:17 +02:00
vec4 final = vec4(0.);
2020-10-13 22:57:06 +02:00
xCOffset = xC + 1 + ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
2020-10-11 18:41:17 +02:00
final = getX(batch, xR, xCOffset, d1);
}
2020-10-29 05:16:50 +01:00
xR${E}C${F+1} = vec4(xTexelR${E}C${F+2}.xy, final.xy);
`)):(x+=`
2020-10-13 22:57:06 +02:00
if(xC >= 0 && xC < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = getX(batch, xR, xC, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
xCOffset = xC + ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-29 05:16:50 +01:00
xTexelR${E}C${F+2} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
xR${E}C${F} = vec4(
xTexelR${E}C${F}.xy, xTexelR${E}C${F+2}.xy);
`,F+1<w&&(x+=`
xR${E}C${F+1} = vec4(
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.zw);
`)),x+="}");F<w&&(x+=`
vec4 wTexelR${E}C${F} = getW(${E}, ${F}, d1, q);
wR${E}C${F} = vec4(wTexelR${E}C${F}.xz, wTexelR${E}C${F}.xz);
`,F+1<w&&(x+=`
vec4 wTexelR${E}C${F+1} = getW(${E}, ${F+1}, d1, q);
wR${E}C${F+1} =
vec4(wTexelR${E}C${F+1}.xz, wTexelR${E}C${F+1}.xz);`))}for(let E=0;E<b;E++)for(let k=0;k<w;k++)x+=`dotProd += xR${E}C${k} * wR${E}C${k};`;let v="",N="";n&&(s?v=`vec4 activation(vec4 a) {
2020-10-11 18:41:17 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
2020-10-29 05:16:50 +01:00
}`:v=`vec4 activation(vec4 x) {
2020-10-13 22:57:06 +02:00
${n}
2020-10-29 05:16:50 +01:00
}`,N="result = activation(result);");const O=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${v}
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${h}, ${d});
const ivec2 pads = ivec2(${a}, ${c});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
2020-10-29 05:16:50 +01:00
${x}
2020-10-11 18:41:17 +02:00
vec4 result = dotProd;
2020-10-29 05:16:50 +01:00
${O}
2020-10-13 22:57:06 +02:00
${N}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class h6{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,h]=e,[d]=t,[m,f]=n;this.outputShape=[d,m,f,h];const b=s==="bilinear"?1:0,[w,L]=[`${a-1}.0`,`${c-1}.0`],[x,v,N]=m>1?[`${(a-1)/(m-1)}`,"(y2-y1) * height_ratio",`y1*${w} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${w}`],[O,E,k]=f>1?[`${(c-1)/(f-1)}`,"(x2-x1) * width_ratio",`x1*${L} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${L}`];this.userCode=`
const float height_ratio = float(${x});
const float width_ratio = float(${O});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
2020-10-13 22:57:06 +02:00
if(bInd < 0 || bInd >= ${o}) {
2020-10-11 18:41:17 +02:00
return;
}
2020-10-29 05:16:50 +01:00
float height_scale = ${v};
float width_scale = ${E};
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
float in_y = ${N};
if( in_y < 0.0 || in_y > ${w} ) {
2020-10-11 18:41:17 +02:00
setOutput(float(${i}));
return;
}
2020-10-29 05:16:50 +01:00
float in_x = ${k};
2020-10-13 22:57:06 +02:00
if( in_x < 0.0 || in_x > ${L} ) {
2020-10-11 18:41:17 +02:00
setOutput(float(${i}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
2020-10-13 22:57:06 +02:00
if(${b} == 1) {
2020-10-11 18:41:17 +02:00
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
2020-10-29 05:16:50 +01:00
`}}class fC{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${gC(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-11 18:41:17 +02:00
uniform float index;
void main() {
2020-10-29 05:16:50 +01:00
${Rt(s)} coords = getOutputCoords();
int end = ${yC(s,"coords")};
2020-10-11 18:41:17 +02:00
float val = ${i};
int pow2 = int(pow(2.0, index));
2020-10-13 22:57:06 +02:00
if (${a}) {
int idx = ${c};
2020-10-29 05:16:50 +01:00
${yC(s,"coords")} = idx;
val += getX(${gC(s,"coords")});
2020-10-11 18:41:17 +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 gC(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 yC(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 u6{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=wu.DENSE;const t=Su(e),n=Pn();this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-29 05:16:50 +01:00
${ea(["r","c","d"],e)}
2020-10-11 18:41:17 +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);
}
2020-10-13 22:57:06 +02:00
${n.output} = result;
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class d6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=wu.DENSE;const t=Su(e),n=Pn();this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-29 05:16:50 +01:00
${ea(["r","c","d"],e)}
2020-10-11 18:41:17 +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));
}
2020-10-13 22:57:06 +02:00
${n.output} = result;
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class p6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
2020-10-11 18:41:17 +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 m6{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
2020-10-11 18:41:17 +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 f6{constructor(e){this.variableNames=["A"],this.outTexUsage=Ns.DOWNLOAD;const t=Pn();this.outputShape=e,this.userCode=`
${rC}
2020-10-11 18:41:17 +02:00
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
2020-10-29 05:16:50 +01:00
`}}class g6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ns.DOWNLOAD;const t=Pn();this.outputShape=e,this.userCode=`
${rC}
2020-10-11 18:41:17 +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 y6{constructor(e,t,n=!1){this.variableNames=["A"];const s=Pn(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
${XS(e)}
2020-10-11 18:41:17 +02:00
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
2020-10-13 22:57:06 +02:00
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);
2020-10-11 18:41:17 +02:00
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
2020-10-13 22:57:06 +02:00
${s.output} = vec4(${a}, 0., 0., 0.);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class b6{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Pn(),[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 d=0;d<=1;d++){const m=h*2+d;a+=`
2020-10-11 18:41:17 +02:00
localCoords = coords;
2020-10-13 22:57:06 +02:00
if(localCoords[2] + ${d} < ${e[2]}) {
localCoords[2] += ${d};
if(localCoords[1] + ${h} < ${e[1]}) {
localCoords[1] += ${h};
2020-10-11 18:41:17 +02:00
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
2020-10-13 22:57:06 +02:00
r = flatIndex / ${o};
c = imod(flatIndex, ${o});
uv = (vec2(c, r) + halfCR) / vec2(${o}.0, ${i}.0);
values = ${s.texture2D}(A, uv);
2020-10-11 18:41:17 +02:00
if(offset == 0) {
2020-10-13 22:57:06 +02:00
result[${m}] = values[0];
2020-10-11 18:41:17 +02:00
} else if(offset == 1) {
2020-10-13 22:57:06 +02:00
result[${m}] = values[1];
2020-10-11 18:41:17 +02:00
} else if(offset == 2) {
2020-10-13 22:57:06 +02:00
result[${m}] = values[2];
2020-10-11 18:41:17 +02:00
} else {
2020-10-13 22:57:06 +02:00
result[${m}] = values[3];
2020-10-11 18:41:17 +02:00
}
}
}
`}this.userCode=`
2020-10-29 05:16:50 +01:00
${XS(e)}
2020-10-11 18:41:17 +02:00
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
2020-10-13 22:57:06 +02:00
${a}
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
${s.output} = ${c};
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class w6{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +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 L6{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=S6(e,n);this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
${i} resRC = getOutputCoords();
2020-10-13 22:57:06 +02:00
setOutput(getA(${o}));
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}function S6(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 I6{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-13 22:57:06 +02:00
${s} strides = ${s}(${this.strides});
2020-10-11 18:41:17 +02:00
void main() {
${i} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
2020-10-13 22:57:06 +02:00
flattenIndex += index * ${o};
2020-10-11 18:41:17 +02:00
}
setOutput(getX(flattenIndex, coords[1]));
}
2020-10-29 05:16:50 +01:00
`}}function x6(e){const t=Pn(),n=`${t.version}
2020-10-11 18:41:17 +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 n5(e,n)}function T6(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 c5(e,t)}function A6(e){const t=new Uint16Array([0,1,2,2,1,3]);return l5(e,t)}function xu(e,t,n,s,i,o){u5(t,n);const a=h5(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 v6(e,t,n,s){const[i,o]=Lu(t,n);return xu(e,i,o,bC(s),s.textureFormatFloat,e.FLOAT)}function wC(e){return e.internalFormatHalfFloat}function N6(e,t,n,s){const[i,o]=Lu(t,n);return xu(e,i,o,wC(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function LC(e){return e.downloadTextureFormat}function C6(e,t,n,s){const[i,o]=Lu(t,n);return xu(e,i,o,LC(s),e.RGBA,e.UNSIGNED_BYTE)}function SC(e){return e.internalFormatPackedFloat}function R6(e,t,n,s){const[i,o]=wc(t,n);return xu(e,i,o,SC(s),e.RGBA,e.FLOAT)}function IC(e){return e.internalFormatPackedHalfFloat}function O6(e,t,n,s){const[i,o]=wc(t,n);return xu(e,i,o,IC(s),e.RGBA,s.textureTypeHalfFloat)}function E6(e,t,n){const s=0,i=3*4,o=3*4+2*4;Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=eC(e,t,"clipSpacePos",n,3,o,s);return a&&eC(e,t,"uv",n,2,o,i)}function D6(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 k6(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 F6(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 _6(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 W6(e,t,n,s){const[i,o]=Lu(t,n),a=4,c=new Uint8Array(KK(t*n,a));return Ee(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function $6(e,t,n,s,i,o,a,c){const h=e,d=new Float32Array(XK(o,a));return h.bindBuffer(h.PIXEL_PACK_BUFFER,t),h.getBufferSubData(h.PIXEL_PACK_BUFFER,0,d),h.bindBuffer(h.PIXEL_PACK_BUFFER,null),d}function U6(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 B6{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=oe().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,HK(t,e)):this.gl=Fi(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(oe().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=Wm(this.gl,i),Gs(this.gl,o))this.textureHalfFloatExtension=Wm(this.gl,o);else if(oe().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),Gs(this.gl,s))this.colorBufferHalfFloatExtension=Wm(this.gl,s);else if(oe().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",Gs(this.gl,n))this.colorBufferFloatExt
blockIndex = rc.y + ${F};
pos = rc.x + ${k};
2020-10-11 18:41:17 +02:00
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
2020-10-13 22:57:06 +02:00
offsetY = int(blockIndex / (${h})) * ${a} - ${w};
d0 = offsetY + ${m} * (pos / ${L});
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
if(d0 < ${t[N]} && d0 >= 0) {
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
offsetX = int(mod(float(blockIndex), ${h}.) * ${o}. - ${b}.);
d1 = offsetX + ${d} * (int(mod(float(pos), ${L}.) / ${i}.));
2020-10-11 18:41:17 +02:00
2020-10-29 05:16:50 +01:00
if(d1 < ${t[O]} && d1 >= 0) {
2020-10-11 18:41:17 +02:00
ch = int(mod(float(pos), ${i}.));
2020-10-29 05:16:50 +01:00
if (${v}) {
2020-10-11 18:41:17 +02:00
innerDims = vec2(d1, ch);
2020-10-29 05:16:50 +01:00
result[${k*2+F}] = getChannel(
2020-10-11 18:41:17 +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-11 18:41:17 +02:00
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
2020-10-29 05:16:50 +01:00
${E}
2020-10-11 18:41:17 +02:00
2020-10-29 05:16:50 +01:00
${x.output} = result;
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class Y6{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-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
2020-10-13 22:57:06 +02:00
for (int j = -${o}; j <= ${o}; j++) {
2020-10-11 18:41:17 +02:00
int idx = d + j;
2020-10-13 22:57:06 +02:00
if (idx >= 0 && idx <= ${a}) {
2020-10-11 18:41:17 +02:00
float z = getX(b, r, c, idx);
sum += z * z;
}
}
2020-10-13 22:57:06 +02:00
float val = x * ${c};
2020-10-11 18:41:17 +02:00
setOutput(val);
}
2020-10-29 05:16:50 +01:00
`}}class H6{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-11 18:41:17 +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;
}
}
2020-10-13 22:57:06 +02:00
norm = float(${s}) * norm + float(${n});
2020-10-11 18:41:17 +02:00
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
2020-10-13 22:57:06 +02:00
float dyi = -2.0 * float(${s})
2020-10-11 18:41:17 +02:00
* 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 q6{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-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
2020-10-13 22:57:06 +02:00
int firstChannel = d - ${o};
2020-10-11 18:41:17 +02:00
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
2020-10-13 22:57:06 +02:00
for (int j = - ${o}; j <= ${o}; j++) {
2020-10-11 18:41:17 +02:00
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
2020-10-13 22:57:06 +02:00
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));
2020-10-11 18:41:17 +02:00
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
2020-10-13 22:57:06 +02:00
vec4 result = xAtOutputCoords * ${c};
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class j6{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-13 22:57:06 +02:00
const ivec2 pads = ivec2(${a}, ${c});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${i};
2020-10-13 22:57:06 +02:00
wR += ${s}) {
2020-10-11 18:41:17 +02:00
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
2020-10-11 18:41:17 +02:00
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-13 22:57:06 +02:00
int maxPosValue = ${h} - int(getMaxPos(b, idyR, idyC, d));
2020-10-11 18:41:17 +02:00
// Get the current value, check it against the value from the
// position matrix.
2020-10-13 22:57:06 +02:00
int curPosValue = wR * ${o} + wC;
2020-10-11 18:41:17 +02:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class K6{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,d=e.effectiveFilterWidth,m=c-1-e.padInfo.front,f=h-1-e.padInfo.top,b=d-1-e.padInfo.left,w=c*h*d-1;this.userCode=`
const ivec3 pads = ivec3(${m}, ${f}, ${b});
2020-10-11 18:41:17 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-10-13 22:57:06 +02:00
for (int wD = 0; wD < ${c};
2020-10-11 18:41:17 +02:00
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-13 22:57:06 +02:00
for (int wR = 0; wR < ${h};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
2020-10-11 18:41:17 +02:00
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${d};
wC += ${a}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
2020-10-11 18:41:17 +02:00
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);
2020-10-13 22:57:06 +02:00
int maxPosValue = ${w} -
2020-10-11 18:41:17 +02:00
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
2020-10-13 22:57:06 +02:00
wD * ${h} * ${d} +
wR * ${d} + wC;
2020-10-11 18:41:17 +02:00
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
2020-10-29 05:16:50 +01:00
`}}class JS{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],d=Math.ceil(h/2),m=s?"i * 2, rc.y":"rc.y, i * 2",f=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="",x="";a&&(c?L=`vec4 activation(vec4 a) {
2020-10-11 18:41:17 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-10-29 05:16:50 +01:00
${a}
}`:L=`vec4 activation(vec4 x) {
${a}
}`,x="result = activation(result);");const v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights");let N="rc.x",O="rc.x";e[0]<t[0]?N=`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-11 18:41:17 +02:00
2020-10-29 05:16:50 +01:00
const float sharedDimension = ${d}.0;
2020-10-11 18:41:17 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
2020-10-29 05:16:50 +01:00
for (int i = 0; i < ${d}; i++) {
int batchA = ${N};
int batchB = ${O};
vec4 a = getMatrixA(batchA, ${m});
vec4 b = getMatrixB(batchB, ${f});
2020-10-11 18:41:17 +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-11 18:41:17 +02:00
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2020-10-29 05:16:50 +01:00
${v}
2020-10-11 18:41:17 +02:00
2020-10-29 05:16:50 +01:00
${x}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class X6{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode=`
2020-10-11 18:41:17 +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 J6{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
2020-10-13 22:57:06 +02:00
setOutput(mix(float(${s}), float(${n}),
2020-10-11 18:41:17 +02:00
float(index == coords.y)));
}
2020-10-29 05:16:50 +01:00
`}}class Z6{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-11 18:41:17 +02:00
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
2020-10-29 05:16:50 +01:00
`;else{const n=Mn("rc",t),s=Rt(t),i=eX(t,e,n),o=tX(t,e[e.length-1],e[e.length-2],n),a=nX(e,n);this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} rc = getOutputCoords();
2020-10-11 18:41:17 +02:00
if(${i}) {
setOutput(vec4(0));
} else {
2020-10-13 22:57:06 +02:00
${o}
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
setOutput(vec4(${a}));
2020-10-11 18:41:17 +02:00
}
}
2020-10-29 05:16:50 +01:00
`}}}function Q6(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 eX(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 tX(e,t,n,s){if(e===1)return"";const i=s.slice(-2);return`
2020-10-11 18:41:17 +02:00
int r = ${i[0]};
int c = ${i[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
2020-10-13 22:57:06 +02:00
bool rEdge = rp1 >= ${n};
2020-10-29 05:16:50 +01:00
`}function nX(e,t){const n=e.length,s=Q6(n,t);return n===1?`getA(rc),
2020-10-11 18:41:17 +02:00
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
2020-10-13 22:57:06 +02:00
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 sX{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((h,d)=>h[0]+e[d]+h[1]);const s=e.length,i=Rt(s),o=t.map(h=>h[0]).join(","),a=t.map((h,d)=>h[0]+e[d]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=`
2020-10-13 22:57:06 +02:00
int start = ${o};
int end = ${a};
2020-10-11 18:41:17 +02:00
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
2020-10-13 22:57:06 +02:00
setOutput(float(${n}));
2020-10-11 18:41:17 +02:00
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
2020-10-13 22:57:06 +02:00
${i} start = ${i}(${o});
${i} end = ${i}(${a});
2020-10-11 18:41:17 +02:00
void main() {
${i} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
2020-10-13 22:57:06 +02:00
setOutput(float(${n}));
2020-10-11 18:41:17 +02:00
} else {
${i} coords = outC - start;
2020-10-13 22:57:06 +02:00
setOutput(getX(${c}));
2020-10-11 18:41:17 +02:00
}
}
2020-10-29 05:16:50 +01:00
`}}class iX{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((L,x)=>L[0]+e[x]+L[1]);const s=e.length,i=Rt(s),o=t.map(L=>L[0]).join(","),a=t.map((L,x)=>L[0]+e[x]).join(","),c=Mn("rc",s),h=Mn("source",s),d=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,f=[`${i} rc = outputLoc;`,`${c[s-1]} += 1;
2020-10-13 22:57:06 +02:00
if(${d}) {
`,s===1?"":`}
2020-10-11 18:41:17 +02:00
rc = outputLoc;
2020-10-13 22:57:06 +02:00
${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(${d}) {`],b=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let w="";for(let L=0,x=s===1?2:4;L<x;L++)w+=`
${f[L]}
2020-10-13 22:57:06 +02:00
if (${b}) {
result[${L}] = float(${n});
2020-10-11 18:41:17 +02:00
} else {
${i} source = rc - start;
2020-10-13 22:57:06 +02:00
result[${L}] = getChannel(getX(${h.join()}), ${m});
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;w+=s===1?"} ":"}}",this.userCode=`
const ${i} start = ${i}(${o});
const ${i} end = ${i}(${a});
2020-10-11 18:41:17 +02:00
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
2020-10-13 22:57:06 +02:00
${w}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}class Tu{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,d=e.dilationWidth,m=e.effectiveFilterHeight,f=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const L=t==="avg",x=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,v=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let N="0.0";if(L||(N="-1.0 / 1e-20"),n){const $=">=";this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${m};
wR += ${h}) {
2020-10-11 18:41:17 +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 < ${f};
2020-10-13 22:57:06 +02:00
wC += ${d}) {
2020-10-11 18:41:17 +02:00
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
2020-10-13 22:57:06 +02:00
if (value ${$} currMinMaxValue) {
2020-10-11 18:41:17 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
2020-10-29 05:16:50 +01:00
minMaxPosition = ${s?i?x:v:`wR * ${f} + wC`};
2020-10-11 18:41:17 +02:00
}
}
}
setOutput(float(minMaxPosition));
}
2020-10-29 05:16:50 +01:00
`;return}const O="max";let E=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(E="avgValue / count");const k=Math.floor(o/4)*4,F=o%4,U=`
2020-10-13 22:57:06 +02:00
if (${L}) {
2020-10-11 18:41:17 +02:00
avgValue += dot(values, ones);
} else {
2020-10-29 05:16:50 +01:00
minMaxValue = ${O}(values, minMaxValue);
2020-10-11 18:41:17 +02:00
}
`;this.userCode=`
2020-10-13 22:57:06 +02:00
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
const float initializationValue = ${N};
2020-10-11 18:41:17 +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-13 22:57:06 +02:00
vec4 minMaxValue = vec4(${N});
2020-10-11 18:41:17 +02:00
float avgValue = 0.0;
count = 0.0;
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${m};
wR += ${h}) {
2020-10-11 18:41:17 +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-13 22:57:06 +02:00
int xC = xCCorner + wC * ${d};
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2020-10-13 22:57:06 +02:00
getValue(batch, xR, xC + ${d}, d),
getValue(batch, xR, xC + 2 * ${d}, d),
getValue(batch, xR, xC + 3 * ${d}, d)
2020-10-11 18:41:17 +02:00
);
2020-10-29 05:16:50 +01:00
${U}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
int xC = xCCorner + ${k};
if (${F===1}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${U}
} else if (${F===2}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2020-10-13 22:57:06 +02:00
getValue(batch, xR, xC + ${d}, d),
2020-10-11 18:41:17 +02:00
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${U}
} else if (${F===3}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
2020-10-13 22:57:06 +02:00
getValue(batch, xR, xC + ${d}, d),
getValue(batch, xR, xC + 2 * ${d}, d),
2020-10-11 18:41:17 +02:00
initializationValue
);
2020-10-29 05:16:50 +01:00
${U}
2020-10-11 18:41:17 +02:00
}
}
2020-10-29 05:16:50 +01:00
setOutput(${E});
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class ZS{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,d=e.dilationDepth,m=e.dilationHeight,f=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,L=e.effectiveFilterWidth,x=e.padInfo.front,v=e.padInfo.top,N=e.padInfo.left;this.outputShape=e.outShape;const O=t==="avg";let E="0.0";if(O||(E="-1.0 / 1e-20"),n){const j=">=";this.userCode=`
2020-10-11 18:41:17 +02:00
const ivec3 strides =
2020-10-13 22:57:06 +02:00
ivec3(${a}, ${c}, ${h});
2020-10-29 05:16:50 +01:00
const ivec3 pads = ivec3(${x}, ${v}, ${N});
2020-10-11 18:41:17 +02:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
2020-10-13 22:57:06 +02:00
for (int wD = 0; wD < ${b};
wD += ${d}) {
2020-10-11 18:41:17 +02:00
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${w};
wR += ${m}) {
2020-10-11 18:41:17 +02:00
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
2020-10-13 22:57:06 +02:00
for (int wC = 0; wC < ${L};
2020-10-29 05:16:50 +01:00
wC += ${f}) {
2020-10-11 18:41:17 +02:00
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-11 18:41:17 +02:00
minMaxValue = value;
minMaxValueFound = 1.0;
2020-10-13 22:57:06 +02: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-11 18:41:17 +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 U=Math.floor(o/4)*4,$=o%4,Y=`
if (${O}) {
2020-10-11 18:41:17 +02:00
avgValue += dot(values, ones);
} else {
2020-10-29 05:16:50 +01:00
minMaxValue = ${k}(values, minMaxValue);
2020-10-11 18:41:17 +02:00
}
`;this.userCode=`
const ivec3 strides =
2020-10-13 22:57:06 +02:00
ivec3(${a}, ${c}, ${h});
2020-10-29 05:16:50 +01:00
const ivec3 pads = ivec3(${x}, ${v}, ${N});
const float initializationValue = ${E};
2020-10-11 18:41:17 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
2020-10-29 05:16:50 +01:00
vec4 minMaxValue = vec4(${E});
2020-10-11 18:41:17 +02:00
float avgValue = 0.0;
count = 0.0;
2020-10-13 22:57:06 +02:00
for (int wD = 0; wD < ${b};
wD += ${d}) {
2020-10-11 18:41:17 +02:00
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
2020-10-13 22:57:06 +02:00
for (int wR = 0; wR < ${w};
wR += ${m}) {
2020-10-11 18:41:17 +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 < ${U}; wC += 4) {
int xC = xCCorner + wC * ${f};
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-29 05:16:50 +01:00
getValue(batch, xD, xR, xC + ${f}, ch),
getValue(batch, xD, xR, xC + 2 * ${f}, ch),
getValue(batch, xD, xR, xC + 3 * ${f}, ch)
2020-10-11 18:41:17 +02:00
);
2020-10-29 05:16:50 +01:00
${Y}
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
int xC = xCCorner + ${U};
2020-10-13 22:57:06 +02:00
if (${$===1}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${Y}
2020-10-13 22:57:06 +02:00
} else if (${$===2}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-29 05:16:50 +01:00
getValue(batch, xD, xR, xC + ${f}, ch),
2020-10-11 18:41:17 +02:00
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${Y}
2020-10-13 22:57:06 +02:00
} else if (${$===3}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-29 05:16:50 +01:00
getValue(batch, xD, xR, xC + ${f}, ch),
getValue(batch, xD, xR, xC + 2 * ${f}, ch),
2020-10-11 18:41:17 +02:00
initializationValue
);
2020-10-29 05:16:50 +01:00
${Y}
2020-10-11 18:41:17 +02:00
}
}
2020-10-29 05:16:50 +01:00
setOutput(${F});
2020-10-11 18:41:17 +02:00
}
}
2020-10-29 05:16:50 +01:00
`}}class TC{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 d=Math.floor(n/4)*4,m=n%4;let f=`
2020-10-11 18:41:17 +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 {
2020-10-13 22:57:06 +02:00
minMaxValue = ${c}(values, minMaxValue);
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`,b="vec4";t==="all"?(a="1.0",f=`
2020-10-11 18:41:17 +02:00
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
2020-10-29 05:16:50 +01:00
`,b="bvec4"):t==="any"&&(a="0.0",f=`
2020-10-11 18:41:17 +02:00
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
2020-10-13 22:57:06 +02:00
`,b="bvec4");let w="";i%n>0&&(w=`
2020-10-11 18:41:17 +02:00
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`),this.userCode=`
2020-10-13 22:57:06 +02:00
const float initializationValue = ${a};
2020-10-11 18:41:17 +02:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
2020-10-13 22:57:06 +02:00
${w}
2020-10-11 18:41:17 +02:00
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
2020-10-13 22:57:06 +02:00
int inOffset = outIdx * ${n};
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
vec4 minMaxValue = vec4(${a});
2020-10-11 18:41:17 +02:00
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
2020-10-13 22:57:06 +02:00
for (int i = 0; i < ${d}; i += 4) {
2020-10-11 18:41:17 +02:00
int inIdx = inOffset + i;
2020-10-13 22:57:06 +02:00
${b} values = ${b}(
2020-10-11 18:41:17 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
int inIdx = inOffset + ${d};
if (${m===1}) {
${b} values = ${b}(
2020-10-11 18:41:17 +02:00
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-13 22:57:06 +02:00
} else if (${m===2}) {
${b} values = ${b}(
2020-10-11 18:41:17 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-13 22:57:06 +02:00
} else if (${m===3}) {
${b} values = ${b}(
2020-10-11 18:41:17 +02:00
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
setOutput(${h});
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class AC{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-11 18:41:17 +02:00
${i}
2020-10-13 22:57:06 +02:00
${s>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
2020-10-11 18:41:17 +02:00
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
2020-10-13 22:57:06 +02:00
result[${s}] =
2020-10-11 18:41:17 +02:00
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
2020-10-13 22:57:06 +02:00
${s>0?"}":""}
2020-10-11 18:41:17 +02:00
`}this.userCode=`
2020-10-29 05:16:50 +01:00
${rX(t)}
${XS(e)}
2020-10-11 18:41:17 +02:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
2020-10-13 22:57:06 +02:00
${n}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}function rX(e){const t=ea(["r","c","d"],e);return`
2020-10-11 18:41:17 +02:00
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
2020-10-29 05:16:50 +01:00
`}class oX{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],d=c[0]/h[0],m=c[1]/h[1],f=1/d,b=1/m,w=Math.ceil(f)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
2020-10-13 22:57:06 +02:00
const float heightScale = float(${d});
const float widthScale = float(${m});
2020-10-11 18:41:17 +02:00
2020-10-29 05:16:50 +01:00
const float invHeightScale = float(${f});
2020-10-13 22:57:06 +02:00
const float invWidthScale = float(${b});
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
const int winHeight = int(${w});
const int winWidth = int(${L});
2020-10-11 18:41:17 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
2020-10-13 22:57:06 +02:00
if (dyR < 0 || dyR >= ${o}) {
2020-10-11 18:41:17 +02:00
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
2020-10-13 22:57:06 +02:00
if (dyC < 0 || dyC >= ${a}) {
2020-10-11 18:41:17 +02:00
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
2020-10-13 22:57:06 +02:00
int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));
2020-10-11 18:41:17 +02:00
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 aX{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],d=[s&&t>1?t-1:t,s&&n>1?n-1:n];this.userCode=`
2020-10-11 18:41:17 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2020-10-13 22:57:06 +02:00
${h[0]/d[0]},
${h[1]/d[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${a}.0);
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
2020-10-29 05:16:50 +01:00
`}}class cX{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],d=[s&&t>1?t-1:t,s&&n>1?n-1:n];this.userCode=`
2020-10-11 18:41:17 +02:00
const vec3 effectiveInputOverOutputRatioRC = vec3(
2020-10-13 22:57:06 +02:00
${h[0]/d[0]},
${h[1]/d[1]},
${h[1]/d[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${a}.0,
${a}.0);
2020-10-11 18:41:17 +02:00
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
2020-10-13 22:57:06 +02:00
bool hasNextCol = d < ${c-1};
bool hasNextRow = coords.z < ${n-1};
2020-10-11 18:41:17 +02:00
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
2020-10-29 05:16:50 +01:00
`}}class lX{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],d=c[0]/h[0],m=c[1]/h[1],f=1/d,b=1/m,w=Math.ceil(f)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
2020-10-13 22:57:06 +02:00
const float heightScale = float(${d});
const float widthScale = float(${m});
2020-10-11 18:41:17 +02:00
2020-10-29 05:16:50 +01:00
const float invHeightScale = float(${f});
2020-10-13 22:57:06 +02:00
const float invWidthScale = float(${b});
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
const int winHeight = int(${w});
const int winWidth = int(${L});
2020-10-11 18:41:17 +02:00
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
2020-10-13 22:57:06 +02:00
if (dyR < 0 || dyR >= ${o}) {
2020-10-11 18:41:17 +02:00
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
2020-10-13 22:57:06 +02:00
if (dyC < 0 || dyC >= ${a}) {
2020-10-11 18:41:17 +02:00
continue;
}
float sourceFracRow =
2020-10-13 22:57:06 +02:00
float(${c[0]}) *
(float(dyR) / float(${h[0]}));
2020-10-11 18:41:17 +02:00
float sourceFracCol =
2020-10-13 22:57:06 +02:00
float(${c[1]}) *
(float(dyC) / float(${h[1]}));
2020-10-11 18:41:17 +02:00
int sourceNearestRow = int(min(
2020-10-13 22:57:06 +02:00
float(int(${s}) - 1),
${n} ? float(round(sourceFracRow)) :
2020-10-11 18:41:17 +02:00
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${i}) - 1),
2020-10-13 22:57:06 +02:00
${n} ? float(round(sourceFracCol)) :
2020-10-11 18:41:17 +02:00
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 hX{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],d=[s&&t>1?t-1:t,s&&n>1?n-1:n],m=s?"0.5":"0.0";this.userCode=`
2020-10-11 18:41:17 +02:00
const vec2 effectiveInputOverOutputRatioRC = vec2(
2020-10-13 22:57:06 +02:00
${h[0]/d[0]},
${h[1]/d[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${a}.0);
2020-10-11 18:41:17 +02:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
2020-10-13 22:57:06 +02:00
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
2020-10-11 18:41:17 +02:00
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
2020-10-29 05:16:50 +01:00
`}}class uX{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-11 18:41:17 +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-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${o} coords = getOutputCoords();
2020-10-11 18:41:17 +02:00
setOutput(getX(${i}));
}
2020-10-29 05:16:50 +01:00
`}}class dX{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=Mn("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-11 18:41:17 +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() {
2020-10-13 22:57:06 +02:00
${a} rc = getOutputCoords();
2020-10-11 18:41:17 +02:00
vec4 result = vec4(0.);
2020-10-13 22:57:06 +02:00
result.r = ${c(s.slice())};
2020-10-11 18:41:17 +02:00
if(${i}){
2020-10-13 22:57:06 +02:00
result.g = ${h(s.slice())};
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
if(${o}) {
result.b = ${d(s.slice())};
2020-10-11 18:41:17 +02:00
if(${i}) {
2020-10-13 22:57:06 +02:00
result.a = ${m(s.slice())};
2020-10-11 18:41:17 +02:00
}
}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`;function c(w){return f(w)}function h(w){return w[n-1]="("+w[n-1]+" + 1)",f(w)}function d(w){return w[n-2]="("+w[n-2]+" + 1)",f(w)}function m(w){return w[n-1]="("+w[n-1]+" + 1)",w[n-2]="("+w[n-2]+" + 1)",f(w)}function f(w){const L=e.map((N,O)=>b(O,w)),x=L.join(","),v=L.slice(-2).join(",");return`getChannel(getX(${x}), vec2(${v}))`}function b(w,L){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${L[w]} - 1`:`${L[w]}`}}}class vC{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 d="";n===1?d="i":n===2&&(d="i, j");const m=`getIndices(${d})`;let f="";s===1?f="i":s===2&&(f="i, coords[1]");const b=`getUpdates(${f})`,w=t>1?"strides[j]":"strides";this.userCode=`
2020-10-13 22:57:06 +02:00
${c} strides = ${c}(${i});
2020-10-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${h} coords = getOutputCoords();
2020-10-11 18:41:17 +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++) {
2020-10-13 22:57:06 +02:00
int index = round(${m});
flattenedIndex += index * ${w};
2020-10-11 18:41:17 +02:00
}
if (flattenedIndex == coords[0]) {
2020-10-13 22:57:06 +02:00
sum += ${b};
2020-10-11 18:41:17 +02:00
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
2020-10-29 05:16:50 +01:00
`}}class pX{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",d=Math.floor(n/4)*4,m=n%4,f=`
2020-10-11 18:41:17 +02:00
sumValue += dot(values, segFilter);
2020-10-13 22:57:06 +02:00
`;let b="";i%n>0&&(b=`
2020-10-11 18:41:17 +02:00
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
2020-10-13 22:57:06 +02:00
`);let w="";i%n>0&&(w=`
2020-10-11 18:41:17 +02:00
if (inIdx < 0 || inIdx >= ${i}) {
return -1.0;
}
`),this.userCode=`
2020-10-13 22:57:06 +02:00
const float initializationValue = ${c};
2020-10-11 18:41:17 +02:00
float getValue(int batch, int inIdx) {
2020-10-13 22:57:06 +02:00
${b}
2020-10-11 18:41:17 +02:00
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
2020-10-13 22:57:06 +02:00
${w}
2020-10-11 18:41:17 +02:00
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
2020-10-13 22:57:06 +02:00
${o})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${o})));
2020-10-11 18:41:17 +02:00
float sumValue = 0.0;
2020-10-13 22:57:06 +02:00
for (int i = 0; i < ${d}; i += 4) {
2020-10-11 18:41:17 +02:00
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
int inIdx = inOffset + ${d};
if (${m===1}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-13 22:57:06 +02:00
} else if (${m===2}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-13 22:57:06 +02:00
} else if (${m===3}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
2020-10-29 05:16:50 +01:00
${f}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
setOutput(${h});
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class mX{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 d=0;d<t.length;d++)h.push(`${a[d]}`),d<e&&c.push(`${a[d]}`);s=c.join(),i=h.join()}const o=Rt(n);this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${o} resRC = getOutputCoords();
float cVal = getC(${s});
2020-10-11 18:41:17 +02:00
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
2020-10-29 05:16:50 +01:00
`}}class fX{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=`uniform int start[${this.rank}];`,s=gX(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${QS[c]} = start[${c}] + coords.${QS[c]};`);i=`
2020-10-11 18:41:17 +02:00
${t} sourceLoc;
${t} coords = getOutputCoords();
2020-10-13 22:57:06 +02:00
${o.join(`
2020-10-11 18:41:17 +02:00
`)}
`,this.userCode=`
2020-10-13 22:57:06 +02:00
${n}
2020-10-11 18:41:17 +02:00
void main() {
${i}
2020-10-13 22:57:06 +02:00
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 QS=["x","y","z","w","u","v"];function gX(e){if(e===1)return"sourceLoc";if(e<=6)return QS.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class yX{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=Mn("coords",this.rank),s=Mn("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,o=`getChannel(getSource(${s.join()}), ${i})`,a=`
2020-10-13 22:57:06 +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};
}
}
`,h=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((d,m)=>`start[${m}]`).join()});`:e.map((d,m)=>`${s[m]} = ${n[m]} + start[${m}];`).join(`
2020-10-11 18:41:17 +02:00
`);this.userCode=`
uniform int start[${this.rank}];
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
2020-10-13 22:57:06 +02:00
${h}
2020-10-11 18:41:17 +02:00
vec4 result = vec4(0.);
${a}
2020-10-13 22:57:06 +02:00
${c}
2020-10-11 18:41:17 +02:00
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 bX{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,d)=>(c++,n.length===1?`coords * strides[${d}] + begin[${d}]`:`coords[${c-1}] * strides[${d}] + begin[${d}]`)).join(",")}this.userCode=`
2020-10-11 18:41:17 +02:00
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
void main() {
2020-10-13 22:57:06 +02:00
${o} coords = getOutputCoords();
setOutput(getX(${a}));
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}class wX{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=CC(t,n),i=RC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=NC(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===Cn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Cn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Cn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Cn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Cn.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=CC(n,s),o=RC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=NC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=oe().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],d=h.indexOf(e);if(d<0)throw new Error("Cannot release a texture that was never provided by this texture manager");h.splice(d,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 LX(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 NC(e,t,n,s,i){const o=SX(t,s);let a;if(i){const[h,d]=wc(e[0],e[1]);a=h*d}else{const[h,d]=Lu(e[0],e[1]);a=h*d}const c=LX(n,o);return a*c}function SX(e,t){switch(e){case Cn.PACKED_2X2_FLOAT32:return SC(t);case Cn.PACKED_2X2_FLOAT16:return IC(t);case Cn.UNPACKED_FLOAT32:return bC(t);case Cn.UNPACKED_FLOAT16:return wC(t);case Cn.PACKED_4X1_UNSIGNED_BYTE:return LC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function IX(e){return oe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Cn.PACKED_2X2_FLOAT32:Cn.UNPACKED_FLOAT32:e?Cn.PACKED_2X2_FLOAT16:Cn.UNPACKED_FLOAT16}function CC(e,t){if(e===Ns.UPLOAD)return Cn.PACKED_2X2_FLOAT32;if(e===Ns.RENDER||e==null)return IX(t);if(e===Ns.DOWNLOAD||e===Ns.PIXELS)return Cn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function RC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class xX{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=TX(e);this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} resRC = getOutputCoords();
2020-10-11 18:41:17 +02:00
setOutput(getA(${i}));
}
2020-10-29 05:16:50 +01:00
`}}function TX(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 st{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +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 dr="if (isnan(x)) return x;",AX="return x;",OC="return abs(x);",EC=dr+`
2020-10-11 18:41:17 +02:00
return (x < 0.0) ? 0.0 : x;
2020-10-29 05:16:50 +01:00
`,DC=dr+`
2020-10-11 18:41:17 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2020-10-29 05:16:50 +01:00
`,kC="return (x >= 0.0) ? x : (exp(x) - 1.0);",vX=`
2020-10-11 18:41:17 +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 = ${Hp};
float scale = ${qp};
2020-10-11 18:41:17 +02:00
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2020-10-29 05:16:50 +01:00
`;function NX(e=0){return dr+`
2020-10-11 18:41:17 +02:00
return x > 0.0 ? 1.0 : float(${e});
2020-10-29 05:16:50 +01:00
`}const FC="return -x;",_C="return ceil(x);",WC="return floor(x);",CX=`
2020-10-11 18:41:17 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2020-10-29 05:16:50 +01:00
`,RX="return float(isnan(x));",OX="return float(isinf(x));",EX="return float(!isnan(x) && !isinf(x));",DX=`
2020-10-11 18:41:17 +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
`,$C="return exp(x);",UC="return exp(x) - 1.0;",kX=`if (x < 0.0) return NAN;
return log(x);`,FX="return log(1.0 + x);",_X="return sqrt(x);",WX="return inversesqrt(x);",$X="return 1.0 / (1.0 + exp(-1.0 * x));",UX=`
2020-10-11 18:41:17 +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
`,BX=dr+`
2020-10-11 18:41:17 +02:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
2020-10-29 05:16:50 +01:00
`,MX=dr+`
2020-10-11 18:41:17 +02:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
2020-10-29 05:16:50 +01:00
`,PX=dr+`
2020-10-11 18:41:17 +02:00
return atan(x);
2020-10-29 05:16:50 +01:00
`,zX=`
2020-10-11 18:41:17 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2020-10-29 05:16:50 +01:00
`,VX=`
2020-10-11 18:41:17 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2020-10-29 05:16:50 +01:00
`,GX=`
2020-10-11 18:41:17 +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
`,YX=dr+"return log(x + sqrt(x * x + 1.0));",HX=dr+`
2020-10-11 18:41:17 +02:00
if (x < 1.0) return NAN;
2020-10-29 05:16:50 +01:00
return log(x + sqrt(x * x - 1.0));`,qX=dr+`
2020-10-11 18:41:17 +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;`,jX=`
2020-10-11 18:41:17 +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 = ${Cw};
float a1 = ${Rw};
float a2 = ${Ow};
float a3 = ${Ew};
float a4 = ${Dw};
float a5 = ${kw};
2020-10-11 18:41:17 +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
`,KX="return 1.0 / x;",XX="return float(!(x >= 1.0));",Gm="return x;";const JX="return x;",ZX=`
2020-10-11 18:41:17 +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
`,BC=`
2020-10-11 18:41:17 +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
`,MC=`
2020-10-11 18:41:17 +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
`,PC=`
2020-10-11 18:41:17 +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 Au{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +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 QX{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=Mn("rc",t),s=Rt(t),i=z5(t,n),o=n.slice(-2),a=t<=1?"rc":`vec2(${o.join(",")})`;this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} rc = getOutputCoords();
2020-10-11 18:41:17 +02:00
vec4 packedInput = getA(${i});
2020-10-13 22:57:06 +02:00
setOutput(getChannel(packedInput, ${a}));
2020-10-11 18:41:17 +02:00
}
2020-10-29 05:16:50 +01:00
`}}const{segment_util:zC}=Ww,e7=$w,t7=Uw,n7=Bw,s7=_p,i7=1e-7,r7=1e-4,Ym={};function o7(e){return e in Ym||(Ym[e]={}),Ym[e]}function Hm(e,t=!1){if(e==="linear")return t?JX:AX;if(e==="relu")return t?BC:EC;if(e==="elu")return t?PC:kC;if(e==="relu6")return t?MC:DC;if(e==="prelu")return t?uC:hC;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const a7=128,c7=600;function l7(){return oe().global.screen==null?1024:oe().global.screen.height*oe().global.screen.width*window.devicePixelRatio*c7/1024/1024}const VC=1e3;class h7 extends y{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,!oe().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Fi(oe().getNumber("WEBGL_VERSION"));this.binaryCache=o7(oe().getNumber("WEBGL_VERSION")),this.gpgpu=new B6(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 wX(this.gpgpu),this.numMBBeforeWarning=l7(),this.texData=new p(this,Ji())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((oe().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||oe().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:Ns.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(oe().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:Ns.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 f;c?f=new Au(a,Gm):f=new st(a,Gm);const b=this.runWebGLProgram(f,[{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 d;h&&(d=Kn());let m;if(s==="complex64"){const f=this.readSync(i.real.dataId),b=this.readSync(i.imag.dataId);m=sr(f,b)}else m=this.getValuesFromTexture(e);return h&&(this.downloadWaitMs+=Kn()-d),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 Au(s,Gm):w=new st(s,Gm);const L=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),x=this.read(L.dataId);return this.disposeIntermediateTensorInfo(L),x}if(n!=null)return this.convertAndCacheOnCPU(e);if(!oe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&oe().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,d;if(o!=="complex64"&&oe().get("WEBGL_BUFFER_SUPPORTED")){d=this.decode(e);const w=this.texData.get(d.dataId);h=this.gpgpu.createBufferFromTexture(w.texture,...Su(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],x=w[1];m=sr(L,x)}else if(h==null)m=this.getValuesFromTexture(e);else{const w=P(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(h,w)}d!=null&&this.d
2020-10-11 18:41:17 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-29 05:16:50 +01:00
`,y7=`
2020-10-11 18:41:17 +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 qm(e){return({inputs:t,backend:n})=>{const{x:s}=t,i=n,o=new st(s.shape,e);return i.runWebGLProgram(o,[s],s.dtype)}}function Nc({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:i,dtype:o}){return({inputs:a,backend:c})=>{const{a:h,b:d}=a,m=c;if(s&&h.dtype==="complex64"){const L=m.texData.get(h.dataId),x=m.texData.get(d.dataId),[v,N]=[[L.complexTensorInfos.real,x.complexTensorInfos.real],[L.complexTensorInfos.imag,x.complexTensorInfos.imag]].map(E=>{const[k,F]=E,U={dataId:k.dataId,dtype:k.dtype,shape:h.shape},$={dataId:F.dataId,dtype:F.dtype,shape:d.shape},Y=new Wn(e,h.shape,d.shape);return m.runWebGLProgram(Y,[U,$],$n(k.dtype,F.dtype))}),O=vc({inputs:{real:v,imag:N},backend:m});return m.disposeIntermediateTensorInfo(v),m.disposeIntermediateTensorInfo(N),O}const f=o||$n(h.dtype,d.dtype);if(m.shouldExecuteOnCPU([h,d])&&i!=null){const L=m.texData.get(h.dataId),x=m.texData.get(d.dataId),[v,N]=i(h.shape,d.shape,L.values,x.values,f),O=m.makeTensorInfo(N,f),E=m.texData.get(O.dataId);return E.values=v,O}const b=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null;let w;return b?w=new ur(t,h.shape,d.shape,n):w=new Wn(e,h.shape,d.shape),m.runWebGLProgram(w,[h,d],f)}}const YC="return a + b;",b7=Nc({opSnippet:YC,packedOpSnippet:YC,supportsComplex:!0,cpuKernelImpl:N5}),w7={kernelName:Co,backendName:"webgl",kernelFunc:b7};const L7=g7+`
2020-10-11 18:41:17 +02:00
return atan(a, b);
2020-10-29 05:16:50 +01:00
`,S7=`
2020-10-11 18:41:17 +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
`+y7+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-29 05:16:50 +01:00
`,I7=Nc({opSnippet:L7,packedOpSnippet:S7}),x7={kernelName:dd,backendName:"webgl",kernelFunc:I7};function T7(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Iu(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;A(cn(a,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Un(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ae(m.inShape,m.outShape))return pr({inputs:{x:i},backend:n});const f=new Tu(m,"avg",!1);return n.runWebGLProgram(f,[i],"float32")}const A7={kernelName:Il,backendName:"webgl",kernelFunc:T7};function v7(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;Iu([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:d}=s,m=Un(a.shape,c,h,1,d),f=new v8(m);return n.runWebGLProgram(f,[i],a.dtype)}const N7={kernelName:pd,backendName:"webgl",kernelFunc:v7};class C7{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="0.0";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(nt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
2020-10-13 22:57:06 +02:00
float offset = ${a};
float scale = ${c};
float inv = scale * inversesqrt(variance + float(${o}));
2020-10-11 18:41:17 +02:00
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
2020-10-29 05:16:50 +01:00
`}}class R7{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="vec4(0.0)";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(nt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
vec4 offset = ${a};
vec4 scale = ${c};
2020-10-11 18:41:17 +02:00
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
2020-10-13 22:57:06 +02:00
vec4 inv = scale * inversesqrt(variance + vec4(${o}));
2020-10-11 18:41:17 +02:00
setOutput((x - mean) * inv + offset);
}
2020-10-29 05:16:50 +01:00
`}}const O7=({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 d=[s,i,o];let m=null;a!=null&&(m=a.shape,d.push(a));let f=null;c!=null&&(f=c.shape,d.push(c));const b=oe().getBool("WEBGL_PACK_NORMALIZATION")?new R7(s.shape,i.shape,o.shape,m,f,h):new C7(s.shape,i.shape,o.shape,m,f,h),w=t.runWebGLProgram(b,d,d[0].dtype);return w},E7={kernelName:Dl,backendName:"webgl",kernelFunc:O7};const D7="return float(a != b);",HC=Nc({opSnippet:D7,dtype:"bool"}),k7={kernelName:zl,backendName:"webgl",kernelFunc:HC};function eI(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return pr({inputs:{x:i.complexTensorInfos.real},backend:n})}const F7={kernelName:Fd,backendName:"webgl",kernelFunc:eI};const _7="return float(int(x));";function W7(e,t){const n=new st(e.shape,_7),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function tI(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return pr({inputs:{x:i},backend:n});const a=dt(i.shape),c=tI({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),h=vc({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),h}if(i.dtype==="complex64"){const a=eI({inputs:{input:i},backend:n}),c=tI({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!Ta(i.dtype,o)){const a=pr({inputs:{x:i},backend:n});return{dataId:a.dataId,shape:a.shape,dtype:o}}if(o==="int32")return W7(i,n);if(o==="bool"){const a=n.makeTensorInfo([],"bool",bt("bool",1)),c={a:i,b:a},h=HC({inputs:c,backend:n});return n.disposeIntermediateTensorInfo(a),h}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}const $7={kernelName:Na,backendName:"webgl",kernelFunc:tI};class U7{constructor(e){this.outputShape=[],this.outputShape=Zi(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 B7{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Zi(e,t);const n=this.outputShape,s=n.length,i=Rt(s),o=Mn("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((L,x)=>`T${x}`);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],d=a.slice(-2),m=a.join();let f=`if (${h} < ${c[0]}) {
return getChannel(
getT0(${m}), vec2(${d.join()}));
}`;for(let L=1;L<c.length;L++){const x=c[L-1];f+=`
if (${h} < ${c[L]} && ${h} >= ${c[L-1]}) {
return getChannel(
getT${L}(${jm(a,h,x)}),
vec2(${jm(d,h,x)}));
}`}const b=c.length,w=c[c.length-1];f+=`
return getChannel(
getT${b}(${jm(a,h,w)}),
vec2(${jm(d,h,w)}));`,this.userCode=`
float getValue(${a.map(L=>"int "+L)}) {
${f}
}
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 jm(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}function qC(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return pr({inputs:{x:i.complexTensorInfos.imag},backend:n})}const M7={kernelName:vd,backendName:"webgl",kernelFunc:qC};function P7(e,t,n){const s=[Lc(e.shape),...Sc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[Lc(t),...Sc(t)],a=new AC(o,s),c=!0,h=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:h.dataId,shape:t,dtype:h.dtype}}function mr(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=P(i.shape),h=Gt(o,c),d=P(h);A(c===d,()=>`The new shape (${h}) has ${d} 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&&!Bm(i.shape,h)&&!(m.texture!==null&&Bm(m.shape,h))?P7(i,h,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:h,dtype:i.dtype})}const z7={kernelName:Yl,backendName:"webgl",kernelFunc:mr};function Cc(e,t,n){const s=e[0].dtype;if(s==="complex64"){const d=e.map(L=>eI({inputs:{input:L},backend:n})),m=e.map(L=>qC({inputs:{input:L},backend:n})),f=Cc(d,t,n),b=Cc(m,t,n),w=vc({inputs:{real:f,imag:b},backend:n});return d.forEach(L=>n.disposeIntermediateTensorInfo(L)),m.forEach(L=>n.disposeIntermediateTensorInfo(L)),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),w}if(e.length>oe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const d=Math.floor(e.length/2),m=Cc(e.slice(0,d),t,n),f=Cc(e.slice(d),t,n),b=Cc([m,f],t,n);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),b}if(oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const d=new B7(e.map(m=>m.shape),t);return n.runWebGLProgram(d,e,s)}const i=Zi(e.map(d=>d.shape),t),o=e.map(d=>mr({inputs:{x:d},attrs:{shape:[-1,P(d.shape.slice(t))]},backend:n})),a=new U7(o.map(d=>d.shape)),c=n.runWebGLProgram(a,o,s);o.forEach(d=>n.disposeIntermediateTensorInfo(d));const h=mr({inputs:{x:c},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(c),h}function V7(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=qe(i,t[0].shape)[0],a=Zi(t.map(d=>d.shape),o);if(P(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(d=>P(d.shape)>0);if(c.length===1)return c[0];const h=c.map(d=>d.shape);return dp(h,o),Cc(c,o,n)}const G7={kernelName:Al,backendName:"webgl",kernelFunc:V7};const Y7=GC+`
2020-10-11 18:41:17 +02:00
return cos(x);
2020-10-29 05:16:50 +01:00
`,H7=qm(Y7),q7={kernelName:Ca,backendName:"webgl",kernelFunc:H7};const j7=`
2020-10-11 18:41:17 +02:00
if (a == b) {
return 1.0;
};
2020-10-29 05:16:50 +01:00
return a / b;`,K7=`
2020-10-11 18:41:17 +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
`,X7=Nc({opSnippet:j7,packedOpSnippet:K7,checkOutOfBounds:!0}),J7={kernelName:Ra,backendName:"webgl",kernelFunc:X7};class jC{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 KC(e,t,n){const s=n.texData.get(e.dataId),i=P(e.shape),o=e.shape[e.shape.length-1],a=i/o,c=mr({inputs:{x:e},backend:n,attrs:{shape:[a,o]}}),h=c.shape,d=new jC("real",h,t),m=new jC("imag",h,t),f=[{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(d,f,"float32"),w=n.runWebGLProgram(m,f,"float32"),L=vc({inputs:{real:b,imag:w},backend:n});n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w);const x=mr({inputs:{x:L},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(x),x}function Z7(e){const{inputs:t,backend:n}=e,{input:s}=t;return KC(s,!1,n)}const Q7={kernelName:xd,backendName:"webgl",kernelFunc:Z7};class eJ{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +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 tJ={kernelName:Td,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new eJ(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class nJ{constructor(e){this.variableNames=["A"];const t=Pn(),[n,s]=e;this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
2020-10-13 22:57:06 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);
2020-10-11 18:41:17 +02:00
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 sJ{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Pn(),[n,s]=e;this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
2020-10-13 22:57:06 +02:00
vec2(${s}.0, ${n}.0);
2020-10-11 18:41:17 +02:00
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 iJ={kernelName:Bd,backendName:"webgl",kernelFunc:rJ};let Rc;function rJ(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,d]=a?[i.videoWidth,i.videoHeight]:[i.width,i.height],m=[d,h],f=[d,h,o];(c||a)&&(Rc==null&&(Rc=document.createElement("canvas").getContext("2d")),Rc.canvas.width=h,Rc.canvas.height=d,Rc.drawImage(i,0,0,h,d),i=Rc.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=Ns.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=oe().getBool("WEBGL_PACK")?new sJ(f):new nJ(f),L=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),L}function oJ(e){const{inputs:t,backend:n}=e,{input:s}=t;return KC(s,!0,n)}const aJ={kernelName:Ad,backendName:"webgl",kernelFunc:oJ};class XC{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 * ${Le(m)?m.toPrecision(2):m}, ones);`}let d="";i%n>0&&(d=`
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) {
${d}
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 cJ(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=Sh(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function JC(e,t,n,s){const i=cJ(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:h,outSize:d}=i[a];let m,f;n==="mean"?m=a===0?new XC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d},c):new XC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d}):m=new TC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d},n),f=o,o=s.runWebGLProgram(m,[o],t),f.dataId!==e.dataId&&s.disposeIntermediateTensorInfo(f)}return o}function lJ(e,t,n,s){const i=P(t),o=P(e.shape),a=o/i,c=mr({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=JC(c,e.dtype,"max",s),d=mr({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),d}class hJ{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=uJ(t);this.userCode=`
2020-10-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} resRC = getOutputCoords();
2020-10-11 18:41:17 +02:00
setOutput(getA(${i}));
}
2020-10-29 05:16:50 +01:00
`}}function uJ(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 dJ{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let d=0;d<n.length;d++)n[d]=e[t[d]];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=iC("rc",this.rank),o=new Array(this.rank);for(let d=0;d<t.length;d++)o[t[d]]=i[d];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-11 18:41:17 +02:00
void main() {
2020-10-13 22:57:06 +02:00
${s} rc = getOutputCoords();
2020-10-11 18:41:17 +02:00
vec4 result = vec4(0.);
2020-10-13 22:57:06 +02:00
result[0] = ${h};
if(${c}) {
result[1] = ${h};
2020-10-11 18:41:17 +02:00
}
--${i[this.rank-1]};
2020-10-13 22:57:06 +02:00
if(++${i[this.rank-2]} < ${n[this.rank-2]}) {
result[2] = ${h};
if(${c}) {
result[3] = ${h};
2020-10-11 18:41:17 +02:00
}
}
setOutput(result);
}
2020-10-29 05:16:50 +01:00
`}}function nI(e,t,n){const s=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new dJ(e.shape,t):new hJ(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const pJ={kernelName:Bl,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=qe(i,s.shape);let d=h;const m=Jn(d,c),f=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(f){if(b){const O=a.texData.get(w.dataId),E=O.values,k=new Array(c);for(let $=0;$<k.length;$++)k[$]=s.shape[m[$]];const F=KS(E,s.shape,s.dtype,m,k);w=a.makeTensorInfo(k,s.dtype);const U=a.texData.get(w.dataId);U.values=F}else w=nI(s,m,a);d=cs(d.length,c)}Xn("max",d,c);const[L,x]=An(w.shape,d);let v=L;o&&(v=vn(L,h));let N;if(b){const O=a.texData.get(w.dataId),E=O.values,k=k5(E,P(x),v,s.dtype);N=a.makeTensorInfo(v,s.dtype);const F=a.texData.get(N.dataId);F.values=k}else N=lJ(w,x,v,a);return f&&a.disposeIntermediateTensorInfo(w),N}};function mJ(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Iu(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;A(cn(a,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Un(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ae(m.inShape,m.outShape))return pr({inputs:{x:i},backend:n});const f=new Tu(m,"max",!1);return n.runWebGLProgram(f,[i],i.dtype)}const fJ={kernelName:Ml,backendName:"webgl",kernelFunc:mJ};function gJ(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;Iu([o,a],"maxPoolBackprop");const{filterSize:h,strides:d,pad:m,dimRoundingMode:f}=s,b=Un(c.shape,h,d,1,m,f),w=!0,L=new Tu(b,"max",w),x=n.runWebGLProgram(L,[c],c.dtype),v=new j6(b),N=n.runWebGLProgram(v,[i,x],c.dtype);return n.disposeIntermediateTensorInfo(x),N}const yJ={kernelName:Cd,backendName:"webgl",kernelFunc:gJ};function bJ(e,t,n,s){let i=new Tu(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new Tu(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const wJ={kernelName:Rd,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 d=[1,1];A(cn(o,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);const m=Un(s.shape,i,o,d,a),[f,b]=bJ(s,c,m,h);return[f,b]}};function LJ(e,t,n,s){const i=P(t),o=P(e.shape),a=o/i,c=mr({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=JC(c,"float32","mean",s),d=mr({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),d}const SJ={kernelName:Uy,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=qe(o,s.shape);let d=h;const m=Jn(d,c),f=m!=null,b=a.shouldExecuteOnCPU([s]),w=[];let L=s;if(f){if(b){const E=a.texData.get(L.dataId),k=E.values,F=new Array(c);for(let Y=0;Y<F.length;Y++)F[Y]=s.shape[m[Y]];const U=KS(k,s.shape,s.dtype,m,F);L=a.makeTensorInfo(F,s.dtype);const $=a.texData.get(L.dataId);$.values=U}else L=nI(s,m,a);w.push(L),d=cs(d.length,c)}Xn("sum",d,c);const[x,v]=An(L.shape,d);let N=x;i&&(N=vn(x,h));const O=LJ(L,v,N,a);for(const E of w)a.disposeIntermediateTensorInfo(E);return O}};class IJ{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((d,m)=>d[0]+e[m]+d[1]);const s=e.length,i=Rt(s),o=t.map(d=>d[0]).join(","),a=t.map((d,m)=>d[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 xJ{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=Mn("rc",s),h=Mn("source",s),d=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,f=n==="reflect"?0:1;let b="";if(s===1){const w=`
${i} source = rc;
if (source < start) {
source = start * 2 - source - ${f};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${f};
}
source -= start;
`;b=`
${i} rc = outputLoc;
${w}
result[0] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${d}) {
${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 - ${f}) +
gte * ((end - 1) * 2 - source + ${f});
source -= start;
`;b=`
${i} rc = outputLoc;
${w}
result[0] = getChannel(getX(${h.join()}), ${m});
${c[s-1]} += 1;
if(${d}) {
${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(${d}) {
${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 TJ=({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:i,mode:o}=n,a=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new xJ(s.shape,i,o):new IJ(s.shape,i,o),c=t.runWebGLProgram(a,[s],s.dtype);return c},AJ={kernelName:Pl,backendName:"webgl",kernelFunc:TJ};const ZC={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class QC{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=nt(t,n),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}}const e2="return a * b;";function vJ(e){const{inputs:t,backend:n}=e,{a:s,b:i}=t,o=$n(s.dtype,i.dtype);if(s.dtype==="complex64"){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),d=new QC(ZC.REAL,s.shape,i.shape),m=new QC(ZC.IMAG,s.shape,i.shape),f=[{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(d,f,"float32"),w=n.runWebGLProgram(m,f,"float32"),L=vc({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),[d,m]=F5(s.shape,i.shape,c.values,h.values,o),f=n.makeTensorInfo(m,o),b=n.texData.get(f.dataId);return b.values=d,f}let a;return oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new ur(e2,s.shape,i.shape):a=new Wn(e2,s.shape,i.shape),n.runWebGLProgram(a,[s,i],o)}const NJ={kernelName:Oa,backendName:"webgl",kernelFunc:vJ};const CJ={kernelName:Vy,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{ic("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,d=h.readSync(s.dataId),m=h.readSync(i.dataId),f=o,b=a,w=c;return zp(d,m,f,b,w)}};const RJ=Vp,OJ={kernelName:Od,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{ic("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,d=t,m=d.readSync(s.dataId),f=d.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=RJ(m,f,o,a,c,h);return[b,w]}};const EJ=Gp,DJ={kernelName:Ed,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{ic("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,d=t,m=d.readSync(s.dataId),f=d.readSync(i.dataId),b=o,w=a,L=c,x=h,{selectedIndices:v,selectedScores:N}=EJ(m,f,b,w,L,x);return[v,N]}};class kJ{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,d]=Aw(s,i,o),m=h.toFixed(3),f=d.toFixed(3);let b="";typeof n=="number"?b=`float outputValue = ${n.toFixed(2)};`:b=`
2020-10-13 22:57:06 +02:00
vec3 fill = vec3(${n.join(",")});
2020-10-11 18:41:17 +02:00
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
2020-10-29 05:16:50 +01:00
float coordXFloat = (float(x) - ${m}) * ${c} - (float(y) - ${f}) * ${a};
float coordYFloat = (float(x) - ${m}) * ${a} + (float(y) - ${f}) * ${c};
2020-10-13 22:57:06 +02:00
int coordX = int(round(coordXFloat + ${m}));
2020-10-29 05:16:50 +01:00
int coordY = int(round(coordYFloat + ${f}));
2020-10-13 22:57:06 +02:00
${b}
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${i}) {
2020-10-11 18:41:17 +02:00
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
2020-10-29 05:16:50 +01:00
`}}const FJ={kernelName:Md,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=new kJ(s.shape,i,o,a),d=c.runWebGLProgram(h,[s],s.dtype);return d}};const _J=GC+`
2020-10-11 18:41:17 +02:00
return sin(x);
2020-10-29 05:16:50 +01:00
`,WJ=qm(_J),$J={kernelName:Ea,backendName:"webgl",kernelFunc:WJ};const UJ="return x * x;",BJ=qm(UJ),MJ={kernelName:$d,backendName:"webgl",kernelFunc:BJ};const t2="return (a - b) * (a - b);",PJ=Nc({opSnippet:t2,packedOpSnippet:t2}),zJ={kernelName:Da,backendName:"webgl",kernelFunc:PJ};const n2="return a - b;",VJ=Nc({opSnippet:n2,packedOpSnippet:n2,supportsComplex:!0,cpuKernelImpl:$5}),GJ={kernelName:ka,backendName:"webgl",kernelFunc:VJ};const YJ="return tan(x);",HJ=qm(YJ),qJ={kernelName:Fa,backendName:"webgl",kernelFunc:HJ};const jJ={kernelName:nh,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 d=0;d<c.length;d++)c[d]=s.shape[i[d]];let h;if(o.shouldExecuteOnCPU([s])){const d=o.texData.get(s.dataId),m=d.values,f=KS(m,s.shape,s.dtype,i,c);h=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(h.dataId);b.values=f}else h=nI(s,i,o);return h}};function KJ(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;Iu(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:d}=U5(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([d.length],"int32",d)]}const XJ={kernelName:Ud,backendName:"webgl",kernelFunc:KJ};const JJ=[w7,x7,A7,N7,E7,$7,f7,G7,q7,J7,Q7,tJ,iJ,m7,aJ,M7,pJ,fJ,yJ,wJ,SJ,AJ,NJ,CJ,OJ,DJ,k7,F7,z7,FJ,$J,MJ,GJ,zJ,qJ,jJ,XJ];for(const e of JJ)Yd(e);const ZJ="2.7.0";const QJ={"tfjs-core":KT,"tfjs-backend-cpu":f4,"tfjs-backend-webgl":d7,"tfjs-data":T0,"tfjs-layers":wm,"tfjs-converter":n0,tfjs:ZJ};r.Abs=ud,r.Acos=gl,r.Acosh=yl,r.AdadeltaOptimizer=Fh,r.AdagradOptimizer=_h,r.AdamOptimizer=Wh,r.AdamaxOptimizer=$h,r.Add=Co,r.AddN=by,r.All=Wx,r.Any=$x,r.ArgMax=wy,r.ArgMin=Ly,r.Asin=bl,r.Asinh=wl,r.Atan=Ll,r.Atan2=dd,r.Atanh=Sl,r.AvgPool=Il,r.AvgPool3D=Sy,r.AvgPool3DBackprop=Ux,r.AvgPoolBackprop=pd,r.BatchMatMul=md,r.BatchToSpaceND=Iy,r.BroadcastTo=xy,r.Callback=PN,r.CallbackList=_v,r.Cast=Na,r.Ceil=xl,r.ClipByValue=Tl,r.Complex=fd,r.Concat=Al,r.Conv2D=gd,r.Conv2DBackpropFilter=Ty,r.Conv2DBackpropInput=yd,r.Conv3D=bd,r.Conv3DBackpropFilterV2=Ay,r.Conv3DBackpropInputV2=vy,r.Cos=Ca,r.Cosh=vl,r.CropAndResize=Bx,r.Cumsum=Ny,r.CustomCallback=$v,r.DataStorage=p,r.DepthToSpace=Mx,r.DepthwiseConv2dNative=wd,r.DepthwiseConv2dNativeBackpropFilter=Cy,r.DepthwiseConv2dNativeBackpropInput=Ry,r.Diag=Px,r.Dilation2D=Ld,r.Dilation2DBackpropFilter=Id,r.Dilation2DBackpropInput=Sd,r.Div=Ra,r.EarlyStopping=VN,r.Elu=Nl,r.EluGrad=zx,r.Environment=kx,r.Equal=Vx,r.Erf=Cl,r.Exp=Rl,r.Expm1=Ol,r.FFT=xd,r.Fill=Oy,r.FlipLeftRight=Td,r.Floor=El,r.FloorDiv=Ey,r.FromPixels=Bd,r.FusedBatchNorm=Dl,r.FusedConv2D=zd,r.FusedDepthwiseConv2D=Vd,r.GatherNd=Gx,r.GatherV2=Dy,r.GraphModel=t0,r.Greater=Yx,r.GreaterEqual=ky,r.History=Wv,r.IFFT=Ad,r.Identity=kl,r.Imag=vd,r.InputSpec=Ln,r.IsFinite=Fl,r.IsInf=_l,r.IsNan=Wl,r.KernelBackend=y,r.LRN=_y,r.LRNBackprop=Jx,r.LayerVariable=oi,r.LayersModel=ar,r.Less=Hx,r.LessEqual=qx,r.LinSpace=jx,r.Log=$l,r.Log1p=Ul,r.LogSoftmax=Fy,r.LogicalAnd=Kx,r.LogicalNot=Nd,r.LogicalOr=Xx,r.Max=Bl,r.MaxPool=Ml,r.MaxPool3D=$y,r.MaxPool3DBackprop=Zx,r.MaxPoolBackprop=Cd,r.MaxPoolWithArgmax=Rd,r.Maximum=Wy,r.Mean=Uy,r.Min=By,r.Minimum=My,r.MirrorPad=Pl,r.Mod=Py,r.MomentumOptimizer=Uh,r.Multiply=Oa,r.Negate=zy,r.NonMaxSuppressionV3=Vy,r.NonMaxSuppressionV4=Od,r.NonMaxSuppressionV5=Ed,r.NotEqual=zl,r.OP_SCOPE_SUFFIX=LT,r.OneHot=Yy,r.OnesLike=Gy,r.Optimizer=nr,r.PadV2=Dd,r.Pool=Ok,r.Pow=Hy,r.Prelu=kd,r.Prod=Qx,r.RMSPropOptimizer=Bh,r.RNN=Di,r.Range=eT,r.Real=Fd,r.Reciprocal=Vl,r.Relu=Gl,r.Relu6=Hl,r.Reshape=Yl,r.ResizeBilinear=jy,r.ResizeBilinearGrad=nT,r.ResizeNearestNeighbor=qy,r.ResizeNearestNeighborGrad=tT,r.Reverse=Ky,r.RotateWithOffset=Md,r.Round=ql,r.Rsqrt=jl,r.SGDOptimizer=sc,r.ScatterNd=sT,r.SelectV2=Xy,r.Selu=Kl,r.Sequential=uc,r.Sigmoid=Zl,r.Sign=Jl,r.Sin=Ea,r.Sinh=Xl,r.Slice=_d,r.Softmax=Qy,r.Softplus=Ql,r.SpaceToBatchND=Wd,r.SparseToDense=iT,r.SplitV=Zy,r.Sqrt=eh,r.Square=$d,r.SquaredDifference=Da,r.Step=sh,r.StridedSlice=rT,r.Sub=
`)),T.join(`
`)}function O9(r,l,u,p){const y=Zt(l),g=p[p.length-1],I=new Array(g).fill(0),S=l.length,T=u==="complex64"?zu(r):r;if(S>1)for(let C=0;C<y/g;C++){const D=C*g;for(let _=0;_<g;_++)I[_]=Math.max(I[_],Pu(T[D+_],0,u).length)}return I}function Pu(r,l,u){let p;return Array.isArray(r)?p=`${parseFloat(r[0].toFixed(kI))} + ${parseFloat(r[1].toFixed(kI))}j`:$u(r)?p=`'${r}'`:u==="bool"?p=PO(r):p=parseFloat(r.toFixed(kI)).toString(),Yc(p,l)}function PO(r){return r===0?"false":"true"}function kg(r,l,u,p,y,g=!0){const I=u==="complex64"?2:1,S=l[0],T=l.length;if(T===0){if(u==="complex64"){const te=zu(r);return[Pu(te[0],0,u)]}return u==="bool"?[PO(r[0])]:[r[0].toString()]}if(T===1){if(S>BO){const P=Mu*I;let ge=Array.from(r.slice(0,P)),ae=Array.from(r.slice((S-Mu)*I,S*I));return u==="complex64"&&(ge=zu(ge),ae=zu(ae)),["["+ge.map((Le,ve)=>Pu(Le,y[ve],u)).join(", ")+", ..., "+ae.map((Le,ve)=>Pu(Le,y[S-Mu+ve],u)).join(", ")+"]"]}const te=u==="complex64"?zu(r):Array.from(r);return["["+te.map((P,ge)=>Pu(P,y[ge],u)).join(", ")+"]"]}const C=l.slice(1),D=p.slice(1),_=p[0]*I,A=[];if(S>BO){for(let te=0;te<Mu;te++){const P=te*_,ge=P+_;A.push(...kg(r.slice(P,ge),C,u,D,y,!1))}A.push("...");for(let te=S-Mu;te<S;te++){const P=te*_,ge=P+_;A.push(...kg(r.slice(P,ge),C,u,D,y,te===S-1))}}else for(let te=0;te<S;te++){const P=te*_,ge=P+_;A.push(...kg(r.slice(P,ge),C,u,D,y,te===S-1))}const B=T===2?",":"";A[0]="["+A[0]+B;for(let te=1;te<A.length-1;te++)A[te]=" "+A[te]+B;let ne=`,
`;for(let te=2;te<T;te++)ne+=`
`;return A[A.length-1]=" "+A[A.length-1]+"]"+(g?"":ne),A}function zu(r){const l=[];for(let u=0;u<r.length;u+=2)l.push([r[u],r[u+1]]);return l}class zO{constructor(r,l,u){if(this.dtype=l,this.shape=r.slice(),this.size=Zt(r),u!=null){const p=u.length;J(p===this.size,()=>`Length of values '${p}' 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||Z2(l,this.size),this.strides=Bu(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 p of r){if(p<0||p>=this.shape[l]){const y=`Requested out of range element at ${r}. Buffer shape=${this.shape}`;throw new Error(y)}l++}let u=r[r.length-1];for(let p=0;p<r.length-1;++p)u+=this.strides[p]*r[p];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 Pi().makeTensor(this.values,this.shape,this.dtype)}}let Pi=null,jc=null,E9=null;function VO(r){Pi=r}function GO(r){jc=r}function YO(r){E9=r}class Dn{constructor(r,l,u,p){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=Zt(r),this.strides=Bu(r),this.dataId=u,this.id=p,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 xI(this.shape,r)}arraySync(){return xI(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const r=Pi().read(this.dataId);if(this.dtype==="string"){const l=await r;try{return l.map(u=>DI(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=Pi().readSync(this.dataId);if(this.dtype==="string")try{return r.map(l=>DI(l))}catch(l){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return r}async bytes(){this.throwIfDisposed();const r=await Pi().read(this.dataId);return this.dtype==="string"?r:new Uint8Array(r.buffer)}dispose(){if(this.isDisposed)return;Pi().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 MO(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),jc.cast(this,r)}variable(r=!0,l,u){return this.throwIfDisposed(),Pi().makeVariable(this,r,l,u)}}Object.defineProperty(Dn,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class Fg extends Dn{constructor(r,l,u,p){super(r.shape,r.dtype,r.dataId,p);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(!Wu(r.shape,this.shape))throw new Error(`shape of the new value (${r.shape}) and previous value (${this.shape}) must match`);Pi().disposeTensor(this),this.dataId=r.dataId,Pi().incRef(this,null)}dispose(){Pi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Fg,Symbol.hasInstance,{value:r=>r instanceof Dn&&r.assign!=null&&r.assign instanceof Function});var HO;(function(r){r.R0="R0",
with dtype ${I.dtype}. `)});const p=(I,S)=>{const T=gt(l,u[0].shape)[0],C=o1(u.map(A=>A.shape),T);if(Zt(C)===0)return BI([],C);if(u=u.filter(A=>A.size>0),u.length===1)return u[0];const D=u.map(A=>A.shape);r1(D,T);const _=I.concat(u,T);return S(u),_},y=u,g={axis:l};return H.runKernelFunc(p,y,null,Bf,g)}const Tn=V({concat_:iZ});function rZ(r){const l=M(r,"x","sigmoid"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.sigmoid(l);return y([g]),g},u,null,bg)}const YI=V({sigmoid_:rZ});function oZ(r,l,u){const p=M(r,"x","slice");if(p.rank===0)throw new Error("Slicing scalar is not possible");const y=(S,T)=>{const[C,D]=$g(p,l,u);return e1(p,C,D),T([p]),S.slice(p,C,D)},g={x:p},I={begin:l,size:u};return H.runKernelFunc(y,g,null,fg,I)}const Tt=V({slice_:oZ});function aZ(r,l,u){const p=M(r,"x","batchToSpaceND"),y=l.reduce((T,C)=>T*C);J(p.rank>=1+l.length,()=>`input rank is ${p.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(p.shape[0]%y===0,()=>`input tensor batch is ${p.shape[0]} but is not divisible by the product of the elements of blockShape ${l.join(" * ")} === ${y}`);const g=T=>T.batchToSpaceND(p,l,u),I={x:p},S={blockShape:l,crops:u};return H.runKernelFunc(g,I,null,$f,S)}const HI=V({batchToSpaceND_:aZ});function cZ(r,l){let u=M(r,"broadcastTo","x");const p=u.shape;if(l.some(D=>!(D>0)||D%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 D=u.shape.slice();for(;D.length<l.length;)D.unshift(1);u=re(u,D)}const y=u.shape,g=Array.from(l);for(let D=l.length-1;D>=0;D--)if(y[D]===l[D])g[D]=1;else if(u.shape[D]!==1)throw new Error(`broadcastTo(): [${p}] cannot be broadcast to [${l}].`);const I=g.map((D,_)=>D>1?_:-1).filter(D=>D>=0);if(I.length===0)return gi(u);const S=D=>D.tile(u,g),T={x:u},C={shape:l,inputShape:y};return H.runKernelFunc(S,T,null,Uf,C)}const Pg=V({broadcastTo_:cZ});function lZ(r,l,u,p,y="NHWC",g=[1,1],I){const S=M(r,"x","conv2d"),T=M(l,"filter","conv2d");let C=S,D=!1;S.rank===3&&(D=!0,C=re(S,[1,S.shape[0],S.shape[1],S.shape[2]])),J(C.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${C.rank}.`),J(T.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${T.rank}.`),I!=null&&J(nn(p),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${p}.`);const _=y==="NHWC"?C.shape[3]:C.shape[1];J(_===T.shape[2],()=>`Error in conv2d: depth of input (${_}) must match input depth for filter ${T.shape[2]}.`),J(yo(u,g),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${u} and dilations '${g}'`);const A=(P,ge)=>{const ae=Zc(y),Le=yi(C.shape,T.shape,u,g,p,I,!1,ae),ve=P.conv2d(C,T,Le);return ge([C,T]),ve},B={x:C,filter:T},ne={strides:u,pad:p,dataFormat:y,dilations:g,dimRoundingMode:I},te=H.runKernelFunc(A,B,null,Mf,ne);return D?re(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const qI=V({conv2d_:lZ});function hZ(r,l,u,p,y,g="NHWC",I){J(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let S=r,T=l,C=!1;l.rank===3&&(C=!0,T=re(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(T.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${T.rank}`),J(u.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${u.rank}`);const D=g==="NHWC"?S[3]:S[1],_=g==="NHWC"?T.shape[3]:T.shape[1];J(D===u.shape[2],()=>`Error in conv2dDerInput: depth of input (${D}) 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(y),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${I} but got pad ${y}.`);const A=(P,ge)=>{const ae=1,Le=Zc(g),ve=yi(S,u.shap
2020-10-11 18:41:17 +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. */
//# sourceMappingURL=face-api.js.map