face-api/dist/face-api.js

3982 lines
1.1 MiB
JavaScript
Raw Normal View History

2020-10-13 22:57:06 +02:00
var faceapi=(()=>{var wm=Object.defineProperty,y7=Object.prototype.hasOwnProperty,Lm=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),NC=r=>wm(r,"__esModule",{value:!0}),uu=(r,l)=>{NC(r);for(var u in l)wm(r,u,{get:l[u],enumerable:!0})},b7=(r,l)=>{if(NC(r),typeof l=="object"||typeof l=="function")for(let u in l)!y7.call(r,u)&&u!=="default"&&wm(r,u,{get:()=>l[u],enumerable:!0});return r},Xe=r=>r&&r.__esModule?r:b7(wm({},"default",{value:r,enumerable:!0}),r);var RC=Lm((bc,CC)=>{"use strict";var w7=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof lr!="undefined")return lr;throw new Error("unable to locate global object")},lr=w7();CC.exports=bc=lr.fetch;lr.fetch&&(bc.default=lr.fetch.bind(lr));bc.Headers=lr.Headers;bc.Request=lr.Request;bc.Response=lr.Response});var Je=Lm((Sm,OC)=>{(function(r,l){typeof Sm=="object"&&typeof OC!="undefined"?l(Sm):typeof define=="function"&&define.amd?define(["exports"],l):(r=r||self,l(r.tf=r.tf||{}))})(Sm,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 g{time(e){return f("time")}read(e){return f("read")}readSync(e){return f("readSync")}numDataIds(){return f("numDataIds")}disposeData(e){return f("disposeData")}write(e,t,n){return f("write")}move(e,t,n,s){return f("move")}memory(){return f("memory")}floatPrecision(){return f("floatPrecision")}epsilon(){return this.floatPrecision()===32?l:u}batchMatMul(e,t,n,s){return f("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){return f("fusedBatchMatMul")}slice(e,t,n){return f("slice")}stridedSlice(e,t,n,s){return f("stridedSlice")}unstack(e,t){return f("unstack")}reverse(e,t){return f("reverse")}concat(e,t){return f("concat")}neg(e){return f("neg")}add(e,t){return f("add")}addN(e){return f("addN")}subtract(e,t){return f("subtract")}multiply(e,t){return f("multiply")}realDivide(e,t){return f("realDivide")}floorDiv(e,t){return f("floorDiv")}sum(e,t){return f("sum")}prod(e,t){return f("prod")}unsortedSegmentSum(e,t,n){return f("unsortedSegmentSum")}argMin(e,t){return f("argMin")}argMax(e,t){return f("argMax")}equal(e,t){return f("equal")}notEqual(e,t){return f("notEqual")}less(e,t){return f("less")}lessEqual(e,t){return f("lessEqual")}greater(e,t){return f("greater")}greaterEqual(e,t){return f("greaterEqual")}logicalNot(e){return f("logicalNot")}logicalAnd(e,t){return f("logicalAnd")}logicalOr(e,t){return f("logicalOr")}where(e){return f("where")}select(e,t,n){return f("select")}topk(e,t,n){return f("topk")}min(e,t){return f("min")}minimum(e,t){return f("minimum")}mod(e,t){return f("mod")}max(e,t){return f("max")}maximum(e,t){return f("maximum")}all(e,t){return f("all")}any(e,t){return f("any")}squaredDifference(e,t){return f("squaredDifference")}ceil(e){return f("ceil")}floor(e){return f("floor")}round(e){return f("round")}sign(e){return f("sign")}isNaN(e){return f("isNaN")}isInf(e){return f("isInf")}isFinite(e){return f("isFinite")}pow(e,t){return f("pow")}exp(e){return f("exp")}expm1(e){return f("expm1")}softmax(e,t){return f("softmax")}log(e){return f("log")}log1p(e){return f("log1p")}sqrt(e){return f("sqrt")}rsqrt(e){return f("rsqrt")}square(e){return f("square")}reciprocal(e){return f("reciprocal")}relu(e){return f("relu")}relu6(e){return f("relu6")}prelu(e,t){return f("prelu")}elu(e){return f("elu")}eluDer(e,t){return f("eluDer")}selu(e){return f("selu")}int(e){return f("int")}clip(e,t,n){return f("clip")}abs(e){return f("abs")}complexAbs(e){return f("complexAbs")}sigmoid(e){return f("sigmoid")}softplus(e){return f("softplus")}sin(e){return f("sin")}cos(e){return f("cos")}tan(e){return f("tan")}asin(e){return f("asin")}acos(e){return f("acos")}atan(e){return f("a
`)),h.join(`
`)}function lk(e,t,n,s){const i=we(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,h=n==="complex64"?Yl(e):e;if(c>1)for(let d=0;d<i/o;d++){const m=d*o;for(let y=0;y<o;y++)a[y]=Math.max(a[y],Vl(h[m+y],0,n).length)}return a}function Vl(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(Uy))} + ${parseFloat(e[1].toFixed(Uy))}j`:xr(e)?s=`'${e}'`:n==="bool"?s=Hx(e):s=parseFloat(e.toFixed(Uy)).toString(),go(s,t)}function Hx(e){return e===0?"false":"true"}function yd(e,t,n,s,i,o=!0){const a=n==="complex64"?2:1,c=t[0],h=t.length;if(h===0){if(n==="complex64"){const T=Yl(e);return[Vl(T[0],0,n)]}return n==="bool"?[Hx(e[0])]:[e[0].toString()]}if(h===1){if(c>Yx){const A=Gl*a;let N=Array.from(e.slice(0,A)),E=Array.from(e.slice((c-Gl)*a,c*a));return n==="complex64"&&(N=Yl(N),E=Yl(E)),["["+N.map((D,F)=>Vl(D,i[F],n)).join(", ")+", ..., "+E.map((D,F)=>Vl(D,i[c-Gl+F],n)).join(", ")+"]"]}const T=n==="complex64"?Yl(e):Array.from(e);return["["+T.map((A,N)=>Vl(A,i[N],n)).join(", ")+"]"]}const d=t.slice(1),m=s.slice(1),y=s[0]*a,b=[];if(c>Yx){for(let T=0;T<Gl;T++){const A=T*y,N=A+y;b.push(...yd(e.slice(A,N),d,n,m,i,!1))}b.push("...");for(let T=c-Gl;T<c;T++){const A=T*y,N=A+y;b.push(...yd(e.slice(A,N),d,n,m,i,T===c-1))}}else for(let T=0;T<c;T++){const A=T*y,N=A+y;b.push(...yd(e.slice(A,N),d,n,m,i,T===c-1))}const w=h===2?",":"";b[0]="["+b[0]+w;for(let T=1;T<b.length-1;T++)b[T]=" "+b[T]+w;let L=`,
`;for(let T=2;T<h;T++)L+=`
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":L),b}function Yl(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class vr{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=we(e),n!=null){const s=n.length;k(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||yo(t,this.size),this.strides=Ot(e)}set(e,...t){t.length===0&&(t=[0]),k(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const s of e){if(s<0||s>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let n=e[e.length-1];for(let s=0;s<e.length-1;++s)n+=this.strides[s]*e[s];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Ii().makeTensor(this.values,this.shape,this.dtype)}}let Ii=null,Aa=null,qx=null;function hk(e){Ii=e}function uk(e){Aa=e}function dk(e){qx=e}class Q{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=we(e),this.strides=Ot(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Aa.buffer(this.shape,this.dtype,e)}bufferSync(){return Aa.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return ys(this.shape,e)}arraySync(){return ys(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=>zl(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=>zl(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 Aa.print(this,e)}clone(){return this.throwIfDisposed(),Aa.clone(this)}toString(e=!1){const t=this.dataSync();return ck(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Aa.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ii().makeVariable(this,e,t,n)}}Object.defineProperty(Q,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class Hl extends Q{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ot(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Ii().disposeTensor(this),this.dataId=e.dataId,Ii().incRef(this,null)}dispose(){Ii().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Hl,Symbol.hasInstance,{value:e=>e instanceof Q&&e.assign!=null&&e.assign instanceof Function});(function(e){e.R0="R0",e.R1="R1",e.
Manifest JSON has weights with names: ${c.join(", ")}.`)}const h=i.reduce((w,L,T)=>(L&&w.push(T),w),[]),d=[];h.forEach(w=>{t[w].paths.forEach(L=>{const T=n+(n.endsWith("/")?"":"/")+L;d.push(T)})});const m=await e(d),y={};let b=0;return h.forEach(w=>{const L=t[w].paths.length;let T=0;for(let F=0;F<L;F++)T+=m[b+F].byteLength;const A=new ArrayBuffer(T),N=new Uint8Array(A);let E=0;for(let F=0;F<L;F++){const _=new Uint8Array(m[b+F]);N.set(_,E),E+=_.byteLength}const D=o[w];D.forEach(F=>{const _=A.slice(F.groupOffset,F.groupOffset+F.sizeBytes),B=Sd(_,[F.manifestEntry]);for(const $ in B)y[$]=B[$]}),b+=L}),y}}const sF="application/octet-stream",iF="application/json";class Zy{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(k(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=C().platform.fetch,k(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&k(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(s)],{type:iF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:sF}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Kl(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},y=t.modelInitializer;return y&&(m.modelInitializer=y),m}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=rF(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 pT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,Id(h)]}}Zy.URL_SCHEME_REGEX=/^https?:\/\//;function r
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-13 22:57:06 +02:00
Expected: ${o}.`)}}function AF(e,t){e().then(()=>t.fail(),()=>t())}function vF(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return xr(e)||xr(e[0])||xr(t)||xr(t[0])?ab(e,n,(s,i)=>s==i):ab(e,t,(s,i)=>lb(s,i,0))}function cb(e,t,n){if(n==null&&(n=Od()),!lb(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function lb(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function NF(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 CF(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var RF=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:RT,expectArraysClose:TF,testEpsilon:Od,expectPromiseToFail:AF,expectArraysEqual:vF,expectNumbersClose:cb,expectValuesInRange:NF,expectArrayBuffersEqual:CF});const OT="2.6.0";function OF(){C().set("PROD",!0)}function EF(){C().set("DEBUG",!0)}function DF(){C().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function tn(e){C().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}dk(tn);function kF(){V.disposeVariables()}function _s(){return V}function Ed(){return V.memory()}function FF(e){return V.profile(e)}function ee(e,t){return V.tidy(e,t)}function He(e){const t=ji(e);t.forEach(n=>n.dispose())}function Cn(e){return V.keep(e)}function _F(e){return V.time(e)}function ET(e){return V.setBackend(e)}function WF(){return V.ready()}function $F(){return V.backendName}function UF(e){V.removeBackend(e)}function BF(e){return V.findBackend(e)}function MF(e){return V.findBackendFactory(e)}function hb(e,t,n=1){return V.registerBackend(e,t,n)}function DT(){return V.backend}function PF(e,t){C().setPlatform(e,t)}function zF(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.add(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Te)}const be=P({add_:zF});function GF(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.floorDiv(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Yg)}const Dd=P({floorDiv_:GF});function VF(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Mt(n,s),n.dtype==="int32"&&s.dtype==="int32")return Dd(n,s);const i=(c,h)=>{const d=c.realDivide(n,s);return h([n,s]),d},o={a:n,b:s},a={};return V.runKernelFunc(i,o,null,ya,a)}const _e=P({div_:VF});function YF(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.multiply(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Al)}const X=P({mul_:YF});function HF(e){const t=W(e,"x","abs"),n={x:t};return V.runKernelFunc((s,i)=>(i([t]),t.dtype==="complex64"?s.complexAbs(t):s.abs(t)),n,null,ge)}const nn=P({abs_:HF});function qF(e){const t=W(e,"x","acos"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.acos(t);return i([t]),o},n,null,fe)}const ub=P({acos_:qF});function jF(e){const t=W(e,"x","acosh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.acosh(t);return i([t]),o},n,null,Ae)}const db=P({acosh_:jF});function KF(e){k(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),k(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((o,a)=>W(o,`tensors${a}`,"addN")),n=t[0];t.forEach(o=>{if(o.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!ot(o.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const s=(o,a)=>{const c=o.addN(t);return a(t),c},i=t;return V.runKernelFunc(s,i,null,Ve)}const kT=P({addN_:KF});function pb(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function FT(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 Rn(e,t){const n=[],s=e.length;for(let o=0;o<s;o++)t.indexOf(o)===-1&&n.pu
with dtype ${a.dtype}. `)});const s=(a,c)=>{const h=gt(t,n[0].shape)[0],d=Er(n.map(b=>b.shape),h);if(we(d)===0)return en([],d);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);xb(m,h);const y=a.concat(n,h);return c(n),y},i=n,o={axis:t};return V.runKernelFunc(s,i,null,qu,o)}const Pt=P({concat_:u_});function d_(e){const t=W(e,"x","sigmoid"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sigmoid(t);return i([o]),o},n,null,kl)}const Ni=P({sigmoid_:d_});function p_(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]=Rd(s,t,n);return ib(s,d,m),h([s]),c.slice(s,d,m)},o={x:s},a={begin:t,size:n};return V.runKernelFunc(i,o,null,rd,a)}const nt=P({slice_:p_});function m_(e){const t=W(e,"x","tanh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.tanh(t);return i([o]),o},n,null,$l)}const Da=P({tanh_:m_});function f_(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"),y=W(o,"h","basicLSTMCell"),b=Pt([d,y],1),w=at(b,c),L=be(w,h),T=L.shape[0],A=L.shape[1]/4,N=[T,A],E=nt(L,[0,0],N),D=nt(L,[0,A],N),F=nt(L,[0,A*2],N),_=nt(L,[0,A*3],N),B=be(X(Ni(E),Da(D)),X(m,Ni(be(a,F)))),$=X(Da(B),Ni(_));return[B,$]}const g_=P({basicLSTMCell_:f_});function y_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((h,d)=>h*d);k(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),k(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),k(s.shape[0]%i===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const o=h=>h.batchToSpaceND(s,t,n),a={x:s},c={blockShape:t,crops:n};return V.runKernelFunc(o,a,null,Wg,c)}const sh=P({batchToSpaceND_:y_});function b_(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 w_(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")),k(c.rank===h.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(m==null||c.rank===m.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(d==null||c.rank===d.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const y=b_(a),b=(A,N)=>(N([y,c,h,d]),A.batchNorm(y,Wd(c),Wd(h),Wd(m),Wd(d),o)),w={x:y,scale:d,offset:m,mean:c,variance:h},L={varianceEpsilon:o},T=V.runKernelFunc(b,w,null,gl,L);return K(T,a.shape)}function Wd(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 Ao=P({batchNorm_:w_});function L_(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")),k(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),k(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${c.rank}.`),k(h.rank===2||h.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${h.rank}.`),d!=null&&k(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${d.rank}.`),m!=null&&k(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${m.rank}.`),Ao(a,c,h,m,d,o)}const _T=P({batchNorm2d_:L_});function S_(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")),k(a.rank===3,()=>`Error in b
2020-10-11 18:41:17 +02:00
${i} and ${t} for depthToSpace with input shape
2020-10-13 22:57:06 +02:00
${s.shape}`),k(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
${s.shape}`),k(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${s.shape}`);const c=m=>m.depthToSpace(s,t,n),h={x:s},d={blockSize:t,dataFormat:n};return V.runKernelFunc(c,h,null,dx,d)}const Nb=P({depthToSpace_:P_});function z_(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]])),k(d.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`),k(h.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),k(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&&k(Bt(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const y=(T,A)=>{o==null&&(o=[1,1]),k(sn(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const N=vi(d.shape,h.shape,n,o,s,a,!0),E=T.depthwiseConv2D(d,h,N);return A([d,h]),E},b={x:d,filter:h},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},L=V.runKernelFunc(y,b,null,Gg,w);return m?K(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const vo=P({depthwiseConv2d_:z_});function G_(e){const t=W(e,"x","diag"),n=i=>{const o=K(t,[t.size]),a=i.diag(o),c=[...e.shape,...e.shape];return K(a,c)},s={x:t};return V.runKernelFunc(n,s,null,fx)}const V_=P({diag_:G_});function Y_(e,t,n,s,i=[1,1],o="NHWC"){const a=W(e,"x","dilation2d"),c=W(t,"filter","dilation2d");k(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),k(c.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${c.rank}.`),k(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let 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},y={strides:n,pad:s,dilations:i},b=V.runKernel(ju,m,y);return d?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Cb=P({dilation2d_:Y_});function No(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 rn(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 tt(e,t){const n=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let o=e[e.length-i-1];o==null&&(o=1);let a=t[t.length-i-1];if(a==null&&(a=1),o===1)n.unshift(a);else if(a===1)n.unshift(o);else if(o!==a){const c=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(c)}else n.unshift(o)}return n}function H_(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Mt(n,s),tt(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,yx)}const ti=P({equal_:H_});function q_(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=tt(s.shape,i.shape),c=ih(s,a),h=ih(i,a);o.rank===1&&k(o.shape[0]===s.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&pt(o.shape,h.shape,"Error in where: ");const d=(y,b)=>{const w=y.select(o,c,h);return b([o]),w},m={condition:o,t:c,e:h};return V.runKernelFunc(d,m,null,fy)}const _n=P({where_:q_});function j_(e){const t=W(e,"x","zerosLike"),n={x:t};return V.runKernelFunc(s=>s.zerosLike(t),n,null,Iy)}const Qe=P({zerosLike_:j_});function K_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Mt(n,s);const i=_e(n,s),o=Qe(i),a=ti(s,o);return _n(a,o,i)}const Rb=P({divNoNan_:K_});function X_(e,t){const n=W(e,"t1","dot"),s=W(t,"t2","dot");k((n.rank===1||n.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);const i=n.rank===1?n.size:n.shape[1],o=s.rank===1?s.size:s.shape[0];if(k(i===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${o}.`),n.rank=
rank ${o.rank}.`),k(Bt(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},y=V.runKernelFunc(h,d,null,Jg,m);return c?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const kb=P({localResponseNormalization_:wW});function LW(e){const t=W(e,"x","log"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.log(t);return i([t]),o},n,null,Sl)}const ns=P({log_:LW});function SW(e){const t=W(e,"x","log1p"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.log1p(t);return i([t]),o},n,null,Il)}const Gd=P({log1p_:SW});function IW(e){return k(Tr(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const s=W(t,"x","tf.grad",null),i=n!=null?W(n,"dy","tf.grad"):null;return V.tidy(()=>{const{value:o,grads:a}=V.gradients(()=>e(s),[s],i);return i!=null&&pt(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Vd(a),a[0]})}}function xW(e){return k(Tr(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{k(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=jl(t,"args","tf.grads",null),i=n!=null?W(n,"dy","tf.grads"):null;return V.tidy(()=>{const{value:o,grads:a}=V.gradients(()=>e(...s),s,i);return i!=null&&pt(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Vd(a),a})}}function TW(e){return k(Tr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{k(t instanceof Q,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),k(n==null||n instanceof Q,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=V.gradients(()=>e(t),[t],n);return Vd(s),{grad:s[0],value:i}}}function AW(e){return k(Tr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{k(Array.isArray(t)&&t.every(i=>i instanceof Q),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),k(n==null||n instanceof Q,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=V.gradients(()=>e(...t),t,n);return n!=null&&pt(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Vd(s.grads),s}}function Fb(e,t){k(Tr(e),()=>"The f passed in variableGrads(f) must be a function"),k(t==null||Array.isArray(t)&&t.every(d=>d instanceof Hl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const d in V.registeredVariables)t.push(V.registeredVariables[d])}const s=n?t.filter(d=>!d.trainable):null,i=t.length;t=t.filter(d=>d.trainable),k(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const o=!0,{value:a,grads:c}=V.gradients(e,t,null,o);k(c.some(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()."),k(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 Ci(e){return V.customGrad(e)}function Vd(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 vW(e){const t=W(e,"x","neg"),n={x:t};return V.runKernelFunc(s=>s.neg(t),n,null,sy)}const zt=P({neg_:vW});function NW(e){const t=W(e,"x","softplus"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.softplus(t);return i([t]),o},n,null,Fl)}const Wa=P({softplus_:NW});function CW(e){const t=W(e,"x","logSigmoid"),n=Ci(s=>{const i=zt(Wa(zt(s))),o=a=>{const c=X(a,Ni(zt(s)));return c};return{value:i,gradFunc:o}});return n(t)}const KT=P({logSigmoid_:CW});function RW(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,h)=>{const d=gt(t,s.shape);let m=d;const y=kn(m,s.rank);let b=s;y!=null&&(b=Me(s,y),m=ws(m.length,b.rank));const w=c.max(b,m);y!=null&&b.dispose();let L=w;if(n){const T=On(L.shape,gt(t,s.shape));L=K(L,T),w.dispose()}return h([s,L]),L},o={x:s},a={reductionIndices:t,keepDims:n};return V.runKernelFunc(i,o,null,xl,a)}const jn=P({max_:RW});function OW(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.subtract(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Wl)}const Ce=P({sub_:OW});function EW(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=ve(s,"int32"));const i=(c,h)=>{h([s]);const d=gt(t,s.shape),m=kn(d,s.rank);let y=d,b=s;m!=null&&(b=Me(s,m),y=ws(y.length,s.rank));let w=c.sum(b,y);if(n){const L=On(w.shape,d);w=K(w,L)}return w},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,gy,a)}const Ue=P({sum_:EW});function DW(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=jn(e,t,!0),m=Ce(e,d),y=Ce(ve(m,"float32"),ns(Ue(Ls(m),t,h)));return c([y]),y},i={logits:n},o={axis:t};return V.runKernelFunc(s,i,null,Xg,o)}const Yd=P({logSoftmax_:DW});function kW(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=gt(t,s.shape),o=jn(s,i,!0),a=Ce(s,o),c=Ls(a),h=Ue(c,i),d=ns(h),m=be(K(o,d.shape),d);if(n){const y=On(m.shape,i);return K(m,y)}return m}const _b=P({logSumExp_:kW});function FW(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");tt(n.shape,s.shape);const i={a:n,b:s};return V.runKernelFunc(o=>o.logicalAnd(n,s),i,null,Tx)}const $s=P({logicalAnd_:FW});function _W(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return V.runKernelFunc(s=>s.logicalNot(t),n,null,Zu)}const lh=P({logicalNot_:_W});function WW(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");tt(n.shape,s.shape);const i={a:n,b:s};return V.runKernelFunc(o=>o.logicalOr(n,s),i,null,Ax)}const Hd=P({logicalOr_:WW});function $W(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return tt(n.shape,s.shape),$s(Hd(e,t),lh($s(e,t)))}const XT=P({logicalXor_:$W});function UW(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]])),k(c.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${c.rank}.`),k(sn(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&k(Bt(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const d=(w,L)=>{const T=Fn(c.shape,t,n,1,s,i);let A;return T.filterWidth===1&&T.filterHeight===1&&ot(T.inShape,T.outShape)?A=c.clone():A=w.maxPool(c,T),L([c,A]),A},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=V.runKernelFunc(d,m,null,Tl,y);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const hh=P({maxPool_:UW});function BW(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:tn("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]])),k(h.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${h.rank}.`),k(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),k(sn(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. G
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}else{const o=e;if(o.className==null||o.config==null)throw new j(`${s}: Improper config format: ${JSON.stringify(o)}.
'className' and 'config' must set.`);const a=o.className;let c,h;if(a in n?[c,h]=n[a]:a in Us?[c,h]=Us.className:a in t&&([c,h]=t[a]),c==null)throw new j(`Unknown ${s}: ${a}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
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(Us))d[w]=Us[w];for(const w of Object.keys(n))d[w]=n[w];const m=o.config;m.customObjects=d;const y=Object.assign({},Us);for(const w of Object.keys(n))Us[w]=n[w];bw(o.config);const b=h(c,o.config,n,i);return Us=Object.assign({},y),b}else{const d=Object.assign({},Us);for(const y of Object.keys(n))Us[y]=n[y];const m=new c(o.config);return Us=Object.assign({},d),m}}}function pz(e,t){return e<t?-1:e>t?1:0}function bp(e,t){return-1*pz(e,t)}function qZ(e){switch(e){case"float32":return"float32";default:throw new j(`Invalid dtype: ${e}`)}}function jZ(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 Ur(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function mz(e){if(e==null)throw new j(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Ha(e,t,n){if(n==null)return;if(e.indexOf(n)<0)throw new j(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function ww(e,t,n=0,s=Infinity){return xs(n>=0),xs(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function pn(e,t){Array.isArray(e)?(k(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>pn(n,`element ${s+1} of ${t}`))):k(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${XA(e)}.`)}function XA(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>XA(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function fz(e,t){let n=Yn(),s;const i=(...o)=>{const a=Yn();return a-n<t||(n=a,s=e(...o)),s};return i}function JA(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function KZ(...e){xs(e.length>0,"arrayOfValues is empty");for(const t of e)xs(Array.isArray(t),"one of the values is not an array"),xs(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 Lw(e,t){return ee(()=>Ln(Ue(X(e,e),t,!0)))}class Rh extends xo{getConfig(){return{}}}class Sw extends Rh{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>{const t=Lw(e,this.axis),n=Hn(t,0,this.maxValue);return X(e,_e(n,be(on(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Sw.className="MaxNorm",me(Sw);class Iw extends Rh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>_e(e,be(on(),Lw(e,this.axis))))}getConfig(){return{axis:this.axis}}}Iw.className="UnitNorm",me(Iw);class xw extends Rh{apply(e){return Oi(e)}}xw.className="NonNeg",me(xw);class Tw extends Rh{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>{const t=Lw(e,this.axis),n=be(X(this.rate,Hn(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,_e(n,be(on(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Tw.className="MinMaxNorm",me(Tw);const ZA={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function an(e){return yw(e)}function QA(e,t={}){return Ch(e,Fs.getMap().classNameMap,t,"constraint")}function cn(e){if(e==null)return null;if(typeof e=="string"){const t=e in ZA?ZA[e]:e,n={className:t,config:{}};return QA(n)}else return e instanceof Rh?e:QA(e)}function gz(e){return new Sw(e)}function yz(e){return new Iw(e)}function bz(){return new xw}function wz(e){return new Tw(e)}var Lz=Object.freeze({__pro
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),Ps(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,Cn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s<this.size();s++)e.push(s)}if(e.length===0)return en([],[0].concat(this.elementShape));const n=this.readMany(e);return Ps(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),rs(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return en([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const n=this.readMany(t);return Ps(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Pt(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,Ei(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-13 22:57:06 +02:00
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const i=n===0?0:t.size/n,o=[];ee(()=>{t=K(t,[1,n,i]);for(let c=0;c<e.length;++c){const h=c===0?0:s[c-1],d=[0,h,0],m=[1,e[c],i];o[c]=K(nt(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 Jh{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}`);Ps(t,i.shape,"TensorList shape mismatch: "),Cn(i)}),this.idTensor=Ne(0),this.maxNumElements=s,Cn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Jh([...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 Ps(e,this.elementShape,"TensorList shape mismatch: "),ee(()=>{const s=this.tensors.map(i=>K(i,e));return rs(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 Ps(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(Ps(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Cn(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 Ps(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.`);Ps(this.elementShape,t.shape,"TensorList shape mismatch: "),Cn(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 Ps(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?en([],[0].concat(this.elementShape)):ee(()=>{const s=e.map(i=>K(this.tensors[i],n));return rs(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Ps(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?en([],[0].concat(this.elementShape)):ee(()=>{const n=this.tensors.map(s=>K(s,t));return Pt(n,0)})}}function $Y(e,t,n){const s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);const i=e.s
2020-10-11 18:41:17 +02:00
tensor.shape[0], but sum of lengths is
2020-10-13 22:57:06 +02:00
${s}, and tensor's shape is: ${e.shape}`);const o=s===0?0:e.size/s,a=ee(()=>{const h=[];e=K(e,[1,s,o]);for(let d=0;d<t.length;++d){const m=d===0?0:i[d-1],y=[0,m,0],b=[1,t[d],o];h[d]=K(nt(e,y,b),n)}return e.dispose(),h}),c=new Jh([],n,e.dtype,t.length);for(let h=0;h<a.length;h++)c.setItem(h,a[h]);return c}const PY=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 y=d.map(w=>w.id);m.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&y.indexOf(w.id)===-1&&w.dispose()});const b=await n.functionMap[i].executeFunctionAsync(d,n.tensorArrayMap,n.tensorListMap);h=await b[0].data(),b.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&y.indexOf(w.id)===-1&&w.dispose()})}return d}case"LoopCond":{const s=R("pred",e,t,n);return[or(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=or(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>Jn(i,t,n)!==void 0);if(s){const i=Jn(s,t,n);return[or(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[or(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[or(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[or(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 WY(d,i,s,o,h,a,c);return n.addTensorArray(m),[m.idTensor,Ne(1)]}case"TensorArrayWriteV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.write(i,o),[a.idTensor]}case"TensorArrayReadV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=n.getTensorArray(s.id);return[o.read(i)]}case"TensorArrayGatherV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("dtype",e,t,n),a=n.getTensorArray(s.id);return[a.gather(i,o)]}case"TensorArrayScatterV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.scatter(i,o),[a.idTensor]}case"TensorArrayConcatV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id),o=R("dtype",e,t,n);return[i.concat(o)]}case"TensorArraySplitV3":{const s=R("tensorArrayId",e,t,n),i=R("tensor",e,t,n),o=R("lengths",e,t,n),a=n.getTensorArray(s.id);return a.split(o,i),[a.idTensor]}case"TensorArraySizeV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return[Ne(i.size(),"int32")]}case"TensorArrayCloseV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorList(s.id);return a.setItem(i,o),[a.idTensor]}case"TensorListGetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.getItem(i,o,a)]}case"TensorListScatterV2":case"TensorListScatter":{const s=R("indices",e,t,n),i=R("tensor",e,t,n),o=R("elementShape",e,t,n),a=R("numElements",e,t,n),c=BY(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=UY(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),cs(async()=>(await n.iterator()).columnMajorBatch(e,t,RH),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,cs(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,cs(async()=>(await t.iterator()).filter(s=>ee(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return cs(async()=>(await t.iterator()).map(n=>ee(()=>e(n))),this.size)}mapAsync(e){const t=this;return cs(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 cs(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,cs(async()=>{const s=Zh(async()=>({value:await t.iterator(),done:!1}));return VN(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,cs(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=Ba(t||Yn().toString());return cs(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,cs(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()}}nc.MAX_BUFFER_SIZE=1e4;function cs(e,t=null){return new class extends nc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function NH(e){return cs(async()=>GN(e),e.length)}function CH(e){if(!tc(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 cs(async()=>{const n=await PN(e,s=>{if(s instanceof nc)return{value:s.iterator(),recurse:!1};if(tc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return mH(n,Hr.SHORTEST)},t)}function RH(e){if(e===null)return null;const t=e[0];if(hH(t)){const n=OH(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function OH(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Q?rs(e):en(e)}class jN extends nc{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 nm='"',Qh=Symbol("out"),KN=Symbol("field"),sm=Symbol("quote"),dS=Symbol("quoteafterquote"),XN=Symbol("quoteinquote");class JN extends nc{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 jN(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(k(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&k(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((s,i)=>(s[i]=s[i]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(k(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs)for(const s of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(s);if(i===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value,s=this.parseRow(n,!1);return s}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),n={},s={};for(let i=0;i<this.fullColumnNames.length;i++){const o=this.fullColumnNames[i],a=this.columnConfigs?this.columnConfigs[o]:null;if(this.configuredColumnsOnly&&!a)continue;{const c=t[i];let 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=Qh;for(let a=0;a<i;a++)switch(o){case Qh:switch(e.charAt(a)){case nm:s=a+1,o=sm;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=Qh;break;default:o=KN,s=a;break}break;case KN:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=Qh,s=a+1;break;default:}break;case sm:switch(e.charAt(a)){case nm:o=dS;break;default:}break;case dS:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=Qh,s=a+1;break;case nm:o=sm;break;default:o=XN;break}break;case XN:switch(e.charAt(a)){case nm:o=sm;break;default:}break;default:}if(o===dS?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 ZN extends fn{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-13 22:57:06 +02:00
============================`));const s={};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){const s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,n,s){this.data.set(e,{values:t,dtype:s,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){const s=this.readSync(n.real.dataId),i=this.readSync(n.imag.dataId);return er(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=>zl(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ze(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return _s().makeTensorFromDataId(s,t,n,this)}disposeData(e){if(this.data.has(e)){const{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.data.has(t)){const n=this.data.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}async time(e){const t=Yn();e();const n=Yn()-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){xe(e,"stridedSlice");const i=Cd(t,n,s);if(i.some(c=>c===0))return en([],i);const o=Ze(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=Ze([e.size,e.size],e.dtype),s=n.values;for(let i=0;i<t.length;i++)s[i*e.size+i]=t[i];return n.toTensor()}unstack(e,t){const n=e.shape[t],s=new Array(e.rank-1);let i=0;for(let h=0;h<e.rank;h++)h!==t&&(s[i++]=e.shape[h]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let h=0;h<c.length;h++)o[t]=h,c[h]=nt(e,o,a).reshape(s);return c}reverse(e,t){xe(e,"reverse");const n=Ze(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 xe(e,"neg"),X(Ne(-1),e)}addN(e){xe(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),n=Ze(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=gt([t],e.shape),s=jn(e,n),i=On(s.shape,n),o=Ce(e,s.reshape(i)),a=Ls(o),c=this.sum(a,n).reshape(i);return _e(a,c)}pow(e,t){return xe([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.pow(n,s))}batchMatMul(e,t,n,s){xe([e,t],"matMul");const i=n?e.shape[1]:e.shape[2],o=n?e.shape[2]:e.shape[1],a=s?t.shape[1]:t.shape[2],c=e.shape[0],h=this.readSync(e.dataId),d=this.readSync(t.dataId),[m,y,b]=n?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],[w,L,T]=s?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],A=o*a,N=Ze([c,o,a],e.dtype),E=N.values,D=this.blockSize;for(let F=0;F<c;F++)for(let _=0;_<o;_+=D)for(let B=0;B<a;B+=D)for(let $=0;$<i;$+=D){const H=Math.min(_+D,o),q=Math.min(B+D,a),J=Math.min($+D,i);for(let re=_;re<H;re++)for(let ce=B;ce<q;ce++){let ue=0;for(let he=$;he<J;he++)ue+=h[F*m+re*y+he*b]*d[he*w+ce*L+F*T];E[F*A+(re*a+ce)]+=ue}}return N.toTensor()}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){let c=this.batchMatMul(e,t,n,s);return i&&(c=be(c,i)),o&&(c=pS(this,c,o,a)),c}floorDiv(e,t){xe([e,t],"floorDiv");const n=(i,o)=>Math.floor(i/o),s="int32";return this.broadcastedBinaryOp(e,t,s,n)}sum(e,t){xe(e,"sum"),ts("sum",t,e.rank);const[n,s]=Rn(e.shape,t),i=Nn(e.dtype,"int32"),o=ct(n,i),a=we(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let y=0;for(let b=0;b<a;++b)y+=h[m+b];c[d]
`),o=i.length.toString().length+2,a=i.map((y,b)=>go((b+1).toString(),o)+y);let c=0;for(let y=0;y<a.length;y++)c=Math.max(a[y].length,c);const h=a.slice(0,s-1),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-13 22:57:06 +02:00
`)[0]),console.log(`%c ${go(d[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
`))}function zj(e){return ar(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function Gj(e,t){if(Re(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function IS(e,t){if(Re(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Vj(e,t){const n=ar(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Re(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Yj(e,t){const n=ar(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Re(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Re(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function pee(){return C().getNumber("WEBGL_VERSION")===2?1:4}function Hj(e){return ar(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function qj(e,t){const n=C().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const s=`[${e}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(e>n||t>n){const s=`[${e}x${t}]`,i=`[${n}x${n}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+i+".")}}function jj(e){return ar(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function C0(e,t,n,s,i,o,a){const c=e.getAttribLocation(t,n);return c===-1?!1:(Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Re(e,()=>e.vertexAttribPointer(c,i,e.FLOAT,!1,o,a)),Re(e,()=>e.enableVertexAttribArray(c)),!0)}function Kj(e,t,n){O0(e,n),Re(e,()=>e.activeTexture(e.TEXTURE0+n)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function mee(e,t){O0(e,t),Re(e,()=>e.activeTexture(e.TEXTURE0+t)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Xj(e,t,n){return ar(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function Jj(e,t,n){return e.getUniformLocation(t,n)}function Zj(e,t,n,s){Re(e,()=>Kj(e,t,s)),Re(e,()=>e.uniform1i(n,s))}function fee(e){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Re(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Re(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function xS(e,t,n){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Re(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function R0(e,t){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Re(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function om(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Qj(e,t))}function Qj(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 ar(e,t,n){const s=Re(e,()=>t());if(s==null)throw new Error(n);return s}function O0(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 cc(e,t=2){return we(e.slice(0,e.length-t))}function lc(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 TS(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[cc(e),...lc(e)]),t}function eK(e,t=!1){let n=C().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?Oy(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=Ir(e);e=i.newShape}let s=we(e);if(e.length<=1&&s<=n)return[1,s];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e
2020-10-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-13 22:57:06 +02:00
`}}class IK{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-13 22:57:06 +02:00
`}}class xK{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-13 22:57:06 +02:00
`}}function k0(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function ls(e,t){return t===1?[e]:k0(e,t)}function TK(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 Wn(){let e,t,n,s,i,o,a,c,h,d;return C().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",i="texture",o="outputColor",a="out vec4 outputColor;",c=`
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-13 22:57:06 +02:00
`),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:i,output:o,defineOutput:a,defineSpecialNaN:c,defineSpecialInf:h,defineRound:d}}function Ho(e,t,n="index"){const s=Ot(t);return s.map((i,o)=>{const a=`int ${e[o]} = ${n} / ${i}`,c=o===s.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${i}`:`index -= ${e[o]} * ${i}`;return`${a}; ${c};`}).join("")}function um(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function bee(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(`${um(a)}, ${um(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(`${um(o)}, ${um(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function vS(e){const t=Ot(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-13 22:57:06 +02:00
`}const F0=`
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-13 22:57:06 +02:00
`;const{getBroadcastDims:_0}=pw;function AK(e,t,n,s){const i=[];e.forEach(L=>{const T=we(L.shapeInfo.logicalShape);L.shapeInfo.isUniform?i.push(`uniform float ${L.name}${T>1?`[${T}]`:""};`):(i.push(`uniform sampler2D ${L.name};`),i.push(`uniform int offset${L.name};`))});const o=i.join(`
`),a=e.map(L=>vK(L,t,s)).join(`
`),c=t.texShape,h=Wn(),d=RK(h);let m,y,b=DK(h);t.isPacked?(m=NK(t.logicalShape,c),y=EK(h)):(m=CK(t.logicalShape,c),y=OK(h)),s&&(b+=WK);const w=[b,d,y,o,m,a,n].join(`
`);return w}function hc(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return jK(e);case 1:return XK(e);case 2:return ZK(e);case 3:return e5(e);case 4:return n5(e);case 5:return s5(e);case 6:return i5(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function W0(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return qK(e);case 1:return KK(e);case 2:return JK(e);case 3:return QK(e);default:return t5(e)}}function vK(e,t,n=!1){let s="";n?s+=W0(e):s+=hc(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=r5(e,t):s+=o5(e,t)),s}function NK(e,t){switch(e.length){case 0:return $0();case 1:return $K(e,t);case 2:return YK(e,t);case 3:return BK(e,t);default:return PK(e,t)}}function CK(e,t){switch(e.length){case 0:return $0();case 1:return UK(e,t);case 2:return HK(e,t);case 3:return MK(e,t);case 4:return zK(e,t);case 5:return GK(e,t);case 6:return VK(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function RK(e){return`
2020-10-11 18:41:17 +02:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
2020-10-13 22:57:06 +02:00
`}function OK(e){return`
2020-10-11 18:41:17 +02:00
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
2020-10-13 22:57:06 +02:00
`}function EK(e){return`
2020-10-11 18:41:17 +02:00
void setOutput(vec4 val) {
${e.output} = val;
}
2020-10-13 22:57:06 +02:00
`}function DK(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-13 22:57:06 +02:00
${kK}
${FK}
${_K}
`;return t}const kK=`
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-13 22:57:06 +02:00
`,FK=`
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-13 22:57:06 +02:00
`,_K=`
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-13 22:57:06 +02:00
`,WK=`
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-13 22:57:06 +02:00
`;function $0(){return`
2020-10-11 18:41:17 +02:00
int getOutputCoords() {
return 0;
}
2020-10-13 22:57:06 +02:00
`}function $K(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-13 22:57:06 +02:00
`}function UK(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-13 22:57:06 +02:00
`}function BK(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-13 22:57:06 +02:00
`}function MK(e,t){const n=Ho(["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-13 22:57:06 +02:00
`}function PK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),i=s*Math.ceil(e[e.length-2]/2);let o=i,a="",c="b, r, c";for(let h=2;h<e.length-1;h++)o*=e[e.length-h-1],a=`
int b${h} = index / ${o};
index -= b${h} * ${o};
`+a,c=`b${h}, `+c;return`
2020-10-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-13 22:57:06 +02:00
`}function zK(e,t){const n=Ho(["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-13 22:57:06 +02:00
`}function GK(e,t){const n=Ho(["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-13 22:57:06 +02:00
`}function VK(e,t){const n=Ho(["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-13 22:57:06 +02:00
`}function YK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ot(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-13 22:57:06 +02:00
`}function HK(e,t){return ot(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-13 22:57:06 +02:00
`}function qo(e){return`offset${e}`}function qK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Wn();return`
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`}function jK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${t};}`;const[s,i]=e.shapeInfo.texShape;if(s===1&&i===1)return`
float ${n}() {
2020-10-11 18:41:17 +02:00
return sampleTexture(${t}, halfCR);
}
2020-10-13 22:57:06 +02:00
`;const[o,a]=e.shapeInfo.texShape,c=qo(t);return`
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
2020-10-11 18:41:17 +02:00
return sampleTexture(${t}, uv);
}
2020-10-13 22:57:06 +02:00
`}function KK(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=Wn();return`
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-13 22:57:06 +02:00
`}function XK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${n}(int index) {
${uc(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-13 22:57:06 +02:00
`;const a=qo(t);return o===1?`
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-13 22:57:06 +02:00
`}function JK(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=Wn();if(i!=null&&ot(t,i))return`
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-13 22:57:06 +02:00
`}function ZK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(i!=null&&ot(t,i)){const y=i[0],b=i[1];return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`}const{newShape:o,keptDims:a}=Ir(t),c=o;if(c.length<t.length){const y=dc(e,c),b=["row","col"];return`
${hc(y)}
float ${s}(int row, int col) {
return ${s}(${pc(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-13 22:57:06 +02:00
${uc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const h=i[0],d=i[1],m=qo(n);return d===1?`
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-13 22:57:06 +02:00
`}function QK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const y=t.slice(1),b=[1,2],w=dc(e,y),L=["b","row","col"];return`
${W0(w)}
vec4 ${s}(int b, int row, int col) {
return ${s}(${pc(L,b)});
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`}const a=o[0],c=o[1],h=Math.ceil(t[2]/2),d=h*Math.ceil(t[1]/2),m=Wn();return`
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-13 22:57:06 +02:00
`}function e5(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}=Ir(t),h=a;if(h.length<t.length){const L=dc(e,h),T=["row","col","depth"];return`
${hc(L)}
float ${s}(int row, int col, int depth) {
return ${s}(${pc(T,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)));
${uc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const d=e.shapeInfo.texShape,m=d[0],y=d[1],b=e.shapeInfo.flatOffset;if(y===i&&b==null)return`
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-13 22:57:06 +02:00
vec2(${y}.0, ${m}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;if(y===o&&b==null)return`
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-13 22:57:06 +02:00
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${y}.0, ${m}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const w=qo(n);return`
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};
vec2 uv = uvFromFlat(${m}, ${y}, index);
return sampleTexture(${n}, uv);
}
`}function t5(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),y="int b, int row, int col",b=`b * ${m} + (row / 2) * ${d} + (col / 2)`;for(let L=2;L<n-1;L++)y=`int b${L}, `+y,m*=t[n-L-1],b=`b${L} * ${m} + `+b;const w=Wn();return`
vec4 ${i}(${y}) {
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-13 22:57:06 +02:00
`}function n5(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}=Ir(t);if(c.length<t.length){const L=dc(e,c),T=["row","col","depth","depth2"];return`
${hc(L)}
float ${s}(int row, int col, int depth, int depth2) {
return ${s}(${pc(T,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)));
${uc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const d=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,y=m[0],b=m[1];if(b===a&&d==null)return`
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-13 22:57:06 +02:00
vec2(${b}.0, ${y}.0);
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-13 22:57:06 +02:00
vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const w=qo(n);return`
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-13 22:57:06 +02:00
vec2 uv = uvFromFlat(${y}, ${b}, index + ${w});
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`}function s5(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}=Ir(t);if(h.length<t.length){const T=dc(e,h),A=["row","col","depth","depth2","depth3"];return`
${hc(T)}
float ${s}(int row, int col, int depth, int depth2, int depth3) {
return ${s}(${pc(A,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-13 22:57:06 +02:00
${uc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const m=e.shapeInfo.flatOffset,y=e.shapeInfo.texShape,b=y[0],w=y[1];if(w===c&&m==null)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
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-13 22:57:06 +02:00
`;const L=qo(n);return`
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-13 22:57:06 +02:00
`}function i5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=Ir(t);if(i.length<t.length){const A=dc(e,i),N=["row","col","depth","depth2","depth3","depth4"];return`
${hc(A)}
float ${s}(int row, int col, int depth,
2020-10-11 18:41:17 +02:00
int depth2, int depth3, int depth4) {
2020-10-13 22:57:06 +02:00
return ${s}(${pc(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)));
${uc(e)}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`;const y=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],L=b[1];if(L===m&&y==null)return`
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-13 22:57:06 +02:00
`;if(L===a&&y==null)return`
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-13 22:57:06 +02:00
`;const T=qo(n);return`
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} +
depth2 * ${c} + depth3 * ${a} + depth4 + ${T};
vec2 uv = uvFromFlat(${w}, ${L}, index);
return sampleTexture(${n}, uv);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`}function uc(e){const t=e.name,n=we(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
for (int i = 0; i < ${n}; i++) {
2020-10-11 18:41:17 +02:00
if (i == index) {
return ${t}[i];
}
}
2020-10-13 22:57:06 +02:00
`}function r5(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=_0(e.shapeInfo.logicalShape,t.logicalShape),h=Et(a),d=a-o;let m;const y=["x","y","z","w","u","v"];o===0?m="":a<2&&c.length>=1?m="coords = 0;":m=c.map(E=>`coords.${y[E+d]} = 0;`).join(`
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((E,D)=>`coords.${y[D+d]}`).join(", ");let w="return outputValue;";const L=we(e.shapeInfo.logicalShape),T=L===1,A=we(t.logicalShape),N=A===1;if(o===1&&!T&&!N)w=`
2020-10-11 18:41:17 +02:00
return vec4(outputValue.xy, outputValue.xy);
2020-10-13 22:57:06 +02:00
`;else if(T&&!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-13 22:57:06 +02:00
`;else if(c.length){const E=o-2,D=o-1;c.indexOf(E)>-1&&c.indexOf(D)>-1?w="return vec4(outputValue.x);":c.indexOf(E)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(D)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
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-13 22:57:06 +02:00
`}function o5(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&&ot(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-13 22:57:06 +02:00
`;const d=Et(h),m=_0(e.shapeInfo.logicalShape,t.logicalShape),y=h-c;let b;const w=["x","y","z","w","u","v"];c===0?b="":h<2&&m.length>=1?b="coords = 0;":b=m.map(T=>`coords.${w[T+y]} = 0;`).join(`
`);let L="";return h<2&&c>0?L="coords":L=e.shapeInfo.logicalShape.map((T,A)=>`coords.${w[A+y]}`).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-13 22:57:06 +02:00
`}function Et(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function dc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function pc(e,t){return t.map(n=>e[n]).join(", ")}class a5{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],o=Math.ceil(i/t);this.outputShape=e.slice(0,-1),o>1&&this.outputShape.push(o),s||this.variableNames.push("bestIndicesA");const a=this.outputShape,c=a.length,h=Et(c),d=ls("coords",c);let m,y;if(o===1){y=c+1;const $=Et(y);m=`
${$} 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);
--${d[c-2]};`}else y=c,m=`
${h} sourceLocR = coords;
++${d[c-1]};
${h} sourceLocG = coords;
++${d[c-2]};
${h} sourceLocA = coords;
--${d[c-1]};
${h} sourceLocB = coords;
--${d[c-2]};`;const b=["x","y","z","w","u","v"].slice(0,y),w="."+b[y-1],L=b.map($=>"int "+$),T=ls("sourceLocR",y-1).concat("inIdx.r"),A=ls("sourceLocG",y-1).concat("inIdx.g"),N=ls("sourceLocB",y-1).concat("inIdx.b"),E=ls("sourceLocA",y-1).concat("inIdx.a"),D=n==="max"?"greaterThan":"lessThan",F=s?"":`
inIdx = round(vec4(getBestIndicesAChannel(${T.join()}),
getBestIndicesAChannel(${A.join()}),
getBestIndicesAChannel(${N.join()}),
getBestIndicesAChannel(${E.join()})));`,_=`vec4(
getAChannel(${T.join()}),
hasNextCol ? getAChannel(${A.join()}) : 0.,
hasNextRow ? getAChannel(${N.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${E.join()}) : 0.)`,B=s?"":`
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()}));
}
${B}
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-13 22:57:06 +02:00
vec4 bestValue = ${_};
2020-10-11 18:41:17 +02:00
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
2020-10-13 22:57:06 +02:00
${F}
vec4 candidate = ${_};
2020-10-11 18:41:17 +02:00
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
2020-10-13 22:57:06 +02:00
vec4(${D}(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-13 22:57:06 +02:00
`}}class c5{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,y=1/(t*n);this.userCode=`
const ivec2 pads = ivec2(${d}, ${m});
const float avgMultiplier = float(${y});
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-13 22:57:06 +02:00
`}}class l5{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,y=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,L=y-1-e.padInfo.top,T=b-1-e.padInfo.left,A=1/(t*n*s);this.userCode=`
const ivec3 pads = ivec3(${w}, ${L}, ${T});
const float avgMultiplier = float(${A});
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-13 22:57:06 +02:00
for (int wR = 0; wR < ${y};
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-13 22:57:06 +02:00
`}}const U0={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class B0{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=tt(t,n),this.userCode=`
2020-10-11 18:41:17 +02:00
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
2020-10-13 22:57:06 +02:00
`}}const M0=`
2020-10-11 18:41:17 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-13 22:57:06 +02:00
`,NS="return a + b;",CS="return a - b;",P0="return a * b;",h5=`
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-13 22:57:06 +02:00
`,u5=`
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-13 22:57:06 +02:00
`,wee="return (a - b) * (a - b);",d5="return float(a == b);",p5="return float(a != b);",m5="return float(a < b);",f5="return float(a <= b);",g5="return float(a > b);",y5="return float(a >= b);",b5="return float(a >= 1.0 && b >= 1.0);",w5="return float(a >= 1.0 || b >= 1.0);",L5=M0+`
2020-10-11 18:41:17 +02:00
return max(a, b);
2020-10-13 22:57:06 +02:00
`,S5=M0+`
2020-10-11 18:41:17 +02:00
return min(a, b);
2020-10-13 22:57:06 +02:00
`,I5=`if (b == 0.0) return NAN;
return mod(a, b);`,x5="return (b >= 1.0) ? a : a * (b + 1.0);",z0="return (a < 0.) ? b * a : a;";class ln{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=tt(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-13 22:57:06 +02:00
`}}const dm=`
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-13 22:57:06 +02:00
`,T5=`
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-13 22:57:06 +02:00
`,A5=`
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-13 22:57:06 +02:00
`+dm+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-13 22:57:06 +02:00
`,G0=`
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-13 22:57:06 +02:00
`,v5=`
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-13 22:57:06 +02:00
`,N5=`
2020-10-11 18:41:17 +02:00
return vec4(equal(a, b));
2020-10-13 22:57:06 +02:00
`,C5=`
2020-10-11 18:41:17 +02:00
return vec4(notEqual(a, b));
2020-10-13 22:57:06 +02:00
`,R5=`
2020-10-11 18:41:17 +02:00
return vec4(lessThan(a, b));
2020-10-13 22:57:06 +02:00
`,O5=`
2020-10-11 18:41:17 +02:00
return vec4(lessThanEqual(a, b));
2020-10-13 22:57:06 +02:00
`,E5=`
2020-10-11 18:41:17 +02:00
return vec4(greaterThan(a, b));
2020-10-13 22:57:06 +02:00
`,D5=`
2020-10-11 18:41:17 +02:00
return vec4(greaterThanEqual(a, b));
2020-10-13 22:57:06 +02:00
`,k5=`
2020-10-11 18:41:17 +02:00
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
2020-10-13 22:57:06 +02:00
`,F5=`
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-13 22:57:06 +02:00
`,_5=`
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-13 22:57:06 +02:00
`+dm+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-13 22:57:06 +02:00
`,W5=`
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-13 22:57:06 +02:00
`+dm+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-13 22:57:06 +02:00
`,$5=`
2020-10-11 18:41:17 +02:00
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
2020-10-13 22:57:06 +02:00
`+dm+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-13 22:57:06 +02:00
`;class jr{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=tt(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||we(this.outputShape)===1)o=`
2020-10-11 18:41:17 +02:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
2020-10-13 22:57:06 +02:00
`;else{const a=Et(i);if(o=`
${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-13 22:57:06 +02:00
`;else{const c=ls("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-13 22:57:06 +02:00
`}}class U5{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-13 22:57:06 +02: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 B5{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-13 22:57:06 +02: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 M5{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-13 22:57:06 +02:00
`}}class P5{constructor(e){this.outputShape=[],this.outputShape=Er(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=`
2020-10-11 18:41:17 +02:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
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
`}}class z5{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Er(e,t);const n=this.outputShape,s=n.length,i=Et(s),o=ls("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((L,T)=>`T${T}`);const c=new Array(e.length-1);c[0]=e[0][t];for(let L=1;L<c.length;L++)c[L]=c[L-1]+e[L][t];const h=a[t],d=a.slice(-2),m=a.join();let y=`if (${h} < ${c[0]}) {
2020-10-11 18:41:17 +02:00
return getChannel(
2020-10-13 22:57:06 +02:00
getT0(${m}), vec2(${d.join()}));
}`;for(let L=1;L<c.length;L++){const T=c[L-1];y+=`
if (${h} < ${c[L]} && ${h} >= ${c[L-1]}) {
2020-10-11 18:41:17 +02:00
return getChannel(
2020-10-13 22:57:06 +02:00
getT${L}(${pm(a,h,T)}),
vec2(${pm(d,h,T)}));
}`}const b=c.length,w=c[c.length-1];y+=`
2020-10-11 18:41:17 +02:00
return getChannel(
2020-10-13 22:57:06 +02:00
getT${b}(${pm(a,h,w)}),
vec2(${pm(d,h,w)}));`,this.userCode=`
float getValue(${a.map(L=>"int "+L)}) {
${y}
2020-10-11 18:41:17 +02:00
}
void main() {
${i} coords = getOutputCoords();
2020-10-13 22:57:06 +02:00
vec4 result = vec4(getValue(${o}), 0., 0., 0.);
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
${o[s-1]} = ${o[s-1]} + 1;
if (${o[s-1]} < ${n[s-1]}) {
result.g = getValue(${o});
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
${o[s-2]} = ${o[s-2]} + 1;
if (${o[s-2]} < ${n[s-2]}) {
result.a = getValue(${o});
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
${o[s-1]} = ${o[s-1]} - 1;
if (${o[s-2]} < ${n[s-2]} &&
${o[s-1]} < ${n[s-1]}) {
result.b = getValue(${o});
2020-10-11 18:41:17 +02:00
}
setOutput(result);
}
2020-10-13 22:57:06 +02:00
`}}function pm(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}class G5{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-13 22:57:06 +02:00
`}}class V5{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=`
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-13 22:57:06 +02:00
`}}class Y5{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-13 22:57:06 +02:00
`}}class H5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=t-1-e.padInfo.front,h=n-1-e.padInfo.top,d=s-1-e.padInfo.left;this.userCode=`
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-13 22:57:06 +02:00
`}}class q5{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-13 22:57:06 +02:00
`}}class j5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.top,a=n-1-e.padInfo.left,c=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
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-13 22:57:06 +02:00
`}}class V0{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,y=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,L=e.dataFormat==="channelsLast",T=L?1:2,A=L?2:3,N=L?3:1;let E="",D="";n&&(s?E=`float activation(float a) {
2020-10-11 18:41:17 +02:00
float b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
}`:E=`
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-13 22:57:06 +02:00
`,D="result = activation(result);");const F=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${E}
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-13 22:57:06 +02:00
ivec2(coords[${T}], coords[${A}]) * 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-13 22:57:06 +02:00
for (int wC = 0; wC < ${y}; 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 < ${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-13 22:57:06 +02:00
${F}
${D}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-13 22:57:06 +02:00
`}}class K5{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,y=e.filterHeight,b=e.filterWidth,w=Math.floor(e.inChannels/4)*4,L=e.inChannels%4;this.userCode=`
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-13 22:57:06 +02:00
for (int wR = 0; wR < ${y}; wR++) {
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-13 22:57:06 +02:00
`}}class Y0{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,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=e.outChannels/e.inChannels;let T="",A="";n&&(s?T=`float activation(float a) {
2020-10-11 18:41:17 +02:00
float b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
}`:T=`
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-13 22:57:06 +02:00
`,A="result = activation(result);");const N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${T}
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++) {
int xC = xCCorner + wC * ${y};
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}
${A}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-13 22:57:06 +02:00
`}}class H0{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,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=w;let T="int xR; int xC; int xCOffset;";for(let D=0;D<b;D++)for(let F=0;F<w;F++)T+=`
vec4 xTexelR${D}C${F*2} = vec4(0.);
vec4 wR${D}C${F} = vec4(0.);
vec4 xR${D}C${F} = vec4(0.);`;for(let D=0;D<b;D++)for(let F=0;F<L;F++){const _=F*2;if(T+=`
xR = xRCorner + ${D*m};
xC = xCCorner + ${_*y};
`,d===1){if(_<w&&(c%2===1?T+=`
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}) {
xTexelR${D}C${_} = 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}) {
xTexelR${D}C${_}.zw = vec2(0.);
2020-10-11 18:41:17 +02:00
}
} else {
2020-10-13 22:57:06 +02:00
xTexelR${D}C${_} = 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-13 22:57:06 +02:00
xR${D}C${_} = vec4(previous.zw, xTexelR${D}C${_}.xy);
2020-10-11 18:41:17 +02:00
} else {
2020-10-13 22:57:06 +02:00
xR${D}C${_} = vec4(0, 0, xTexelR${D}C${_}.xy);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`:T+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xC, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-13 22:57:06 +02:00
xTexelR${D}C${_} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
xR${D}C${_} = xTexelR${D}C${_};
`,_+1<w)){const B=c%2===0?Oy(y):y;y%2===0&&c%2===1||y%2!==0&&c%2!==1?(T+=`
xCOffset = xC + ${c%2} + ${B};
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}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`,y>1&&(T+=`
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}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-13 22:57:06 +02:00
xTexelR${D}C${_} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`),T+=`
xR${D}C${_+1} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.xy);
`):T+=`
xCOffset = xC + ${B};
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}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
xR${D}C${_+1} = xTexelR${D}C${_+2};
`}}else _<w&&(T+=`
2020-10-11 18:41:17 +02:00
if(xR >= 0 && xR < ${i}) {
2020-10-13 22:57:06 +02:00
`,c%2===1?(T+=`
xCOffset = xC + 1 - ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-13 22:57:06 +02:00
xTexelR${D}C${_} = 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}) {
xTexelR${D}C${_+2} = getX(batch, xR, xC + 1, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-13 22:57:06 +02:00
xTexelR${D}C${_+2} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
xR${D}C${_} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.zw);
`,_+1<w&&(T+=`
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-13 22:57:06 +02:00
xR${D}C${_+1} = vec4(xTexelR${D}C${_+2}.xy, final.xy);
`)):(T+=`
if(xC >= 0 && xC < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xC, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-13 22:57:06 +02:00
xTexelR${D}C${_} = 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}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
2020-10-11 18:41:17 +02:00
} else {
2020-10-13 22:57:06 +02:00
xTexelR${D}C${_+2} = vec4(0.);
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
xR${D}C${_} = vec4(
xTexelR${D}C${_}.xy, xTexelR${D}C${_+2}.xy);
`,_+1<w&&(T+=`
xR${D}C${_+1} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.zw);
`)),T+="}");_<w&&(T+=`
vec4 wTexelR${D}C${_} = getW(${D}, ${_}, d1, q);
wR${D}C${_} = vec4(wTexelR${D}C${_}.xz, wTexelR${D}C${_}.xz);
`,_+1<w&&(T+=`
vec4 wTexelR${D}C${_+1} = getW(${D}, ${_+1}, d1, q);
wR${D}C${_+1} =
vec4(wTexelR${D}C${_+1}.xz, wTexelR${D}C${_+1}.xz);`))}for(let D=0;D<b;D++)for(let F=0;F<w;F++)T+=`dotProd += xR${D}C${F} * wR${D}C${F};`;let A="",N="";n&&(s?A=`vec4 activation(vec4 a) {
2020-10-11 18:41:17 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${n}
}`:A=`vec4 activation(vec4 x) {
${n}
}`,N="result = activation(result);");const E=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${A}
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-13 22:57:06 +02:00
${T}
2020-10-11 18:41:17 +02:00
vec4 result = dotProd;
2020-10-13 22:57:06 +02:00
${E}
${N}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-13 22:57:06 +02:00
`}}class X5{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,h]=e,[d]=t,[m,y]=n;this.outputShape=[d,m,y,h];const b=s==="bilinear"?1:0,[w,L]=[`${a-1}.0`,`${c-1}.0`],[T,A,N]=m>1?[`${(a-1)/(m-1)}`,"(y2-y1) * height_ratio",`y1*${w} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${w}`],[E,D,F]=y>1?[`${(c-1)/(y-1)}`,"(x2-x1) * width_ratio",`x1*${L} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${L}`];this.userCode=`
const float height_ratio = float(${T});
const float width_ratio = float(${E});
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-13 22:57:06 +02:00
float height_scale = ${A};
float width_scale = ${D};
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-13 22:57:06 +02:00
float in_x = ${F};
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-13 22:57:06 +02:00
`}}class q0{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${j0(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-13 22:57:06 +02:00
${Et(s)} coords = getOutputCoords();
int end = ${K0(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};
${K0(s,"coords")} = idx;
val += getX(${j0(s,"coords")});
2020-10-11 18:41:17 +02:00
}
setOutput(val);
}
2020-10-13 22:57:06 +02:00
`}getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}}function j0(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 K0(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 J5{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=su.DENSE;const t=ru(e),n=Wn();this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-13 22:57:06 +02:00
${Ho(["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-13 22:57:06 +02:00
`}}class Z5{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=su.DENSE;const t=ru(e),n=Wn();this.outputShape=e,this.userCode=`
2020-10-11 18:41:17 +02:00
ivec3 outCoordsFromFlatIndex(int index) {
2020-10-13 22:57:06 +02:00
${Ho(["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-13 22:57:06 +02:00
`}}class Q5{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-13 22:57:06 +02:00
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}class e8{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-13 22:57:06 +02:00
`}}class t8{constructor(e){this.variableNames=["A"],this.outTexUsage=As.DOWNLOAD;const t=Wn();this.outputShape=e,this.userCode=`
${F0}
2020-10-11 18:41:17 +02:00
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
2020-10-13 22:57:06 +02:00
`}}class n8{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=As.DOWNLOAD;const t=Wn();this.outputShape=e,this.userCode=`
${F0}
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-13 22:57:06 +02:00
`}}class s8{constructor(e,t,n=!1){this.variableNames=["A"];const s=Wn(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
${vS(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-13 22:57:06 +02:00
`}}class i8{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Wn(),[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-13 22:57:06 +02:00
${vS(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-13 22:57:06 +02:00
`}}const X0={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"};class J0{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const i=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,o=n?`${s}.0`:"1.0";this.userCode=`
2020-10-11 18:41:17 +02:00
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${e}
}
float mulMatDFT(int batch, int index) {
2020-10-13 22:57:06 +02:00
float indexRatio = float(index) / float(${s});
2020-10-11 18:41:17 +02:00
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
2020-10-13 22:57:06 +02:00
for (int i = 0; i < ${s}; i++) {
2020-10-11 18:41:17 +02:00
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
2020-10-13 22:57:06 +02:00
unaryOpComplex(real, expR, imag, expI) / ${o};
2020-10-11 18:41:17 +02:00
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
2020-10-13 22:57:06 +02:00
`}}class r8{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-13 22:57:06 +02:00
`}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class o8{constructor(e,t,n){this.variableNames=["A","indices"];const s=e.slice();s[n]=t,this.outputShape=s,this.rank=s.length;const i=Et(this.rank),o=a8(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-13 22:57:06 +02:00
`}}function a8(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 c8{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=Et(t.length),i=Et(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${s} strides = ${s}(${this.strides});
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-13 22:57:06 +02:00
`}}function l8(e){const t=Wn(),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-13 22:57:06 +02:00
}`;return Uj(e,n)}function h8(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 Vj(e,t)}function u8(e){const t=new Uint16Array([0,1,2,2,1,3]);return Yj(e,t)}function au(e,t,n,s,i,o){qj(t,n);const a=Hj(e),c=e.TEXTURE_2D;return Re(e,()=>e.bindTexture(c,a)),Re(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Re(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Re(e,()=>e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)),Re(e,()=>e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)),Re(e,()=>e.texImage2D(c,0,s,t,n,0,i,o,null)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null)),a}function Z0(e){return e.internalFormatFloat}function d8(e,t,n,s){const[i,o]=iu(t,n);return au(e,i,o,Z0(s),s.textureFormatFloat,e.FLOAT)}function Q0(e){return e.internalFormatHalfFloat}function p8(e,t,n,s){const[i,o]=iu(t,n);return au(e,i,o,Q0(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function eC(e){return e.downloadTextureFormat}function m8(e,t,n,s){const[i,o]=iu(t,n);return au(e,i,o,eC(s),e.RGBA,e.UNSIGNED_BYTE)}function tC(e){return e.internalFormatPackedFloat}function f8(e,t,n,s){const[i,o]=ac(t,n);return au(e,i,o,tC(s),e.RGBA,e.FLOAT)}function nC(e){return e.internalFormatPackedHalfFloat}function g8(e,t,n,s){const[i,o]=ac(t,n);return au(e,i,o,nC(s),e.RGBA,s.textureTypeHalfFloat)}function y8(e,t,n){const s=0,i=3*4,o=3*4+2*4;Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=C0(e,t,"clipSpacePos",n,3,o,s);return a&&C0(e,t,"uv",n,2,o,i)}function b8(e,t,n,s,i,o){Re(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),Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,h,n,s,0,e.RGBA,c,a)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function w8(e,t,n){Re(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function L8(e,t,n,s){const i=e.createBuffer();Re(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const o=4,a=4,c=o*a*t*n;return Re(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,c,e.STREAM_READ)),Re(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Re(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function S8(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 I8(e,t,n,s){const[i,o]=iu(t,n),a=4,c=new Uint8Array(Ej(t*n,a));return Re(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function x8(e,t,n,s,i,o,a,c){const h=e,d=new Float32Array(Dj(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 T8(e,t,n){const s=new Float32Array(t*n*4);return Re(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}class A8{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=C().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Cj(t,e)):this.gl=Wi(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(C().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=rm(this.gl,i),zs(this.gl,o))this.textureHalfFloatExtension=rm(this.gl,o);else if(C().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),zs(this.gl,s))this.colorBufferHalfFloatExtension=rm(this.gl,s);else if(C().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",zs(this.gl,n))this.colorBufferFloatExtensi
blockIndex = rc.y + ${_};
pos = rc.x + ${F};
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-13 22:57:06 +02:00
if(d1 < ${t[E]} && d1 >= 0) {
2020-10-11 18:41:17 +02:00
ch = int(mod(float(pos), ${i}.));
2020-10-13 22:57:06 +02:00
if (${A}) {
2020-10-11 18:41:17 +02:00
innerDims = vec2(d1, ch);
2020-10-13 22:57:06 +02:00
result[${F*2+_}] = 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-13 22:57:06 +02:00
result[${F*2+_}] = 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-13 22:57:06 +02:00
${D}
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
${T.output} = result;
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`}}class E8{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-13 22:57:06 +02:00
`}}class D8{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-13 22:57:06 +02:00
`}}class k8{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-13 22:57:06 +02:00
`}}class F8{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=`
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-13 22:57:06 +02:00
`}}class _8{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,y=h-1-e.padInfo.top,b=d-1-e.padInfo.left,w=c*h*d-1;this.userCode=`
const ivec3 pads = ivec3(${m}, ${y}, ${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-13 22:57:06 +02:00
`}}class RS{constructor(e,t,n=!1,s=!1,i=!1,o=null,a=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;const c=n?e[1]:e[2],h=Math.ceil(c/2),d=n?"i * 2, rc.y":"rc.y, i * 2",m=s?"rc.z, i * 2":"i * 2, rc.z",y=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],b=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let w="",L="";o&&(a?w=`vec4 activation(vec4 a) {
2020-10-11 18:41:17 +02:00
vec4 b = getPreluActivationWeightsAtOutCoords();
2020-10-13 22:57:06 +02:00
${o}
}`:w=`vec4 activation(vec4 x) {
${o}
}`,L="result = activation(result);");const T=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${w}
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
const float sharedDimension = ${h}.0;
2020-10-11 18:41:17 +02:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
2020-10-13 22:57:06 +02:00
for (int i = 0; i < ${h}; i++) {
vec4 a = getMatrixA(rc.x, ${d});
vec4 b = getMatrixB(rc.x, ${m});
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-13 22:57:06 +02:00
result += (${y[0]} * ${b[0]});
result += (${y[1]} * ${b[1]});
2020-10-11 18:41:17 +02:00
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2020-10-13 22:57:06 +02:00
${T}
2020-10-11 18:41:17 +02:00
2020-10-13 22:57:06 +02:00
${L}
2020-10-11 18:41:17 +02:00
setOutput(result);
}
2020-10-13 22:57:06 +02:00
`}}class W8{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-13 22:57:06 +02:00
`}getCustomSetupFunc(e){return(t,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class $8{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-13 22:57:06 +02:00
`}}class U8{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-13 22:57:06 +02:00
`;else{const n=ls("rc",t),s=Et(t),i=M8(t,e,n),o=P8(t,e[e.length-1],e[e.length-2],n),a=z8(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-13 22:57:06 +02:00
`}}}function B8(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 M8(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 P8(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};
`}function z8(e,t){const n=e.length,s=B8(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]}),
rEdge || cEdge ? 0. : getA(${s[3]})`}class G8{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((h,d)=>h[0]+e[d]+h[1]);const s=e.length,i=Et(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=`
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-13 22:57:06 +02:00
`}}class V8{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((L,T)=>L[0]+e[T]+L[1]);const s=e.length,i=Et(s),o=t.map(L=>L[0]).join(","),a=t.map((L,T)=>L[0]+e[T]).join(","),c=ls("rc",s),h=ls("source",s),d=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,y=[`${i} rc = outputLoc;`,`${c[s-1]} += 1;
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;
if(${d}) {`],b=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let w="";for(let L=0,T=s===1?2:4;L<T;L++)w+=`
${y[L]}
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-13 22:57:06 +02:00
`}}class cu{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,d=e.dilationWidth,m=e.effectiveFilterHeight,y=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const L=t==="avg",T=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,A=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let N="0.0";if(L||(N="-1.0 / 1e-20"),n){const $=">=";this.userCode=`
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-13 22:57:06 +02:00
for (int wC = 0; wC < ${y};
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-13 22:57:06 +02:00
minMaxPosition = ${s?i?T:A:`wR * ${y} + wC`};
2020-10-11 18:41:17 +02:00
}
}
}
setOutput(float(minMaxPosition));
}
2020-10-13 22:57:06 +02:00
`;return}const E="max";let D=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(D="avgValue / count");const F=Math.floor(o/4)*4,_=o%4,B=`
if (${L}) {
2020-10-11 18:41:17 +02:00
avgValue += dot(values, ones);
} else {
2020-10-13 22:57:06 +02:00
minMaxValue = ${E}(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-13 22:57:06 +02:00
for (int wC = 0; wC < ${F}; wC += 4) {
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-13 22:57:06 +02:00
${B}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
int xC = xCCorner + ${F};
if (${_===1}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
2020-10-13 22:57:06 +02:00
${B}
} else if (${_===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-13 22:57:06 +02:00
${B}
} else if (${_===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-13 22:57:06 +02:00
${B}
2020-10-11 18:41:17 +02:00
}
}
2020-10-13 22:57:06 +02:00
setOutput(${D});
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
`}}class OS{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,y=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,L=e.effectiveFilterWidth,T=e.padInfo.front,A=e.padInfo.top,N=e.padInfo.left;this.outputShape=e.outShape;const E=t==="avg";let D="0.0";if(E||(D="-1.0 / 1e-20"),n){const q=">=";this.userCode=`
2020-10-11 18:41:17 +02:00
const ivec3 strides =
2020-10-13 22:57:06 +02:00
ivec3(${a}, ${c}, ${h});
const ivec3 pads = ivec3(${T}, ${A}, ${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};
wC += ${y}) {
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-13 22:57:06 +02:00
if (value ${q} 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-13 22:57:06 +02:00
`;return}const F="max";let _=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(_="avgValue / count");const B=Math.floor(o/4)*4,$=o%4,H=`
if (${E}) {
2020-10-11 18:41:17 +02:00
avgValue += dot(values, ones);
} else {
2020-10-13 22:57:06 +02:00
minMaxValue = ${F}(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});
const ivec3 pads = ivec3(${T}, ${A}, ${N});
const float initializationValue = ${D};
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-13 22:57:06 +02:00
vec4 minMaxValue = vec4(${D});
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-13 22:57:06 +02:00
for (int wC = 0; wC < ${B}; wC += 4) {
int xC = xCCorner + wC * ${y};
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-13 22:57:06 +02:00
getValue(batch, xD, xR, xC + ${y}, ch),
getValue(batch, xD, xR, xC + 2 * ${y}, ch),
getValue(batch, xD, xR, xC + 3 * ${y}, ch)
2020-10-11 18:41:17 +02:00
);
2020-10-13 22:57:06 +02:00
${H}
2020-10-11 18:41:17 +02:00
}
2020-10-13 22:57:06 +02:00
int xC = xCCorner + ${B};
if (${$===1}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
2020-10-13 22:57:06 +02:00
${H}
} else if (${$===2}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-13 22:57:06 +02:00
getValue(batch, xD, xR, xC + ${y}, ch),
2020-10-11 18:41:17 +02:00
initializationValue,
initializationValue
);
2020-10-13 22:57:06 +02:00
${H}
} else if (${$===3}) {
2020-10-11 18:41:17 +02:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
2020-10-13 22:57:06 +02:00
getValue(batch, xD, xR, xC + ${y}, ch),
getValue(batch, xD, xR, xC + 2 * ${y}, ch),
2020-10-11 18:41:17 +02:00
initializationValue
);
2020-10-13 22:57:06 +02:00
${H}
2020-10-11 18:41:17 +02:00
}
}
2020-10-13 22:57:06 +02:00
setOutput(${_});
2020-10-11 18:41:17 +02:00
}
}
2020-10-13 22:57:06 +02:00
`}}class iC{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 y=`
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-13 22:57:06 +02:00
`,b="vec4";t==="all"?(a="1.0",y=`
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-13 22:57:06 +02:00
`,b="bvec4"):t==="any"&&(a="0.0",y=`
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-13 22:57:06 +02:00
${y}
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-13 22:57:06 +02:00
${y}
} 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-13 22:57:06 +02:00
${y}
} 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-13 22:57:06 +02:00
${y}
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-13 22:57:06 +02:00
`}}class rC{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-13 22:57:06 +02:00
${Y8(t)}
${vS(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-13 22:57:06 +02:00
`}}function Y8(e){const t=Ho(["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-13 22:57:06 +02:00
`}class H8{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],d=c[0]/h[0],m=c[1]/h[1],y=1/d,b=1/m,w=Math.ceil(y)*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-13 22:57:06 +02:00
const float invHeightScale = float(${y});
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-13 22:57:06 +02:00
`}}class q8{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-13 22:57:06 +02:00
`}}class j8{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-13 22:57:06 +02:00
`}}class K8{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],y=1/d,b=1/m,w=Math.ceil(y)*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-13 22:57:06 +02:00
const float invHeightScale = float(${y});
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-13 22:57:06 +02:00
`}}class X8{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-13 22:57:06 +02:00
`}}class J8{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-13 22:57:06 +02: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=Et(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-13 22:57:06 +02:00
`}}class Z8{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=ls("rc",n),i=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,o=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Et(n);n===1?this.userCode=`
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-13 22:57:06 +02:00
`;function c(w){return y(w)}function h(w){return w[n-1]="("+w[n-1]+" + 1)",y(w)}function d(w){return w[n-2]="("+w[n-2]+" + 1)",y(w)}function m(w){return w[n-1]="("+w[n-1]+" + 1)",w[n-2]="("+w[n-2]+" + 1)",y(w)}function y(w){const L=e.map((N,E)=>b(E,w)),T=L.join(","),A=L.slice(-2).join(",");return`getChannel(getX(${T}), vec2(${A}))`}function b(w,L){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${L[w]} - 1`:`${L[w]}`}}}class oC{constructor(e,t,n,s,i,o,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=Et(i.length),h=Et(o.length);let d="";n===1?d="i":n===2&&(d="i, j");const m=`getIndices(${d})`;let y="";s===1?y="i":s===2&&(y="i, coords[1]");const b=`getUpdates(${y})`,w=t>1?"strides[j]":"strides";this.userCode=`
${c} strides = ${c}(${i});
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-13 22:57:06 +02:00
`}}class Q8{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,y=`
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-13 22:57:06 +02:00
${y}
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-13 22:57:06 +02:00
${y}
} 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-13 22:57:06 +02:00
${y}
} 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-13 22:57:06 +02:00
${y}
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-13 22:57:06 +02:00
`}}class e6{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=Et(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-13 22:57:06 +02:00
`}}class t6{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Et(this.rank),n=`uniform int start[${this.rank}];`,s=n6(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${ES[c]} = start[${c}] + coords.${ES[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}));
}
`}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 ES=["x","y","z","w","u","v"];function n6(e){if(e===1)return"sourceLoc";if(e<=6)return ES.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class s6{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Et(this.rank),n=ls("coords",this.rank),s=ls("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,o=`getChannel(getSource(${s.join()}), ${i})`,a=`
result.x = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.y = ${o};
--${s[this.rank-1]};
}
`,c=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
++${s[this.rank-2]};
result.z = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.w = ${o};
}
}
`,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-13 22:57:06 +02: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 i6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,i=Et(n.length),o=Et(n.length);let a="";if(s===1)a="coords * strides + begin";else{let c=0;a=n.map((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-13 22:57:06 +02:00
`}}class r6{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=lC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=aC(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===Sn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Sn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Sn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Sn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Sn.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=lC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=aC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=C().get("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=a):(this.freeTextures[o].push(e),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const 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 o6(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 aC(e,t,n,s,i){const o=a6(t,s);let a;if(i){const[h,d]=ac(e[0],e[1]);a=h*d}else{const[h,d]=iu(e[0],e[1]);a=h*d}const c=o6(n,o);return a*c}function a6(e,t){switch(e){case Sn.PACKED_2X2_FLOAT32:return tC(t);case Sn.PACKED_2X2_FLOAT16:return nC(t);case Sn.UNPACKED_FLOAT32:return Z0(t);case Sn.UNPACKED_FLOAT16:return Q0(t);case Sn.PACKED_4X1_UNSIGNED_BYTE:return eC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function c6(e){return C().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Sn.PACKED_2X2_FLOAT32:Sn.UNPACKED_FLOAT32:e?Sn.PACKED_2X2_FLOAT16:Sn.UNPACKED_FLOAT16}function cC(e,t){if(e===As.UPLOAD)return Sn.PACKED_2X2_FLOAT32;if(e===As.RENDER||e==null)return c6(t);if(e===As.DOWNLOAD||e===As.PIXELS)return Sn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function lC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class l6{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[o]*t[o];this.outputShape=n,this.rank=n.length;const s=Et(this.rank),i=h6(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-13 22:57:06 +02:00
`}}function h6(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-13 22:57:06 +02:00
`}}const cr="if (isnan(x)) return x;",u6="return x;",hC="return abs(x);",uC=cr+`
2020-10-11 18:41:17 +02:00
return (x < 0.0) ? 0.0 : x;
2020-10-13 22:57:06 +02:00
`,dC=cr+`
2020-10-11 18:41:17 +02:00
return (x < 0.0) ? 0.0 : min(6.0, x);
2020-10-13 22:57:06 +02:00
`,pC="return (x >= 0.0) ? x : (exp(x) - 1.0);",d6=`
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-13 22:57:06 +02:00
float scaleAlpha = ${fp};
float scale = ${gp};
2020-10-11 18:41:17 +02:00
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
2020-10-13 22:57:06 +02:00
`;function p6(e=0){return cr+`
2020-10-11 18:41:17 +02:00
return x > 0.0 ? 1.0 : float(${e});
2020-10-13 22:57:06 +02:00
`}const mC="return -x;",fC="return ceil(x);",gC="return floor(x);",m6=`
2020-10-11 18:41:17 +02:00
if (isnan(x)) { return 0.0; }
return sign(x);
2020-10-13 22:57:06 +02:00
`,f6="return float(isnan(x));",g6="return float(isinf(x));",y6="return float(!isnan(x) && !isinf(x));",b6=`
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-13 22:57:06 +02:00
`,yC="return exp(x);",bC="return exp(x) - 1.0;",w6=`if (x < 0.0) return NAN;
return log(x);`,L6="return log(1.0 + x);",S6="return sqrt(x);",I6="return inversesqrt(x);",x6="return 1.0 / (1.0 + exp(-1.0 * x));",T6=`
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-13 22:57:06 +02:00
`,A6=cr+`
2020-10-11 18:41:17 +02:00
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
2020-10-13 22:57:06 +02:00
`,v6=cr+`
2020-10-11 18:41:17 +02:00
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
2020-10-13 22:57:06 +02:00
`,N6=cr+`
2020-10-11 18:41:17 +02:00
return atan(x);
2020-10-13 22:57:06 +02:00
`,C6=`
2020-10-11 18:41:17 +02:00
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
2020-10-13 22:57:06 +02:00
`,R6=`
2020-10-11 18:41:17 +02:00
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
2020-10-13 22:57:06 +02:00
`,O6=`
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-13 22:57:06 +02:00
`,E6=cr+"return log(x + sqrt(x * x + 1.0));",D6=cr+`
2020-10-11 18:41:17 +02:00
if (x < 1.0) return NAN;
2020-10-13 22:57:06 +02:00
return log(x + sqrt(x * x - 1.0));`,k6=cr+`
2020-10-11 18:41:17 +02:00
if ((x < -1.0) || (x > 1.0)) return NAN;
2020-10-13 22:57:06 +02:00
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,F6=`
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-13 22:57:06 +02:00
float p = ${rw};
float a1 = ${ow};
float a2 = ${aw};
float a3 = ${cw};
float a4 = ${lw};
float a5 = ${hw};
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-13 22:57:06 +02:00
`,_6="return 1.0 / x;",W6="return float(!(x >= 1.0));",$6="return float(int(x));",mm="return x;";const U6="return x;",B6=`
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-13 22:57:06 +02:00
`,wC=`
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-13 22:57:06 +02:00
`,LC=`
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-13 22:57:06 +02:00
`,SC=`
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-13 22:57:06 +02:00
`;class lu{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-13 22:57:06 +02:00
`}}class M6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=ls("rc",t),s=Et(t),i=TK(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-13 22:57:06 +02:00
`}}const{segment_util:IC}=pw,P6=mw,z6=fw,G6=gw,V6=ip,Y6=1e-7,H6=1e-4,fm={};function q6(e){return e in fm||(fm[e]={}),fm[e]}function gm(e,t=!1){if(e==="linear")return t?U6:u6;if(e==="relu")return t?wC:uC;if(e==="elu")return t?SC:pC;if(e==="relu6")return t?LC:dC;if(e==="prelu")return t?G0:z0;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const j6=128,K6=600;function X6(){return C().global.screen==null?1024:C().global.screen.height*C().global.screen.width*window.devicePixelRatio*K6/1024/1024}const xC=1e3;class J6 extends g{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!C().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Wi(C().getNumber("WEBGL_VERSION"));this.binaryCache=q6(C().getNumber("WEBGL_VERSION")),this.gpgpu=new A8(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 r6(this.gpgpu),this.numMBBeforeWarning=X6(),this.texData=new p(this,_s())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((C().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||C().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:As.UPLOAD,refCount:1}),s}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,n,s){if(C().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:As.UPLOAD,refCount:1})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const n=this.texData.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:n,dtype:s,complexTensors:i,slice:o,shape:a,isPacked:c}=t;if(o!=null){let y;c?y=new lu(a,mm):y=new st(a,mm);const b=this.runWebGLProgram(y,[{dataId:e,shape:a,dtype:s}],s),w=this.readSync(b.dataId);return this.disposeIntermediateTensorInfo(b),w}if(n!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return n;const h=this.activeTimers!=null;let d;h&&(d=Yn());let m;if(s==="complex64"){const y=i.real.dataSync(),b=i.imag.dataSync();m=er(y,b)}else m=this.getValuesFromTexture(e);return h&&(this.downloadWaitMs+=Yn()-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,complexTensors:a,isPacked:c}=t;if(i!=null){let w;c?w=new lu(s,mm):w=new st(s,mm);const L=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),T=this.read(L.dataId);return this.disposeIntermediateTensorInfo(L),T}if(n!=null)return this.convertAndCacheOnCPU(e);if(!C().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&C().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let h=null,d;if(o!=="complex64"&&C().get("WEBGL_BUFFER_SUPPORTED")){d=this.decode(e);const w=this.texData.get(d.dataId);h=this.gpgpu.createBufferFromTexture(w.texture,...ru(s))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let m;if(o==="complex64"){const w=await Promise.all([a.real.data(),a.imag.data()]),L=w[0],T=w[1];m=er(L,T)}else if(h==null)m=this.getValuesFromTexture(e);else{const w=we(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(h,w)}d!=null&&this.disposeIntermediateTensorInfo(d);const y=this.convertAndCacheOnCPU(e,m),b=this.pendingRead.get(e);return this.pe
2020-10-11 18:41:17 +02:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-10-13 22:57:06 +02:00
`,nX=`
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-13 22:57:06 +02:00
`;function ym(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 DS(e,t,n,s){return({inputs:i,backend:o})=>{const{a,b:c}=i,h=o,d=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jr(t,a.shape,c.shape,!!n):new ln(e,a.shape,c.shape),m=s||a.dtype,y=h.runWebGLProgram(d,[a,c],m);return y}}const sX=tX+`
2020-10-11 18:41:17 +02:00
return atan(a, b);
2020-10-13 22:57:06 +02:00
`,iX=`
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-13 22:57:06 +02:00
`+nX+`
2020-10-11 18:41:17 +02:00
return result;
2020-10-13 22:57:06 +02:00
`,rX=DS(sX,iX),oX={kernelName:Si,backendName:"webgl",kernelFunc:rX};function kS(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const aX={kernelName:yl,backendName:"webgl",kernelFunc:kS};function cX(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;ou(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;k(sn(a,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Fn(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))return kS({inputs:{x:i},backend:n});const y=new cu(m,"avg",!1);return n.runWebGLProgram(y,[i],"float32")}const lX={kernelName:Qs,backendName:"webgl",kernelFunc:cX};function hX(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;ou([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:d}=s,m=Fn(a.shape,c,h,1,d),y=new c5(m);return n.runWebGLProgram(y,[i],a.dtype)}const uX={kernelName:fa,backendName:"webgl",kernelFunc:hX};class dX{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],tt(e,t),tt(e,n);let a="0.0";s!=null&&(tt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(tt(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-13 22:57:06 +02:00
`}}class pX{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],tt(e,t),tt(e,n);let a="vec4(0.0)";s!=null&&(tt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(tt(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-13 22:57:06 +02:00
`}}const mX=({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:i,variance:o,offset:a,scale:c}=e;k(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(c==null||i.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:h}=n;h==null&&(h=.001);const d=[s,i,o];let m=null;a!=null&&(m=a.shape,d.push(a));let y=null;c!=null&&(y=c.shape,d.push(c));const b=C().getBool("WEBGL_PACK_NORMALIZATION")?new pX(s.shape,i.shape,o.shape,m,y,h):new dX(s.shape,i.shape,o.shape,m,y,h),w=t.runWebGLProgram(b,d,d[0].dtype);return w},fX={kernelName:gl,backendName:"webgl",kernelFunc:mX};const gX=TC+`
2020-10-11 18:41:17 +02:00
return cos(x);
2020-10-13 22:57:06 +02:00
`,yX=ym(gX),bX={kernelName:ga,backendName:"webgl",kernelFunc:yX};const wX=`
2020-10-11 18:41:17 +02:00
if (a == b) {
return 1.0;
};
2020-10-13 22:57:06 +02:00
return a / b;`,LX=`
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-13 22:57:06 +02:00
`,SX=DS(wX,LX,!0),IX={kernelName:ya,backendName:"webgl",kernelFunc:SX};class xX{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-13 22:57:06 +02:00
`}}const TX={kernelName:Ju,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new xX(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class AX{constructor(e){this.variableNames=["A"];const t=Wn(),[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-13 22:57:06 +02:00
`}}class vX{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Wn(),[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-13 22:57:06 +02:00
`}}const NX={kernelName:ld,backendName:"webgl",kernelFunc:CX};let mc;function CX(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],y=[d,h,o];(c||a)&&(mc==null&&(mc=document.createElement("canvas").getContext("2d")),mc.canvas.width=h,mc.canvas.height=d,mc.drawImage(i,0,0,h,d),i=mc.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=As.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=C().getBool("WEBGL_PACK")?new vX(y):new AX(y),L=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),L}function RX(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const n=t.length?t[t.length-1].outSize:e[1],s=ah(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function OX(e,t,n,s){const i=RX(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:h,outSize:d}=i[a],m=new iC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d},n),y=o;o=s.runWebGLProgram(m,[o],t),y.dataId!==e.dataId&&s.disposeData(y.dataId)}return o}function EX(e,t,n){const s=[cc(e.shape),...lc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[cc(t),...lc(t)],a=new rC(o,s),c=!0,h=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:h.dataId,shape:t,dtype:h.dtype}}function FS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=we(i.shape),h=md(o,c),d=we(h);k(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&&!cm(i.shape,h)&&!(m.texture!==null&&cm(m.shape,h))?EX(i,h,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:h,dtype:i.dtype})}const DX={kernelName:Nl,backendName:"webgl",kernelFunc:FS};function kX(e,t,n,s){const i=we(t),o=we(e.shape),a=o/i,c=FS({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=OX(c,e.dtype,"max",s),d=FS({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),d}class FX{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[t[o]];this.outputShape=n,this.rank=n.length;const s=Et(this.rank),i=_X(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-13 22:57:06 +02:00
`}}function _X(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 WX{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=Et(this.rank),i=k0("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-13 22:57:06 +02:00
`}}function AC(e,t,n){const s=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new WX(e.shape,t):new FX(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const $X={kernelName:xl,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=gt(i,s.shape);let d=h;const m=kn(d,c),y=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(y){if(b){const E=a.texData.get(w.dataId),D=E.values,F=new Array(c);for(let $=0;$<F.length;$++)F[$]=s.shape[m[$]];const _=D0(D,s.shape,s.dtype,m,F);w=a.makeTensorInfo(F,s.dtype);const B=a.texData.get(w.dataId);B.values=_}else w=AC(s,m,a);d=ws(d.length,c)}ts("max",d,c);const[L,T]=Rn(w.shape,d);let A=L;o&&(A=On(L,h));let N;if(b){const E=a.texData.get(w.dataId),D=E.values,F=fK(D,we(T),A,s.dtype);N=a.makeTensorInfo(A,s.dtype);const _=a.texData.get(N.dataId);_.values=F}else N=kX(w,T,A,a);return y&&a.disposeIntermediateTensorInfo(w),N}};function UX(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;ou(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;k(sn(a,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Fn(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))return kS({inputs:{x:i},backend:n});const y=new cu(m,"max",!1);return n.runWebGLProgram(y,[i],i.dtype)}const BX={kernelName:Tl,backendName:"webgl",kernelFunc:UX};function MX(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;ou([o,a],"maxPoolBackprop");const{filterSize:h,strides:d,pad:m,dimRoundingMode:y}=s,b=Fn(c.shape,h,d,1,m,y),w=!0,L=new cu(b,"max",w),T=n.runWebGLProgram(L,[c],c.dtype),A=new F8(b),N=n.runWebGLProgram(A,[i,T],c.dtype);return n.disposeIntermediateTensorInfo(T),N}const PX={kernelName:Qu,backendName:"webgl",kernelFunc:MX};function zX(e,t,n,s){let i=new cu(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new cu(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const GX={kernelName:ed,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;k(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const d=[1,1];k(sn(o,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);const m=Fn(s.shape,i,o,d,a),[y,b]=zX(s,c,m,h);return[y,b]}};const VX={kernelName:iy,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Ya("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),y=o,b=a,w=c;return up(d,m,y,b,w)}};const YX=dp,HX={kernelName:nd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Ya("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),y=d.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=YX(m,y,o,a,c,h);return[b,w]}};const qX=pp,jX={kernelName:sd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{Ya("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),y=d.readSync(i.dataId),b=o,w=a,L=c,T=h,{selectedIndices:A,selectedScores:N}=qX(m,y,b,w,L,T);return[A,N]}};class KX{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]=nw(s,i,o),m=h.toFixed(3),y=d.toFixed(3);let b="";typeof n=="number"?b=`float outputValue = ${n.toFixed(2)};`:b=`
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-13 22:57:06 +02:00
float coordXFloat = (float(x) - ${m}) * ${c} - (float(y) - ${y}) * ${a};
float coordYFloat = (float(x) - ${m}) * ${a} + (float(y) - ${y}) * ${c};
int coordX = int(round(coordXFloat + ${m}));
int coordY = int(round(coordYFloat + ${y}));
${b}
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${i}) {
2020-10-11 18:41:17 +02:00
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
2020-10-13 22:57:06 +02:00
`}}const XX={kernelName:hd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=new KX(s.shape,i,o,a),d=c.runWebGLProgram(h,[s],s.dtype);return d}};const JX=TC+`
2020-10-11 18:41:17 +02:00
return sin(x);
2020-10-13 22:57:06 +02:00
`,ZX=ym(JX),QX={kernelName:ba,backendName:"webgl",kernelFunc:ZX};const e7="return x * x;",t7=ym(e7),n7={kernelName:ad,backendName:"webgl",kernelFunc:t7};const vC="return (a - b) * (a - b);",s7=DS(vC,vC),i7={kernelName:wa,backendName:"webgl",kernelFunc:s7};const r7="return tan(x);",o7=ym(r7),a7={kernelName:La,backendName:"webgl",kernelFunc:o7};const c7={kernelName:Ul,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,y=D0(m,s.shape,s.dtype,i,c);h=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(h.dataId);b.values=y}else h=AC(s,i,o);return h}};function l7(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;ou(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}=LK(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([d.length],"int32",d)]}const h7={kernelName:cd,backendName:"webgl",kernelFunc:l7};const u7=[oX,lX,uX,fX,bX,IX,TX,NX,aX,$X,BX,PX,GX,VX,HX,jX,DX,XX,QX,n7,i7,a7,c7,h7];for(const e of u7)dd(e);const d7="2.6.0";const p7={"tfjs-core":OT,"tfjs-backend-cpu":Iq,"tfjs-backend-webgl":Q6,"tfjs-data":o0,"tfjs-layers":zp,"tfjs-converter":UN,tfjs:d7};r.Abs=ge,r.Acos=fe,r.Acosh=Ae,r.AdadeltaOptimizer=wh,r.AdagradOptimizer=Lh,r.AdamOptimizer=Sh,r.AdamaxOptimizer=Ih,r.Add=Te,r.AddN=Ve,r.All=rt,r.Any=Ct,r.ArgMax=Ut,r.ArgMin=Kt,r.Asin=Dn,r.Asinh=An,r.Atan=vn,r.Atan2=Si,r.Atanh=Zs,r.AvgPool=Qs,r.AvgPool3D=ol,r.AvgPool3DBackprop=ax,r.AvgPoolBackprop=fa,r.BatchMatMul=_g,r.BatchToSpaceND=Wg,r.BroadcastTo=$g,r.Callback=xN,r.CallbackList=yv,r.Cast=al,r.Ceil=cl,r.ClipByValue=ll,r.Complex=Ug,r.Concat=qu,r.Conv2D=Bg,r.Conv2DBackpropFilter=cx,r.Conv2DBackpropInput=Mg,r.Conv3D=Pg,r.Conv3DBackpropFilterV2=lx,r.Conv3DBackpropInputV2=hx,r.Cos=ga,r.Cosh=hl,r.CropAndResize=ux,r.Cumsum=zg,r.CustomCallback=wv,r.DataStorage=p,r.DepthToSpace=dx,r.DepthwiseConv2dNative=Gg,r.DepthwiseConv2dNativeBackpropFilter=px,r.DepthwiseConv2dNativeBackpropInput=mx,r.Diag=fx,r.Dilation2D=ju,r.Dilation2DBackpropFilter=Xu,r.Dilation2DBackpropInput=Ku,r.Div=ya,r.EarlyStopping=AN,r.Elu=ul,r.EluGrad=gx,r.Environment=S,r.Equal=yx,r.Erf=dl,r.Exp=pl,r.Expm1=ml,r.FFT=Vg,r.Fill=bx,r.FlipLeftRight=Ju,r.Floor=fl,r.FloorDiv=Yg,r.FromPixels=ld,r.FusedBatchNorm=gl,r.FusedConv2D=Ty,r.FusedDepthwiseConv2D=Ay,r.GatherNd=wx,r.GatherV2=Hg,r.GraphModel=$N,r.Greater=Lx,r.GreaterEqual=qg,r.History=bv,r.IFFT=jg,r.Identity=yl,r.Imag=Kg,r.InputSpec=mn,r.IsFinite=bl,r.IsInf=wl,r.IsNan=Ll,r.KernelBackend=g,r.LRN=Jg,r.LRNBackprop=vx,r.LayerVariable=ai,r.LayersModel=ir,r.Less=Sx,r.LessEqual=Ix,r.LinSpace=xx,r.Log=Sl,r.Log1p=Il,r.LogSoftmax=Xg,r.LogicalAnd=Tx,r.LogicalNot=Zu,r.LogicalOr=Ax,r.Max=xl,r.MaxPool=Tl,r.MaxPool3D=Qg,r.MaxPool3DBackprop=Nx,r.MaxPoolBackprop=Qu,r.MaxPoolWithArgmax=ed,r.Maximum=Zg,r.Mean=YD,r.Min=ey,r.Minimum=ty,r.Mod=ny,r.MomentumOptimizer=xh,r.Multiply=Al,r.Negate=sy,r.NonMaxSuppressionV3=iy,r.NonMaxSuppressionV4=nd,r.NonMaxSuppressionV5=sd,r.NotEqual=td,r.OP_SCOPE_SUFFIX=tT,r.OneHot=oy,r.OnesLike=ry,r.Optimizer=Qi,r.PadV2=id,r.Pool=HD,r.Pow=ay,r.Prelu=cy,r.Prod=Cx,r.RMSPropOptimizer=Th,r.RNN=_i,r.Range=Rx,r.Real=ly,r.Reciprocal=vl,r.Relu=hy,r.Relu6=py,r.Reshape=Nl,r.ResizeBilinear=dy,r.ResizeBilinearGrad=Ex,r.ResizeNearestNeighbor=uy,r.ResizeNearestNeighborGrad=Ox,r.Reverse=my,r.RotateWithOffset=hd,r.Round=Cl,r.Rsqrt=Rl,r.SGDOptimizer=Va,r.ScatterNd=Dx,r.SelectV2=fy,r.Selu=Ol,r.Sequential=Za,r.Sigmoid=kl,r.Sign=Dl,r.Sin=ba,r.Sinh=El,r.Slice=rd,r.Softmax=by,r.Softplus=Fl,r.SpaceToBatchND=od,r.SparseToDense=kx,r.SplitV=yy,r.Sqrt=_l,r.Square=ad,r.SquaredDifference=wa,r.Step=Bl,r.StridedSlice=Fx,r.Sub=Wl,r.Sum=gy,r.SymbolicTensor=ci,r.Tan=La,r.Tanh=$l,r.Tensor=Q,r.TensorBuffer=vr,r.Tile=wy,r.TopK=_x,r.Transpose=Ul,r.Unique=cd,r.Unpack=Ly,r.UnsortedSegmentSum=Sy,r.Variable=Hl,r.ZerosLike=Iy,r._FusedMatMul=xy,r.abs=nn,r.acos=ub,r.acosh=d
`)),x.join(`
`)}function Y7(r,l,u,p){const g=qt(l),f=p[p.length-1],I=new Array(f).fill(0),S=l.length,x=u==="complex64"?vu(r):r;if(S>1)for(let v=0;v<g/f;v++){const O=v*f;for(let C=0;C<f;C++)I[C]=Math.max(I[C],Au(x[O+C],0,u).length)}return I}function Au(r,l,u){let p;return Array.isArray(r)?p=`${parseFloat(r[0].toFixed(uI))} + ${parseFloat(r[1].toFixed(uI))}j`:Su(r)?p=`'${r}'`:u==="bool"?p=cO(r):p=parseFloat(r.toFixed(uI)).toString(),_c(p,l)}function cO(r){return r===0?"false":"true"}function tg(r,l,u,p,g,f=!0){const I=u==="complex64"?2:1,S=l[0],x=l.length;if(x===0){if(u==="complex64"){const te=vu(r);return[Au(te[0],0,u)]}return u==="bool"?[cO(r[0])]:[r[0].toString()]}if(x===1){if(S>oO){const oe=Tu*I;let ge=Array.from(r.slice(0,oe)),fe=Array.from(r.slice((S-Tu)*I,S*I));return u==="complex64"&&(ge=vu(ge),fe=vu(fe)),["["+ge.map((Ae,Te)=>Au(Ae,g[Te],u)).join(", ")+", ..., "+fe.map((Ae,Te)=>Au(Ae,g[S-Tu+Te],u)).join(", ")+"]"]}const te=u==="complex64"?vu(r):Array.from(r);return["["+te.map((oe,ge)=>Au(oe,g[ge],u)).join(", ")+"]"]}const v=l.slice(1),O=p.slice(1),C=p[0]*I,U=[];if(S>oO){for(let te=0;te<Tu;te++){const oe=te*C,ge=oe+C;U.push(...tg(r.slice(oe,ge),v,u,O,g,!1))}U.push("...");for(let te=S-Tu;te<S;te++){const oe=te*C,ge=oe+C;U.push(...tg(r.slice(oe,ge),v,u,O,g,te===S-1))}}else for(let te=0;te<S;te++){const oe=te*C,ge=oe+C;U.push(...tg(r.slice(oe,ge),v,u,O,g,te===S-1))}const G=x===2?",":"";U[0]="["+U[0]+G;for(let te=1;te<U.length-1;te++)U[te]=" "+U[te]+G;let ne=`,
`;for(let te=2;te<x;te++)ne+=`
`;return U[U.length-1]=" "+U[U.length-1]+"]"+(f?"":ne),U}function vu(r){const l=[];for(let u=0;u<r.length;u+=2)l.push([r[u],r[u+1]]);return l}class lO{constructor(r,l,u){if(this.dtype=l,this.shape=r.slice(),this.size=qt(r),u!=null){const p=u.length;Z(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||JR(l,this.size),this.strides=xu(r)}set(r,...l){l.length===0&&(l=[0]),Z(l.length===this.rank,()=>`The number of provided coordinates (${l.length}) must match the rank (${this.rank})`);const 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 g=`Requested out of range element at ${r}. Buffer shape=${this.shape}`;throw new Error(g)}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 zi().makeTensor(this.values,this.shape,this.dtype)}}let zi=null,Wc=null,H7=null;function hO(r){zi=r}function uO(r){Wc=r}function dO(r){H7=r}class xn{constructor(r,l,u,p){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=qt(r),this.strides=xu(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 Wc.buffer(this.shape,this.dtype,r)}bufferSync(){return Wc.buffer(this.shape,this.dtype,this.dataSync())}async array(){const r=await this.data();return cI(this.shape,r)}arraySync(){return cI(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const r=zi().read(this.dataId);if(this.dtype==="string"){const l=await r;try{return l.map(u=>hI(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=zi().readSync(this.dataId);if(this.dtype==="string")try{return r.map(l=>hI(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 zi().read(this.dataId);return this.dtype==="string"?r:new Uint8Array(r.buffer)}dispose(){if(this.isDisposed)return;zi().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(r=!1){return Wc.print(this,r)}clone(){return this.throwIfDisposed(),Wc.clone(this)}toString(r=!1){const l=this.dataSync();return aO(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),Wc.cast(this,r)}variable(r=!0,l,u){return this.throwIfDisposed(),zi().makeVariable(this,r,l,u)}}Object.defineProperty(xn,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class ng extends xn{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(!sa(r.shape,this.shape))throw new Error(`shape of the new value (${r.shape}) and previous value (${this.shape}) must match`);zi().disposeTensor(this),this.dataId=r.dataId,zi().incRef(this,null)}dispose(){zi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(ng,Symbol.hasInstance,{value:r=>r instanceof xn&&r.assign!=null&&r.assign instanceof Function});var pO;(function(r){r.R0="R0",
2020-10-14 13:53:11 +02:00
with dtype ${I.dtype}. `)});const p=(I,S)=>{const x=ut(l,u[0].shape)[0],v=NO(u.map(U=>U.shape),x);if(qt(v)===0)return yI([],v);if(u=u.filter(U=>U.size>0),u.length===1)return u[0];const O=u.map(U=>U.shape);vO(O,x);const C=I.concat(u,x);return S(u),C},g=u,f={axis:l};return Y.runKernelFunc(p,g,null,rf,f)}const yn=z({concat_:wJ});function LJ(r){const l=M(r,"x","sigmoid"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.sigmoid(l);return g([f]),f},u,null,Uf)}const xI=z({sigmoid_:LJ});function SJ(r,l,u){const p=M(r,"x","slice");if(p.rank===0)throw new Error("Slicing scalar is not possible");const g=(S,x)=>{const[v,O]=rg(p,l,u);return SO(p,v,O),x([p]),S.slice(p,v,O)},f={x:p},I={begin:l,size:u};return Y.runKernelFunc(g,f,null,_f,I)}const vt=z({slice_:SJ});function IJ(r,l,u){const p=M(r,"x","batchToSpaceND"),g=l.reduce((x,v)=>x*v);Z(p.rank>=1+l.length,()=>`input rank is ${p.rank} but should be > than blockShape.length ${l.length}`),Z(u.length===l.length,()=>`crops.length is ${u.length} but should be equal to blockShape.length ${l.length}`),Z(p.shape[0]%g===0,()=>`input tensor batch is ${p.shape[0]} but is not divisible by the product of the elements of blockShape ${l.join(" * ")} === ${g}`);const f=x=>x.batchToSpaceND(p,l,u),I={x:p},S={blockShape:l,crops:u};return Y.runKernelFunc(f,I,null,nf,S)}const TI=z({batchToSpaceND_:IJ});function xJ(r,l){let u=M(r,"broadcastTo","x");const p=u.shape;if(l.some(O=>!(O>0)||O%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 O=u.shape.slice();for(;O.length<l.length;)O.unshift(1);u=ie(u,O)}const g=u.shape,f=Array.from(l);for(let O=l.length-1;O>=0;O--)if(g[O]===l[O])f[O]=1;else if(u.shape[O]!==1)throw new Error(`broadcastTo(): [${p}] cannot be broadcast to [${l}].`);const I=f.map((O,C)=>O>1?C:-1).filter(O=>O>=0);if(I.length===0)return gi(u);const S=O=>O.tile(u,f),x={x:u},v={shape:l,inputShape:g};return Y.runKernelFunc(S,x,null,sf,v)}const lg=z({broadcastTo_:xJ});function TJ(r,l,u,p,g="NHWC",f=[1,1],I){const S=M(r,"x","conv2d"),x=M(l,"filter","conv2d");let v=S,O=!1;S.rank===3&&(O=!0,v=ie(S,[1,S.shape[0],S.shape[1],S.shape[2]])),Z(v.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${v.rank}.`),Z(x.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${x.rank}.`),I!=null&&Z(Qt(p),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${p}.`);const C=g==="NHWC"?v.shape[3]:v.shape[1];Z(C===x.shape[2],()=>`Error in conv2d: depth of input (${C}) must match input depth for filter ${x.shape[2]}.`),Z(ao(u,f),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${u} and dilations '${f}'`);const U=(oe,ge)=>{const fe=Mc(g),Ae=fr(v.shape,x.shape,u,f,p,I,!1,fe),Te=oe.conv2d(v,x,Ae);return ge([v,x]),Te},G={x:v,filter:x},ne={strides:u,pad:p,dataFormat:g,dilations:f,dimRoundingMode:I},te=Y.runKernelFunc(U,G,null,of,ne);return O?ie(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const AI=z({conv2d_:TJ});function AJ(r,l,u,p,g,f="NHWC",I){Z(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let S=r,x=l,v=!1;l.rank===3&&(v=!0,x=ie(l,[1,l.shape[0],l.shape[1],l.shape[2]]),S=[1,r[0],r[1],r[2]]),Z(S.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${S.length}.`),Z(x.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${x.rank}`),Z(u.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${u.rank}`);const O=f==="NHWC"?S[3]:S[1],C=f==="NHWC"?x.shape[3]:x.shape[1];Z(O===u.shape[2],()=>`Error in conv2dDerInput: depth of input (${O}) must match input depth for filter ${u.shape[2]}.`),Z(C===u.shape[3],()=>`Error in conv2dDerInput: depth of output (${C}) must match output depth for filter ${u.shape[3]}.`),I!=null&&Z(Qt(g),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`);const U=(oe,ge)=>{const fe=1,Ae=Mc(f),Te=fr(S,u.s
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